jwtutil

package
v1.59.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultJWKSPath = "/.well-known/jwks.json"
View Source
const MaxActorDepth = 8

MaxActorDepth bounds an "act" chain. A deeper chain is refused when creating a token and when validating one.

Variables

View Source
var (
	ErrTokenExpired = errors.New("token is expired")
	ErrTokenInvalid = errors.New("token is invalid")
)
View Source
var ErrKeyNotPublished = errors.New("token signing key is not published")

ErrKeyNotPublished reports that a token's kid is absent from a key set fetched successfully after the token was issued. authn publishes its signing key from the moment it signs with it, so that key has since been retired (for example to revoke the tokens it signed) or was never authn's: no retry will make the token verify. ValidateWithKeySource reports it together with ErrTokenInvalid, so callers answer 401 and the client signs in again. It never matches ErrKeyUnavailable.

View Source
var ErrKeyUnavailable = errKeyUnavailable{}

ErrKeyUnavailable reports that the key a token was signed with could not be resolved — the key set was unreachable, malformed, or carried no key for the token's "kid". It is distinct from ErrTokenInvalid on purpose: the token may be perfectly valid and the fault ours, so callers should answer 503 rather than 401 and let the client retry.

Functions

func CreateToken

func CreateToken(opts CreateTokenOptions) (string, error)

CreateToken generates a signed JWT token using the provided username, group list, and expiration duration. The token is signed asymmetrically using the RS256 algorithm and the supplied RSA private key, and carries a "kid" header identifying the key so that JWKS-based validators (e.g. agentgateway) can select the matching public key. The corresponding public key must be published in the JWKS under the same KeyID.

func JWKSURL

func JWKSURL(base string) string

