jwtkit

package
v0.51.0 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AccessTokenType          = "access+jwt"
	DelegatedAccessTokenType = "delegated-access+jwt"
	// RemoteApplicationAccessTokenType is the JOSE `typ` for a remote application
	// access token. It carries neither sub nor delegated_sub; identity is the
	// validated iss -> remote_application mapping.
	RemoteApplicationAccessTokenType = "remote-application-access+jwt"
)

AuthKit JOSE `typ` header values. These separate AuthKit JWT classes before claims are mapped into principals.

View Source
const (
	// DefaultAuthKeysPath is the default directory where External Secrets mounts auth keys
	DefaultAuthKeysPath = "/vault/auth"

	// DefaultKeyReloadInterval is how often a ReloadableKeySource re-stats
	// keys.json for changes. Short keeps the post-rotation multi-replica skew
	// window small; the cost is one stat() per tick. See authkit #90.
	DefaultKeyReloadInterval = 10 * time.Second
)
View Source
const (
	// DefaultGeneratedKeysDir is the default directory under which the
	// development GeneratedKeySource persists its auto-generated keypair.
	DefaultGeneratedKeysDir = ".runtime/authkit"
)

Variables

View Source
var ErrUnsupportedJWK = errors.New("unsupported_jwk")

Functions

func AlgorithmForPublicKey added in v0.12.3

func AlgorithmForPublicKey(pub crypto.PublicKey) string

AlgorithmForPublicKey returns a default JWS alg for a public key when none is specified.

func BaseRegisteredClaims

func BaseRegisteredClaims(subject string, audiences []string, ttl time.Duration) jwt.RegisteredClaims

Helper to make base registered claims.

func JWKSToPublicKeys added in v0.12.3

func JWKSToPublicKeys(ks JWKS) (map[string]crypto.PublicKey, error)

JWKSToPublicKeys parses all supported keys in a JWKS document.

func JWKToPublicKey added in v0.12.3

func JWKToPublicKey(j JWK) (crypto.PublicKey, error)

JWKToPublicKey parses a single JWK into a crypto.PublicKey.

func ParsePublicKeyFromPEM added in v0.12.3

func ParsePublicKeyFromPEM(pemText string) (crypto.PublicKey, error)

ParsePublicKeyFromPEM parses a PKIX/SPKI, certificate, or PKCS#1 RSA public key PEM.

func ParsePublicKeyFromPEMBytes added in v0.12.3

func ParsePublicKeyFromPEMBytes(pemBytes []byte) (crypto.PublicKey, error)

ParsePublicKeyFromPEMBytes parses a supported public key PEM block.

func ServeJWKS

func ServeJWKS(w http.ResponseWriter, r *http.Request, ks JWKS)

ServeJWKS writes JWKS JSON to the ResponseWriter.

func SetLogger added in v0.12.3

func SetLogger(l Logger)

SetLogger installs the package-level logger used for key-load warnings. Pass nil to restore the default no-op logger.

Types

type ClaimsBuilder

type ClaimsBuilder interface {
	// Build returns application-specific claims to embed.
	Build(ctx context.Context, userID string, base jwt.RegisteredClaims) (map[string]any, error)
}

ClaimsBuilder builds custom claims layered on top of RegisteredClaims.

type ECDSASigner added in v0.12.3

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

ECDSASigner signs JWTs with ES256, ES384, or ES512 based on the private key curve.

func (*ECDSASigner) Algorithm added in v0.12.3

func (s *ECDSASigner) Algorithm() string

func (*ECDSASigner) KID added in v0.12.3

func (s *ECDSASigner) KID() string

func (*ECDSASigner) PublicKey added in v0.12.3

func (s *ECDSASigner) PublicKey() crypto.PublicKey

func (*ECDSASigner) Sign added in v0.12.3

func (s *ECDSASigner) Sign(_ context.Context, claims jwt.MapClaims) (string, error)

func (*ECDSASigner) SignWithHeaders added in v0.12.3

func (s *ECDSASigner) SignWithHeaders(_ context.Context, claims jwt.MapClaims, headers map[string]any) (string, error)

type Ed25519Signer added in v0.12.3

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

Ed25519Signer signs JWTs with EdDSA (Ed25519).

func NewEd25519Signer added in v0.12.3

func NewEd25519Signer(kid string) (*Ed25519Signer, error)

NewEd25519Signer generates a new Ed25519 key pair for development/testing.

func (*Ed25519Signer) Algorithm added in v0.12.3

func (s *Ed25519Signer) Algorithm() string

func (*Ed25519Signer) KID added in v0.12.3

func (s *Ed25519Signer) KID() string

func (*Ed25519Signer) PublicKey added in v0.12.3

func (s *Ed25519Signer) PublicKey() crypto.PublicKey

func (*Ed25519Signer) Sign added in v0.12.3

func (s *Ed25519Signer) Sign(_ context.Context, claims jwt.MapClaims) (string, error)

func (*Ed25519Signer) SignWithHeaders added in v0.12.3

