Documentation
¶
Overview ¶
Package jwk implements JWK as described in https://tools.ietf.org/html/rfc7517
This package implements jwk.Key to represent a single JWK, and jwk.Set to represent a set of JWKs.
The `jwk.Key` type is an interface, which hides the underlying implementation for each key type. Each key type can further be converted to interfaces for known types, such as `jwk.ECDSAPrivateKey`, `jwk.RSAPublicKey`, etc. This may not necessarily work for third party key types (see section on "Registering a key type" below).
Users can create a JWK in two ways. One is to unmarshal a JSON representation of a key. The second one is to use `jwk.Import()` to import a raw key, validate it, and convert it to a jwk.Key.
Simple Usage ¶
You can parse a JWK from a JSON payload:
jwk.ParseKey([]byte(`{"kty":"EC",...}`))
You can go back and forth between raw key types and JWKs:
jwkKey, _ := jwk.Import[jwk.Key](rsaPrivateKey) rawKey, _ := jwk.Export[*rsa.PrivateKey](jwkKey)
When you know the expected key type, use a concrete type parameter:
rsaKey, _ := jwk.Import[jwk.RSAPrivateKey](rsaPrivateKey) ecKey, _ := jwk.ParseKeyAs[jwk.ECDSAPublicKey](jsonData)
You can use them to sign/verify/encrypt/decrypt:
jws.Sign([]byte(`...`), jws.WithKey(jwa.RS256, jwkKey)) jwe.Encrypt([]byte(`...`), jwe.WithKey(jwa.RSA_OAEP, jwkKey))
See examples/jwk_parse_example_test.go and other files in the examples/ directory for more.
Registering a custom key type ¶
The library supports adding new key types not implemented out of the box (vendor-specific algorithms, post-quantum work, etc.) via four registration points:
- KeyProbe — partial JSON unmarshaling that picks out hint fields used to decide what concrete key type to construct. Add fields with RegisterProbeField.
- KeyParser — converts a JSON payload into a jwk.Key using the probe's hints. Register with RegisterKeyParser.
- KeyImporter — converts a raw Go crypto value into a jwk.Key. Register with RegisterKeyImporter (generic, one importer per Go type).
- KeyExporter — converts a jwk.Key back into a raw Go value. Register with RegisterKeyExporter, keyed by KeyKind.
The whole extension surface is **experimental**: the API may change in backward-incompatible ways even between minor versions.
See the "Registering a custom key type" section in docs/04-jwk.md for the full walkthrough including a worked example.
Index ¶
- Constants
- func AssignKeyID(key Key, options ...AssignKeyIDOption) error
- func ContinueError() error
- func Equal(k1, k2 Key) bool
- func Export[T any](key Key) (T, error)
- func ExportAll[T any](set Set) ([]T, error)
- func Get[T any](key Key, name string) (T, error)
- func Import[T Key](raw any) (T, error)
- func ImportError() error
- func IsKeyValidationError(err error) bool
- func IsPrivateKey(k Key) (bool, error)
- func IsUnsupportedKey(key Key) bool
- func NewKeyValidationError(err error) error
- func ParseError() error
- func ParseKeyAs[T Key](data []byte, options ...ParseOption) (T, error)
- func ParseRawKey(data []byte, rawkey any) error
- func PublicRawKeyOf(v any) (any, error)
- func RegisterCustomDecoder[T any](name string, dec CustomDecodeFunc[T]) error
- func RegisterCustomField[T any](name string) error
- func RegisterKeyExporter(ident KeyKind, conv KeyExporter) error
- func RegisterKeyImporter[T any](ki KeyImporter[T]) error
- func RegisterKeyParser(kp KeyParser) error
- func RegisterKeyUsage(v string) error
- func RegisterOKPRawKeyImporter(imp OKPRawKeyImporter) error
- func RegisterProbeField[T any](name, jsonKey string) error
- func Settings(options ...GlobalOption) error
- func UnregisterCustomField(name string) error
- func UnregisterKeyImporter[T any]() bool
- func UnregisterKeyUsage(v string) error
- type AKPPrivateKey
- type AKPPublicKey
- type AssignKeyIDOption
- type AsymmetricKey
- type CustomDecodeFunc
- type CustomDecoder
- type DecodeCtx
- type ECDSAPrivateKey
- type ECDSAPublicKey
- type Fetcher
- type FieldNotFoundError
- type FieldTypeMismatchError
- type GlobalOption
- type GlobalParseOption
- type Key
- type KeyExportFunc
- type KeyExporter
- type KeyImportFunc
- type KeyImporter
- type KeyKind
- type KeyKinder
- type KeyOperation
- type KeyOperationList
- type KeyParseFunc
- type KeyParser
- type KeyProbe
- type KeyTypeMismatchError
- type KeyUnmarshaler
- type KeyUsageType
- type KeyWithDecodeCtx
- type OKPPrivateKey
- type OKPPublicKey
- type OKPRawKeyImporter
- type OKPRawKeyImporterFunc
- type Option
- type ParseOption
- type PublicKeyer
- type PublicSetOption
- type RSAPrivateKey
- type RSAPublicKey
- type Set
- func NewSet() Set
- func Parse(src []byte, options ...ParseOption) (Set, error)
- func ParseFS(fsys fs.FS, path string, options ...ParseOption) (Set, error)
- func ParseReader(src io.Reader, options ...ParseOption) (Set, error)
- func ParseString(s string, options ...ParseOption) (Set, error)
- func PublicSetOf(v Set, options ...PublicSetOption) (Set, error)
- func ReadFile(path string, options ...ParseOption) (Set, error)deprecated
- type SymmetricKey
- type UnknownKeyTypeError
- type UnsupportedKey
Constants ¶
const ( AKPPrivKey = "priv" AKPPubKey = "pub" )
const ( ECDSACrvKey = "crv" ECDSADKey = "d" ECDSAXKey = "x" ECDSAYKey = "y" )
const ( KeyTypeKey = "kty" KeyUsageKey = "use" KeyOpsKey = "key_ops" AlgorithmKey = "alg" KeyIDKey = "kid" X509URLKey = "x5u" X509CertChainKey = "x5c" X509CertThumbprintKey = "x5t" X509CertThumbprintS256Key = "x5t#S256" )
const ( OKPCrvKey = "crv" OKPDKey = "d" OKPXKey = "x" )
const ( RSADKey = "d" RSADPKey = "dp" RSADQKey = "dq" RSAEKey = "e" RSANKey = "n" RSAPKey = "p" RSAQIKey = "qi" RSAQKey = "q" )
const (
SymmetricOctetsKey = "k"
)
Variables ¶
This section is empty.
Functions ¶
func AssignKeyID ¶
func AssignKeyID(key Key, options ...AssignKeyIDOption) error
AssignKeyID is a convenience function to automatically assign the "kid" section of the key, if it already doesn't have one. It uses Key.Thumbprint method with crypto.SHA256 as the default hashing algorithm.
By default, if the key already carries a `kid`, `AssignKeyID` leaves it alone and returns nil. Pass `jwk.WithForceAssign(true)` to force recomputation (for example, when upgrading to a stronger thumbprint hash via `jwk.WithThumbprintHash`).
func ContinueError ¶
func ContinueError() error
ContinueError returns an opaque error that can be returned when a `KeyParser`, `KeyImporter`, or `KeyExporter` cannot handle the given payload, but would like the process to continue with the next handler.
func Equal ¶
Equal compares two keys and returns true if they are equal. The comparison is solely done against the thumbprints of k1 and k2. It is possible for keys that have, for example, different key IDs, key usage, etc, to be considered equal.
func Export ¶
Export converts a jwk.Key into a raw key of type T.
The type parameter T specifies the desired output type. For most keys, the type is unambiguous (e.g. RSA keys always export as *rsa.PrivateKey). For EC keys, the type parameter selects between *ecdsa.PrivateKey and *ecdh.PrivateKey.
Use [any] as the type parameter to let the exporter choose the default type:
raw, err := jwk.Export[any](key)
Examples:
privkey, err := jwk.Export[*rsa.PrivateKey](key) ecdhkey, err := jwk.Export[*ecdh.PrivateKey](key) octets, err := jwk.Export[[]byte](key)
func ExportAll ¶
ExportAll exports every key in the given Set to type T, preserving insertion order. It is the plural counterpart to Export and fails fast on the first key whose raw representation cannot be asserted to T.
For a heterogeneous Set whose members don't share a concrete raw type, use `T = any`:
raws, err := jwk.ExportAll[any](set)
Each element's dynamic type then matches the source key's raw form (e.g. *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey).
Use a concrete T when every member shares a representation:
privkeys, err := jwk.ExportAll[*rsa.PrivateKey](set)
An empty Set returns an empty slice and a nil error.
func Get ¶
Get is a type-safe generic accessor that retrieves a field value from a key. It returns the value and an error if the field does not exist or cannot be converted to type T.
Usage:
kid, err := jwk.Get[string](key, jwk.KeyIDKey) custom, err := jwk.Get[MyType](key, "my-custom-field")
Callers that need to distinguish "field missing" from "field present but wrong type" should use errors.Is with FieldNotFoundError{} / FieldTypeMismatchError{}, or errors.AsType to recover the Name, Got, and Want fields.
func Import ¶
Import creates a validated jwk.Key from the given key (RSA/ECDSA/symmetric keys).
The constructor auto-detects the type of key to be instantiated based on the input type:
- "crypto/rsa".PrivateKey and "crypto/rsa".PublicKey creates an RSA based key
- "crypto/ecdsa".PrivateKey and "crypto/ecdsa".PublicKey creates an EC based key
- "crypto/ed25519".PrivateKey and "crypto/ed25519".PublicKey creates an OKP based key
- "crypto/ecdh".PrivateKey and "crypto/ecdh".PublicKey for X25519 creates an OKP based key; for the NIST P-curves (P-256, P-384, P-521) creates an EC based key (the same key material is valid for both ECDH and ECDSA, so JWK has no separate "EC for ECDH" type)
- []byte creates a symmetric key
The type parameter T specifies the expected key type. Use Key when you do not need a specific subtype:
key, err := jwk.Import[jwk.Key](rawKey)
Use a concrete key type to obtain a typed result directly:
rsaKey, err := jwk.Import[jwk.RSAPrivateKey](rawRSAKey)
Import validates the populated JWK before returning it. Malformed raw keys fail at import time instead of being returned for later validation.
Import expects well-formed raw keys, such as those produced by the standard library generators (e.g. ecdsa.GenerateKey, rsa.GenerateKey) or by parsing an encoded key. Hand-crafting raw key structs with internally inconsistent or out-of-range fields is not supported and may cause the underlying crypto primitives to panic; avoid doing so.
func ImportError ¶
func ImportError() error
func IsKeyValidationError ¶
func IsPrivateKey ¶
IsPrivateKey returns true if the supplied key is a private key of an asymmetric key pair. The argument `k` must implement the `AsymmetricKey` interface.
An error is returned if the supplied key is not an `AsymmetricKey`.
func IsUnsupportedKey ¶ added in v4.2.0
IsUnsupportedKey reports whether key is a placeholder retained for a JWK Set entry that could not be parsed. Only placeholders produced by this package satisfy the check; a user-defined Key type can never be mistaken for one. It is the sanctioned way to skip placeholders when iterating a set; type-assert to UnsupportedKey when you also need Reason().
func NewKeyValidationError ¶
NewKeyValidationError wraps the given error with an error that denotes `key.Validate()` has failed. This error type should ONLY be used as return value from the `Validate()` method.
func ParseError ¶
func ParseError() error
func ParseKeyAs ¶
func ParseKeyAs[T Key](data []byte, options ...ParseOption) (T, error)
ParseKeyAs behaves like ParseKey but asserts the parsed key to the concrete type T. On a type mismatch it returns a KeyTypeMismatchError carrying the parsed and requested types; the underlying error chain also satisfies errors.Is with a sentinel ParseError.
ecKey, err := jwk.ParseKeyAs[jwk.ECDSAPublicKey](data)
func ParseRawKey ¶
ParseRawKey is a combination of ParseKey and Raw. It parses a single JWK key, and assigns the "raw" key to the given parameter. The key must either be a pointer to an empty interface, or a pointer to the actual raw key type such as *rsa.PrivateKey, *ecdsa.PublicKey, *[]byte, etc.
func PublicRawKeyOf ¶
PublicRawKeyOf returns the corresponding public key of the given value `v` (e.g. given *rsa.PrivateKey, *rsa.PublicKey is returned) If `v` is already a public key, the key itself is returned.
The returned value will always be a pointer to the public key, except when a []byte (e.g. symmetric key, ed25519 key) is passed to `v`. In this case, the same []byte value is returned.
This function must go through converting the object once to a jwk.Key, then back to a raw key, so it's not exactly efficient.
func RegisterCustomDecoder ¶
func RegisterCustomDecoder[T any](name string, dec CustomDecodeFunc[T]) error
RegisterCustomDecoder registers a private field with a custom decoder function. This option has a global effect.
For example, below shows how to register a decoder that can parse RFC1123 format string:
jwk.RegisterCustomDecoder(`x-birthday`, jwk.CustomDecodeFunc[time.Time](func(data []byte) (time.Time, error) {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return time.Time{}, err
}
return time.Parse(time.RFC1123, s)
}))
The error return is reserved for future validation. The current implementation always returns nil, but callers — especially extension modules calling this from init() — must check the return value and panic on failure to stay forward-compatible.
func RegisterCustomField ¶
RegisterCustomField registers a private field to be decoded as type T using json.Unmarshal. This option has a global effect.
For example, suppose you have a custom field `x-birthday`, which you want to represent as a string formatted in RFC3339 in JSON, but want it back as `time.Time`.
jwk.RegisterCustomField[time.Time](`x-birthday`)
For more fine-tuned control over the decoding process, use RegisterCustomDecoder instead.
Please note that use of custom fields can be problematic if you are using a library that does not implement MarshalJSON/UnmarshalJSON and you try to roundtrip from an object to JSON, and then back to an object. To avoid this, it's always better to use a custom type that wraps your desired type and implement MarshalJSON and UnmarshalJSON.
The error return is reserved for future validation. The current implementation always returns nil, but callers — especially extension modules calling this from init() — must check the return value and panic on failure to stay forward-compatible.
func RegisterKeyExporter ¶
func RegisterKeyExporter(ident KeyKind, conv KeyExporter) error
RegisterKeyExporter registers a KeyExporter for the given KeyKind identity.
When Export is called, the library resolves exporters in two steps:
- If the key implements KeyKinder, its KeyKind() value is used to look up exporters registered for that specific identity (e.g. "OKP:Ed448").
- If no exporter is found (or the key does not implement KeyKinder), the library falls back to exporters registered for the key type string alone (i.e. KeyKind(key.KeyType().String()), e.g. "OKP").
This two-level dispatch allows extension modules to register exporters for specific curves or algorithms without interfering with built-in exporters.
For most key types, pass KeyKind(kty.String()) as the identity:
// Handles all RSA keys.
jwk.RegisterKeyExporter(jwk.KeyKind("RSA"), myRSAExporter)
For curve- or algorithm-specific exporters, use a compound identity that matches the value returned by the key's KeyKind() method:
// Handles only OKP keys whose curve is Ed448.
// Built-in OKP keys return "OKP:<curve>" from KeyKind().
jwk.RegisterKeyExporter(jwk.KeyKind("OKP:Ed448"), myEd448Exporter)
The identity is normalized to uppercase before storage, so registration is case-insensitive: KeyKind("OKP:Ed448") and KeyKind("okp:ed448") refer to the same entry.
Multiple exporters can be registered for the same identity. They are tried in reverse registration order (last registered is tried first). An exporter can return ContinueError to decline a key and let the next exporter try.
The error return is reserved for future validation. The current implementation always returns nil, but callers — especially extension modules calling this from init() — must check the return value and panic on failure to stay forward-compatible.
func RegisterKeyImporter ¶
func RegisterKeyImporter[T any](ki KeyImporter[T]) error
RegisterKeyImporter registers a KeyImporter for the raw key type T. The type parameter is normally inferred from the importer's typed Import method; pass it explicitly only when inference would fail (e.g. when supplying a KeyImportFunc without arguments).
When Import is called, the library looks up the importer for the raw value's runtime type (via reflect) and invokes its Import method through a closure that handles the any → T re-typing.
Importer dispatch is single-valued per Go type T: there is exactly one importer per reflect.Type. Subsequent registrations for the same T return an error ("already registered") and do not replace the previous entry. Callers (e.g. tests) that need to swap an existing importer must first call UnregisterKeyImporter for the same T. This intentionally differs from the stacking behavior of RegisterKeyExporter and RegisterKeyParser, which dispatch by KeyKind / untyped JSON and therefore have a meaningful fallback chain; importer dispatch is a single-value map keyed by Go type, with no equivalent dimension to try next.
The importers for stdlib raw key types — both value and pointer forms of rsa.PrivateKey / rsa.PublicKey / ecdsa.PrivateKey / ecdsa.PublicKey / ecdh.PrivateKey / ecdh.PublicKey, plus ed25519.PrivateKey, ed25519.PublicKey, and []byte — are owned by jwk and cannot be overridden. RegisterKeyImporter for any of these types returns an error; UnregisterKeyImporter for them is a silent no-op. Use a wrapper type if you need to apply additional validation.
Extension modules calling this from init() must check the returned error and panic on failure.
To register from a typed function (the common case for extensions), wrap it with KeyImportFunc:
jwk.RegisterKeyImporter(jwk.KeyImportFunc[*mypkg.Key](importMyKey))
func RegisterKeyParser ¶
RegisterKeyParser adds a new KeyParser. Parsers are called in FILO order. That is, the last parser to be registered is called first. There is no check for duplicate entries.
The error return is reserved for future validation. The current implementation always returns nil, but callers — especially extension modules calling this from init() — must check the return value and panic on failure to stay forward-compatible.
func RegisterKeyUsage ¶
RegisterKeyUsage registers a possible value that can be used for KeyUsageType. Normally, key usage (or the "use" field in a JWK) is either "sig" or "enc", but other values may be used.
While this module only works with "sig" and "enc", it is possible that systems choose to use other values. This function allows users to register new values to be accepted as valid key usage types. Values are case sensitive.
Furthermore, the check against registered values can be completely turned off by setting the global option `jwk.WithStrictKeyUsage(false)`.
The error return is reserved for future validation. The current implementation always returns nil, but callers — especially extension modules calling this from init() — must check the return value and panic on failure to stay forward-compatible.
func RegisterOKPRawKeyImporter ¶
func RegisterOKPRawKeyImporter(imp OKPRawKeyImporter) error
RegisterOKPRawKeyImporter registers an OKPRawKeyImporter consulted by the OKP import path for unknown raw key types. To register a plain function, wrap it with OKPRawKeyImporterFunc.
The error return is reserved for future validation. The current implementation always returns nil, but callers — especially extension modules calling this from init() — must check the return value and panic on failure to stay forward-compatible.
func RegisterProbeField ¶
RegisterProbeField adds a new field to be probed during the initial phase of parsing. This is done by streaming through the JSON payload and extracting only the registered fields, skipping everything else.
The `name` parameter is used to identify the field when calling `KeyProbe.Field()`. The `jsonKey` parameter is the JSON field name to extract from the payload.
The field name must be unique. If you believe that your field name may collide with other packages that may want to add their own probes, it is the responsibility of the caller to ensure that the field name is unique (possibly by prefixing the field name with a unique string). It is important to note that the field name need not be the same as the JSON field name. For example, your field name could be "MyPkg_MyHint", while the actual JSON field name could be "my_hint".
If the field name is not unique, an error is returned.
func Settings ¶
func Settings(options ...GlobalOption) error
Settings is used to configure global behavior of the jwk package.
Returns a non-nil error and applies no changes if any option fails validation (for example, a non-positive WithMaxKeys). Extension modules calling this from init() must check the return value and panic on failure.
func UnregisterCustomField ¶
UnregisterCustomField removes the registration for a custom field.
The error return is reserved for future validation (for example, refusing to unregister a built-in field) and is always nil today. Callers — especially extension modules scripting Register/Unregister cycles from init() — should check the returned value and propagate on failure to stay forward-compatible, matching the convention on RegisterCustomField / RegisterCustomDecoder.
func UnregisterKeyImporter ¶
UnregisterKeyImporter removes the importer previously registered for type T. Returns true if an importer was removed, false if none was registered for T or if T is one of the built-in raw key types (see RegisterKeyImporter for the list); built-in importers cannot be unregistered.
This is primarily useful for tests or for extension modules that need to replace a previously installed importer. In steady-state code, prefer letting RegisterKeyImporter fail with the already-registered error; that loud failure catches accidental collisions between unrelated extension modules at import time.
func UnregisterKeyUsage ¶
UnregisterKeyUsage removes v from the allowlist maintained by RegisterKeyUsage. The error return is reserved for future validation (for example, refusing to unregister a built-in usage value like "sig" or "enc") and is always nil today. Callers scripting Register/Unregister cycles should check the returned value and propagate on failure to stay forward-compatible, matching the convention on RegisterKeyUsage.
Types ¶
type AKPPrivateKey ¶
AKPPrivateKey represents the private portion of an Algorithm Key Pair (AKP) JWK, used by post-quantum algorithms such as ML-DSA (FIPS 204) and ML-KEM (FIPS 203). ML-KEM support lives in the github.com/jwx-go/mlkem companion module.
type AKPPublicKey ¶
AKPPublicKey represents the public portion of an Algorithm Key Pair (AKP) JWK, used by post-quantum algorithms such as ML-DSA (FIPS 204) and ML-KEM (FIPS 203). ML-KEM support lives in the github.com/jwx-go/mlkem companion module.
type AssignKeyIDOption ¶
type AssignKeyIDOption interface {
Option
// contains filtered or unexported methods
}
func WithForceAssign ¶
func WithForceAssign(v bool) AssignKeyIDOption
WithForceAssign forces `jwk.AssignKeyID` to recompute and overwrite the `kid` header even when the key already has one. The default behavior preserves any existing `kid`; use this option to upgrade the thumbprint hash (e.g. with `jwk.WithThumbprintHash`) or to refresh a `kid` after mutating a key field that invalidates the cached thumbprint.
func WithThumbprintHash ¶
func WithThumbprintHash(v crypto.Hash) AssignKeyIDOption
WithThumbprintHash specifies the hash algorithm `jwk.AssignKeyID` uses to compute the thumbprint. If the hash is unavailable (e.g. its package has not been imported), `AssignKeyID` returns an error rather than panicking.
type AsymmetricKey ¶
type AsymmetricKey interface {
IsPrivate() bool
}
AsymmetricKey describes a Key that represents a key in an asymmetric key pair, which in turn can be either a private or a public key. This interface allows those keys to be queried if they are one or the other.
type CustomDecodeFunc ¶
type CustomDecodeFunc[T any] = json.CustomDecodeFunc[T]
CustomDecodeFunc is a function-based implementation of CustomDecoder[T].
type CustomDecoder ¶
type CustomDecoder[T any] = json.CustomDecoder[T]
CustomDecoder is a generic interface for custom field decoders.
type ECDSAPrivateKey ¶
type ECDSAPublicKey ¶
type Fetcher ¶
Fetcher retrieves a JWK Set from a URL. The main jwx module is transport-agnostic: there is no concrete implementation of this interface in `jwk` itself. Use a companion such as `github.com/jwx-go/jwkfetch` to construct a concrete fetcher, or implement this interface directly on your own type.
All transport and policy concerns (HTTP client, whitelist, body-size caps, caching) are the implementation's responsibility — this interface takes no options on purpose.
type FieldNotFoundError ¶
type FieldNotFoundError struct {
// Name is the name of the field that was not found.
Name string
}
FieldNotFoundError is returned when jwk.Get fails to find the requested field on a jwk.Key.
func (FieldNotFoundError) Error ¶
func (e FieldNotFoundError) Error() string
func (FieldNotFoundError) Is ¶
func (e FieldNotFoundError) Is(target error) bool
type FieldTypeMismatchError ¶
type FieldTypeMismatchError struct {
// Name is the name of the field whose value could not be converted.
Name string
// Got is the value currently stored under the field. Use %T to
// inspect its concrete type.
Got any
// Want is a zero value of the requested type T. Use %T to inspect
// its concrete type.
Want any
}
FieldTypeMismatchError is returned when jwk.Get finds the requested field but the stored value cannot be converted to the requested type.
Callers that need to distinguish "field missing" from "field present but wrong type" should use errors.Is with FieldNotFoundError{} / FieldTypeMismatchError{}, or errors.AsType to recover Name, Got, and Want fields.
func (FieldTypeMismatchError) Error ¶
func (e FieldTypeMismatchError) Error() string
func (FieldTypeMismatchError) Is ¶
func (e FieldTypeMismatchError) Is(target error) bool
type GlobalOption ¶
type GlobalOption interface {
Option
// contains filtered or unexported methods
}
GlobalOption is a type of Option that can be passed to `jwk.Settings()` to change the global configuration of the jwk package.
func WithMinRSAModulusBits ¶
func WithMinRSAModulusBits(v int) GlobalOption
WithMinRSAModulusBits specifies the minimum RSA modulus size, in bits, accepted by JWK validation and raw/PEM/X.509 import.
The default is 2048. Lower this only for legacy interoperability with older key material. Any value <= 0 disables the modulus-size floor.
func WithMinRSAPublicExponent ¶
func WithMinRSAPublicExponent(v int) GlobalOption
WithMinRSAPublicExponent specifies the minimum RSA public exponent accepted by JWK validation and raw/PEM/X.509 import.
The default is 3. The exponent must still be odd and fit in a Go `int`. Lower this only for legacy interoperability. Any value <= 0 disables the minimum-exponent floor.
func WithStrictKeyUsage ¶
func WithStrictKeyUsage(v bool) GlobalOption
WithStrictKeyUsage specifies if during JWK parsing, the "use" field should be confined to the values that have been registered via `jwk.RegisterKeyType()`. By default this option is true, and the initial allowed values are "use" and "enc" only.
If this option is set to false, then the "use" field can be any value. If this options is set to true, then the "use" field must be one of the registered values, and otherwise an error will be reported during parsing / assignment to `jwk.KeyUsageType`
type GlobalParseOption ¶
type GlobalParseOption interface {
Option
// contains filtered or unexported methods
}
GlobalParseOption describes an Option that can be passed to both `jwk.Settings()` (to change the default globally) and `jwk.Parse()` / `jwk.ParseReader()` / `jwk.ParseString()` (to override per call).
func WithMaxKeys ¶
func WithMaxKeys(v int) GlobalParseOption
WithMaxKeys specifies the maximum number of keys allowed in a JWK set passed to `jwk.Parse()` / `jwk.ParseReader()` / `jwk.ParseString()`. If the "keys" array of a JSON-encoded JWKS, or the number of PEM blocks in an X.509-encoded input, exceeds this value, parsing returns an error. The default is 1000.
This option can be passed to `jwk.Settings()` to change the default globally, or to `jwk.Parse()` / `jwk.ParseReader()` / `jwk.ParseString()` for a per-call override. A non-positive value is rejected.
The cap defends against amplification: each entry triggers a probe + unmarshal + validation, each of which allocates. Bounding raw input bytes remains the caller's responsibility — see docs/13-input-size.md.
func WithRejectDuplicateKID ¶
func WithRejectDuplicateKID(v bool) GlobalParseOption
WithRejectDuplicateKID instructs `jwk.Parse()` / `jwk.ParseReader()` / `jwk.ParseString()` and the companion `Set.UnmarshalJSON()` to return an error when the JWKS contains two or more keys with the same non-empty `kid`. Keys without a kid are not considered.
Default is false — first-match-wins is retained for compatibility with RFC 7517 (which permits, but does not mandate, unique kids) and with existing callers that rely on `(jwk.Set).LookupKeyID` returning the first entry. Use this option when your issuer should guarantee kid uniqueness and a duplicate is a sign of misconfiguration worth surfacing at parse time rather than at verify time.
Can be set globally via `jwk.Settings()` or per-call on `jwk.Parse()` / `jwk.ParseReader()` / `jwk.ParseString()`.
This does not affect `(*Set).AddKey` — programmatic additions remain permissive (AddKey dedupes only by pointer identity).
func WithStrictKeySetParsing ¶ added in v4.2.0
func WithStrictKeySetParsing(v bool) GlobalParseOption
WithStrictKeySetParsing restores the fail-fast behavior for JWK Set parsing: when true, the first entry in the "keys" array that cannot be parsed fails the entire set, as in older releases.
This is the same *policy* as v3's default (one unparseable entry fails the whole set), but it is policy parity, not error parity: v4 understands more key types than v3 (for example `AKP`), so an entry that fails under v3 may parse successfully under v4 — or fail at a different stage, with a different error.
By default this option is false. In the default (retain) mode, an unparseable entry is neither dropped nor fatal — it is kept in the set as a `jwk.UnsupportedKey` placeholder that preserves the entry's original JSON and the error that prevented parsing (RFC 7517 §5). This lets a set that mixes understood and not-yet-understood keys (for example, post-quantum keys published by an identity provider) remain usable for the keys you do understand.
Use this option when your issuer guarantees every key is parseable and a failure should surface immediately at parse time rather than later at key-selection time.
This option is distinct from `WithIgnoreParseError`, which silently *drops* unparseable entries instead of retaining placeholders. When both parsing modes are requested, an explicit per-call option beats the global setting: a per-call `WithIgnoreParseError(true)` selects drop mode even under a global strict setting, while an explicit per-call `WithStrictKeySetParsing(true)` in the same call wins over `WithIgnoreParseError(true)` (the set fails fast).
Can be set globally via `jwk.Settings()` or per-call on `jwk.Parse()` / `jwk.ParseReader()` / `jwk.ParseString()`. A per-call value takes precedence over the global setting in both directions: per-call false relaxes a global true, and per-call true tightens a global false. When passed per-call to `jwk.Parse()` whose input turns out to be a bare single JWK rather than a JWK Set, the option is ignored (it is set-scoped); `jwk.ParseKey()` still rejects it outright.
type Key ¶
type Key interface {
// Has returns true if the specified field has a value, even if
// the value is empty-ish (e.g. 0, false, "") as long as it has been
// explicitly set.
Has(string) bool
// Field returns the value of a key field by name, along with a boolean indicating
// whether the field was found. For type-safe access, use the `jwk.Get[T]()` generic accessor.
Field(string) (any, bool)
// Set sets the value of a single field. Note that certain fields,
// notably "kty", cannot be altered, but will not return an error
//
// This method, which takes an `any`, exists because
// these objects can contain extra _arbitrary_ fields that users can
// specify, and there is no way of knowing what type they could be
Set(string, any) error
// Remove removes the field associated with the specified key.
// There is no way to remove the `kty` (key type). You will ALWAYS be left with one field in a jwk.Key.
Remove(string) error
// Validate performs _minimal_ checks if the data stored in the key are valid.
// By minimal, we mean that it does not check if the key is valid for use in
// cryptographic operations. For example, it does not check if an RSA key's
// `e` field is a valid exponent, or if the `n` field is a valid modulus.
// Instead, it checks for things such as the _presence_ of some required fields,
// or if certain keys' values are of particular length.
//
// Note that depending on th underlying key type, use of this method requires
// that multiple fields in the key are properly populated. For example, an EC
// key's "x", "y" fields cannot be validated unless the "crv" field is populated first.
//
// Validate is never called by `UnmarshalJSON()` or `Set`. It must explicitly be
// called by the user
Validate() error
// Thumbprint returns the JWK thumbprint using the indicated
// hashing algorithm, according to RFC 7638. An error is returned if the
// hash is unavailable (e.g. crypto.Hash(0) or a hash whose package has
// not been imported); it does not panic.
Thumbprint(crypto.Hash) ([]byte, error)
// Keys returns a list of the keys contained in this jwk.Key.
Keys() []string
// Clone creates a new instance of the same type
Clone() (Key, error)
// PublicKey creates the corresponding PublicKey type for this object.
// All fields are copied onto the new public key, except for those that are not allowed.
//
// If the key is already a public key, it returns a new copy minus the disallowed fields as above.
PublicKey() (Key, error)
// KeyType returns the `kty` of a JWK
KeyType() jwa.KeyType
// KeyUsage returns `use` of a JWK
KeyUsage() (string, bool)
// KeyOps returns `key_ops` of a JWK
KeyOps() (KeyOperationList, bool)
// Algorithm returns the value of the `alg` field.
//
// This field may contain either `jwk.SignatureAlgorithm`, `jwk.KeyEncryptionAlgorithm`, or `jwk.ContentEncryptionAlgorithm`.
// This is why there exists a `jwa.KeyAlgorithm` type that encompasses both types.
Algorithm() (jwa.KeyAlgorithm, bool)
// KeyID returns `kid` of a JWK
KeyID() (string, bool)
// X509URL returns `x5u` of a JWK
X509URL() (string, bool)
// X509CertChain returns `x5c` of a JWK
X509CertChain() (*cert.Chain, bool)
// X509CertThumbprint returns `x5t` of a JWK
X509CertThumbprint() (string, bool)
// X509CertThumbprintS256 returns `x5t#S256` of a JWK
X509CertThumbprintS256() (string, bool)
}
Key defines the minimal interface for each of the key types. Their use and implementation differ significantly between each key type, so you should use type assertions to perform more specific tasks with each key
func ParseKey ¶
func ParseKey(data []byte, options ...ParseOption) (Key, error)
ParseKey parses a single key JWK and returns it as a Key. Unlike Parse this method reports failure if the input is a JWK set. Only use this function when you know that the data is a single JWK.
Given a WithX509(true) option, this function assumes that the given input is a PEM-framed X.509-encoded key.
Note that a successful parsing of any type of key does NOT necessarily guarantee a valid key. For example, no checks against expiration dates are performed for certificate expiration, no checks against missing parameters are performed, etc.
In particular, the "alg" value is stored as-is and is NOT validated against the key type, curve, or key size at parse time. This is intentional: per RFC 7517 section 4.4, "alg" is an OPTIONAL, informational hint identifying the algorithm intended for use with the key, not a constraint on the key itself. An incompatible "alg" is rejected when the key is used in a JOSE operation, not at parse time. Parse-time alg-vs-kty validation must NOT be added.
Use ParseKeyAs when a concrete key subtype (e.g. RSAPrivateKey, ECDSAPublicKey) is required.
func PublicKeyOf ¶
PublicKeyOf returns the corresponding public version of the jwk.Key. If `v` is a SymmetricKey, then the same value is returned. If `v` is already a public key, the key itself is returned.
If `v` is a private key type that has a `PublicKey()` method, be aware that all fields will be copied onto the new public key. It is the caller's responsibility to remove any fields, if necessary
If `v` is a raw key, the key is first converted to a `jwk.Key`.
Symmetric (oct) key pass-through: a symmetric key has no distinct public counterpart, so `PublicKeyOf` returns it unchanged. This is intentional, but it means the returned value is NOT safe to publish: doing so would leak the shared secret. Callers who intend to publish the result (for example as part of a `/.well-known/jwks.json` document) must filter out symmetric keys themselves, or use `PublicSetOf`, which rejects symmetric keys by default and requires an explicit `jwk.WithAllowSymmetric(true)` opt-in for the legacy pass-through behavior.
type KeyExportFunc ¶
KeyExportFunc is a convenience type to implement KeyExporter as a function.
type KeyExporter ¶
type KeyExporter interface {
// Export takes the `jwk.Key` to be converted, and an optional hint
// indicating the desired output type. The hint may be nil, in which
// case the exporter should return the default/natural type for the key.
//
// Export should return jwk.ContinueError if the key is not compatible
// with this exporter, so that the next exporter can be tried.
Export(Key, any) (any, error)
}
KeyExporter is used to convert from a `jwk.Key` to a raw key. From the PoV of the `jwk.Key`, we're _exporting_ it to a raw key.
type KeyImportFunc ¶
KeyImportFunc is the typed-function adapter that satisfies KeyImporter for type T. The Import method just calls f directly — no internal type assertion is needed because KeyImporter's Import is itself typed.
This is the canonical way to register a typed import function:
jwk.RegisterKeyImporter(jwk.KeyImportFunc[*mypkg.Key](importMyKey))
For an importer with non-trivial state, implement KeyImporter on your own type and pass an instance of it directly.
func (KeyImportFunc[T]) Import ¶
func (f KeyImportFunc[T]) Import(raw T) (Key, error)
type KeyImporter ¶
type KeyImporter[T any] interface { // Import takes the raw key to be converted, and returns a // [jwk.Key] or an error if the conversion fails. Import(raw T) (Key, error) }
KeyImporter converts a raw key of Go type T into a jwk.Key. The type parameter T is the raw-key type the importer handles. From the point of view of the `jwk.Key`, we're _importing_ a raw key.
Implementations are registered with RegisterKeyImporter; T flows through to reflect.TypeFor at registration time to key the import dispatch table.
type KeyKind ¶
type KeyKind string
KeyKind identifies a key for exporter dispatch. Built-in key types use the key type string (e.g. "RSA", "EC", "OKP", "oct"). Keys that implement KeyKinder can return a more specific identity (e.g. "OKP:Ed448") to select a curve-specific exporter.
KeyKind values are compared case-insensitively: both registration and lookup normalize to uppercase, so "OKP:Ed448" and "okp:ed448" resolve to the same entry.
See RegisterKeyExporter for details on how KeyKind values are used during export dispatch and how to register exporters for custom key types.
type KeyKinder ¶
type KeyKinder interface {
KeyKind() KeyKind
}
KeyKinder is implemented by keys that need exporter dispatch beyond just their key type.
See KeyKind and RegisterKeyExporter for details on how the returned value is used during export.
type KeyOperation ¶
type KeyOperation string
const ( KeyOpSign KeyOperation = "sign" // (compute digital signature or MAC) KeyOpVerify KeyOperation = "verify" // (verify digital signature or MAC) KeyOpEncrypt KeyOperation = "encrypt" // (encrypt content) KeyOpDecrypt KeyOperation = "decrypt" // (decrypt content and validate decryption, if applicable) KeyOpWrapKey KeyOperation = "wrapKey" // (encrypt key) KeyOpUnwrapKey KeyOperation = "unwrapKey" // (decrypt key and validate decryption, if applicable) KeyOpDeriveKey KeyOperation = "deriveKey" // (derive key) KeyOpDeriveBits KeyOperation = "deriveBits" // (derive bits not to be used as a key) )
type KeyOperationList ¶
type KeyOperationList []KeyOperation
func (*KeyOperationList) Accept ¶
func (ops *KeyOperationList) Accept(v any) error
func (*KeyOperationList) Get ¶
func (ops *KeyOperationList) Get() KeyOperationList
type KeyParseFunc ¶
type KeyParseFunc func(probe *KeyProbe, unmarshaler KeyUnmarshaler, payload []byte) (Key, error)
KeyParseFunc is a type of KeyParser that is based on a function/closure
func (KeyParseFunc) ParseKey ¶
func (f KeyParseFunc) ParseKey(probe *KeyProbe, unmarshaler KeyUnmarshaler, payload []byte) (Key, error)
type KeyParser ¶
type KeyParser interface {
// ParseKey parses a JSON payload to a `jwk.Key` object. The first
// argument is an object that contains some hints as to what kind of
// key the JSON payload contains.
//
// If your KeyParser decides that the payload is not something
// you can parse, and you would like to continue parsing with
// the remaining KeyParser instances that are registered,
// return a `jwk.ContinueError()`. Any other errors will immediately
// halt the parsing process.
//
// When unmarshaling JSON, use the unmarshaler object supplied as
// the second argument. This will ensure that the JSON is unmarshaled
// in a way that is compatible with the rest of the library.
ParseKey(probe *KeyProbe, unmarshaler KeyUnmarshaler, payload []byte) (Key, error)
}
KeyParser represents a type that can parse a JSON representation of a JWK into a jwk.Key. See KeyConvertor for a type that can convert a raw key into a jwk.Key
type KeyProbe ¶
type KeyProbe struct {
// contains filtered or unexported fields
}
KeyProbe is the object that carries the hints when parsing a key. The exact list of fields can vary depending on the types of key that are registered.
Use `Field()` to access the value of a field.
type KeyTypeMismatchError ¶
type KeyTypeMismatchError struct {
// Got is the runtime type of the value the library produced.
Got reflect.Type
// Want is the type requested via the function's type parameter.
Want reflect.Type
}
KeyTypeMismatchError is returned by Import / ParseKeyAs / Export / ExportAll when the value the function produced does not match the generic type parameter supplied by the caller.
Got is the runtime type of the value the library produced; Want is the type the caller asked for via the type parameter. Callers that need to distinguish "wrong generic type parameter" from other failures should use errors.Is with KeyTypeMismatchError{}, or errors.AsType to recover the Got and Want fields.
func (KeyTypeMismatchError) Error ¶
func (e KeyTypeMismatchError) Error() string
func (KeyTypeMismatchError) Is ¶
func (e KeyTypeMismatchError) Is(target error) bool
type KeyUnmarshaler ¶
KeyUnmarshaler is a thin wrapper around json.Unmarshal. It behaves almost exactly like json.Unmarshal, but it allows us to add extra magic that is specific to this library before calling the actual json.Unmarshal.
type KeyUsageType ¶
type KeyUsageType string
KeyUsageType is used to denote what this key should be used for
const ( // ForSignature is the value used in the headers to indicate that // this key should be used for signatures ForSignature KeyUsageType = "sig" // ForEncryption is the value used in the headers to indicate that // this key should be used for encrypting ForEncryption KeyUsageType = "enc" )
func (*KeyUsageType) Accept ¶
func (k *KeyUsageType) Accept(v any) error
func (KeyUsageType) String ¶
func (k KeyUsageType) String() string
type KeyWithDecodeCtx ¶
type OKPPrivateKey ¶
type OKPPublicKey ¶
type OKPRawKeyImporter ¶
type OKPRawKeyImporter interface {
ImportOKPRawKey(key any) (crv jwa.EllipticCurveAlgorithm, x, d []byte, ok bool)
}
OKPRawKeyImporter is an extension point for importing raw keys as OKP JWK fields. Extension modules (for example ed448, x448) register an implementation via RegisterOKPRawKeyImporter; the default OKP import path consults every registered importer when it encounters an unknown raw key type.
ImportOKPRawKey inspects key and, if it recognises the concrete type, returns the corresponding curve, the x component, the d component (nil for public keys), and ok=true. Implementations must return ok=false for unrecognised types so the next importer can be tried.
type OKPRawKeyImporterFunc ¶
type OKPRawKeyImporterFunc func(key any) (crv jwa.EllipticCurveAlgorithm, x, d []byte, ok bool)
OKPRawKeyImporterFunc is a function adapter for OKPRawKeyImporter, letting callers register a plain function without defining a dedicated type.
func (OKPRawKeyImporterFunc) ImportOKPRawKey ¶
func (f OKPRawKeyImporterFunc) ImportOKPRawKey(key any) (jwa.EllipticCurveAlgorithm, []byte, []byte, bool)
type ParseOption ¶
type ParseOption interface {
Option
// contains filtered or unexported methods
}
ParseOption is a type of Option that can be passed to `jwk.Parse()`
func WithIgnoreParseError ¶
func WithIgnoreParseError(v bool) ParseOption
WithIgnoreParseError is only applicable when used with `jwk.Parse()` (i.e. to parse JWK sets). If passed to `jwk.ParseKey()`, the function will return an error no matter what the input is.
DO NOT USE WITHOUT EXHAUSTING ALL OTHER ROUTES FIRST.
The option specifies that errors found during parsing of individual keys are ignored. For example, if you had keys A, B, C where B is invalid (e.g. it does not contain the required fields), then the resulting JWKS will contain keys A and C only.
This options exists as an escape hatch for those times when a key in a JWKS that is irrelevant for your use case is causing your JWKS parsing to fail, and you want to get to the rest of the keys in the JWKS.
Again, DO NOT USE unless you have exhausted all other routes. When you use this option, you will not be able to tell if you are using a faulty JWKS, except for when there are JSON syntax errors.
Precedence versus `WithStrictKeySetParsing`: an explicit per-call option beats the global setting. Passing `WithIgnoreParseError(true)` to `jwk.Parse()` selects drop mode even when strict mode was enabled globally via `jwk.Settings()`. Only when the same call also passes an explicit `WithStrictKeySetParsing(true)` does strict mode win (the whole set fails fast).
This option has no effect on direct JSON unmarshaling into a `jwk.Set` (there is no per-call option channel there): direct unmarshaling retains unparseable entries as `jwk.UnsupportedKey` placeholders by default, or fails fast under a global strict setting.
func WithTypedField ¶
func WithTypedField(name string, object any) ParseOption
WithTypedField allows a private field to be parsed into the object type of your choice. It works much like the RegisterCustomField, but the effect is only applicable to the jwt.Parse function call which receives this option.
While this can be extremely useful, this option should be used with caution: There are many caveats that your entire team/user-base needs to be aware of, and therefore in general its use is discouraged. Only use it when you know what you are doing, and you document its use clearly for others.
First and foremost, this is a "per-object" option. Meaning that given the same serialized format, it is possible to generate two objects whose internal representations may differ. That is, if you parse one _WITH_ the option, and the other _WITHOUT_, their internal representation may completely differ. This could potentially lead to problems.
Second, specifying this option will slightly slow down the decoding process as it needs to consult multiple definitions sources (global and local), so be careful if you are decoding a large number of tokens, as the effects will stack up.
func WithX509 ¶
func WithX509(v bool) ParseOption
WithX509 specifies that the input to `Parse()` / `ParseKey()` is a PEM-framed X.509-encoded key (or key set). Custom PEM block types can be handled by registering decoders via `jwkbb.RegisterX509Decoder`.
type PublicKeyer ¶
type PublicSetOption ¶
type PublicSetOption interface {
Option
// contains filtered or unexported methods
}
PublicSetOption is a type of Option that can be passed to `jwk.PublicSetOf()`
func WithAllowSymmetric ¶
func WithAllowSymmetric(v bool) PublicSetOption
WithAllowSymmetric controls whether `jwk.PublicSetOf` tolerates symmetric (oct) keys in the input set.
By default this option is false: a symmetric key in the input is an error, because a symmetric key has no public form — its "public" representation is the secret itself. Passing such a set through `PublicSetOf` silently and then publishing the result (e.g. as `/.well-known/jwks.json`) would leak HMAC secret material.
Pass `WithAllowSymmetric(true)` only if you are certain the resulting set will not be published. When true, symmetric keys are passed through unchanged, matching the legacy behavior.
func WithOmitUnsupportedKeys ¶ added in v4.2.0
func WithOmitUnsupportedKeys(v bool) PublicSetOption
WithOmitUnsupportedKeys controls how `jwk.PublicSetOf` treats `jwk.UnsupportedKey` placeholders in the input set.
By default this option is false: a placeholder in the input is an error, because there is no way to prove that an unparseable entry contains no private material, and passing it through would risk republishing a private key.
Pass `WithOmitUnsupportedKeys(true)` to drop placeholders from the output set instead. Use this when you intend to publish the public set and want unparseable entries silently excluded.
type RSAPrivateKey ¶
type Set ¶
type Set interface {
// AddKey adds the specified key. If the key already exists in the set,
// an error is returned.
AddKey(Key) error
// Clear resets the list of keys associated with this set, emptying the
// internal list of `jwk.Key`s, as well as clearing any other non-key
// fields
Clear() error
// Get returns the key at index `idx`. If the index is out of range,
// then the second return value is false.
Key(int) (Key, bool)
// Field returns the value of a private field in the key set, along
// with a boolean indicating whether the field was found.
//
// For the purposes of a key set, any field other than the "keys" field is
// considered to be a private field. In other words, you cannot use this
// method to directly access the list of keys in the set
Field(string) (any, bool)
// Set sets the value of a single field.
//
// This method, which takes an `any`, exists because
// these objects can contain extra _arbitrary_ fields that users can
// specify, and there is no way of knowing what type they could be.
Set(string, any) error
// Remove removes the specified non-key field from the set.
// Keys may not be removed using this method. See RemoveKey for
// removing keys.
Remove(string) error
// Index returns the index where the given key exists, -1 otherwise
Index(Key) int
// Len returns the number of keys in the set
Len() int
// LookupKeyID returns the first key matching the given key id.
//
// The second return value is false if there are no keys matching the key id.
// The set *may* contain multiple keys with the same key id. If you
// need all of them, Len() and Key(int)
//
// This method is meant to be used to lookup a key with a unique ID.
// Bacauseof this, you cannot use this method to lookup keys with an empty key ID
// (i.e. `kid` is not specified, or is an empty string).
LookupKeyID(string) (Key, bool)
// RemoveKey removes the key from the set.
// RemoveKey returns an error when the specified key does not exist
// in set.
RemoveKey(Key) error
// Keys returns the list of keys present in the Set, except for `keys`.
// e.g. if you had `{"keys": ["a", "b"], "c": .., "d": ...}`, this method would
// return `["c", "d"]`. Note that the order of the keys is not guaranteed.
//
// TODO: name is confusing between this and Key()
Keys() []string
// All returns an iterator over all keys in the set, yielding
// (index, key) pairs.
//
// Each iteration starts by copying the set's list of keys, and loops
// over that snapshot. The set may therefore be modified inside the
// loop, and changes made there are not seen by the running iteration.
// The keys themselves are shared, not cloned. To walk the keys without
// the copy, index with Len and Key.
All() iter.Seq2[int, Key]
// Fields returns an iterator over all non-key fields in the set
// (i.e. private parameters), yielding (name, value) pairs.
//
// Each iteration starts by copying the set's map of fields, and loops
// over that snapshot. The set may therefore be modified inside the
// loop, and changes made there are not seen by the running iteration.
// The field values themselves are shared, not cloned.
Fields() iter.Seq2[string, any]
// Clone create a new set with identical keys. Keys themselves are not cloned.
Clone() (Set, error)
}
Set represents JWKS object, a collection of jwk.Key objects.
Sets can be marshaled and unmarshaled with the standard `"encoding/json".Marshal` and `"encoding/json".Unmarshal`. The unmarshal path requires JWKS shape (an object with a "keys" field). For input that may be either a single bare JWK or a JWKS, use Parse, which dispatches between the two shapes and always returns a `jwk.Set`.
JWKS-level extension members (any top-level field other than "keys") are preserved as set-level private parameters and are accessible via the `Field()` method. Per-key extension members live on the individual `jwk.Key` objects, accessible via that key's `Field()`.
A set parsed from JSON may contain UnsupportedKey placeholders for entries that could not be parsed; they count toward Len(), appear in iteration, and are found by LookupKeyID. Use IsUnsupportedKey to skip them before performing cryptographic operations.
The set returned by NewSet and Parse takes a lock in every method, so one goroutine may change it while another reads it. A loop over Len and Key does not hold that lock between calls, though. When another goroutine removes a key at or before the loop's current index, the next key moves down into an index the loop has already read, and the loop skips it. Key returns false once the index passes the new end. jws.Verify and jwe.Decrypt walk a set given through WithKeySet this way, so removing keys from that set while they run can make them skip the matching key and fail. To rotate keys that concurrent calls are using, build a new set and swap it in for the old one, leaving the old set unchanged.
func Parse ¶
func Parse(src []byte, options ...ParseOption) (Set, error)
Parse parses JWK from the incoming []byte.
For JWK sets, this is a convenience function. You could just as well call `json.Unmarshal` against an empty set created by `jwk.NewSet()` to parse a JSON buffer into a `jwk.Set`.
This function exists because many times the user does not know before hand if a JWK(s) resource at a remote location contains a single JWK key or a JWK set, and `jwk.Parse()` can handle either case, returning a JWK Set even if the data only contains a single JWK key
When the input is a JWK Set, an entry in the "keys" array that cannot be parsed does not fail the set: by default it is retained as an UnsupportedKey placeholder (RFC 7517 §5), so the returned set can contain placeholders alongside usable keys. Use IsUnsupportedKey to detect them. Pass WithStrictKeySetParsing to fail the whole set instead, or WithIgnoreParseError to drop such entries.
If you are looking for more information on how JWKs are parsed, or if you know for sure that you have a single key, please see the documentation for `jwk.ParseKey()`.
func ParseReader ¶
func ParseReader(src io.Reader, options ...ParseOption) (Set, error)
ParseReader parses a JWK set from the incoming byte buffer.
func ParseString ¶
func ParseString(s string, options ...ParseOption) (Set, error)
ParseString parses a JWK set from the incoming string.
func PublicSetOf ¶
func PublicSetOf(v Set, options ...PublicSetOption) (Set, error)
PublicSetOf returns a new jwk.Set consisting of public keys of the keys contained in the set.
This is useful when you are generating a set of private keys, and you want to generate the corresponding public versions for the users to verify with.
By default, if the input set contains a symmetric (oct) key, this function returns an error: a symmetric key has no public form, and its "public" representation would be the secret itself. Publishing such a set (e.g. as `/.well-known/jwks.json`) would leak secret material. Callers who explicitly want the legacy pass-through behavior can opt in with `jwk.WithAllowSymmetric(true)`.
Be aware that for asymmetric private keys, all fields will be copied onto the new public key. It is the caller's responsibility to remove any fields, if necessary.
func ReadFile
deprecated
func ReadFile(path string, options ...ParseOption) (Set, error)
ReadFile opens path with os.Open and parses the contents. It accepts any path os.Open accepts, including absolute paths.
Deprecated: prefer ParseFS, which works with any fs.FS (e.g. os.DirFS, embed.FS, testing/fstest). ReadFile is retained for v3 source compatibility.
type SymmetricKey ¶
type UnknownKeyTypeError ¶ added in v4.0.2
type UnknownKeyTypeError struct {
// KeyType is the raw "kty" value the input carried, or "" when
// "kty" was missing or non-string.
KeyType string
}
UnknownKeyTypeError is returned by Parse / ParseKey / ParseKeyAs when the input's "kty" hint cannot be resolved to a known key family.
KeyType is empty when the input had no "kty" field at all, or when "kty" was present but not a JSON string (the probe could not extract a usable identifier). KeyType is populated when the input carried a string "kty" that didn't match any registered key family — useful for callers that want to suggest installing an extension module.
Use errors.Is with UnknownKeyTypeError{} to recognize the condition, or errors.AsType to recover the KeyType field. The error chain also satisfies errors.Is with ParseError.
func (UnknownKeyTypeError) Error ¶ added in v4.0.2
func (e UnknownKeyTypeError) Error() string
func (UnknownKeyTypeError) Is ¶ added in v4.0.2
func (UnknownKeyTypeError) Is(target error) bool
type UnsupportedKey ¶ added in v4.2.0
type UnsupportedKey interface {
Key
// Reason returns the error that prevented the entry from parsing.
Reason() error
// contains filtered or unexported methods
}
UnsupportedKey is a placeholder for a JWK Set entry that could not be parsed into a usable key. Per RFC 7517 §5, an entry inside a "keys" array whose key type is not understood, that is missing required members, or whose values are out of the supported range no longer fails the whole set: it is retained as an UnsupportedKey.
A placeholder preserves the entry's original JSON — marshaling it with json.Marshal (alone or as part of its set) reproduces the entry, so a set containing one round-trips losslessly — and it preserves the error that prevented parsing (via UnsupportedKey.Reason).
An UnsupportedKey cannot be used for any cryptographic operation: [UnsupportedKey.Thumbprint], [UnsupportedKey.PublicKey] and [UnsupportedKey.Validate] all return an error wrapping Reason(), and the key is rejected by cryptographic consumers such as jws.Verify / jwe.Decrypt with a descriptive per-key error.
Use IsUnsupportedKey to check whether a key is a placeholder. Use a type assertion when you also need the placeholder's details:
if uk, ok := key.(jwk.UnsupportedKey); ok {
// key type key.KeyType() is not supported by this build;
// uk.Reason() explains why, an extension module may be required.
}
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
registry
Package registry provides an internal registry of JWK key constructors.
|
Package registry provides an internal registry of JWK key constructors. |
|
Package jwkunsafe provides low-level JWK key construction functions.
|
Package jwkunsafe provides low-level JWK key construction functions. |