Skip to content
Open
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
1 change: 1 addition & 0 deletions pkg/authserver/authorization_details_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ func TestIntegration_AuthorizationDetailsOverHTTP(t *testing.T) {
{name: "absent parameter is not echoed", wantStatus: http.StatusOK, wantNoEcho: true},
{name: "empty parameter is not echoed", details: []string{""}, wantStatus: http.StatusOK, wantNoEcho: true},
{name: "repeated form values are rejected before the hook", details: []string{`[{"type":"custom"}]`, `[{"type":"custom"}]`}, wantStatus: http.StatusBadRequest, wantError: "invalid_request", wantDescription: "The authorization_details parameter must not be repeated."},
{name: "two empty form values are rejected as repeated", details: []string{"", ""}, wantStatus: http.StatusBadRequest, wantError: "invalid_request", wantDescription: "The authorization_details parameter must not be repeated."},
{name: "typed hook error keeps its code and reason", details: []string{`[{"type":"custom","reject":true}]`}, wantStatus: http.StatusBadRequest, wantError: "invalid_request", wantDescription: "rejected_by_policy", wantCalls: 1},
{name: "untyped hook error is a server_error without its text", details: []string{`[{"type":"custom","deny":true}]`}, wantStatus: http.StatusInternalServerError, wantError: "server_error", wantDescription: "The authorization_details could not be processed.", wantCalls: 1},
{
Expand Down
59 changes: 42 additions & 17 deletions pkg/authserver/server/tokenexchange/authdetails.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,22 +30,57 @@ const (
rejectHookFailed = "hook_failed"
)

// errRepeatedDetailsParam reports that the authorization_details parameter was
// sent more than once. Callers map it to their own error and log.
var errRepeatedDetailsParam = errors.New("authorization_details parameter repeated")

// readDetailsParam reads the shape of the authorization_details form parameter.
// present is false when the parameter is absent or is one empty value. More
// than one value, empty ones included, is errRepeatedDetailsParam.
func readDetailsParam(form url.Values) (raw string, present bool, err error) {
values := form[authorizationDetailsParam]
switch {
case len(values) > 1:
return "", false, errRepeatedDetailsParam
case len(values) == 0, values[0] == "":
return "", false, nil
}
return values[0], true, nil
}

// detailsSubject builds the hook Subject from validated claims. Audience and
// Claims are copied, so a hook cannot change the validated claims.
func detailsSubject(claims *ValidatedClaims) authorizationdetails.Subject {
return authorizationdetails.Subject{
Issuer: claims.Issuer,
Subject: claims.Subject,
ClientID: claims.ClientID,
JWTID: claims.JWTID,
Audience: slices.Clone(claims.Audience),
IssuedAt: claims.IssuedAt,
Expiry: claims.Expiry,
External: claims.ExternalIssuer != "",
Claims: deepCopyClaims(claims.Claims),
}
}

// parseAuthorizationDetails runs the early, cheap shape checks. It returns a
// nil Pending when the parameter is ignored: no registry is configured, or the
// parameter is absent or empty.
func (h *Handler) parseAuthorizationDetails(form url.Values, clientID string) (*authorizationdetails.Pending, error) {
if h.authorizationDetailsRegistry == nil {
return nil, nil
}
values := form[authorizationDetailsParam]
if len(values) == 0 || (len(values) == 1 && values[0] == "") {
return nil, nil
}
if len(values) > 1 {
raw, present, err := readDetailsParam(form)
// readDetailsParam's only error is errRepeatedDetailsParam.
if err != nil {
warnAuthorizationDetailsRejected(clientID, rejectRepeated)
return nil, repeatedAuthorizationDetailsError()
}
pending, err := h.authorizationDetailsRegistry.Parse(values[0], oauthproto.GrantTypeTokenExchange)
if !present {
return nil, nil
}
pending, err := h.authorizationDetailsRegistry.Parse(raw, oauthproto.GrantTypeTokenExchange)
if err != nil {
warnAuthorizationDetailsRejected(clientID, rejectMalformed)
return nil, invalidAuthorizationDetailsError()
Expand Down Expand Up @@ -73,17 +108,7 @@ func (*Handler) grantAuthorizationDetails(
RequestedTokenType: form.Get("requested_token_type"),
RequestedScopes: slices.Clone([]string(requester.GetRequestedScopes())),
GrantedAudience: slices.Clone([]string(requester.GetGrantedAudience())),
Subject: authorizationdetails.Subject{
Issuer: claims.Issuer,
Subject: claims.Subject,
ClientID: claims.ClientID,
JWTID: claims.JWTID,
Audience: slices.Clone(claims.Audience),
IssuedAt: claims.IssuedAt,
Expiry: claims.Expiry,
External: claims.ExternalIssuer != "",
Claims: deepCopyClaims(claims.Claims),
},
Subject: detailsSubject(claims),
})
if err != nil {
return authorizationDetailsGrantError(clientID, err)
Expand Down
13 changes: 7 additions & 6 deletions pkg/authserver/server/tokenexchange/exchange_grant.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,14 +97,15 @@ func grantExchangeGrantShape(_ context.Context, req authorizationdetails.Request
func parseExchangeGrantDetails(
registry *authorizationdetails.Registry, form url.Values,
) (*authorizationdetails.Pending, error) {
values := form[authorizationDetailsParam]
if len(values) == 0 || (len(values) == 1 && values[0] == "") {
return nil, missingExchangeGrantDetailsError()
}
if len(values) > 1 {
raw, present, err := readDetailsParam(form)
// readDetailsParam's only error is errRepeatedDetailsParam.
if err != nil {
return nil, repeatedAuthorizationDetailsError()
}
pending, err := registry.Parse(values[0], oauthproto.GrantTypeTokenExchange)
if !present {
return nil, missingExchangeGrantDetailsError()
}
pending, err := registry.Parse(raw, oauthproto.GrantTypeTokenExchange)
if err != nil {
return nil, invalidAuthorizationDetailsError()
}
Expand Down
21 changes: 21 additions & 0 deletions pkg/authserver/server/tokenexchange/exchange_grant_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,27 @@ func TestParseExchangeGrantDetails(t *testing.T) {
wantCode: "invalid_request",
wantDesc: "The authorization_details parameter must not be repeated.",
},
{
name: "two empty values",
form: url.Values{authorizationDetailsParam: {"", ""}},
wantFosite: true,
wantCode: "invalid_request",
wantDesc: "The authorization_details parameter must not be repeated.",
},
{
name: "empty value with a second value",
form: url.Values{authorizationDetailsParam: {"", "x"}},
wantFosite: true,
wantCode: "invalid_request",
wantDesc: "The authorization_details parameter must not be repeated.",
},
{
name: "malformed JSON",
form: url.Values{authorizationDetailsParam: {"[{"}},
wantFosite: true,
wantCode: "invalid_authorization_details",
wantDesc: "The authorization_details parameter is invalid.",
},
{
name: "entry with no type",
form: url.Values{authorizationDetailsParam: {`[{"issuable_token_types":["x"]}]`}},
Expand Down
51 changes: 51 additions & 0 deletions pkg/authserver/server/tokenexchange/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1297,6 +1297,7 @@ func TestTokenExchangeHandler_AuthorizationDetails(t *testing.T) {
hookErr error
wantError *fosite.RFC6749Error
wantOAuthError string
wantStatus int
wantDescription string
wantCalls [][]string
wantEntries string
Expand All @@ -1313,6 +1314,20 @@ func TestTokenExchangeHandler_AuthorizationDetails(t *testing.T) {
wantOAuthError: "invalid_request",
wantDescription: "The authorization_details parameter must not be repeated.",
},
{
name: "two empty values",
details: []string{"", ""},
wantOAuthError: "invalid_request",
wantStatus: http.StatusBadRequest,
wantDescription: "The authorization_details parameter must not be repeated.",
},
{
name: "empty value with a second value",
details: []string{"", "x"},
wantOAuthError: "invalid_request",
wantStatus: http.StatusBadRequest,
wantDescription: "The authorization_details parameter must not be repeated.",
},
{
name: "malformed JSON is rejected before the subject token is checked",
details: []string{"[{"},
Expand Down Expand Up @@ -1476,6 +1491,9 @@ func TestTokenExchangeHandler_AuthorizationDetails(t *testing.T) {
require.ErrorAs(t, err, &rfcErr)
assert.Equal(t, tt.wantOAuthError, rfcErr.ErrorField)
assert.Equal(t, tt.wantDescription, rfcErr.DescriptionField)
if tt.wantStatus != 0 {
assert.Equal(t, tt.wantStatus, rfcErr.CodeField)
}
case tt.wantError != nil:
require.Error(t, err)
assert.ErrorIs(t, err, tt.wantError)
Expand Down Expand Up @@ -3769,3 +3787,36 @@ func TestIssueBoundedAccessTokenBuildsElapsedErrorOnlyWhenElapsed(t *testing.T)
})
}
}

// The WARN line for a refused authorization_details shape; a nil registry
// ignores the parameter and logs nothing.
//
//nolint:paralleltest // captures the process-global slog default
func TestTokenExchangeHandler_AuthorizationDetailsShapeLogs(t *testing.T) {
logs := captureLogs(t)
tj := newTestJWKS(t)
run := func(withRegistry bool, details []string) error {
h := newTestHandler(t, tj, 15*time.Minute)
if withRegistry {
h.authorizationDetailsRegistry = newDetailsRegistry(t, func(req authorizationdetails.Request) (authorizationdetails.Result, error) {
return authorizationdetails.Result{Entries: req.Entries}, nil
})
}
form := defaultFormValues(t, tj)
form["authorization_details"] = details
return h.HandleTokenEndpointRequest(context.Background(), newAccessRequest(t, defaultClient(), form))
}

for reason, details := range map[string][]string{"repeated": {"", ""}, "malformed": {"[{"}} {
before := logs.String()
require.Error(t, run(true, details))
added := strings.TrimPrefix(logs.String(), before)
assert.Equal(t, 1, strings.Count(added, `msg="authorization_details rejected"`))
assert.Contains(t, added, "reason="+reason)
assert.Contains(t, added, "client_id="+testAgentClientID)
}

before := logs.String()
require.NoError(t, run(false, []string{"[{"}))
assert.NotContains(t, strings.TrimPrefix(logs.String(), before), "authorization_details rejected")
}
Original file line number Diff line number Diff line change
Expand Up @@ -681,11 +681,7 @@ func decideEntry(
ClientID: clientID,
Actor: clientID,
RequestedTokenType: oauthproto.TokenTypeRefreshToken,
Subject: authorizationdetails.Subject{
Issuer: claims.Issuer, Subject: claims.Subject, ClientID: claims.ClientID, JWTID: claims.JWTID,
Audience: slices.Clone(claims.Audience), IssuedAt: claims.IssuedAt, Expiry: claims.Expiry,
Claims: deepCopyClaims(claims.Claims),
},
Subject: detailsSubject(claims),
})
if err != nil {
return nil, "", time.Time{}, err
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import (
"context"
"errors"
"log/slog"
"net/http"
"net/url"
"slices"
"strings"
"sync"
"testing"
Expand Down Expand Up @@ -516,6 +518,87 @@ func TestRefreshTokenHandlerInternalFailureIsGeneric(t *testing.T) {
}
}

// TestRefreshTokenHandlerHookSubject covers the Subject and Request the
// exchange-grant hook receives when a grant is opened.
func TestRefreshTokenHandlerHookSubject(t *testing.T) {
t.Parallel()

claims := validLoginClaims()
claims.IssuedAt = time.Now().Add(-5 * time.Minute)
claims.Audience = []string{testRefreshAPIAud, "https://other.example.com"}
claims.Claims = map[string]any{
"nested": map[string]any{"k": "v"},
"list": []any{"a", "b"},
}
wantClaims := map[string]any{
"nested": map[string]any{"k": "v"},
"list": []any{"a", "b"},
}
wantAudience := slices.Clone(claims.Audience)

var recorded []authorizationdetails.Request
registry, err := authorizationdetails.New(map[string]authorizationdetails.Type{
exchangeGrantType: {
GrantTypes: []string{oauthproto.GrantTypeTokenExchange},
Grant: func(ctx context.Context, req authorizationdetails.Request) (authorizationdetails.Result, error) {
recorded = append(recorded, req)
return grantExchangeGrantShape(ctx, req)
},
},
})
require.NoError(t, err)

h := newRefreshHandlerForTest(t, &stubSubjectValidator{claims: claims}, &fakeGrantStore{})
h.registry = registry
require.NoError(t, h.HandleTokenEndpointRequest(t.Context(), refreshRequestForTest(brokerClientForTest())))

require.Len(t, recorded, 1)
got := recorded[0]
assert.Equal(t, testRefreshClient, got.ClientID)
assert.Equal(t, testRefreshClient, got.Actor)
assert.Equal(t, oauthproto.TokenTypeRefreshToken, got.RequestedTokenType)

subject := got.Subject
assert.Equal(t, claims.Issuer, subject.Issuer)
assert.Equal(t, claims.Subject, subject.Subject)
assert.Equal(t, claims.ClientID, subject.ClientID)
assert.Equal(t, claims.JWTID, subject.JWTID)
assert.Equal(t, wantAudience, subject.Audience)
assert.Equal(t, claims.IssuedAt, subject.IssuedAt)
assert.Equal(t, claims.Expiry, subject.Expiry)
assert.False(t, subject.External)
assert.Equal(t, wantClaims, subject.Claims)

subject.Claims["nested"].(map[string]any)["k"] = "changed"
subject.Claims["list"].([]any)[0] = "changed"
subject.Claims["added"] = true
subject.Audience[0] = "changed"
assert.Equal(t, wantClaims, claims.Claims, "the hook gets a copy of the claims")
assert.Equal(t, wantAudience, claims.Audience, "the hook gets a copy of the audience")
}

// A refused exchange-grant shape is logged once at WARN with its reason.
//
//nolint:paralleltest // captures the process-global slog default
func TestRefreshTokenHandlerShapeRefusalLog(t *testing.T) {
logs := captureLogs(t)
h := newRefreshHandlerForTest(t, &stubSubjectValidator{claims: validLoginClaims()}, &fakeGrantStore{})
req := refreshRequestForTest(brokerClientForTest())
req.Form["authorization_details"] = []string{"", ""}

err := h.HandleTokenEndpointRequest(t.Context(), req)

var oauthErr *fosite.RFC6749Error
require.ErrorAs(t, err, &oauthErr)
assert.Equal(t, http.StatusBadRequest, oauthErr.CodeField)
assert.Equal(t, "invalid_request", oauthErr.ErrorField)
assert.Equal(t, "The authorization_details parameter must not be repeated.", oauthErr.GetDescription())
out := logs.String()
assert.Equal(t, 1, strings.Count(out, `msg="Exchange grant refused"`))
assert.Contains(t, out, "level=WARN")
assert.Contains(t, out, "reason="+refuseDetailsInvalid)
}

// TestRefreshTokenHandlerDecidesAgainBeforeIssuing covers a subject token that
// stops being acceptable, or is consumed, between handling and the response.
func TestRefreshTokenHandlerDecidesAgainBeforeIssuing(t *testing.T) {
Expand Down
Loading