func (s *Ed25519Signer) SignWithHeaders(_ context.Context, claims jwt.MapClaims, headers map[string]any) (string, error)

type GeneratedKeySource

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

GeneratedKeySource generates and persists RSA keys (for development only).

func NewGeneratedKeySource

func NewGeneratedKeySource() (*GeneratedKeySource, error)

NewGeneratedKeySource creates a KeySource with auto-generated RSA keys, persisting them under DefaultGeneratedKeysDir (".runtime/authkit"). For a custom directory use NewGeneratedKeySourceInDir.

func NewGeneratedKeySourceInDir added in v0.26.0

func NewGeneratedKeySourceInDir(dir string) (*GeneratedKeySource, error)

NewGeneratedKeySourceInDir creates a KeySource with auto-generated RSA keys, loading from / persisting to the given directory. An empty dir defaults to DefaultGeneratedKeysDir. Development only.

func (*GeneratedKeySource) ActiveSigner

func (g *GeneratedKeySource) ActiveSigner() Signer

func (*GeneratedKeySource) PublicKeys

func (g *GeneratedKeySource) PublicKeys() map[string]crypto.PublicKey

type HeaderSigner added in v0.12.0

type HeaderSigner interface {
	Signer
	// SignWithHeaders signs claims and merges the provided extra JOSE header
	// params into the token header (kid is still set by the signer).
	SignWithHeaders(ctx context.Context, claims jwt.MapClaims, headers map[string]any) (token string, err error)
}

HeaderSigner is an extension of Signer that lets callers set extra JOSE header parameters (e.g. `typ`) on the signed token. AuthKit token minting uses it to stamp the token profile header.

type JWK

type JWK struct {
	Kty string `json:"kty"`
	Use string `json:"use,omitempty"`
	Kid string `json:"kid,omitempty"`
	Alg string `json:"alg,omitempty"`
	// RSA
	N string `json:"n,omitempty"`
	E string `json:"e,omitempty"`
	// EC / OKP
	Crv string `json:"crv,omitempty"`
	X   string `json:"x,omitempty"`
	Y   string `json:"y,omitempty"`
}

JWK represents a JSON Web Key (RSA, EC, or OKP).

func PublicToJWK added in v0.12.3

func PublicToJWK(pub crypto.PublicKey, kid, alg string) JWK

PublicToJWK converts a supported public key to a JWK.

func RSAPublicToJWK

func RSAPublicToJWK(pub *rsa.PublicKey, kid, alg string) JWK

RSAPublicToJWK converts an RSA public key to a JWK.

type JWKS

type JWKS struct {
	Keys []JWK `json:"keys"`
}

type KeyRing added in v0.12.3

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

KeyRing is a KeySource that exposes one active signer and a merged set of verification public keys (active + retired).

func NewKeyRing added in v0.12.3

func NewKeyRing(active Signer, verificationKeys map[string]crypto.PublicKey) *KeyRing

NewKeyRing builds a KeyRing. verificationKeys are merged with the active signer's public key (when the signer implements PublicKeySigner). Retired keys remain in JWKS for rotation without being used to sign.

func (*KeyRing) ActiveSigner added in v0.12.3

func (k *KeyRing) ActiveSigner() Signer

func (*KeyRing) PublicKeys added in v0.12.3

func (k *KeyRing) PublicKeys() map[string]crypto.PublicKey

type KeySource

type KeySource interface {
	ActiveSigner() Signer
	PublicKeys() map[string]crypto.PublicKey
}

KeySource provides the active signer and public keys for JWKS.

func EnvKeySource added in v0.26.0

func EnvKeySource() (KeySource, error)

EnvKeySource loads the active signing key and JWKS public keys from environment variables: ACTIVE_KEY_ID, ACTIVE_PRIVATE_KEY_PEM, and the optional PUBLIC_KEYS map (JSON of kid -> PEM). It returns (nil, nil) when no key env vars are set so it can compose as the first step of a resolver.

func FileKeySource added in v0.26.0

func FileKeySource(path string) (KeySource, error)

FileKeySource loads the active signing key and JWKS public keys from a keys.json file located under the given directory (default /vault/auth when path is empty). The file uses the {active_key_id, active_private_key_pem, public_keys} envelope. It returns (nil, nil) when the directory or keys.json does not exist so it can compose as a fallthrough step of a resolver.

func NewAutoKeySource

func NewAutoKeySource() (KeySource, error)

NewAutoKeySource auto-discovers JWT keys from multiple sources with the following priority (using the default filesystem path /vault/auth): 1. Environment variables (ACTIVE_KEY_ID, ACTIVE_PRIVATE_KEY_PEM, PUBLIC_KEYS) 2. Filesystem /vault/auth/keys.json 3. Auto-generated keys in .runtime/authkit/ (development fallback; prod hard-fail)

func NewAutoKeySourceWithPath added in v0.26.0

func NewAutoKeySourceWithPath(path string) (KeySource, error)

