Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/arch/11-auth-server-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -972,7 +972,7 @@ is needed or offered.

A client proves possession of its private key by sending a signed
`client_assertion` at `/oauth/token`; ToolHive stores only the registered public
JWKS. The assertion's `aud` may be the issuer or the token endpoint URL; see
JWKS. The assertion's `aud` must hold the issuer and nothing else; see
[Client-assertion audience](17-token-exchange-delegation.md#client-assertion-audience).
The server accepts a clock difference of 60 seconds in the assertion's `exp`,
`iat` and `nbf`, so an assertion from a client whose clock runs a little fast or
Expand Down
34 changes: 23 additions & 11 deletions docs/arch/17-token-exchange-delegation.md
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ client_assertion=<signed-assertion>
```

The assertion identifies the registered `client_id` in `iss` and `sub`, targets
the token endpoint in `aud`, and includes a unique `jti` and an `exp`. The
the issuer in `aud`, and includes a unique `jti` and an `exp`. The
server verifies it against the stored inline JWKS and rejects replay while the
assertion is valid. No `client_secret` is included in registration or token
exchange.
Expand Down Expand Up @@ -438,26 +438,38 @@ public (`none`) client.

### Client-assertion audience

A `private_key_jwt` client assertion is accepted when its `aud` claim is either
of these, as a string or as an array containing either:
A `private_key_jwt` client assertion is accepted only when its `aud` claim holds
the issuer and nothing else. This follows RFC 10070 section 4, which requires
the issuer identifier as the sole value of `aud` and forbids the token endpoint
URL. The issuer may be sent as a JSON string or as a one-element array; RFC 7519
section 4.1.3 allows both forms.

- the issuer
- the token endpoint URL (`{issuer}/oauth/token`)
The server refuses these with `401 invalid_client` and issues no token:

- the token endpoint URL (`{issuer}/oauth/token`), as a string or inside an array
- an array with more than one value, even when one of them is the issuer
- a missing `aud`, an empty array, or any other value
- an assertion that go-jose v4 cannot read under strict base64url decoding, such
as one with base64 padding on a segment or a space or tab inside it, which
some JOSE parsers tolerate. The check must see `aud` as sent, so the server
does not leave such an assertion to a more lenient parser.

The server logs each of these refusals at WARN with the cause and `client_id`,
because a client that worked with an earlier release can start failing here.

A client that sends the token endpoint URL as `aud` must be updated to send the
issuer instead. The check has no setting; it always applies, including to an
assertion that is accepted only through the 60-second clock skew allowance.

Assertions with the `client-authentication+jwt` JOSE `typ` header
(draft-ietf-oauth-rfc7523bis-11 section 4.1) are accepted.
(RFC 10070 section 4) are accepted.

Accepting the issuer is safe because the assertion is still bound by
`iss == sub == client_id` and a signature from the client's registered keys.
The issuer is this server's unique identifier (RFC 8414 section 2), and `aud` is
compared as an exact string. An assertion addressed to this issuer is therefore
not accepted by another issuer, even one on the same host.

Two things do not meet draft-11 section 4(b), which requires the issuer as the
sole value of `aud`: accepting the token endpoint URL, and accepting an `aud`
array with more than one value that contains the issuer. Both are deprecated. A
later release will require the issuer as the sole value.

This applies to every `private_key_jwt` client. Inbound `private_key_jwt`
clients come from Dynamic Client Registration and from configured delegate
clients. The `aud` checks on
Expand Down
14 changes: 8 additions & 6 deletions pkg/authserver/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6824,7 +6824,7 @@ func TestIntegration_PrivateKeyJWTDCRTokenExchange(t *testing.T) {

now := time.Now()
subjectToken := ts.signSubjectToken("external-subject", now, now.Add(10*time.Minute), "subject-1")
assertion := makeAssertion(registered.ClientID, testIssuer+"/oauth/token", now.Add(2*time.Minute), "client-assertion-1")
assertion := makeAssertion(registered.ClientID, testIssuer, now.Add(2*time.Minute), "client-assertion-1")
response, body := request(assertion, subjectToken)
t.Cleanup(func() { response.Body.Close() })
require.Equal(t, http.StatusOK, response.StatusCode, body)
Expand All @@ -6850,8 +6850,8 @@ func TestIntegration_PrivateKeyJWTDCRTokenExchange(t *testing.T) {
assertion string
}{
{name: "wrong_audience", assertion: makeAssertion(registered.ClientID, "https://wrong.example/token", now.Add(2*time.Minute), "client-assertion-wrong-aud")},
{name: "wrong_subject", assertion: makeAssertion("different-client", testIssuer+"/oauth/token", now.Add(2*time.Minute), "client-assertion-wrong-sub")},
{name: "expired", assertion: makeAssertion(registered.ClientID, testIssuer+"/oauth/token", now.Add(-time.Minute), "client-assertion-expired")},
{name: "wrong_subject", assertion: makeAssertion("different-client", testIssuer, now.Add(2*time.Minute), "client-assertion-wrong-sub")},
{name: "expired", assertion: makeAssertion(registered.ClientID, testIssuer, now.Add(-2*time.Minute), "client-assertion-expired")},
} {
t.Run(negative.name, func(t *testing.T) {
response, body := request(negative.assertion, subjectToken)
Expand All @@ -6866,8 +6866,9 @@ func TestIntegration_PrivateKeyJWTDCRTokenExchange(t *testing.T) {

// TestIntegration_PrivateKeyJWTClientAssertionAudience drives a DCR
// private_key_jwt client through the token endpoint with different assertion
// audiences and JOSE types. The issuer and the token endpoint URL are accepted;
// any other audience is refused with invalid_client.
// audiences and JOSE types. Only the issuer, and nothing else, is accepted;
// the token endpoint URL, an array with another value and any other audience
// are refused with invalid_client.
func TestIntegration_PrivateKeyJWTClientAssertionAudience(t *testing.T) {
t.Parallel()

Expand Down Expand Up @@ -6918,7 +6919,8 @@ func TestIntegration_PrivateKeyJWTClientAssertionAudience(t *testing.T) {
wantOK bool
}{
{name: "issuer", audience: jwt.Audience{testIssuer}, typ: "JWT", wantOK: true},
{name: "token URL", audience: jwt.Audience{testIssuer + "/oauth/token"}, typ: "JWT", wantOK: true},
{name: "token URL", audience: jwt.Audience{testIssuer + "/oauth/token"}, typ: "JWT"},
{name: "issuer and another value in an array", audience: jwt.Audience{testIssuer, "https://other.example.com"}, typ: "JWT"},
{name: "unrelated audience", audience: jwt.Audience{"https://other.example.com"}, typ: "JWT"},
{name: "rfc7523bis typ header with issuer", audience: jwt.Audience{testIssuer}, typ: "client-authentication+jwt", wantOK: true},
}
Expand Down
9 changes: 5 additions & 4 deletions pkg/authserver/server/client_assertion_errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,14 +217,15 @@ func TestClientAssertionErrorStrategy(t *testing.T) {
}
cfg := &fosite.Config{AccessTokenIssuer: assertionTestIssuer, TokenURL: assertionTestTokenURL}
provider := fosite.NewOAuth2Provider(store, newClientAssertionAudienceConfig(cfg))
strategy := newClientAssertionErrorStrategy(newClientAssertionClockSkewStrategy(
provider.DefaultClientAuthenticationStrategy, store, clientAssertionAudiences(cfg),
func() time.Time { return now }, true))
strategy := newClientAssertionErrorStrategy(newClientAssertionAudienceStrategy(
newClientAssertionClockSkewStrategy(provider.DefaultClientAuthenticationStrategy, store,
func() time.Time { return now }, true),
cfg.AccessTokenIssuer))

claims := jwt.Claims{
Issuer: assertionTestClientID,
Subject: assertionTestClientID,
Audience: jwt.Audience{assertionTestTokenURL},
Audience: jwt.Audience{assertionTestIssuer},
ID: "jti-" + tt.name,
IssuedAt: jwt.NewNumericDate(now),
Expiry: jwt.NewNumericDate(now.Add(time.Minute)),
Expand Down
2 changes: 1 addition & 1 deletion pkg/authserver/server/client_assertion_store_e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func signE2EAssertion(t *testing.T, key *ecdsa.PrivateKey, jti string, exp any)
(&josev4.SignerOptions{}).WithType("JWT").WithHeader(josev4.HeaderKey("kid"), e2eKeyID))
require.NoError(t, err)
token, err := jwt.Signed(signer).Claims(map[string]any{
"iss": e2eClientID, "sub": e2eClientID, "aud": e2eTokenURL, "jti": jti, "exp": exp,
"iss": e2eClientID, "sub": e2eClientID, "aud": e2eIssuer, "jti": jti, "exp": exp,
}).Serialize()
require.NoError(t, err)
return token
Expand Down
5 changes: 3 additions & 2 deletions pkg/authserver/server/endpoints.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package server

// TokenEndpointPath is the path of the token endpoint, relative to the issuer.
// Discovery advertises the issuer joined with it, the router serves it, and
// client assertions may name that URL as their audience.
// Discovery advertises the issuer joined with it and the router serves it.
// Clients send client assertions to this URL but address them to the issuer:
// an assertion with this URL as its audience is refused.
const TokenEndpointPath = "/oauth/token" //nolint:gosec // G101: URL path, not a credential
132 changes: 104 additions & 28 deletions pkg/authserver/server/private_key_jwt_client_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ package server

import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"net/url"
"slices"
"strings"
"time"

"github.com/go-jose/go-jose/v4"
Expand Down Expand Up @@ -43,21 +42,18 @@ func (c clientAssertionAudienceConfig) GetTokenURLs(context.Context) []string {
return c.tokenURLs
}

// newClientAssertionAudienceConfig wraps config so that client assertions may
// carry either the issuer or the token endpoint URL as audience.
// newClientAssertionAudienceConfig wraps config so that fosite accepts the
// issuer, and nothing else, as the audience of a client assertion. fosite does
// not accept the issuer on its own, so it is handed over as a token URL. RFC
// 10070 section 4 requires the issuer identifier as the sole aud value and
// forbids the token endpoint URL.
func newClientAssertionAudienceConfig(config *fosite.Config) clientAssertionAudienceConfig {
return clientAssertionAudienceConfig{
Config: config,
tokenURLs: clientAssertionAudiences(config),
tokenURLs: []string{config.AccessTokenIssuer},
}
}

// clientAssertionAudiences returns the values accepted as the audience of a
// client assertion: the issuer and the token endpoint URL.
func clientAssertionAudiences(config *fosite.Config) []string {
return []string{config.AccessTokenIssuer, config.TokenURL}
}

// clientAssertionStore is the part of fosite.Storage that the clock skew
// fallback uses to finish what fosite's strategy would have done. The store
// must be the clientAssertionExpiryStore, so that the marker it records gets the
Expand All @@ -68,11 +64,51 @@ type clientAssertionStore interface {
SetClientAssertionJWT(ctx context.Context, jti string, exp time.Time) error
}

// newClientAssertionAudienceStrategy refuses a private_key_jwt client
// assertion whose aud is not issuer and nothing else, before next runs. The
// issuer may be sent as a string or as a one-element array, which RFC 7519
// section 4.1.3 and RFC 10070 both allow. fosite only checks that aud contains
// an accepted value, so without this an array such as [issuer, "other"] would
// pass. The refusal comes before any client lookup, so such an assertion costs
// no lookup and does not use up its jti.
//
// It applies to every strategy below it, fosite's own or one the caller
// supplied, the same way the JWS guard does. The clock skew recovery does not
// check aud itself and relies on this strategy sitting above it.
//
// An assertion that go-jose v4 cannot read is refused as well, instead of being
// left to next. fosite parses with go-jose v3, which strips spaces and tabs and
// trims base64 padding where v4 does not, so a token v4 rejects can still be
// read and verified by fosite, with an aud array this check never saw.
// Conforming clients send the canonical compact form and are not affected. The
// claims are read without verifying the signature, which is safe because the
// result can only refuse. The JWS guard above this strategy has already
// screened the assertion.
//
// A refusal is logged at WARN on purpose: it is a request shape that older
// releases accepted, and operators need to see why such a client now fails.
func newClientAssertionAudienceStrategy(
next fosite.ClientAuthenticationStrategy,
issuer string,
) fosite.ClientAuthenticationStrategy {
return func(ctx context.Context, r *http.Request, form url.Values) (fosite.Client, error) {
if !isPrivateKeyJWTRequest(form) {
return next(ctx, r, form)
}
if reason, err := checkClientAssertionAudience(form.Get("client_assertion"), issuer); err != nil {
slog.Warn("refused client assertion", "reason", reason, "client_id", form.Get("client_id"))
return nil, err
}
return next(ctx, r, form)
}
}

// newClientAssertionClockSkewStrategy lets a private_key_jwt client assertion
// whose exp, iat or nbf is within clientAssertionClockSkew of now authenticate.
// fosite offers no leeway setting, and its jwt.TimeFunc is a process-wide
// variable, so fosite stays the validator and this wrapper only recovers from
// its time errors. audiences are the values accepted in aud.
// its time errors. It must sit below newClientAssertionAudienceStrategy, which
// checks aud for the recovery.
//
// recoverTimeErrors turns the recovery on. Only fosite's own strategy may have
// it, because the recovery relies on fosite verifying the signature before it
Expand All @@ -92,7 +128,6 @@ type clientAssertionStore interface {
func newClientAssertionClockSkewStrategy(
next fosite.ClientAuthenticationStrategy,
store clientAssertionStore,
audiences []string,
now func() time.Time,
recoverTimeErrors bool,
) fosite.ClientAuthenticationStrategy {
Expand All @@ -116,7 +151,7 @@ func newClientAssertionClockSkewStrategy(
// so the claims can be read without verifying them again. Tests pin
// this order, because a different order in a later fosite release
// would make these claims untrusted.
return recoverSkewedClientAssertion(ctx, store, audiences, form, assertion, now, err)
return recoverSkewedClientAssertion(ctx, store, form, assertion, now, err)
}
}

Expand All @@ -126,11 +161,12 @@ func newClientAssertionClockSkewStrategy(
// returned unchanged. A GetClient error is refused as invalid_client. A storage
// failure while checking the jti is refused as invalid_client here, and becomes
// server_error in newClientAssertionErrorStrategy, which reads the failure the
// backend recorded.
// backend recorded. aud is not checked here: newClientAssertionAudienceStrategy,
// which sits above the clock skew strategy, has already required it to be the
// issuer.
func recoverSkewedClientAssertion(
ctx context.Context,
store clientAssertionStore,
audiences []string,
form url.Values,
assertion string,
now func() time.Time,
Expand All @@ -152,7 +188,7 @@ func recoverSkewedClientAssertion(
if reason, refusalErr := checkClientAssertionTimes(claims, now(), fositeErr); reason != "" {
return refuse(reason, refusalErr)
}
if reason, refusalErr := checkClientAssertionIdentity(claims, clientID, audiences); reason != "" {
if reason, refusalErr := checkClientAssertionIdentity(claims, clientID); reason != "" {
return refuse(reason, refusalErr)
}

Expand Down Expand Up @@ -223,10 +259,11 @@ func errClientAssertionUnreadable() error {
return fosite.ErrInvalidClient.WithHint("The 'client_assertion' claims could not be read.")
}

// checkClientAssertionIdentity checks iss, sub, jti and aud against what fosite
// requires. It returns a refusal reason and error, or an empty reason when the
// claims are fine.
func checkClientAssertionIdentity(claims jwt.Claims, clientID string, audiences []string) (string, error) {
// checkClientAssertionIdentity checks iss, sub and jti against what fosite
// requires. aud is checked before fosite runs, by checkClientAssertionAudience.
// It returns a refusal reason and error, or an empty reason when the claims are
// fine.
func checkClientAssertionIdentity(claims jwt.Claims, clientID string) (string, error) {
if clientID == "" || claims.Issuer != clientID {
return "iss does not match the client", fosite.ErrInvalidClient.WithHint(
"Claim 'iss' from 'client_assertion' must match the 'client_id' of the OAuth 2.0 Client.")
Expand All @@ -239,19 +276,58 @@ func checkClientAssertionIdentity(claims jwt.Claims, clientID string, audiences
return "jti missing", fosite.ErrInvalidClient.WithHint(
"Claim 'jti' from 'client_assertion' must be set but is not.")
}
if !slices.ContainsFunc(claims.Audience, func(aud string) bool {
return aud != "" && slices.Contains(audiences, aud)
}) {
return "audience not accepted", fosite.ErrInvalidClient.WithHintf(
"Claim 'audience' from 'client_assertion' must match the authorization server's token endpoint '%s'.",
strings.Join(slices.DeleteFunc(slices.Clone(audiences), func(a string) bool { return a == "" }), "' or '"))
return "", nil
}

// errClientAssertionAudience is the refusal for an aud that is not the issuer
// and nothing else.
func errClientAssertionAudience(issuer string) error {
return fosite.ErrInvalidClient.WithHintf(
"Claim 'audience' from 'client_assertion' must hold only the authorization server's issuer '%s'.", issuer)
}

// checkClientAssertionAudience refuses an assertion that cannot be read, or
// whose aud is not issuer and nothing else. aud may be the issuer as a string
// or as a one-element array. The raw claim is read, so that a missing, null or
// non-string aud is refused rather than read as empty. It returns a refusal
// reason and error, or an empty reason when the aud is fine. The signature is
// not verified, so the result may only refuse.
func checkClientAssertionAudience(assertion, issuer string) (string, error) {
token, err := jwt.ParseSigned(assertion, clientAssertionSigningAlgorithms)
if err != nil {
return "claims unreadable", errClientAssertionUnreadable()
}
var claims struct {
Audience json.RawMessage `json:"aud"`
}
if token.UnsafeClaimsWithoutVerification(&claims) != nil {
return "claims unreadable", errClientAssertionUnreadable()
}
aud, ok := soleAudience(claims.Audience)
if !ok || aud == "" || aud != issuer {
return "audience is not the issuer alone", errClientAssertionAudience(issuer)
}
return "", nil
}

// soleAudience returns the only value of a raw aud claim, which may be a
// string or an array of strings. ok is false when aud is missing, is not a
// string or an array of strings, or does not hold exactly one value.
func soleAudience(raw json.RawMessage) (aud string, ok bool) {
if json.Unmarshal(raw, &aud) == nil {
return aud, true
}
var auds []string
if json.Unmarshal(raw, &auds) != nil || len(auds) != 1 {
return "", false
}
return auds[0], true
}

// parseVerifiedClientAssertionClaims reads the claims of an assertion without
// verifying the signature. Callers only pass assertions that fosite has
// already verified.
// already verified. A check on claims that were not verified, which may only
// refuse, belongs in checkClientAssertionAudience instead.
func parseVerifiedClientAssertionClaims(assertion string) (jwt.Claims, bool) {
var claims jwt.Claims
parsed, err := jwt.ParseSigned(assertion, clientAssertionSigningAlgorithms)
Expand Down
Loading
Loading