jwtutil

package
v1.28.1 Latest Latest
Warning

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

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

Documentation

Index

Constants

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

Variables

View Source
var (
	ErrTokenExpired = errors.New("token is expired")
	ErrTokenInvalid = errors.New("token is invalid")
)
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 CreateTokenOptions

type CreateTokenOptions struct {
	Username   string
	Groups     []string
	Duration   time.Duration
	KeyID      string
	PrivateKey *rsa.PrivateKey
}

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.

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
}

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

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.

Jump to

Keyboard shortcuts

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