NewAutoKeySourceWithPath is NewAutoKeySource with a host-overridable filesystem directory for the keys.json file. An empty path defaults to DefaultAuthKeysPath ("/vault/auth"). Precedence and the production hard-fail are identical to NewAutoKeySource: env -> FileKeySource(path) -> GeneratedKeySource (non-prod only).

type Logger added in v0.12.3

type Logger func(format string, args ...any)

Logger receives non-fatal key-loading warnings from jwtkit. The default is a no-op logger so libraries do not write to stdout.

type PublicKeySigner added in v0.12.3

type PublicKeySigner interface {
	Signer
	PublicKey() crypto.PublicKey
}

PublicKeySigner is implemented by in-memory signers that expose their public key.

type RSASigner

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

Minimal in-memory RSA signer for bootstrap/dev. Production should load from KMS or DB.

func NewRSASigner

func NewRSASigner(bits int, kid string) (*RSASigner, error)

func NewRSASignerFromPEM

func NewRSASignerFromPEM(kid string, pemBytes []byte) (*RSASigner, error)

NewRSASignerFromPEM constructs an RSASigner from a PEM-encoded RSA private key.

func (*RSASigner) Algorithm

func (s *RSASigner) Algorithm() string

func (*RSASigner) KID

func (s *RSASigner) KID() string

func (*RSASigner) PrivateKey

func (s *RSASigner) PrivateKey() *rsa.PrivateKey

func (*RSASigner) PublicKey

func (s *RSASigner) PublicKey() crypto.PublicKey

func (*RSASigner) Sign

func (s *RSASigner) Sign(_ context.Context, claims jwt.MapClaims) (string, error)

func (*RSASigner) SignWithHeaders added in v0.12.0

func (s *RSASigner) SignWithHeaders(_ context.Context, claims jwt.MapClaims, headers map[string]any) (string, error)

SignWithHeaders implements HeaderSigner: it signs claims and merges extra JOSE header params (e.g. `typ`) into the token header. The signer's own kid is set last and cannot be overridden by the supplied headers.

type ReloadableKeySource added in v0.39.0

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

ReloadableKeySource wraps a file-backed StaticKeySource and hot-reloads it when keys.json changes on disk (e.g. re-rendered by Vault Agent), so signing- key rotation never requires a process restart. It implements KeySource; reads are lock-free via an atomic pointer. A background poller re-stats keys.json at the configured interval and, on change, atomically swaps in a NEW validated keystore. A malformed/unreadable file keeps the last-good keystore — a bad render never bricks signing. See authkit #90 (AK-IMPL-3).

func NewReloadableFileKeySource added in v0.39.0

func NewReloadableFileKeySource(path string, interval time.Duration) (*ReloadableKeySource, error)

NewReloadableFileKeySource loads keys.json from the given directory and starts a background poller that hot-reloads it every interval (<=0 → DefaultKeyReloadInterval). It errors when no valid keys.json is present, so use it only where a file source is expected — env/dev sources don't reload (env is immutable in a running process; generated keys are dev-only).

func (*ReloadableKeySource) ActiveSigner added in v0.39.0

func (r *ReloadableKeySource) ActiveSigner() Signer

func (*ReloadableKeySource) Close added in v0.39.0

func (r *ReloadableKeySource) Close()

Close stops the background poller. Safe to call multiple times; optional for process-lifetime sources (primarily for tests and clean shutdown).

func (*ReloadableKeySource) PublicKeys added in v0.39.0

func (r *ReloadableKeySource) PublicKeys() map[string]crypto.PublicKey

func (*ReloadableKeySource) Reload added in v0.39.0

func (r *ReloadableKeySource) Reload() error

Reload re-reads keys.json, validates it, and atomically swaps it in. On any read/parse/validation failure it KEEPS the current keystore and returns the error — it never serves a partial or empty key set.

type Signer

type Signer interface {
	// Algorithm returns the JWS algorithm (e.g., RS256, EdDSA).
	Algorithm() string
	// KID returns current key id.
	KID() string
	// Sign creates a signed JWT with provided claims.
	Sign(ctx context.Context, claims jwt.MapClaims) (token string, err error)
}

Signer issues and verifies asymmetric JWTs.

func NewSignerFromPEM added in v0.12.3

func NewSignerFromPEM(kid string, pemBytes []byte) (Signer, error)

NewSignerFromPEM constructs a Signer from a PEM-encoded private key (RSA, EC, or Ed25519).

type StaticKeySource

type StaticKeySource struct {
	Active Signer
	Pubs   map[string]crypto.PublicKey
}

StaticKeySource is a simple in-memory implementation.

func NewStaticKeySourceFromRing added in v0.12.3

func NewStaticKeySourceFromRing(active Signer, verificationKeys map[string]crypto.PublicKey) StaticKeySource

NewStaticKeySourceFromRing is a convenience alias for NewKeyRing(...).StaticKeySource().

func (StaticKeySource) ActiveSigner

func (s StaticKeySource) ActiveSigner() Signer

func (StaticKeySource) PublicKeys

func (s StaticKeySource) PublicKeys() map[string]crypto.PublicKey

Jump to

Keyboard shortcuts

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