Documentation
¶
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrInvalidURL = errors.New("invalid url") ErrHTTPStatusNotOK = errors.New("http status not ok") )
var ( // ErrRSAPublicKeyNotFound is returned when a certificate does not contain an RSA public key. ErrRSAPublicKeyNotFound = errors.New("not a RSA public key") // ErrCertificateNotFound is returned when no certificate is provided. ErrCertificateNotFound = errors.New("certificate not found") // ErrNoKeysFound is returned when no keys are found in the JWKS (JSON Web Key Set). ErrNoKeysFound = errors.New("no keys found in jwks") // ErrDuplicateKID is returned when duplicate key IDs are detected. ErrDuplicateKID = errors.New("duplicate kid") // ErrKeyTypeUnsupported is returned when an unsupported key type is encountered. ErrKeyTypeUnsupported = errors.New("key type unsupported") // ErrInvalidKey is returned when key validation fails. ErrInvalidKey = errors.New("invalid key") )
var ( // ErrNoClientFound indicates no JWKS client configured for the given issuer. ErrNoClientFound = errors.New("no client found for issuer") // ErrNoValidatorFound indicates no validator configured for the given issuer. ErrNoValidatorFound = errors.New("no validator found for issuer") // ErrKidNoPublicKeyFound indicates no public key found in cache for the given kid. ErrKidNoPublicKeyFound = errors.New("no public key found for kid") // ErrIssuerEmpty is returned when the issuer value is empty. ErrIssuerEmpty = errors.New("issuer is empty") )
var ( ErrRSAKeyLength = errors.New("RSA key is too small") ErrUndefinedHashingAlgorithm = errors.New("undefined hashing algorithm") ErrUndefinedSigningAlgorithm = errors.New("undefined signing algorithm") ErrNilKeyProvider = errors.New("keyProvider cannot be nil") )
var ( // ErrCACertNotLoaded is returned when a Validator is constructed without a CA certificate. ErrCACertNotLoaded = errors.New("ca cert is not loaded") // ErrX5cEmpty is returned when a JWK has no x5c certificates. ErrX5cEmpty = errors.New("x5c is empty") // ErrInvalidCertEncoding is returned when an x5c entry is not valid base64. ErrInvalidCertEncoding = errors.New("invalid cert encoding") // ErrParseCertificate is returned when a decoded x5c entry cannot be parsed as a certificate. ErrParseCertificate = errors.New("parse certificate") // ErrUnknownSubj is returned when a certificate subject does not match the expected subject. ErrUnknownSubj = errors.New("unknown subject") )
var ( ErrUnexpectedClaimsType = errors.New("unexpected claims type") ErrUnexpectedSigningMethod = errors.New("unexpected signing method") ErrMissingIssOrKid = errors.New("missing iss or kid in token") ErrUntrustedIssuer = errors.New("untrusted issuer") ErrJWTParseFailed = errors.New("jwt parse failed") ErrUnsupportedHashAlgorithm = errors.New("unsupported hash algorithm") ErrSignatureInvalid = errors.New("jwt signature invalid") ErrHashClaimMissing = errors.New("missing hash claim") ErrMessageHashMismatch = errors.New("message hash mismatch") ErrNilPublicKeyProvider = errors.New("publicKeyProvider cannot be nil") ErrNoTrustedIssuers = errors.New("trusted issuers cannot be nil") )
Functions ¶
This section is empty.
Types ¶
type Client ¶ added in v1.10.0
type Client struct {
// contains filtered or unexported fields
}
Client represents a JWKS (JSON Web Key Set) client that fetches keys from a remote endpoint. It uses an HTTP client to perform requests to the specified endpoint.
func NewClient ¶ added in v1.10.0
func NewClient(endpoint string, opts ...HTTPClientOpts) (*Client, error)
NewClient creates and returns a new Client for the given JWKS endpoint. The endpoint parameter specifies the URL to fetch JWKS from. Optional HTTPClientOpts can be provided to customize the underlying http.Client. Returns an error if the endpoint URL is invalid.
func (*Client) Get ¶ added in v1.10.0
Get retrieves the JSON Web Key Set (JWKS) from the configured endpoint. It sends an HTTP GET request using the provided context, checks for a successful response, reads and unmarshals the response body into a JWKS struct, and returns it. Returns an error if the request fails, the status is not OK, or the response cannot be parsed.
type HTTPClientOpts ¶ added in v1.10.0
HTTPClientOpts defines a function type that modifies an http.Client. It can be used to customize the HTTP client's settings when creating a new Client.
type Input ¶ added in v1.10.0
type Input struct {
Kty KeyType
Alg string
Use string
KeyOps []string
Kid string
X509Certs []x509.Certificate
}
Input is used to build JWKS from a set of keys and certificates.
type JWKS ¶ added in v1.10.0
type JWKS struct {
Keys []Key `json:"keys"`
}
JWKS represents a JSON Web Key Set, containing multiple JWK keys.
func NewJWKS ¶ added in v1.10.0
NewJWKS constructs a JWKS from one or more KeyInput values. It ensures each key has a unique KID and at least one certificate.
type JWKSProvider ¶ added in v1.10.0
type JWKSProvider struct {
// contains filtered or unexported fields
}
JWKSProvider fetches JWKS for issuers and provides RSA public keys. It maintains a map of issuer to JWKSClientStore which holds a client, validator and an in-memory cache of public keys.
func NewJWKSProvider ¶ added in v1.10.0
func NewJWKSProvider() *JWKSProvider
NewJWKSProvider creates and returns a new JWKSProvider instance with initialized in-memory storage for issuer client stores.
func (*JWKSProvider) AddClient ¶ added in v1.11.0
func (j *JWKSProvider) AddClient(issuer string, client *Client, validator *Validator) error
AddClient registers a client and validator for a given issuer. It initializes the in-memory cache for the issuer. Returns an error if the issuer, client or validator is nil.
func (*JWKSProvider) VerificationKey ¶ added in v1.10.0
func (j *JWKSProvider) VerificationKey(ctx context.Context, iss string, kid string) (*rsa.PublicKey, error)
VerificationKey returns the RSA public key for the given issuer (iss) and key ID (kid). It first attempts to retrieve the key from the in-memory cache. If the key is not found, it refreshes the JWKS cache for the issuer and tries again. Returns an error if the issuer is not configured or if the key cannot be found or validated.
type Key ¶ added in v1.10.0
type Key struct {
Kty KeyType `json:"kty"` // Key type (e.g., "RSA")
Alg string `json:"alg"` // Algorithm intended for use with the key
Use string `json:"use"` // Intended use of the public key
KeyOps []string `json:"key_ops"` // Permitted operations for the key
Kid string `json:"kid"` // Key ID
X5c []string `json:"x5c"` // X.509 certificate chain
N string `json:"n"` // RSA modulus
E string `json:"e"` // RSA public exponent
}
Key defines the structure of a single JSON Web Key.
type KeyMetadata ¶
type KeyMetadata struct {
Iss string // typically the cluster URL that exposes .well-known/jwks.json
Kid string // uniquely identifies the signing key under that issuer
}
KeyMetadata describes the logical identity of a signing key. It maps directly to the JWT "iss" (issuer) and "kid" (key ID) used by verifiers to look up the matching public key via the configured trust mechanism.
type KeyType ¶ added in v1.10.0
type KeyType string
KeyType specifies the type of cryptographic key (e.g., "RSA").
var KeyTypeRSA KeyType = "RSA"
KeyTypeRSA is the constant for RSA key type.
type PrivateKeyProvider ¶
type PrivateKeyProvider interface {
// CurrentSigningKey returns the key+metadata to use for signing.
CurrentSigningKey(ctx context.Context) (*rsa.PrivateKey, KeyMetadata, error)
}
PrivateKeyProvider supplies the current RSA private key and its metadata for signing outgoing messages.
type PublicKeyProvider ¶
type PublicKeyProvider interface {
// VerificationKey returns the public key for given issuer and kid.
VerificationKey(ctx context.Context, iss, kid string) (*rsa.PublicKey, error)
}
PublicKeyProvider resolves RSA public keys for verification of incoming message signatures.
type SHA256Hasher ¶
type SHA256Hasher struct{}
func (*SHA256Hasher) HashMessage ¶
func (s *SHA256Hasher) HashMessage(body []byte) string
func (*SHA256Hasher) ToString ¶
func (s *SHA256Hasher) ToString() string
type Signer ¶
type Signer struct {
Hasher
// contains filtered or unexported fields
}
Signer signs message bodies into JWS (JWT) tokens.
func (*Signer) Sign ¶
Sign creates a compact JWS (JWT) for the given message body using PS256.
The returned string is suitable for use as a value of an HTTP or message header (e.g. "X-Message-Signature"). The token will contain the following claims and headers:
- claims: iss: issuer from KeyMetadata kid: key ID from KeyMetadata hash: base64url(SHA-256(body)) hash-alg: "SHA256"
- headers: typ: "JWT" alg: "PS256"
Sign obtains the private key and metadata from the configured PrivateKeyProvider and enforces the minimum RSA key size before signing. It returns an error if the provider fails, if the key is too small, or if the token cannot be signed.
type Validator ¶ added in v1.10.0
type Validator struct {
// contains filtered or unexported fields
}
Validator validates x5c certificate chains from JWKs against a configured CA pool and checks that the leaf certificate subject matches an expected subject string.
func NewValidator ¶ added in v1.10.0
func NewValidator(ca *x509.Certificate, subject string) (*Validator, error)
NewValidator returns a Validator initialized with the given CA certificate and subject. The CA certificate is added to a new x509.CertPool used for validation. Returns an error if the CA certificate is nil or the subject is empty.
func (*Validator) Validate ¶ added in v1.10.0
Validate checks the provided x5c certificate chain for validity. It expects the provided Key to include an x5c slice where the first element is the leaf certificate followed by any intermediates. Each entry must be a base64-encoded DER certificate. The chain is verified against the Validator's CA pool and the leaf subject must match the Validator's Subject. Returns an error if the chain cannot be decoded, parsed, verified or if the leaf subject does not match.
type Verifier ¶
type Verifier struct {
Hasher
// contains filtered or unexported fields
}
Verifier verifies signed messages represented as compact JWS (JWT) tokens.
func NewVerifier ¶
func NewVerifier(publicKeyProvider PublicKeyProvider, hasher Hasher, trustedIssuers map[string]struct{}) (*Verifier, error)
func (*Verifier) Verify ¶
Verify checks that the given compact JWS (JWT) token is a valid signature for the provided message body.
Verify performs the following steps:
- Parses the token and enforces the PS256 signing method.
- Extracts "iss" and "kid" claims and validates "iss" against TrustedIssuers if configured.
- Resolves the corresponding RSA public key via the PublicKeyProvider.
- Enforces the minimum RSA key size.
- Verifies the JWS signature using the resolved public key.
- Validates that the "hash-alg" claim is "SHA256".
- Recomputes base64url(SHA-256(body)) and compares it to the "hash" claim in constant time.
If any step fails, Verify returns a non-nil error and the caller should treat the message as untrusted.