Remove Unix() invocations on 'time.Time' objects and removed conversion of time to UTC

This commit is contained in:
vishalnayak 2016-07-07 17:44:14 -04:00
parent 98c13d74d6
commit e09b40e155
31 changed files with 154 additions and 130 deletions

View File

@ -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,

View File

@ -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{}

View File

@ -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
}

View File

@ -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)

View File

@ -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() {

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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
}

View File

@ -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")
}

View File

@ -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,
})
}

View File

@ -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{}{},
}

View File

@ -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,
},
}

View File

@ -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")

View File

@ -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

View File

@ -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
}

View File

@ -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

View File

@ -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"`
}

View File

@ -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
}{

View File

@ -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
}

View File

@ -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 {

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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
}

View File

@ -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)

View File

@ -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")
}

View File

@ -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()

View File

@ -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()

View File

@ -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,

View File

@ -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())

View File

@ -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