Documentation
¶
Overview ¶
Package token signs and verifies Ed25519 compact JWTs whose header may name the verification key by `kid`. The claim set is the caller's: any value that encodes to a JSON object.
A KeySet holds the current signing key and the retired keys that still verify, loaded through a KeyStore so a rotation reaches every replica, and publishes them as a JWK Set. Validate checks the registered claims (issuer, audience, times, typ) when a caller opts in; any other claim policy, such as versioning, and verification caching are the caller's. Other JOSE algorithms are out of scope.
Index ¶
- Constants
- Variables
- func HeaderKeyID(token string) string
- func HeaderType(token string) string
- func KeyID(pub ed25519.PublicKey) string
- func Parse[C any](pub ed25519.PublicKey, token string) (C, error)
- func ReadHeader(token string) (kid, typ string)
- func Sign(priv ed25519.PrivateKey, kid string, claims any) (string, error)
- func Validate(c Claims, now time.Time, want Want) error
- func Verify[C any](ctx context.Context, s *KeySet, token string) (C, error)
- type Audience
- type Claims
- type KeySet
- func (s *KeySet) Current() ed25519.PublicKey
- func (s *KeySet) JWKSet() (PublicJWKSet, error)
- func (s *KeySet) Keys() Keys
- func (s *KeySet) PublicKey(ctx context.Context, kid string) (ed25519.PublicKey, error)
- func (s *KeySet) PublicKeys() []ed25519.PublicKey
- func (s *KeySet) Reload(ctx context.Context) error
- func (s *KeySet) Run(ctx context.Context)
- func (s *KeySet) Sign(claims any) (string, error)
- type KeySetOptions
- type KeyStore
- type Keys
- type PublicJWK
- type PublicJWKSet
- type StaticStore
- type Want
Constants ¶
const ( DefaultRefreshInterval = time.Minute DefaultMinReloadInterval = 10 * time.Second DefaultLoadTimeout = 2 * time.Second )
Defaults for KeySetOptions' zero values.
const ( TypeJWT = "JWT" TypeAccessToken = "at+jwt" )
The header types Parse accepts: a plain JWT, and an OAuth 2.0 access token (RFC 9068). Sign writes TypeJWT.
Variables ¶
var ( ErrType = errors.New("token: unexpected typ") ErrIssuer = errors.New("token: unexpected issuer") ErrAudience = errors.New("token: audience does not match") ErrExpired = errors.New("token: expired") ErrNotYetValid = errors.New("token: not valid yet") ErrIssuedInFuture = errors.New("token: issued in the future") )
Validate's errors, one per check. ErrExpired also covers a missing exp.
var ( ErrNoSigningKey = errors.New("token: no signing key") ErrUnknownKey = fmt.Errorf("%w: no key for the token's kid", ErrSignature) )
ErrNoSigningKey means the key set holds no signing key. ErrUnknownKey means no held key matches the token's kid, even after any reload the rate limit allows; it wraps ErrSignature.
var ( ErrMalformed = errors.New("token: malformed token") ErrSignature = errors.New("token: signature does not verify") )
ErrMalformed is returned for anything that isn't a well-formed EdDSA JWT; ErrSignature for a well-formed one that doesn't verify.
Functions ¶
func HeaderKeyID ¶
HeaderKeyID reports the `kid` a token names, or "" when it carries none. Reads the header only — nothing here is a trust decision.
func HeaderType ¶ added in v0.2.0
HeaderType reports the `typ` a token's header carries, for Claims.Type. Reads the header only; Parse refuses any typ but TypeJWT and TypeAccessToken.
func KeyID ¶
KeyID names a public key in a token's `kid` header. Truncated sha256 of the key bytes: stable across processes, and it reveals nothing the token signature doesn't already.
func Parse ¶
Parse verifies the signature with pub and decodes the payload into C. It checks nothing else — expiry, issuer and version are the caller's policy, not the format's.
func ReadHeader ¶ added in v0.2.0
ReadHeader returns the header's `kid` and `typ` in one decode, for a caller that needs both on a hot path.
func Sign ¶
Sign returns the compact JWT for claims, signed with priv. kid names the verification key so a rotation can keep the previous one live; an empty kid writes the bare header.
func Validate ¶ added in v0.2.0
Validate checks c against want at now, in a fixed order: typ, issuer, audience, then exp (required), nbf and iat (each checked when non-zero). The first failing check is returned. Signature verification is Parse's.
An empty Want.Issuer or Want.Type skips that check. An empty Want.Audience does not: it refuses any token that names an audience, so a token bound to another service cannot be replayed here.
Types ¶
type Audience ¶ added in v0.2.0
type Audience []string
Audience is the `aud` claim, which RFC 7519 lets be one string or an array of them. A single audience encodes as a string.
func (Audience) MarshalJSON ¶ added in v0.2.0
MarshalJSON writes one audience as a string and any other count as an array.
func (*Audience) UnmarshalJSON ¶ added in v0.2.0
UnmarshalJSON accepts a string, an array of strings, or null.
type Claims ¶ added in v0.2.0
type Claims struct {
Issuer string `json:"iss,omitempty"`
Subject string `json:"sub,omitempty"`
Audience Audience `json:"aud,omitempty"`
Expiry int64 `json:"exp,omitempty"`
NotBefore int64 `json:"nbf,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
ID string `json:"jti,omitempty"`
// Type is the header's `typ`, not a claim: set it from HeaderType when
// Want.Type is set.
Type string `json:"-"`
}
Claims are the registered claims Validate checks. A new claim set can embed it; one with its own field names copies the values in.
type KeySet ¶ added in v0.2.0
type KeySet struct {
// contains filtered or unexported fields
}
KeySet is the current signing key plus the retired keys that still verify, read from a KeyStore. A lookup reads memory only, except that an unknown kid may trigger one single-flighted, rate-limited reload.
func NewKeySet ¶ added in v0.2.0
func NewKeySet(store KeyStore, opts KeySetOptions) *KeySet
NewKeySet returns a key set over store. It holds no keys until the first Reload.
func (*KeySet) Current ¶ added in v0.2.0
Current returns the key new tokens are minted under, or nil.
func (*KeySet) JWKSet ¶ added in v0.2.0
func (s *KeySet) JWKSet() (PublicJWKSet, error)
JWKSet returns the verification keys as the document a `jwks_uri` serves.
func (*KeySet) PublicKey ¶ added in v0.2.0
PublicKey returns the key kid names; "" names the current key. A miss may reload the store once, within the rate limit, waiting for the load or ctx.
func (*KeySet) PublicKeys ¶ added in v0.2.0
PublicKeys returns every key that verifies, the current one first.
func (*KeySet) Reload ¶ added in v0.2.0
Reload reads the store and installs what it holds. On error the keys held before stay installed.
type KeySetOptions ¶ added in v0.2.0
type KeySetOptions struct {
// RefreshInterval is how often Run reloads the store.
RefreshInterval time.Duration
// MinReloadInterval is the least time between loads an unknown kid may
// trigger, so a caller spraying random kids costs at most one load per
// interval. Negative turns those loads off, for a store only this process
// writes.
MinReloadInterval time.Duration
// LoadTimeout bounds a load an unknown kid triggers. That load outlives
// the request that triggered it, since other requests may be waiting on it.
LoadTimeout time.Duration
// OnError receives the errors of loads no caller waits on: Run's, and
// those an unknown kid triggers.
OnError func(error)
}
KeySetOptions tune how a KeySet follows its store.
type KeyStore ¶ added in v0.2.0
KeyStore is where a KeySet reads its keys. A store shared by every replica (a database row, a kv entry, a secret manager) makes one replica's rotation reach all of them. An empty Keys with a nil error means no keys: tokens are off. An error means the store could not be read, and the KeySet keeps what it holds.
type Keys ¶ added in v0.2.0
type Keys struct {
// Signing mints new tokens. Nil on a replica that only verifies.
Signing ed25519.PrivateKey
// Current is the key new tokens are minted under, and the one a token
// with no kid is checked against. Derived from Signing when that is set.
Current ed25519.PublicKey
// Previous are retired keys that still verify but never sign.
Previous []ed25519.PublicKey
}
Keys is one generation of a key set.
type PublicJWK ¶ added in v0.2.0
type PublicJWK struct {
Kty string `json:"kty"`
Crv string `json:"crv"`
X string `json:"x"`
// Kid equals KeyID, the value a token's header names.
Kid string `json:"kid"`
Use string `json:"use"`
Alg string `json:"alg"`
}
PublicJWK is an Ed25519 public key as an OKP JSON Web Key (RFC 8037). Its field order is fixed, so the encoding is deterministic.
type PublicJWKSet ¶ added in v0.2.0
type PublicJWKSet struct {
Keys []PublicJWK `json:"keys"`
}
PublicJWKSet is a JWK Set (RFC 7517 §5), the document a `jwks_uri` serves.
type StaticStore ¶ added in v0.2.0
type StaticStore struct {
// contains filtered or unexported fields
}
StaticStore is a KeyStore over keys held in this process, such as keys from the environment. After Set, Reload the KeySets that read it. The zero value holds no keys.
func NewStaticStore ¶ added in v0.2.0
func NewStaticStore(k Keys) *StaticStore
NewStaticStore returns a store holding k.
func (*StaticStore) LoadKeys ¶ added in v0.2.0
func (s *StaticStore) LoadKeys(context.Context) (Keys, error)
LoadKeys returns the keys last Set.
func (*StaticStore) Set ¶ added in v0.2.0
func (s *StaticStore) Set(k Keys)
Set replaces the keys the store holds.
type Want ¶ added in v0.2.0
type Want struct {
// Issuer, when set, must equal the token's `iss`.
Issuer string
// Audience, when set, must be one of the token's audiences. When empty, a
// token that names any audience is refused: it was issued for someone else.
Audience string
// Type, when set, must match the header's `typ` (case-insensitive).
Type string
// Leeway is the clock skew tolerated on exp, nbf and iat. Negative is 0.
Leeway time.Duration
}
Want is what Validate requires of a token.