Harden the authorization-code grant and UserInfo verification
All checks were successful
Build and Publish Container Image / build-and-push (push) Successful in 37s

Closes the local protocol surface of gap G01 from the scope assessment
(KEY-WP-0016). The browser grant validated PKCE, client id and scopes but left
four bindings unenforced, and UserInfo verified less than the caller CLI does.

Authorization-code path: bind the exchange to the redirect URI the code was
issued for, refuse clients whose registration does not permit the grant, and
authenticate confidential clients with a digest-based constant-time comparison
over the same credential sources as the service grant. An empty grantTypes stays
an implicit authorization-code client, matching config validation.

Code consumption: SessionStore.Consume reads and deletes under one lock. The
previous Get/Delete pair spanned JWT signing, and the added test reproduces the
race against that version -- 9 of 16 concurrent exchanges succeeded, and a
failed exchange left the code replayable.

UserInfo: check the JOSE header algorithm before trusting the signature, require
the configured issuer, and require an access token rather than accepting an ID
token of the right shape. Purpose is decided on the scope claim so the issued
token contract, which consumers pin exactly, does not change.

SCOPE.md and the assessment record which bindings are now enforced and that the
Authelia upstream-trust assumption remains open, so G01 is not fully closed and
no profile-conformance claim is made.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NV9oijZukGyGbRQGGKnK4P

Assistant: claude-code
Assistant-Model: opus
Assistant-Process: 713576@bnt-lap001
Assistant-Session: 384c511d-9bce-4cb8-a676-2aef6c0c8df6
This commit is contained in:
tegwick 2026-09-06 22:43:47 +02:00
parent 217223b4d1
commit 139b6ff351
13 changed files with 644 additions and 25 deletions

View file

@ -68,15 +68,44 @@ func (h *TokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
// 2. Validate client exists (basic check; secret auth delegated to future work).
if _, ok := h.ClientConfig[clientID]; !ok {
// 2. Validate client exists and may use this grant.
client, ok := h.ClientConfig[clientID]
if !ok {
profileerrors.InvalidProfileUsage("unknown client_id", "client_id").
Write(w, http.StatusBadRequest)
return
}
// 3. Look up PKCE session.
sess, ok := h.Sessions.Get(code)
// Grant-type eligibility, enforced equivalently to the service path
// (KEY-WP-0016-T02). An empty grantTypes is an implicit authorization-code
// client, matching config validation; a client_credentials-only client must
// not reach the browser path.
if len(client.GrantTypes) > 0 && !containsString(client.GrantTypes, "authorization_code") {
profileerrors.InvalidProfileUsage(
"client is not registered for grant_type=authorization_code",
"grant_type",
).Write(w, http.StatusBadRequest)
return
}
// Confidential authorization-code clients authenticate with their secret,
// using the same credential sources as the service grant. A public client
// must not be able to present a secret and be treated as authenticated.
if client.ClientType == "confidential" {
presentedID, secret, ok := basicClientCredentials(r)
if !ok || presentedID != clientID || client.ClientSecret == "" ||
!secretsEqual(secret, client.ClientSecret) {
profileerrors.InvalidProfileUsage(
"client authentication failed",
"Authorization",
).Write(w, http.StatusUnauthorized)
return
}
}
// 3. Consume the PKCE session. Single-use and atomic: see
// SessionStore.Consume (KEY-WP-0016-T01).
sess, ok := h.Sessions.Consume(code)
if !ok {
profileerrors.InvalidProfileUsage(
"authorization code not found or expired",
@ -94,6 +123,18 @@ func (h *TokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
// Bind the exchange to the redirect URI the code was issued for
// (RFC 6749 section 4.1.3, KEY-WP-0016-T02). /authorize always records an
// exactly-matched registered redirect, so the parameter is always required
// here and must be identical.
if redirectURI := r.FormValue("redirect_uri"); redirectURI != sess.RedirectURI {
profileerrors.InvalidProfileUsage(
"redirect_uri does not match the authorization request",
"redirect_uri",
).Write(w, http.StatusBadRequest)
return
}
// Recheck grants in case the client registration changed after authorization.
for _, scope := range sess.Scopes {
if !containsString(h.ClientConfig[clientID].AllowedScopes, scope) {
@ -118,7 +159,6 @@ func (h *TokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
if isSuspended(user) {
h.Sessions.Delete(code)
profileerrors.RejectedForSafety(
"account is suspended",
"account_lifecycle",
@ -190,10 +230,8 @@ func (h *TokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
// 8. Delete used PKCE session (prevent replay).
h.Sessions.Delete(code)
// 9. Build response.
// 8. Build response. The session was already consumed at lookup, so no
// separate replay-prevention delete is needed here.
resp := tokenResponse{
AccessToken: accessToken,
TokenType: "Bearer",
@ -217,6 +255,31 @@ func (h *TokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(resp)
}
// basicClientCredentials reads client_secret_basic credentials, applying the
// form-encoding decode RFC 6749 appendix B requires of both halves. Shared by
// the service grant and confidential authorization-code client authentication.
func basicClientCredentials(r *http.Request) (clientID, clientSecret string, ok bool) {
clientID, clientSecret, ok = r.BasicAuth()
if !ok {
return "", "", false
}
decodedID, idErr := url.QueryUnescape(clientID)
decodedSecret, secretErr := url.QueryUnescape(clientSecret)
if idErr != nil || secretErr != nil {
return "", "", false
}
return decodedID, decodedSecret, true
}
// secretsEqual compares two secrets in constant time. Digesting first keeps the
// comparison length-independent, so a wrong-length secret is indistinguishable
// from a wrong-value one.
func secretsEqual(presented, expected string) bool {
presentedDigest := sha256.Sum256([]byte(presented))
expectedDigest := sha256.Sum256([]byte(expected))
return subtle.ConstantTimeCompare(presentedDigest[:], expectedDigest[:]) == 1
}
func (h *TokenHandler) serveClientCredentials(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
clientID, clientSecret, ok := r.BasicAuth()