add ability to issue tokens with no expiry

This commit is contained in:
juancwu 2026-04-29 12:44:48 +00:00
commit de907d83cb
5 changed files with 76 additions and 9 deletions

View file

@ -43,10 +43,15 @@ func NewIssuer(keys *KeyRing, revoked RevocationStore, opts ...IssuerOption) (*I
return i, nil
}
// NoExpiry, when passed as the ttl to Issue, produces a token that never
// expires. Such tokens can still be invalidated through the RevocationStore.
const NoExpiry time.Duration = -1
// Issue creates a new token carrying the given permissions and optional
// data blob. data may be nil. ttl must be positive.
// data blob. data may be nil. ttl must be positive, or NoExpiry to mint
// a token without an expiry.
func (i *Issuer) Issue(ctx context.Context, perms []string, data any, ttl time.Duration) (string, error) {
if ttl <= 0 {
if ttl != NoExpiry && ttl <= 0 {
return "", fmt.Errorf("ficha: ttl must be positive, got %v", ttl)
}
@ -68,10 +73,12 @@ func (i *Issuer) Issue(ctx context.Context, perms []string, data any, ttl time.D
p := payload{
ID: id,
Iat: now.Unix(),
Exp: now.Add(ttl).Unix(),
Permissions: perms,
Data: dataBytes,
}
if ttl != NoExpiry {
p.Exp = now.Add(ttl).Unix()
}
plaintext, err := encodePayload(p)
if err != nil {
@ -164,7 +171,11 @@ func (i *Issuer) Revoke(ctx context.Context, token string) error {
return ErrInvalidToken
}
return i.revoked.Revoke(ctx, p.ID, time.Unix(p.Exp, 0))
var until time.Time
if p.Exp != 0 {
until = time.Unix(p.Exp, 0)
}
return i.revoked.Revoke(ctx, p.ID, until)
}
// newTokenID returns a 128-bit random hex string suitable for use as