Skip to content

Commit

Permalink
Remove Unix() invocations on 'time.Time' objects and removed conversi…
Browse files Browse the repository at this point in the history
…on of time to UTC
  • Loading branch information
vishalnayak committed Jul 8, 2016
1 parent d274bcb commit f59a69b
Show file tree
Hide file tree
Showing 31 changed files with 154 additions and 130 deletions.
4 changes: 2 additions & 2 deletions audit/format_json.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func (f *FormatJSON) FormatRequest(
// Encode!
enc := json.NewEncoder(w)
return enc.Encode(&JSONRequestEntry{
Time: time.Now().UTC().Format(time.RFC3339),
Time: time.Now().Format(time.RFC3339),
Type: "request",
Error: errString,

Expand Down Expand Up @@ -100,7 +100,7 @@ func (f *FormatJSON) FormatResponse(
// Encode!
enc := json.NewEncoder(w)
return enc.Encode(&JSONResponseEntry{
Time: time.Now().UTC().Format(time.RFC3339),
Time: time.Now().Format(time.RFC3339),
Type: "response",
Error: errString,

Expand Down
4 changes: 2 additions & 2 deletions audit/hashstructure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func TestCopy_auth(t *testing.T) {
expected := logical.Auth{
LeaseOptions: logical.LeaseOptions{
TTL: 1 * time.Hour,
IssueTime: time.Now().UTC(),
IssueTime: time.Now(),
},

ClientToken: "foo",
Expand Down Expand Up @@ -109,7 +109,7 @@ func TestHashString(t *testing.T) {
}

func TestHash(t *testing.T) {
now := time.Now().UTC()
now := time.Now()

cases := []struct {
Input interface{}
Expand Down
4 changes: 2 additions & 2 deletions builtin/credential/aws-ec2/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func Backend(conf *logical.BackendConfig) (*backend, error) {
func (b *backend) periodicFunc(req *logical.Request) error {
// Run the tidy operations for the first time. Then run it when current
// time matches the nextTidyTime.
if b.nextTidyTime.IsZero() || !time.Now().UTC().Before(b.nextTidyTime) {
if b.nextTidyTime.IsZero() || !time.Now().Before(b.nextTidyTime) {
// safety_buffer defaults to 180 days for roletag blacklist
safety_buffer := 15552000
tidyBlacklistConfigEntry, err := b.lockedConfigTidyRoleTags(req.Storage)
Expand Down Expand Up @@ -154,7 +154,7 @@ func (b *backend) periodicFunc(req *logical.Request) error {
}

// Update the time at which to run the tidy functions again.
b.nextTidyTime = time.Now().UTC().Add(b.tidyCooldownPeriod)
b.nextTidyTime = time.Now().Add(b.tidyCooldownPeriod)
}
return nil
}
Expand Down
4 changes: 2 additions & 2 deletions builtin/credential/aws-ec2/path_login.go
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ func (b *backend) pathLoginUpdate(
}

// Save the login attempt in the identity whitelist.
currentTime := time.Now().UTC()
currentTime := time.Now()
if storedIdentity == nil {
// Role, ClientNonce and CreationTime of the identity entry,
// once set, should never change.
Expand Down Expand Up @@ -550,7 +550,7 @@ func (b *backend) pathLoginRenew(
}

// Only LastUpdatedTime and ExpirationTime change and all other fields remain the same.
currentTime := time.Now().UTC()
currentTime := time.Now()
storedIdentity.LastUpdatedTime = currentTime
storedIdentity.ExpirationTime = currentTime.Add(longestMaxTTL)

Expand Down
2 changes: 1 addition & 1 deletion builtin/credential/aws-ec2/path_roletag_blacklist.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ func (b *backend) pathRoletagBlacklistUpdate(
blEntry = &roleTagBlacklistEntry{}
}

currentTime := time.Now().UTC()
currentTime := time.Now()

// Check if this is a creation of blacklist entry.
if blEntry.CreationTime.IsZero() {
Expand Down
2 changes: 1 addition & 1 deletion builtin/credential/aws-ec2/path_tidy_identity_whitelist.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ func (b *backend) tidyWhitelistIdentity(s logical.Storage, safety_buffer int) er
return err
}

if time.Now().UTC().After(result.ExpirationTime.Add(bufferDuration)) {
if time.Now().After(result.ExpirationTime.Add(bufferDuration)) {
if err := s.Delete("whitelist/identity" + instanceID); err != nil {
return fmt.Errorf("error deleting identity of instanceID %s from storage: %s", instanceID, err)
}
Expand Down
2 changes: 1 addition & 1 deletion builtin/credential/aws-ec2/path_tidy_roletag_blacklist.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (b *backend) tidyBlacklistRoleTag(s logical.Storage, safety_buffer int) err
return err
}

if time.Now().UTC().After(result.ExpirationTime.Add(bufferDuration)) {
if time.Now().After(result.ExpirationTime.Add(bufferDuration)) {
if err := s.Delete("blacklist/roletag" + tag); err != nil {
return fmt.Errorf("error deleting tag %s from storage: %s", tag, err)
}
Expand Down
7 changes: 1 addition & 6 deletions builtin/logical/aws/secret_access_keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,7 @@ func genUsername(displayName, policyName, userType string) (ret string, warning
// with, so don't insert display name or policy name at all
}

ret = fmt.Sprintf(
"vault-%s%d-%d",
midString,
time.Now().Unix(),
rand.Int31n(10000))

ret = fmt.Sprintf("vault-%s%d-%d", midString, time.Now().Unix(), rand.Int31n(10000))
return
}

Expand Down
8 changes: 4 additions & 4 deletions builtin/logical/pki/backend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -958,7 +958,7 @@ func generateCATestingSteps(t *testing.T, caCert, caKey, otherCaCert string, int
return fmt.Errorf("got an error: %s", resp.Data["error"].(string))
}

if resp.Data["revocation_time"].(int64) != 0 {
if !(resp.Data["revocation_time"].(time.Time)).IsZero() {
return fmt.Errorf("expected a zero revocation time")
}

Expand Down Expand Up @@ -1115,7 +1115,7 @@ func generateCATestingSteps(t *testing.T, caCert, caKey, otherCaCert string, int
return fmt.Errorf("got an error: %s", resp.Data["error"].(string))
}

if resp.Data["revocation_time"].(int64) != 0 {
if !(resp.Data["revocation_time"].(time.Time)).IsZero() {
return fmt.Errorf("expected a zero revocation time")
}

Expand Down Expand Up @@ -1169,7 +1169,7 @@ func generateCATestingSteps(t *testing.T, caCert, caKey, otherCaCert string, int
return fmt.Errorf("got an error: %s", resp.Data["error"].(string))
}

if resp.Data["revocation_time"].(int64) == 0 {
if (resp.Data["revocation_time"].(time.Time)).IsZero() {
return fmt.Errorf("expected a non-zero revocation time")
}

Expand All @@ -1187,7 +1187,7 @@ func generateCATestingSteps(t *testing.T, caCert, caKey, otherCaCert string, int
return fmt.Errorf("got an error: %s", resp.Data["error"].(string))
}

if resp.Data["revocation_time"].(int64) == 0 {
if (resp.Data["revocation_time"].(time.Time)).IsZero() {
return fmt.Errorf("expected a non-zero revocation time")
}

Expand Down
8 changes: 4 additions & 4 deletions builtin/logical/pki/crl_util.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import (
)

type revocationInfo struct {
CertificateBytes []byte `json:"certificate_bytes"`
RevocationTime int64 `json:"revocation_time"`
CertificateBytes []byte `json:"certificate_bytes"`
RevocationTime time.Time `json:"revocation_time"`
}

// Revokes a cert, and tries to be smart about error recovery
Expand Down Expand Up @@ -87,7 +87,7 @@ func revokeCert(b *backend, req *logical.Request, serial string, fromLease bool)
}

revInfo.CertificateBytes = certEntry.Value
revInfo.RevocationTime = time.Now().Unix()
revInfo.RevocationTime = time.Now()

certEntry, err = logical.StorageEntryJSON("revoked/"+serial, revInfo)
if err != nil {
Expand Down Expand Up @@ -153,7 +153,7 @@ func buildCRL(b *backend, req *logical.Request) error {

revokedCerts = append(revokedCerts, pkix.RevokedCertificate{
SerialNumber: revokedCert.SerialNumber,
RevocationTime: time.Unix(revInfo.RevocationTime, 0),
RevocationTime: revInfo.RevocationTime,
})
}

Expand Down
3 changes: 2 additions & 1 deletion builtin/logical/pki/path_fetch.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package pki
import (
"encoding/pem"
"fmt"
"time"

"github.com/hashicorp/vault/helper/certutil"
"github.com/hashicorp/vault/logical"
Expand Down Expand Up @@ -101,7 +102,7 @@ func (b *backend) pathFetchRead(req *logical.Request, data *framework.FieldData)
var certEntry, revokedEntry *logical.StorageEntry
var funcErr error
var certificate []byte
var revocationTime int64
var revocationTime time.Time
response = &logical.Response{
Data: map[string]interface{}{},
}
Expand Down
4 changes: 2 additions & 2 deletions builtin/logical/pki/path_root.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ func (b *backend) pathCAGenerateRoot(

resp := &logical.Response{
Data: map[string]interface{}{
"expiration": int64(parsedBundle.Certificate.NotAfter.Unix()),
"expiration": parsedBundle.Certificate.NotAfter,
"serial_number": cb.SerialNumber,
},
}
Expand Down Expand Up @@ -234,7 +234,7 @@ func (b *backend) pathCASignIntermediate(

resp := &logical.Response{
Data: map[string]interface{}{
"expiration": int64(parsedBundle.Certificate.NotAfter.Unix()),
"expiration": parsedBundle.Certificate.NotAfter,
"serial_number": cb.SerialNumber,
},
}
Expand Down
2 changes: 1 addition & 1 deletion builtin/logical/postgresql/path_role_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func (b *backend) pathRoleCreateRead(
if err != nil {
return nil, err
}
expiration := time.Now().UTC().
expiration := time.Now().
Add(lease.Lease).
Format("2006-01-02 15:04:05-0700")

Expand Down
16 changes: 8 additions & 8 deletions builtin/logical/transit/backend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,14 +222,14 @@ func testAccStepReadPolicy(t *testing.T, name string, expectNone, derived bool)
return nil
}
var d struct {
Name string `mapstructure:"name"`
Key []byte `mapstructure:"key"`
Keys map[string]int64 `mapstructure:"keys"`
CipherMode string `mapstructure:"cipher_mode"`
Derived bool `mapstructure:"derived"`
KDFMode string `mapstructure:"kdf_mode"`
DeletionAllowed bool `mapstructure:"deletion_allowed"`
ConvergentEncryption bool `mapstructure:"convergent_encryption"`
Name string `mapstructure:"name"`
Key []byte `mapstructure:"key"`
Keys map[string]time.Time `mapstructure:"keys"`
CipherMode string `mapstructure:"cipher_mode"`
Derived bool `mapstructure:"derived"`
KDFMode string `mapstructure:"kdf_mode"`
DeletionAllowed bool `mapstructure:"deletion_allowed"`
ConvergentEncryption bool `mapstructure:"convergent_encryption"`
}
if err := mapstructure.Decode(resp.Data, &d); err != nil {
return err
Expand Down
3 changes: 2 additions & 1 deletion builtin/logical/transit/path_keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package transit
import (
"fmt"
"strconv"
"time"

"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
Expand Down Expand Up @@ -109,7 +110,7 @@ func (b *backend) pathPolicyRead(
resp.Data["convergent_encryption"] = p.ConvergentEncryption
}

retKeys := map[string]int64{}
retKeys := map[string]time.Time{}
for k, v := range p.Keys {
retKeys[strconv.Itoa(k)] = v.CreationTime
}
Expand Down
8 changes: 4 additions & 4 deletions builtin/logical/transit/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ const (

// KeyEntry stores the key and metadata
type KeyEntry struct {
Key []byte `json:"key"`
CreationTime int64 `json:"creation_time"`
Key []byte `json:"key"`
CreationTime time.Time `json:"creation_time"`
}

// KeyEntryMap is used to allow JSON marshal/unmarshal
Expand Down Expand Up @@ -491,7 +491,7 @@ func (p *Policy) rotate(storage logical.Storage) error {

p.Keys[p.LatestVersion] = KeyEntry{
Key: newKey,
CreationTime: time.Now().Unix(),
CreationTime: time.Now(),
}

// This ensures that with new key creations min decryption version is set
Expand All @@ -510,7 +510,7 @@ func (p *Policy) migrateKeyToKeysMap() {
p.Keys = KeyEntryMap{
1: KeyEntry{
Key: p.Key,
CreationTime: time.Now().Unix(),
CreationTime: time.Now(),
},
}
p.Key = nil
Expand Down
16 changes: 8 additions & 8 deletions http/sys_health.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,17 +115,17 @@ func getSysHealth(core *vault.Core, r *http.Request) (int, *HealthResponse, erro

// Format the body
body := &HealthResponse{
Initialized: init,
Sealed: sealed,
Standby: standby,
ServerTimeUTC: time.Now().UTC().Unix(),
Initialized: init,
Sealed: sealed,
Standby: standby,
ServerTime: time.Now(),
}
return code, body, nil
}

type HealthResponse struct {
Initialized bool `json:"initialized"`
Sealed bool `json:"sealed"`
Standby bool `json:"standby"`
ServerTimeUTC int64 `json:"server_time_utc"`
Initialized bool `json:"initialized"`
Sealed bool `json:"sealed"`
Standby bool `json:"standby"`
ServerTime time.Time `json:"server_time"`
}
18 changes: 9 additions & 9 deletions http/sys_health_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ func TestSysHealth_get(t *testing.T) {
}
testResponseStatus(t, resp, 200)
testResponseBody(t, resp, &actual)
expected["server_time_utc"] = actual["server_time_utc"]
expected["server_time"] = actual["server_time"]
if !reflect.DeepEqual(actual, expected) {
t.Fatalf("bad: %#v", actual)
t.Fatalf("bad: expected:%#v\nactual:%#v", expected, actual)
}

core.Seal(root)
Expand All @@ -49,9 +49,9 @@ func TestSysHealth_get(t *testing.T) {
}
testResponseStatus(t, resp, 500)
testResponseBody(t, resp, &actual)
expected["server_time_utc"] = actual["server_time_utc"]
expected["server_time"] = actual["server_time"]
if !reflect.DeepEqual(actual, expected) {
t.Fatalf("bad: %#v", actual)
t.Fatalf("bad: expected:%#v\nactual:%#v", expected, actual)
}
}

Expand All @@ -78,9 +78,9 @@ func TestSysHealth_customcodes(t *testing.T) {
testResponseStatus(t, resp, 202)
testResponseBody(t, resp, &actual)

expected["server_time_utc"] = actual["server_time_utc"]
expected["server_time"] = actual["server_time"]
if !reflect.DeepEqual(actual, expected) {
t.Fatalf("bad: %#v", actual)
t.Fatalf("bad: expected:%#v\nactual:%#v", expected, actual)
}

core.Seal(root)
Expand All @@ -102,9 +102,9 @@ func TestSysHealth_customcodes(t *testing.T) {
}
testResponseStatus(t, resp, 503)
testResponseBody(t, resp, &actual)
expected["server_time_utc"] = actual["server_time_utc"]
expected["server_time"] = actual["server_time"]
if !reflect.DeepEqual(actual, expected) {
t.Fatalf("bad: %#v", actual)
t.Fatalf("bad: expected:%#v\nactual:%#v", expected, actual)
}
}

Expand All @@ -113,7 +113,7 @@ func TestSysHealth_head(t *testing.T) {
ln, addr := TestServer(t, core)
defer ln.Close()

testData := []struct{
testData := []struct {
uri string
code int
}{
Expand Down
6 changes: 3 additions & 3 deletions logical/framework/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -450,9 +450,9 @@ func (b *Backend) handleWALRollback(
if age == 0 {
age = 10 * time.Minute
}
minAge := time.Now().UTC().Add(-1 * age)
minAge := time.Now().Add(-1 * age)
if _, ok := req.Data["immediate"]; ok {
minAge = time.Now().UTC().Add(1000 * time.Hour)
minAge = time.Now().Add(1000 * time.Hour)
}

for _, k := range keys {
Expand All @@ -466,7 +466,7 @@ func (b *Backend) handleWALRollback(
}

// If the entry isn't old enough, then don't roll it back
if !time.Unix(entry.CreatedAt, 0).Before(minAge) {
if !entry.CreatedAt.Before(minAge) {
continue
}

Expand Down
Loading

0 comments on commit f59a69b

Please sign in to comment.