From f59a69bc5237e076c9809fbb59ae96e37fcad581 Mon Sep 17 00:00:00 2001 From: vishalnayak Date: Thu, 7 Jul 2016 17:44:14 -0400 Subject: [PATCH] Remove Unix() invocations on 'time.Time' objects and removed conversion of time to UTC --- audit/format_json.go | 4 +- audit/hashstructure_test.go | 4 +- builtin/credential/aws-ec2/backend.go | 4 +- builtin/credential/aws-ec2/path_login.go | 4 +- .../aws-ec2/path_roletag_blacklist.go | 2 +- .../aws-ec2/path_tidy_identity_whitelist.go | 2 +- .../aws-ec2/path_tidy_roletag_blacklist.go | 2 +- builtin/logical/aws/secret_access_keys.go | 7 +-- builtin/logical/pki/backend_test.go | 8 +-- builtin/logical/pki/crl_util.go | 8 +-- builtin/logical/pki/path_fetch.go | 3 +- builtin/logical/pki/path_root.go | 4 +- .../logical/postgresql/path_role_create.go | 2 +- builtin/logical/transit/backend_test.go | 16 +++--- builtin/logical/transit/path_keys.go | 3 +- builtin/logical/transit/policy.go | 8 +-- http/sys_health.go | 16 +++--- http/sys_health_test.go | 18 +++--- logical/framework/backend.go | 6 +- logical/framework/backend_test.go | 2 +- logical/framework/lease.go | 4 +- logical/framework/lease_test.go | 2 +- logical/framework/wal.go | 4 +- logical/lease.go | 4 +- logical/lease_test.go | 2 +- vault/expiration.go | 12 ++-- vault/expiration_test.go | 13 +++-- vault/keyring_test.go | 6 +- vault/request_handling.go | 4 +- vault/token_store.go | 55 +++++++++++++------ vault/token_store_test.go | 55 ++++++++++--------- 31 files changed, 154 insertions(+), 130 deletions(-) diff --git a/audit/format_json.go b/audit/format_json.go index 2850ce2472..0e468068af 100644 --- a/audit/format_json.go +++ b/audit/format_json.go @@ -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, @@ -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, diff --git a/audit/hashstructure_test.go b/audit/hashstructure_test.go index 26b1d4153a..ab33acca20 100644 --- a/audit/hashstructure_test.go +++ b/audit/hashstructure_test.go @@ -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", @@ -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{} diff --git a/builtin/credential/aws-ec2/backend.go b/builtin/credential/aws-ec2/backend.go index 16f151156e..5e63eac322 100644 --- a/builtin/credential/aws-ec2/backend.go +++ b/builtin/credential/aws-ec2/backend.go @@ -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) @@ -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 } diff --git a/builtin/credential/aws-ec2/path_login.go b/builtin/credential/aws-ec2/path_login.go index bab8495427..633a5bad9c 100644 --- a/builtin/credential/aws-ec2/path_login.go +++ b/builtin/credential/aws-ec2/path_login.go @@ -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. @@ -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) diff --git a/builtin/credential/aws-ec2/path_roletag_blacklist.go b/builtin/credential/aws-ec2/path_roletag_blacklist.go index 62ef923ead..e008d4494e 100644 --- a/builtin/credential/aws-ec2/path_roletag_blacklist.go +++ b/builtin/credential/aws-ec2/path_roletag_blacklist.go @@ -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() { diff --git a/builtin/credential/aws-ec2/path_tidy_identity_whitelist.go b/builtin/credential/aws-ec2/path_tidy_identity_whitelist.go index f16637dbf6..266d4596f2 100644 --- a/builtin/credential/aws-ec2/path_tidy_identity_whitelist.go +++ b/builtin/credential/aws-ec2/path_tidy_identity_whitelist.go @@ -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) } diff --git a/builtin/credential/aws-ec2/path_tidy_roletag_blacklist.go b/builtin/credential/aws-ec2/path_tidy_roletag_blacklist.go index 307cfdc7fe..d163968ddb 100644 --- a/builtin/credential/aws-ec2/path_tidy_roletag_blacklist.go +++ b/builtin/credential/aws-ec2/path_tidy_roletag_blacklist.go @@ -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) } diff --git a/builtin/logical/aws/secret_access_keys.go b/builtin/logical/aws/secret_access_keys.go index 0c8c3da8ab..ef2e52e5d9 100644 --- a/builtin/logical/aws/secret_access_keys.go +++ b/builtin/logical/aws/secret_access_keys.go @@ -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 } diff --git a/builtin/logical/pki/backend_test.go b/builtin/logical/pki/backend_test.go index 3c2602e78c..8f7cac62f8 100644 --- a/builtin/logical/pki/backend_test.go +++ b/builtin/logical/pki/backend_test.go @@ -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") } @@ -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") } @@ -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") } @@ -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") } diff --git a/builtin/logical/pki/crl_util.go b/builtin/logical/pki/crl_util.go index 2dd32b5f3a..0de2961508 100644 --- a/builtin/logical/pki/crl_util.go +++ b/builtin/logical/pki/crl_util.go @@ -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 @@ -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 { @@ -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, }) } diff --git a/builtin/logical/pki/path_fetch.go b/builtin/logical/pki/path_fetch.go index b37e9ff0fe..1616a204e5 100644 --- a/builtin/logical/pki/path_fetch.go +++ b/builtin/logical/pki/path_fetch.go @@ -3,6 +3,7 @@ package pki import ( "encoding/pem" "fmt" + "time" "github.com/hashicorp/vault/helper/certutil" "github.com/hashicorp/vault/logical" @@ -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{}{}, } diff --git a/builtin/logical/pki/path_root.go b/builtin/logical/pki/path_root.go index b127533dc8..38de7970d1 100644 --- a/builtin/logical/pki/path_root.go +++ b/builtin/logical/pki/path_root.go @@ -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, }, } @@ -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, }, } diff --git a/builtin/logical/postgresql/path_role_create.go b/builtin/logical/postgresql/path_role_create.go index 60ef442a5a..c5538c732b 100644 --- a/builtin/logical/postgresql/path_role_create.go +++ b/builtin/logical/postgresql/path_role_create.go @@ -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") diff --git a/builtin/logical/transit/backend_test.go b/builtin/logical/transit/backend_test.go index 49296a0f9e..f42ea05d4a 100644 --- a/builtin/logical/transit/backend_test.go +++ b/builtin/logical/transit/backend_test.go @@ -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 diff --git a/builtin/logical/transit/path_keys.go b/builtin/logical/transit/path_keys.go index accf00aa68..14ce59c4a4 100644 --- a/builtin/logical/transit/path_keys.go +++ b/builtin/logical/transit/path_keys.go @@ -3,6 +3,7 @@ package transit import ( "fmt" "strconv" + "time" "github.com/hashicorp/vault/logical" "github.com/hashicorp/vault/logical/framework" @@ -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 } diff --git a/builtin/logical/transit/policy.go b/builtin/logical/transit/policy.go index b9ede365c8..733e65b013 100644 --- a/builtin/logical/transit/policy.go +++ b/builtin/logical/transit/policy.go @@ -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 @@ -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 @@ -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 diff --git a/http/sys_health.go b/http/sys_health.go index 2883744c3c..04cb960454 100644 --- a/http/sys_health.go +++ b/http/sys_health.go @@ -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"` } diff --git a/http/sys_health_test.go b/http/sys_health_test.go index 452bd0cf1e..67abe75a18 100644 --- a/http/sys_health_test.go +++ b/http/sys_health_test.go @@ -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) @@ -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) } } @@ -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) @@ -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) } } @@ -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 }{ diff --git a/logical/framework/backend.go b/logical/framework/backend.go index 9f274fd22d..dda2a05d0d 100644 --- a/logical/framework/backend.go +++ b/logical/framework/backend.go @@ -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 { @@ -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 } diff --git a/logical/framework/backend_test.go b/logical/framework/backend_test.go index a3b34d7ca3..d777ecda8a 100644 --- a/logical/framework/backend_test.go +++ b/logical/framework/backend_test.go @@ -263,7 +263,7 @@ func TestBackendHandleRequest_renewExtend(t *testing.T) { } req := logical.RenewRequest("/foo", secret.Response(nil, nil).Secret, nil) - req.Secret.IssueTime = time.Now().UTC() + req.Secret.IssueTime = time.Now() req.Secret.Increment = 1 * time.Hour resp, err := b.HandleRequest(req) if err != nil { diff --git a/logical/framework/lease.go b/logical/framework/lease.go index 3e5ebe154d..4fd2ac902c 100644 --- a/logical/framework/lease.go +++ b/logical/framework/lease.go @@ -45,10 +45,10 @@ func LeaseExtend(backendIncrement, backendMax time.Duration, systemView logical. } // We cannot go past this time - maxValidTime := leaseOpts.IssueTime.UTC().Add(max) + maxValidTime := leaseOpts.IssueTime.Add(max) // Get the current time - now := time.Now().UTC() + now := time.Now() // If we are past the max TTL, we shouldn't be in this function...but // fast path out if we are diff --git a/logical/framework/lease_test.go b/logical/framework/lease_test.go index 0ab036a61a..b45b9c7164 100644 --- a/logical/framework/lease_test.go +++ b/logical/framework/lease_test.go @@ -14,7 +14,7 @@ func TestLeaseExtend(t *testing.T) { MaxLeaseTTLVal: 30 * time.Hour, } - now := time.Now().UTC().Round(time.Hour) + now := time.Now().Round(time.Hour) cases := map[string]struct { BackendDefault time.Duration diff --git a/logical/framework/wal.go b/logical/framework/wal.go index 6e6b234bce..306fecbde2 100644 --- a/logical/framework/wal.go +++ b/logical/framework/wal.go @@ -15,7 +15,7 @@ type WALEntry struct { ID string `json:"-"` Kind string `json:"type"` Data interface{} `json:"data"` - CreatedAt int64 `json:"created_at"` + CreatedAt time.Time `json:"created_at"` } // PutWAL writes some data to the WAL. @@ -37,7 +37,7 @@ func PutWAL(s logical.Storage, kind string, data interface{}) (string, error) { value, err := json.Marshal(&WALEntry{ Kind: kind, Data: data, - CreatedAt: time.Now().UTC().Unix(), + CreatedAt: time.Now(), }) if err != nil { return "", err diff --git a/logical/lease.go b/logical/lease.go index 871954457d..ed0b26b51c 100644 --- a/logical/lease.go +++ b/logical/lease.go @@ -20,7 +20,7 @@ type LeaseOptions struct { // IssueTime is the time of issue for the original lease. This is // only available on a Renew operation and has no effect when returning // a response. It can be used to enforce maximum lease periods by - // a logical backend. This time will always be in UTC. + // a logical backend. IssueTime time.Time `json:"-"` } @@ -42,7 +42,7 @@ func (l *LeaseOptions) LeaseTotal() time.Duration { func (l *LeaseOptions) ExpirationTime() time.Time { var expireTime time.Time if l.LeaseEnabled() { - expireTime = time.Now().UTC().Add(l.LeaseTotal()) + expireTime = time.Now().Add(l.LeaseTotal()) } return expireTime } diff --git a/logical/lease_test.go b/logical/lease_test.go index 9b9ec6a56b..050b7db8e9 100644 --- a/logical/lease_test.go +++ b/logical/lease_test.go @@ -41,7 +41,7 @@ func TestLeaseOptionsExpirationTime(t *testing.T) { var l LeaseOptions l.TTL = 1 * time.Hour - limit := time.Now().UTC().Add(time.Hour) + limit := time.Now().Add(time.Hour) exp := l.ExpirationTime() if exp.Before(limit) { t.Fatalf("bad: %s", exp) diff --git a/vault/expiration.go b/vault/expiration.go index 0b56135bad..30a73e8b67 100644 --- a/vault/expiration.go +++ b/vault/expiration.go @@ -141,7 +141,7 @@ func (m *ExpirationManager) Restore() error { } // Determine the remaining time to expiration - expires := le.ExpireTime.Sub(time.Now().UTC()) + expires := le.ExpireTime.Sub(time.Now()) if expires <= 0 { expires = minRevokeDelay } @@ -334,7 +334,7 @@ func (m *ExpirationManager) Renew(leaseID string, increment time.Duration) (*log le.Data = resp.Data le.Secret = resp.Secret le.ExpireTime = resp.Secret.ExpirationTime() - le.LastRenewalTime = time.Now().UTC() + le.LastRenewalTime = time.Now() if err := m.persistEntry(le); err != nil { return nil, err } @@ -395,7 +395,7 @@ func (m *ExpirationManager) RenewToken(req *logical.Request, source string, toke // Update the lease entry le.Auth = resp.Auth le.ExpireTime = resp.Auth.ExpirationTime() - le.LastRenewalTime = time.Now().UTC() + le.LastRenewalTime = time.Now() if err := m.persistEntry(le); err != nil { return nil, err } @@ -433,7 +433,7 @@ func (m *ExpirationManager) Register(req *logical.Request, resp *logical.Respons Path: req.Path, Data: resp.Data, Secret: resp.Secret, - IssueTime: time.Now().UTC(), + IssueTime: time.Now(), ExpireTime: resp.Secret.ExpirationTime(), } @@ -466,7 +466,7 @@ func (m *ExpirationManager) RegisterAuth(source string, auth *logical.Auth) erro ClientToken: auth.ClientToken, Auth: auth, Path: source, - IssueTime: time.Now().UTC(), + IssueTime: time.Now(), ExpireTime: auth.ExpirationTime(), } @@ -762,7 +762,7 @@ func (le *leaseEntry) renewable() error { } // Determine if the lease is expired - if le.ExpireTime.Before(time.Now().UTC()) { + if le.ExpireTime.Before(time.Now()) { return fmt.Errorf("lease expired") } diff --git a/vault/expiration_test.go b/vault/expiration_test.go index c5a4f8004b..44e3c7daa2 100644 --- a/vault/expiration_test.go +++ b/vault/expiration_test.go @@ -899,9 +899,9 @@ func TestExpiration_PersistLoadDelete(t *testing.T) { TTL: time.Minute, }, }, - IssueTime: time.Now().UTC(), - ExpireTime: time.Now().UTC(), - LastRenewalTime: time.Time{}.UTC(), + IssueTime: time.Now(), + ExpireTime: time.Now(), + LastRenewalTime: time.Time{}, } if err := exp.persistEntry(le); err != nil { t.Fatalf("err: %v", err) @@ -911,8 +911,9 @@ func TestExpiration_PersistLoadDelete(t *testing.T) { if err != nil { t.Fatalf("err: %v", err) } + le.LastRenewalTime = out.LastRenewalTime if !reflect.DeepEqual(out, le) { - t.Fatalf("\nout: %#v\nexpect: %#v\n", out, le) + t.Fatalf("bad: expected:%#v\nactual:%#v", le, out) } err = exp.deleteEntry("foo/bar/1234") @@ -941,8 +942,8 @@ func TestLeaseEntry(t *testing.T) { TTL: time.Minute, }, }, - IssueTime: time.Now().UTC(), - ExpireTime: time.Now().UTC(), + IssueTime: time.Now(), + ExpireTime: time.Now(), } enc, err := le.encode() diff --git a/vault/keyring_test.go b/vault/keyring_test.go index e7b369e4ab..5fc482797f 100644 --- a/vault/keyring_test.go +++ b/vault/keyring_test.go @@ -140,8 +140,8 @@ func TestKeyring_Serialize(t *testing.T) { testKey := []byte("testing") testSecond := []byte("second") - k, _ = k.AddKey(&Key{Term: 1, Version: 1, Value: testKey, InstallTime: time.Now().UTC()}) - k, _ = k.AddKey(&Key{Term: 2, Version: 1, Value: testSecond, InstallTime: time.Now().UTC()}) + k, _ = k.AddKey(&Key{Term: 1, Version: 1, Value: testKey, InstallTime: time.Now()}) + k, _ = k.AddKey(&Key{Term: 2, Version: 1, Value: testSecond, InstallTime: time.Now()}) buf, err := k.Serialize() if err != nil { @@ -177,7 +177,7 @@ func TestKey_Serialize(t *testing.T) { Term: 10, Version: 1, Value: []byte("foobarbaz"), - InstallTime: time.Now().UTC(), + InstallTime: time.Now(), } buf, err := k.Serialize() diff --git a/vault/request_handling.go b/vault/request_handling.go index ae2021e031..2191c7483f 100644 --- a/vault/request_handling.go +++ b/vault/request_handling.go @@ -327,7 +327,7 @@ func (c *Core) handleLoginRequest(req *logical.Request) (*logical.Response, *log Policies: auth.Policies, Meta: auth.Metadata, DisplayName: auth.DisplayName, - CreationTime: time.Now().Unix(), + CreationTime: time.Now(), TTL: auth.TTL, } @@ -389,7 +389,7 @@ func (c *Core) wrapInCubbyhole(req *logical.Request, resp *logical.Response) (*l te := TokenEntry{ Path: req.Path, Policies: []string{"response-wrapping"}, - CreationTime: creationTime.Unix(), + CreationTime: creationTime, TTL: resp.WrapInfo.TTL, NumUses: 1, ExplicitMaxTTL: resp.WrapInfo.TTL, diff --git a/vault/token_store.go b/vault/token_store.go index 685285a92d..a3253fc27d 100644 --- a/vault/token_store.go +++ b/vault/token_store.go @@ -414,18 +414,41 @@ func NewTokenStore(c *Core, config *logical.BackendConfig) (*TokenStore, error) // TokenEntry is used to represent a given token type TokenEntry struct { - ID string // ID of this entry, generally a random UUID - Accessor string // Accessor for this token, a random UUID - Parent string // Parent token, used for revocation trees - Policies []string // Which named policies should be used - Path string // Used for audit trails, this is something like "auth/user/login" - Meta map[string]string // Used for auditing. This could include things like "source", "user", "ip" - DisplayName string // Used for operators to be able to associate with the source - NumUses int // Used to restrict the number of uses (zero is unlimited). This is to support one-time-tokens (generalized). - CreationTime int64 // Time of token creation - TTL time.Duration // Duration set when token was created - ExplicitMaxTTL time.Duration // Explicit maximum TTL on the token - Role string // If set, the role that was used for parameters at creation time + // ID of this entry, generally a random UUID + ID string `json:"id" mapstructure:"id" structs:"id"` + + // Accessor for this token, a random UUID + Accessor string `json:"accessor" mapstructure:"accessor" structs:"accessor"` + + // Parent token, used for revocation trees + Parent string `json:"parent" mapstructure:"parent" structs:"parent"` + + // Which named policies should be used + Policies []string `json:"policies" mapstructure:"policies" structs:"policies"` + + // Used for audit trails, this is something like "auth/user/login" + Path string `json:"path" mapstructure:"path" structs:"path"` + + // Used for auditing. This could include things like "source", "user", "ip" + Meta map[string]string `json:"meta" mapstructure:"meta" structs:"meta"` + + // Used for operators to be able to associate with the source + DisplayName string `json:"display_name" mapstructure:"display_name" structs:"display_name"` + + // Used to restrict the number of uses (zero is unlimited). This is to support one-time-tokens (generalized). + NumUses int `json:"num_uses" mapstructure:"num_uses" structs:"num_uses"` + + // Time of token creation + CreationTime time.Time `json:"creation_time" mapstructure:"creation_time" structs:"creation_time"` + + // Duration set when token was created + TTL time.Duration `json:"ttl" mapstructure:"ttl" structs:"ttl"` + + // Explicit maximum TTL on the token + ExplicitMaxTTL time.Duration `json:"" mapstructure:"" structs:""` + + // If set, the role that was used for parameters at creation time + Role string `json:"role" mapstructure:"role" structs:"role"` } // tsRoleEntry contains token store role information @@ -474,7 +497,7 @@ func (ts *TokenStore) rootToken() (*TokenEntry, error) { Policies: []string{"root"}, Path: "auth/token/root", DisplayName: "root", - CreationTime: time.Now().Unix(), + CreationTime: time.Now(), } if err := ts.create(te); err != nil { return nil, err @@ -970,7 +993,7 @@ func (ts *TokenStore) handleCreateCommon( Meta: data.Metadata, DisplayName: "token", NumUses: data.NumUses, - CreationTime: time.Now().Unix(), + CreationTime: time.Now(), } renewable := true @@ -1306,7 +1329,7 @@ func (ts *TokenStore) handleLookup( "display_name": out.DisplayName, "num_uses": out.NumUses, "orphan": false, - "creation_time": int64(out.CreationTime), + "creation_time": out.CreationTime, "creation_ttl": int64(out.TTL.Seconds()), "ttl": int64(0), "role": out.Role, @@ -1325,7 +1348,7 @@ func (ts *TokenStore) handleLookup( } if leaseTimes != nil { if !leaseTimes.LastRenewalTime.IsZero() { - resp.Data["last_renewal_time"] = leaseTimes.LastRenewalTime.Unix() + resp.Data["last_renewal_time"] = leaseTimes.LastRenewalTime } if !leaseTimes.ExpireTime.IsZero() { resp.Data["ttl"] = int64(leaseTimes.ExpireTime.Sub(time.Now().Round(time.Second)).Seconds()) diff --git a/vault/token_store_test.go b/vault/token_store_test.go index 0c093fdf62..dc85cc68a7 100644 --- a/vault/token_store_test.go +++ b/vault/token_store_test.go @@ -156,7 +156,7 @@ func TestTokenStore_RootToken(t *testing.T) { t.Fatalf("err: %v", err) } if !reflect.DeepEqual(out, te) { - t.Fatalf("bad: %#v", out) + t.Fatalf("bad: expected:%#v\nactual:%#v", te, out) } } @@ -175,8 +175,9 @@ func TestTokenStore_CreateLookup(t *testing.T) { if err != nil { t.Fatalf("err: %v", err) } + ent.CreationTime = out.CreationTime if !reflect.DeepEqual(out, ent) { - t.Fatalf("bad: %#v", out) + t.Fatalf("bad: expected:%#v\nactual:%#v", ent, out) } // New store should share the salt @@ -191,7 +192,7 @@ func TestTokenStore_CreateLookup(t *testing.T) { t.Fatalf("err: %v", err) } if !reflect.DeepEqual(out, ent) { - t.Fatalf("bad: %#v", out) + t.Fatalf("bad: expected:%#v\nactual:%#v", ent, out) } } @@ -207,15 +208,16 @@ func TestTokenStore_CreateLookup_ProvidedID(t *testing.T) { t.Fatalf("err: %v", err) } if ent.ID != "foobarbaz" { - t.Fatalf("bad: %#v", ent) + t.Fatalf("bad: ent.ID: expected:\"foobarbaz\"\n actual:%s", ent.ID) } out, err := ts.Lookup(ent.ID) if err != nil { t.Fatalf("err: %v", err) } + ent.CreationTime = out.CreationTime if !reflect.DeepEqual(out, ent) { - t.Fatalf("bad: %#v", out) + t.Fatalf("bad: expected:%#v\nactual:%#v", ent, out) } // New store should share the salt @@ -230,7 +232,7 @@ func TestTokenStore_CreateLookup_ProvidedID(t *testing.T) { t.Fatalf("err: %v", err) } if !reflect.DeepEqual(out, ent) { - t.Fatalf("bad: %#v", out) + t.Fatalf("bad: expected:%#v\nactual:%#v", ent, out) } } @@ -259,7 +261,7 @@ func TestTokenStore_UseToken(t *testing.T) { } if !reflect.DeepEqual(ent, ent2) { - t.Fatalf("bad: %#v %#v", ent, ent2) + t.Fatalf("bad: ent:%#v ent2:%#v", ent, ent2) } // Create a retstricted token @@ -411,8 +413,9 @@ func TestTokenStore_Revoke_Orphan(t *testing.T) { if err != nil { t.Fatalf("err: %v", err) } + ent2.CreationTime = out.CreationTime if !reflect.DeepEqual(out, ent2) { - t.Fatalf("bad: %#v", out) + t.Fatalf("bad: expected:%#v\nactual:%#v", ent2, out) } } @@ -530,7 +533,7 @@ func TestTokenStore_HandleRequest_CreateToken_DisplayName(t *testing.T) { } expected.CreationTime = out.CreationTime if !reflect.DeepEqual(out, expected) { - t.Fatalf("bad:\ngot:\n%#v\nexpected:\n%#v\n", out, expected) + t.Fatalf("bad: expected:%#v\nactual:%#v", expected, out) } } @@ -562,7 +565,7 @@ func TestTokenStore_HandleRequest_CreateToken_NumUses(t *testing.T) { } expected.CreationTime = out.CreationTime if !reflect.DeepEqual(out, expected) { - t.Fatalf("bad: %#v", out) + t.Fatalf("bad: expected:%#v\nactual:%#v", expected, out) } } @@ -625,7 +628,7 @@ func TestTokenStore_HandleRequest_CreateToken_NoPolicy(t *testing.T) { } expected.CreationTime = out.CreationTime if !reflect.DeepEqual(out, expected) { - t.Fatalf("bad: %#v", out) + t.Fatalf("bad: expected:%#v\nactual:%#v", expected, out) } } @@ -812,7 +815,7 @@ func TestTokenStore_HandleRequest_CreateToken_Metadata(t *testing.T) { out, _ := ts.Lookup(resp.Auth.ClientToken) if !reflect.DeepEqual(out.Meta, meta) { - t.Fatalf("bad: %#v", out) + t.Fatalf("bad: expected:%#v\nactual:%#v", meta, out.Meta) } } @@ -982,13 +985,13 @@ func TestTokenStore_HandleRequest_Lookup(t *testing.T) { "explicit_max_ttl": int64(0), } - if resp.Data["creation_time"].(int64) == 0 { + if (resp.Data["creation_time"].(time.Time)).IsZero() { t.Fatalf("creation time was zero") } delete(resp.Data, "creation_time") if !reflect.DeepEqual(resp.Data, exp) { - t.Fatalf("bad:\n%#v\nexp:\n%#v\n", resp.Data, exp) + t.Fatalf("bad: expected:%#v\nactual:%#v", exp, resp.Data) } testCoreMakeToken(t, c, root, "client", "3600s", []string{"foo"}) @@ -1019,7 +1022,7 @@ func TestTokenStore_HandleRequest_Lookup(t *testing.T) { "renewable": true, } - if resp.Data["creation_time"].(int64) == 0 { + if (resp.Data["creation_time"].(time.Time)).IsZero() { t.Fatalf("creation time was zero") } delete(resp.Data, "creation_time") @@ -1030,7 +1033,7 @@ func TestTokenStore_HandleRequest_Lookup(t *testing.T) { } if !reflect.DeepEqual(resp.Data, exp) { - t.Fatalf("bad:\n%#v\nexp:\n%#v\n", resp.Data, exp) + t.Fatalf("bad: expected:%#v\nactual:%#v", exp, resp.Data) } // Test via POST @@ -1062,7 +1065,7 @@ func TestTokenStore_HandleRequest_Lookup(t *testing.T) { "renewable": true, } - if resp.Data["creation_time"].(int64) == 0 { + if (resp.Data["creation_time"].(time.Time)).IsZero() { t.Fatalf("creation time was zero") } delete(resp.Data, "creation_time") @@ -1073,7 +1076,7 @@ func TestTokenStore_HandleRequest_Lookup(t *testing.T) { } if !reflect.DeepEqual(resp.Data, exp) { - t.Fatalf("bad:\n%#v\nexp:\n%#v\n", resp.Data, exp) + t.Fatalf("bad: expected:%#v\nactual:%#v", exp, resp.Data) } // Test last_renewal_time functionality @@ -1095,7 +1098,7 @@ func TestTokenStore_HandleRequest_Lookup(t *testing.T) { t.Fatalf("bad: %#v", resp) } - if resp.Data["last_renewal_time"].(int64) == 0 { + if (resp.Data["last_renewal_time"].(time.Time)).IsZero() { t.Fatalf("last_renewal_time was zero") } } @@ -1127,13 +1130,13 @@ func TestTokenStore_HandleRequest_LookupSelf(t *testing.T) { "explicit_max_ttl": int64(0), } - if resp.Data["creation_time"].(int64) == 0 { + if (resp.Data["creation_time"].(time.Time)).IsZero() { t.Fatalf("creation time was zero") } delete(resp.Data, "creation_time") if !reflect.DeepEqual(resp.Data, exp) { - t.Fatalf("bad:\ngot %#v\nexpected: %#v\n", resp.Data, exp) + t.Fatalf("bad: expected:%#v\nactual:%#v", exp, resp.Data) } } @@ -1163,7 +1166,7 @@ func TestTokenStore_HandleRequest_Renew(t *testing.T) { // Get the original expire time to compare originalExpire := auth.ExpirationTime() - beforeRenew := time.Now().UTC() + beforeRenew := time.Now() req := logical.TestRequest(t, logical.UpdateOperation, "renew/"+root.ID) req.Data["increment"] = "3600s" resp, err := ts.HandleRequest(req) @@ -1207,7 +1210,7 @@ func TestTokenStore_HandleRequest_RenewSelf(t *testing.T) { // Get the original expire time to compare originalExpire := auth.ExpirationTime() - beforeRenew := time.Now().UTC() + beforeRenew := time.Now() req := logical.TestRequest(t, logical.UpdateOperation, "renew-self") req.ClientToken = auth.ClientToken req.Data["increment"] = "3600s" @@ -1279,7 +1282,7 @@ func TestTokenStore_RoleCRUD(t *testing.T) { } if !reflect.DeepEqual(expected, resp.Data) { - t.Fatalf("expected:\n%v\nactual:\n%v\n", expected, resp.Data) + t.Fatalf("bad: expected:%#v\nactual:%#v", expected, resp.Data) } // Now test updating; this should be set to an UpdateOperation @@ -1322,7 +1325,7 @@ func TestTokenStore_RoleCRUD(t *testing.T) { } if !reflect.DeepEqual(expected, resp.Data) { - t.Fatalf("expected:\n%v\nactual:\n%v\n", expected, resp.Data) + t.Fatalf("bad: expected:%#v\nactual:%#v", expected, resp.Data) } // Now test setting explicit max ttl at the same time as period, which @@ -1370,7 +1373,7 @@ func TestTokenStore_RoleCRUD(t *testing.T) { } if !reflect.DeepEqual(expected, resp.Data) { - t.Fatalf("expected:\n%v\nactual:\n%v\n", expected, resp.Data) + t.Fatalf("bad: expected:%#v\nactual:%#v", expected, resp.Data) } req.Operation = logical.ListOperation