Documentation
¶
Overview ¶
Package dpop implements OAuth 2.0 Demonstrating Proof of Possession (RFC 9449): clients build DPoP proof JWTs for HTTP requests with Signer and ForRequest; servers verify them with VerifyRequestClaims or VerifyClaimsContext and bind the resulting key thumbprint to the access token "cnf.jkt" claim.
Verification is opt-in beyond the proof itself. Set VerifyConfig.ReplayCache to reject a replayed jti: NewMemoryReplayCache for one process, or NewSharedReplayCache over a store that all instances of the server share, such as Redis (SET NX with an expiry); without it replay detection is the caller's job. At a protected resource set both AccessToken, to require a matching "ath" claim, and ExpectedThumbprint, to the token "cnf.jkt"; these are per-request values, so set them on a copy of a shared config. Set ExternalURL when the server's public scheme or host differs from the request it receives:
cfg := dpop.VerifyConfig{
ExternalURL: "https://api.example.com",
ReplayCache: replayCache, // shared by all requests
AccessToken: accessToken,
ExpectedThumbprint: cnfJKT,
}
res, err := dpop.VerifyRequestClaims(cfg, req)
Set VerifyConfig.NonceSource to require server-provided nonces (RFC 9449 §8 and §9), which bound the age of a proof by the server's clock and stop proofs generated in advance. NewHMACNonceSource needs no store: every instance with the same secrets, label and rotation issues and accepts the same nonces. A proof without a recent nonce fails with an error that errors.Is matches to ErrUseDPoPNonce; the server answers it with NonceSource.Nonce in the NonceHTTPHeader (DPoP-Nonce) header, as an HTTP 400 error with the code ErrorUseDPoPNonce from an authorization server or an HTTP 401 with UseDPoPNonceChallenge from a resource server, and the client retries with map[string]any{dpop.ClaimNonce: nonce} as the ForRequest extra claims. A server may also send a new nonce in any other response, for example when NonceSource.Nonce differs from the nonce claim of the proof it just accepted, which saves clients the use_dpop_nonce round trip when the nonce changes; responses that carry one should not be cached.
A proof can be signed with an ML-DSA key (NewSigner with any crypto.Signer whose public key is an *mldsa.PublicKey): RFC 9964 algorithms are accepted, and the embedded jwk is an AKP key. An ML-DSA proof carries the public key and the signature, about 6 KB with ML-DSA-44, 8 KB with ML-DSA-65 and 11 KB with ML-DSA-87, which can exceed the header limit of an HTTP server or proxy.
Clients add the "ath" claim with map[string]any{dpop.ClaimAccessTokenHash: dpop.AccessTokenHash(token)} as the ForRequest extra claims.
Index ¶
- Constants
- Variables
- func AccessTokenHash(accessToken string) string
- func ForRequest(p Signer, r *http.Request, extraClaims any) (string, error)
- func GenerateKey(label string) (*jose.JSONWebKey, error)
- func GetCnfClaim(claims map[string]any) (string, error)
- func LoadKey(path string) (*jose.JSONWebKey, string, error)
- func SaveKey(folder string, k *jose.JSONWebKey) (string, error)
- func SetCnfClaim(claims map[string]any, thumbprint string)
- func Thumbprint(k *jose.JSONWebKey) (string, error)
- type HMACNonceConfig
- type HMACNonceSource
- type MemoryReplayCache
- type NonceSource
- type ReplayCache
- type ReplayStore
- type ReplayStoreFunc
- type Result
- type SharedReplayCache
- type SharedReplayCacheConfig
- type Signer
- type TokenInfo
- type VerifyConfig
Examples ¶
Constants ¶
const ( // HTTPHeader header name for DPoP HTTPHeader = "DPoP" // ContentType value ContentType = "application/dpop+jwt" )
const ( // DefaultExpiration for the proof DefaultExpiration = time.Minute * 10 // DefaultNotBefore offset for NotBefore DefaultNotBefore = -10 * time.Minute )
const ( // CnfThumbprint is the claim name for JKT thumbprint CnfThumbprint = "jkt" // ClaimAccessTokenHash is the proof claim name for the access token hash ClaimAccessTokenHash = "ath" )
https://datatracker.ietf.org/doc/html/draft-ietf-oauth-dpop-04
const ( // NonceHTTPHeader is the response header that carries a server-provided // nonce (RFC 9449 §8). A response has at most one, and a response that // carries it should be uncacheable (Cache-Control: no-store). NonceHTTPHeader = "DPoP-Nonce" // ClaimNonce is the proof claim that carries the server-provided nonce. // Clients add it to the ForRequest extra claims: // map[string]any{dpop.ClaimNonce: nonce}. ClaimNonce = "nonce" // ErrorUseDPoPNonce is the OAuth error code of a response that asks the // client to retry with the nonce in the DPoP-Nonce header: an HTTP 400 // error response from an authorization server (RFC 9449 §8), or an HTTP // 401 with UseDPoPNonceChallenge from a resource server (§9). ErrorUseDPoPNonce = "use_dpop_nonce" // UseDPoPNonceChallenge is the WWW-Authenticate value of a resource // server's HTTP 401 response that asks for a nonce (RFC 9449 §9). UseDPoPNonceChallenge = `DPoP error="use_dpop_nonce", error_description="Resource server requires nonce in DPoP proof"` )
const ( // DefaultNonceRotation is how often HMACNonceSource issues a new nonce // when HMACNonceConfig.Rotation is zero. DefaultNonceRotation = 5 * time.Minute // MinNonceRotation is the shortest HMACNonceConfig.Rotation. MinNonceRotation = time.Second // MaxNonceRotation is the longest HMACNonceConfig.Rotation: a nonce is // meant to limit the life of a proof to minutes (RFC 9449 §11.1). MaxNonceRotation = time.Hour // MinNonceSecretSize is the minimum size in bytes of every // HMACNonceConfig secret. MinNonceSecretSize = 32 )
const ( // DefaultReplayKeyPrefix is the prefix SharedReplayCache puts before // every key it stores when SharedReplayCacheConfig.KeyPrefix is empty. DefaultReplayKeyPrefix = "dpop:jti:" // DefaultReplayClockSkew is how long SharedReplayCache keeps a key // beyond the expiry the verifier asked for when // SharedReplayCacheConfig.ClockSkew is zero. It covers the clock // differences between the instances that share the store. DefaultReplayClockSkew = time.Minute )
const DefaultReplayCacheSize = 100000
DefaultReplayCacheSize is the capacity used by NewMemoryReplayCache when the requested size is not positive. Size the cache as peak accepted proofs per second times the acceptance window (DefaultExpiration plus jwt.DefaultTimeSkew).
Variables ¶
var ( // ErrReplay is returned when a proof with the same key and jti was // already accepted within its acceptance window. ErrReplay = errors.New("dpop: proof replayed") // ErrReplayCacheFull is returned by MemoryReplayCache when every entry // is still unexpired. The proof is rejected (fail closed). ErrReplayCacheFull = errors.New("dpop: replay cache is full") )
var ErrUseDPoPNonce = errors.New("dpop: server nonce required")
ErrUseDPoPNonce is matched by errors.Is for a proof that VerifyClaims rejects because its nonce claim is missing, unknown or stale. The server answers with a fresh nonce in the DPoP-Nonce header and the ErrorUseDPoPNonce error code, and the client retries with that nonce.
var TimeNowFn = time.Now
TimeNowFn to override in unit tests
Functions ¶
func AccessTokenHash ¶
AccessTokenHash returns the ath claim value for accessToken: the base64url-encoded SHA-256 hash of its ASCII value (RFC 9449 §4.2). Clients add it to the proof extra claims when calling a protected resource.
func ForRequest ¶
ForRequest creates a DPoP proof for the request method and URL and sets it as the DPoP header; the proof is also returned.
func GenerateKey ¶
func GenerateKey(label string) (*jose.JSONWebKey, error)
GenerateKey returns JSONWebKey to sign JWT
func GetCnfClaim ¶
GetCnfClaim gets DPoP `cnf` claim
func LoadKey ¶
func LoadKey(path string) (*jose.JSONWebKey, string, error)
LoadKey returns *jose.JSONWebKey
func SaveKey ¶
func SaveKey(folder string, k *jose.JSONWebKey) (string, error)
SaveKey saves the key to storage
func SetCnfClaim ¶
SetCnfClaim sets DPoP `cnf` claim
func Thumbprint ¶
func Thumbprint(k *jose.JSONWebKey) (string, error)
Thumbprint returns key thumbprint. An invalid key, such as an uninitialized ML-DSA key, on which go-jose panics, is an error.
Types ¶
type HMACNonceConfig ¶ added in v2.0.330
type HMACNonceConfig struct {
// Secrets are the HMAC keys, each at least MinNonceSecretSize bytes from
// crypto/rand. The first issues nonces; every one is accepted. Every
// instance of a server uses the same list. To rotate, append the new
// secret on every instance, then move it first on every instance, and
// remove the old one 2 * Rotation, plus the clock difference between the
// instances, after the last instance moved it.
Secrets [][]byte
// Rotation is how often a new nonce is issued; zero means
// DefaultNonceRotation, and it must be between MinNonceRotation and
// MaxNonceRotation. It is part of the nonce MAC: every instance uses the
// same value, and a change rejects the nonces in use once.
Rotation time.Duration
// Label keeps apart the nonces of servers that share secrets, such as
// an authorization server and a resource server, whose nonces must not
// be accepted by each other (RFC 9449 §9). Every instance of a server
// uses the same label.
Label string
}
HMACNonceConfig configures NewHMACNonceSource.
type HMACNonceSource ¶ added in v2.0.330
type HMACNonceSource struct {
// contains filtered or unexported fields
}
HMACNonceSource is a NonceSource that needs no store: a nonce is the number of the time window it was issued in, authenticated with HMAC-SHA256 under a secret that every instance of the server shares. All clients get the same nonce during a window: RFC 9449 leaves the scheme to the server (§8) and lets a nonce be used for more than one proof (§11.1), and the nonce cannot be predicted without the secret. A nonce is accepted in its own window and the next, so for at least Rotation and less than 2 * Rotation after it was issued; a nonce of the window after the current one, which an instance whose clock runs ahead issues, is accepted as well. The nonce bounds the age of a proof by the server's clock; the iat and exp claims are still checked. It uses TimeNowFn as its clock and is safe for concurrent use.
Example ¶
A server that issues nonces answers a proof without one, or with a stale one, with a use_dpop_nonce error and a fresh nonce in the DPoP-Nonce header; the client signs a new proof with that nonce and keeps using it until the server sends another.
package main
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"errors"
"fmt"
"net/http"
"net/url"
"github.com/effective-security/xpki/v2/jwt/dpop"
)
func main() {
secret := make([]byte, dpop.MinNonceSecretSize)
_, _ = rand.Read(secret) // the same secret on every instance of the server
nonces, _ := dpop.NewHMACNonceSource(dpop.HMACNonceConfig{
Secrets: [][]byte{secret},
Label: "api.example.com",
})
cfg := dpop.VerifyConfig{NonceSource: nonces}
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
signer, _ := dpop.NewSigner(key)
u, _ := url.Parse("https://api.example.com/v1/items")
ctx := context.Background()
proof, _ := signer.Sign(ctx, http.MethodGet, u, nil)
_, err := dpop.VerifyClaims(cfg, proof, http.MethodGet, u.String())
if errors.Is(err, dpop.ErrUseDPoPNonce) {
// a resource server answers HTTP 401 with WWW-Authenticate:
// dpop.UseDPoPNonceChallenge, an authorization server HTTP 400 with
// the error code dpop.ErrorUseDPoPNonce; both set the nonce header
nonce, _ := nonces.Nonce(ctx)
fmt.Println(err, "->", dpop.NonceHTTPHeader)
proof, _ = signer.Sign(ctx, http.MethodGet, u, map[string]any{dpop.ClaimNonce: nonce})
}
_, err = dpop.VerifyClaims(cfg, proof, http.MethodGet, u.String())
fmt.Println(err)
}
Output: dpop: claim not found: nonce -> DPoP-Nonce <nil>
func NewHMACNonceSource ¶ added in v2.0.330
func NewHMACNonceSource(cfg HMACNonceConfig) (*HMACNonceSource, error)
NewHMACNonceSource returns an HMACNonceSource for cfg. The secrets are copied.
func (*HMACNonceSource) Nonce ¶ added in v2.0.330
func (s *HMACNonceSource) Nonce(_ context.Context) (string, error)
Nonce returns the nonce of the current window; see NonceSource.
func (*HMACNonceSource) VerifyNonce ¶ added in v2.0.330
func (s *HMACNonceSource) VerifyNonce(_ context.Context, nonce string) error
VerifyNonce checks nonce; see NonceSource and HMACNonceSource.
type MemoryReplayCache ¶
type MemoryReplayCache struct {
// contains filtered or unexported fields
}
MemoryReplayCache is a bounded, process-local ReplayCache. Expired entries are evicted before a new key is admitted; when the cache is still full the new proof is rejected with ErrReplayCacheFull. Failing closed means a client that can mint valid proofs (at a token endpoint, any client) can fill the cache and have other proofs rejected for up to the acceptance window; size it for peak load and rate-limit proof sources. It uses TimeNowFn as its clock.
func NewMemoryReplayCache ¶
func NewMemoryReplayCache(maxEntries int) *MemoryReplayCache
NewMemoryReplayCache returns a MemoryReplayCache holding at most maxEntries unexpired proofs, or DefaultReplayCacheSize when maxEntries is not positive.
func (*MemoryReplayCache) Len ¶
func (c *MemoryReplayCache) Len() int
Len returns the number of retained entries, including entries that have expired but were not evicted yet.
type NonceSource ¶ added in v2.0.330
type NonceSource interface {
// Nonce returns the nonce to send in the DPoP-Nonce header now: with
// every use_dpop_nonce error, and in any other response when the
// server wants the client to move to a new nonce early.
Nonce(ctx context.Context) (string, error)
// VerifyNonce returns nil when nonce is one that this source issued
// recently. It returns an error that errors.Is matches to
// ErrUseDPoPNonce when nonce is empty, unknown or stale, and any other
// error when it cannot decide; VerifyClaims rejects the proof in both
// cases.
VerifyNonce(ctx context.Context, nonce string) error
}
NonceSource issues the nonces of a server and checks the nonce claim of the proofs it receives (RFC 9449 §8 and §9). VerifyConfig.NonceSource makes VerifyClaims require a nonce from it. Implementations must be safe for concurrent use.
type ReplayCache ¶
type ReplayCache interface {
// Add atomically records key through expiresAt (inclusive: the verifier
// still accepts a proof at that instant). It returns an error
// wrapping ErrReplay when key is already recorded and not expired, and
// any other error when the key cannot be recorded; VerifyClaims rejects
// the proof in both cases. Of concurrent Add calls for the same key,
// exactly one may succeed.
Add(ctx context.Context, key string, expiresAt time.Time) error
}
ReplayCache records accepted DPoP proofs so that VerifyClaims can reject a second use of the same proof (RFC 9449 §11.1). Implementations must be safe for concurrent use; a shared store (for example Redis SET NX with an expiry) is needed when several server instances accept proofs for the same resource.
type ReplayStore ¶ added in v2.0.330
type ReplayStore interface {
// SetIfAbsent stores key with a time to live of ttl when key is absent
// or expired, and reports whether it stored it. Of concurrent calls for
// the same key, from any instance, at most one may return true. The
// store must keep the key for at least ttl: one with a coarser expiry
// rounds ttl up, and a Redis that evicts keys under memory pressure
// (a maxmemory-policy other than noeviction) lets replays through, so
// use noeviction, which makes a full store an error and rejects the
// proof, or a dedicated instance. With Redis it is SET key value NX PX
// ttl, which go-redis offers as SetNX.
SetIfAbsent(ctx context.Context, key string, ttl time.Duration) (bool, error)
}
ReplayStore is the one operation SharedReplayCache needs from a store that several server instances share.
type ReplayStoreFunc ¶ added in v2.0.330
ReplayStoreFunc adapts a function to ReplayStore.
func (ReplayStoreFunc) SetIfAbsent ¶ added in v2.0.330
func (f ReplayStoreFunc) SetIfAbsent(ctx context.Context, key string, ttl time.Duration) (bool, error)
SetIfAbsent calls f.
type Result ¶
type Result struct {
Claims *jwtgo.Claims
Key *jose.JSONWebKey
// Thumbprint is the RFC 7638 SHA-256 thumbprint of Key, to compare
// with the access token cnf.jkt claim
Thumbprint string
// AccessTokenHash is the proof ath claim, if present
AccessTokenHash string
}
Result is returned from VerifyClaims
func VerifyClaims ¶
func VerifyClaims(cfg VerifyConfig, phdr, httpMethod, httpURI string) (*Result, error)
VerifyClaims is VerifyClaimsContext with context.Background().
func VerifyClaimsContext ¶
func VerifyClaimsContext(ctx context.Context, cfg VerifyConfig, phdr, httpMethod, httpURI string) (*Result, error)
VerifyClaimsContext verifies DPoP proof phdr for a request with httpMethod and httpURI (RFC 9449 §4.3) and returns its claims, key and key thumbprint. The signature is verified with the embedded public jwk before any claim is used. htu is compared with httpURI after URI normalization (scheme and host case-insensitive, path case-sensitive, query and fragment ignored). When set, cfg.AccessToken requires a matching ath claim and must be paired with cfg.ExpectedThumbprint, which requires the proof key to match the access token cnf.jkt; cfg.NonceSource or cfg.ExpectedNonce requires a server-provided nonce, rejecting a missing, unknown or stale one with an error that errors.Is matches to ErrUseDPoPNonce; cfg.ReplayCache records the proof after every other check passed, rejecting a replayed jti with ErrReplay. Without cfg.ReplayCache the caller is responsible for replay detection.
func VerifyRequestClaims ¶
func VerifyRequestClaims(cfg VerifyConfig, req *http.Request) (*Result, error)
VerifyRequestClaims verifies the DPoP proof of an HTTP request received by a server; see VerifyClaims. The htu claim is compared with the request URI built from cfg.ExternalURL, or else from the request URL and Host (https when the URL has no scheme), without query and fragment. The request context is passed to cfg.NonceSource and cfg.ReplayCache.
Example ¶
A protected resource verifies the proof sent with a DPoP-bound access token: htu against its trusted external origin, ath against the presented token, the proof key against the token cnf.jkt, and jti against a replay cache shared by all requests.
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"fmt"
"net/http"
"net/http/httptest"
"github.com/effective-security/xpki/v2/jwt/dpop"
)
func main() {
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
signer, _ := dpop.NewSigner(key)
accessToken := "access-token-bound-to-the-key"
cnfJKT := signer.JWKThumbprint() // from the access token cnf.jkt claim
// client
creq, _ := http.NewRequest(http.MethodGet, "https://api.example.com/v1/items?page=2", nil)
_, _ = dpop.ForRequest(signer, creq, map[string]any{
dpop.ClaimAccessTokenHash: dpop.AccessTokenHash(accessToken),
})
// server, behind a proxy that forwards the request as plain HTTP
replay := dpop.NewMemoryReplayCache(0)
cfg := dpop.VerifyConfig{
ExternalURL: "https://api.example.com",
ReplayCache: replay,
AccessToken: accessToken,
ExpectedThumbprint: cnfJKT,
}
sreq := httptest.NewRequest(http.MethodGet, "/v1/items?page=2", nil)
sreq.Host = "backend:8080"
sreq.Header.Set(dpop.HTTPHeader, creq.Header.Get(dpop.HTTPHeader))
res, err := dpop.VerifyRequestClaims(cfg, sreq)
fmt.Println(err, res.Claims.HTTPUri)
_, err = dpop.VerifyRequestClaims(cfg, sreq)
fmt.Println(err)
}
Output: <nil> https://api.example.com/v1/items dpop: proof rejected: dpop: proof replayed
type SharedReplayCache ¶ added in v2.0.330
type SharedReplayCache struct {
// contains filtered or unexported fields
}
SharedReplayCache is a ReplayCache over a ReplayStore, for servers that run several instances: a proof accepted by one instance is a replay for all of them. Each Add is one SetIfAbsent with a relative time to live, from TimeNowFn to expiresAt, which the store counts on its own clock: the clock of the store does not matter, and the clocks of the instances need to agree within ClockSkew. A store error rejects the proof (fail closed).
func NewSharedReplayCache ¶ added in v2.0.330
func NewSharedReplayCache(store ReplayStore, cfg SharedReplayCacheConfig) (*SharedReplayCache, error)
NewSharedReplayCache returns a SharedReplayCache that records proofs in store. A go-redis client fits ReplayStore with ReplayStoreFunc:
store := dpop.ReplayStoreFunc(func(ctx context.Context, key string, ttl time.Duration) (bool, error) {
return rdb.SetNX(ctx, key, 1, ttl).Result()
})
type SharedReplayCacheConfig ¶ added in v2.0.330
type SharedReplayCacheConfig struct {
// other data in the store; empty means DefaultReplayKeyPrefix. Servers
// that accept proofs for different resources may share one prefix: the
// key is scoped by the proof key thumbprint and jti, not the resource.
KeyPrefix string
// instance whose clock is behind still finds the key while it accepts
// the proof; zero means DefaultReplayClockSkew. It must not be negative.
ClockSkew time.Duration
}
SharedReplayCacheConfig configures NewSharedReplayCache.
type Signer ¶
type Signer interface {
// Sign returns DPoP token
Sign(ctx context.Context, method string, u *url.URL, extraClaims any) (string, error)
// JWKThumbprint returns base64 hash of the key
JWKThumbprint() string
}
Signer specifies an interface to sign HTTP requests with DPoP
type TokenInfo ¶
type TokenInfo struct {
Token *jwt.JSONWebToken
Claims jwtgo.Claims
Key *jose.JSONWebKey
Thumbprint string
CnfJkt string
IsPublicKey bool
IsFresh bool
}
TokenInfo is returned from GetTokenInfo
func GetTokenInfo ¶
GetTokenInfo returns token info, if it's JWT or nil otherwise
type VerifyConfig ¶
type VerifyConfig struct {
// ExpectedIssuer validates the iss claim of a JWT matches this value
ExpectedIssuer string
// ExpectedSubject validates the sub claim of a JWT matches this value
ExpectedSubject string
// ExpectedAudience validates that the aud claim of a JWT contains this value
ExpectedAudience string
// ExpectedNonce validates that the nonce claim of a JWT contains this
// value; a mismatch is an error that errors.Is matches to
// ErrUseDPoPNonce. It cannot be set together with NonceSource.
ExpectedNonce string
// NonceSource, when set, requires every proof to carry a nonce claim
// that the source issued recently (RFC 9449 §8 and §9). A missing,
// unknown or stale nonce is an error that errors.Is matches to
// ErrUseDPoPNonce: answer it with NonceSource.Nonce in the DPoP-Nonce
// header and the ErrorUseDPoPNonce error code. Share one source among
// all requests, and among all instances through its configuration.
NonceSource NonceSource
// EnableQuery specifies to get `dpop` header from the QueryString
EnableQuery bool
// ExternalURL is the trusted external origin of this server, as
// scheme://host[:port]. When set, VerifyRequestClaims takes the htu
// scheme and host from it instead of the request URL and Host header,
// which are client-controlled. Set it for plain-HTTP servers and for
// servers reached under a different name than the Host they receive.
ExternalURL string
// ReplayCache, when set, records each accepted proof and rejects a
// second use of the same jti with the same key (ErrReplay) until the
// proof leaves its acceptance window. When nil, VerifyClaims does not
// detect replayed proofs.
ReplayCache ReplayCache
// AccessToken, when set, is the access token presented with the proof
// to a protected resource. The proof must then carry an ath claim equal
// to AccessTokenHash(AccessToken), and ExpectedThumbprint must be set
// too: ath alone does not bind the proof key to the token. Leave it
// empty at the token endpoint. Set it per request, on a copy of a shared
// VerifyConfig.
AccessToken string
// ExpectedThumbprint, when set, is the cnf.jkt value of the access token
// presented with the proof; the proof key thumbprint must equal it. Set
// it per request, with AccessToken.
ExpectedThumbprint string
}
VerifyConfig expresses the possible options for validating a JWT