Skip to content
This repository has been archived by the owner on Feb 27, 2023. It is now read-only.

optional date claims #220

Merged
merged 3 commits into from
Feb 26, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 12 additions & 10 deletions jwt/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,18 +94,20 @@ func (c Claims) ValidateWithLeeway(e Expected, leeway time.Duration) error {
}
}

if !e.Time.IsZero() && e.Time.Add(leeway).Before(c.NotBefore.Time()) {
return ErrNotValidYet
}
if !e.Time.IsZero() {
if c.NotBefore != nil && e.Time.Add(leeway).Before(c.NotBefore.Time()) {
return ErrNotValidYet
}

if !e.Time.IsZero() && e.Time.Add(-leeway).After(c.Expiry.Time()) {
return ErrExpired
}
if c.Expiry != nil && e.Time.Add(-leeway).After(c.Expiry.Time()) {
return ErrExpired
}

// IssuedAt is optional but cannot be in the future. This is not required by the RFC, but
// something is misconfigured if this happens and we should not trust it.
if !e.Time.IsZero() && e.Time.Add(leeway).Before(c.IssuedAt.Time()) {
return ErrIssuedInTheFuture
// IssuedAt is optional but cannot be in the future. This is not required by the RFC, but
// something is misconfigured if this happens and we should not trust it.
if c.IssuedAt != nil && e.Time.Add(leeway).Before(c.IssuedAt.Time()) {
return ErrIssuedInTheFuture
}
}

return nil
Expand Down
39 changes: 39 additions & 0 deletions jwt/validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,42 @@ func TestIssuedInFuture(t *testing.T) {
assert.Equal(t, err, ErrIssuedInTheFuture)
}
}

func TestOptionalDateClaims(t *testing.T) {
var epoch time.Time

testCases := []struct {
name string
claim Claims
want error
}{
{
"no claims",
Claims{},
nil,
},
{
"fail nbf",
Claims{NotBefore: NewNumericDate(time.Now())},
ErrNotValidYet,
},
{
"fail exp",
Claims{Expiry: NewNumericDate(epoch.Add(-7 * 24 * time.Hour))},
ErrExpired,
},
{
"fail iat",
Claims{IssuedAt: NewNumericDate(time.Now())},
ErrIssuedInTheFuture,
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
expect := Expected{}.WithTime(epoch.Add(-24 * time.Hour))
err := tc.claim.Validate(expect)
assert.Equal(t, tc.want, err)
})
}
}