JWKSURL joins a base URL (e.g. authn's service URL) with DefaultJWKSPath. A base that already points at a .json document is returned unchanged, so callers may configure either form.

func ParseRSAPrivateKeyFromPEM

func ParseRSAPrivateKeyFromPEM(pemBytes []byte) (*rsa.PrivateKey, error)

ParseRSAPrivateKeyFromPEM parses a PEM-encoded RSA private key, as produced by e.g. `openssl genrsa`. It is the key type expected by CreateToken.

func ParseRSAPublicKeyFromPEM

func ParseRSAPublicKeyFromPEM(pemBytes []byte) (*rsa.PublicKey, error)

ParseRSAPublicKeyFromPEM parses a PEM-encoded RSA public key. It is the key type expected by Validate.

Types

type Actor added in v1.30.0

type Actor struct {
	Sub string `json:"sub"`
	Act *Actor `json:"act,omitempty"`
	// Principal is the kind of identity Sub is, as an extra actor claim
	// (RFC 8693 §4.1 allows them).
	Principal Principal `json:"principal,omitempty"`
}

Actor is one link of RFC 8693's "act" claim (§4.1). Sub is the acting identity; Act, when set, is the actor that delegated to it, so the outermost Actor is the current actor and each nested one is earlier in the chain.

type CreateTokenOptions

type CreateTokenOptions struct {
	Username   string
	Groups     []string
	Duration   time.Duration
	KeyID      string
	PrivateKey *rsa.PrivateKey
	// Act makes the token a delegated one (RFC 8693): Username stays the
	// subject, and Act names who acts for it. Nil for an ordinary token.
	Act *Actor
	// Principal is the kind of identity Username is. Empty leaves the claim
	// out, as before it existed.
	Principal Principal
}

type JWKSKeySource

type JWKSKeySource struct {
	// contains filtered or unexported fields
}

JWKSKeySource resolves signing keys from a remote JWKS document (authn's /.well-known/jwks.json), caching the result.

Nothing is fetched at construction: the first fetch happens on the first validation. A component wired to an authn that is not up yet therefore still starts and serves its unauthenticated routes, and recovers on its own once authn answers — no startup ordering dependency, no crash loop.

Cache behaviour:

  • A key set younger than TTL answers from memory.
  • Past TTL, or when a token names a kid the cache does not hold (key rotation), a refetch is attempted — but never more often than MinRefreshInterval, so an unknown kid cannot turn into a request-rate stampede against authn.
  • If a refetch fails but the cache still holds the requested kid, the stale-but-known key is served. A brief authn outage does not invalidate tokens that were already verifiable.
  • A kid absent from the set of a successful latest attempt is reported with that set's fetch time, so ValidateWithKeySource can tell a retired key (ErrKeyNotPublished, 401) from one the set predates (ErrKeyUnavailable, 503). While the latest attempt has failed, an absent kid is ErrKeyUnavailable. A retired kid still in a set younger than TTL keeps verifying until the set is refreshed, so a revocation takes effect within TTL.

func NewJWKSKeySource

func NewJWKSKeySource(url string, opts ...JWKSOption) *JWKSKeySource

NewJWKSKeySource returns a KeySource that reads authn's key set from url. url must be the full JWKS document URL; see JWKSURL for building it from a base URL.

func (*JWKSKeySource) PublicKey

func (s *JWKSKeySource) PublicKey(kid string) (*rsa.PublicKey, error)

PublicKey returns the key named by kid, fetching or refreshing the key set as needed. An empty kid resolves to the only key in the set when the set holds exactly one — tokens minted before "kid" headers existed stay verifiable.

type JWKSOption

type JWKSOption func(*JWKSKeySource)

JWKSOption customises a JWKSKeySource.

func WithJWKSCacheTTL

func WithJWKSCacheTTL(ttl time.Duration) JWKSOption

WithJWKSCacheTTL sets how long a fetched key set is served before refresh. Non-positive values are ignored.

func WithJWKSHTTPClient

func WithJWKSHTTPClient(c *http.Client) JWKSOption

WithJWKSHTTPClient replaces the HTTP client used for fetches. The client should set a timeout; it bounds how long a validation can block.

func WithJWKSMinRefreshInterval

func WithJWKSMinRefreshInterval(d time.Duration) JWKSOption

WithJWKSMinRefreshInterval sets the floor between two fetch attempts. Non-positive values are ignored.

func WithJWKSRequestTimeout

func WithJWKSRequestTimeout(d time.Duration) JWKSOption

WithJWKSRequestTimeout sets the per-fetch timeout on the default client. Ignored when WithJWKSHTTPClient supplied a client of its own.

type KeySource

type KeySource interface {
	PublicKey(kid string) (*rsa.PublicKey, error)
}

KeySource resolves the RSA public key that a token's "kid" header names. Implementations must be safe for concurrent use.

type KrateoClaims

type KrateoClaims struct {
	UserInfo
	jwt.RegisteredClaims
}

func ValidateClaimsWithKeySource added in v1.31.0

func ValidateClaimsWithKeySource(keys KeySource, bearer string) (KrateoClaims, error)

ValidateClaimsWithKeySource verifies bearer exactly as ValidateWithKeySource does, with the same errors, and returns all of its verified claims: the identity and, unlike ValidateWithKeySource, the registered claims such as ExpiresAt. Use it when a decision depends on one of those, for example a token issued from this one that must not outlive it.

type Principal added in v1.34.0

type Principal string

Principal is the kind of identity a token names. authn sets it from how the token was obtained, never from anything the client sends, so a validator can tell a person from a workload without looking anything up.

const (
	// PrincipalHuman is a person who signed in (basic, LDAP, OAuth, OIDC).
	PrincipalHuman Principal = "human"
	// PrincipalAgent is an AI agent acting as itself.
	PrincipalAgent Principal = "agent"
	// PrincipalController is a controller reconciling resources, such as a
	// composition controller.
	PrincipalController Principal = "controller"
	// PrincipalService is any other workload, and the default for a service
	// that doesn't declare its kind.
	PrincipalService Principal = "service"
)

func (Principal) Known added in v1.34.0

func (p Principal) Known() bool

Known reports whether p is one of the four kinds above.

func (*Principal) UnmarshalJSON added in v1.34.0

func (p *Principal) UnmarshalJSON(b []byte) error

UnmarshalJSON reads a known kind as itself and anything else (an unknown string, a number, null) as "". A validator therefore never fails on the claim: a token from an older issuer has none, one from a newer issuer may carry a kind this version doesn't know, and both read as "", which callers treat as unknown.

type StaticKeySource

type StaticKeySource struct {
	// contains filtered or unexported fields
}

StaticKeySource serves one fixed key for every kid. It is the adapter that keeps the plain Validate(publicKey, bearer) form working, and is the simplest stand-in in tests.

func NewStaticKeySource

func NewStaticKeySource(key *rsa.PublicKey) *StaticKeySource

NewStaticKeySource returns a KeySource that always yields key.

func (*StaticKeySource) PublicKey

func (s *StaticKeySource) PublicKey(string) (*rsa.PublicKey, error)

PublicKey ignores kid and returns the configured key.

type UserInfo

type UserInfo struct {
	Username string   `json:"username"`
	Groups   []string `json:"groups"`
	// Act is RFC 8693's actor claim: present only on a delegated token, it
	// names the identity acting for Username (the subject). Nil on every
	// other token.
	Act *Actor `json:"act,omitempty"`
	// Principal is the kind of identity Username is. Empty on a token from
	// an issuer that doesn't set it, and omitted from the token then.
	Principal Principal `json:"principal,omitempty"`
}

func ExtractUserInfo

func ExtractUserInfo(token string) (UserInfo, error)

ExtractUserInfo extracts the "sub" and "groups" fields from a JWT payload without verifying the signature. Use only for non-security-critical use (e.g., logging).

func Validate

func Validate(publicKey *rsa.PublicKey, bearer string) (UserInfo, error)

Validate parses and verifies the given bearer token against the supplied RSA public key. Only the RS256 asymmetric algorithm is accepted; tokens signed with any other method (in particular symmetric HMAC) are rejected to prevent algorithm-confusion attacks.

Prefer ValidateWithKeySource when the key comes from authn's JWKS endpoint; this form is for callers holding a single key already.

func ValidateWithKeySource

func ValidateWithKeySource(keys KeySource, bearer string) (UserInfo, error)

ValidateWithKeySource parses and verifies the given bearer token, resolving the verification key through keys using the token's "kid" header. This is the JWKS-friendly form: a JWKSKeySource fetches authn's published key set and caches it, so key rotation needs no redeploy of the validating component.

As with Validate, only RS256 is accepted — a token offering any other algorithm (notably symmetric HMAC) is rejected before the key is consulted, which is what makes algorithm confusion impossible here.

Errors are separated by fault so callers can answer with the right status: ErrTokenExpired and ErrTokenInvalid mean the caller's token is at fault (401), whereas ErrKeyUnavailable means we could not obtain the key (503) and says nothing about the token. A token whose kid is absent from a key set fetched after the token was issued is ErrTokenInvalid and ErrKeyNotPublished: its key was retired, so it will never verify again.

func (UserInfo) Actor added in v1.30.0

func (u UserInfo) Actor() string

Actor returns the identity performing the request: the outermost actor of a delegated token, or Username when the token isn't delegated.

func (UserInfo) ActorPrincipal added in v1.34.0

func (u UserInfo) ActorPrincipal() Principal

ActorPrincipal returns the kind of the identity performing the request: the outermost actor's on a delegated token, otherwise the token's own. "" means the issuer didn't say.

func (UserInfo) DelegationChain added in v1.30.0

func (u UserInfo) DelegationChain() []string

DelegationChain returns every identity on the token, current actor first and ending with the subject. A token that isn't delegated returns just Username.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL