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

@ -39,8 +39,9 @@ func (h *UserinfoHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
// 2. Validate token (signature + expiry) and extract claims.
claims, err := validateJWT(tokenStr, h.SigningKey)
// 2. Validate token (algorithm, signature, expiry, issuer, purpose) and
// extract claims.
claims, err := validateAccessToken(tokenStr, h.SigningKey, h.Issuer)
if err != nil {
http.Error(w, `{"error":"invalid_token","description":"token validation failed"}`, http.StatusUnauthorized)
return
@ -135,21 +136,45 @@ func lookupUserBySubject(
// JWT validation (stdlib only — no external JWT library)
// ---------------------------------------------------------------------------
// validateJWT parses and validates a JWT signed with RS256.
// It checks the signature using pubKey and verifies the exp claim.
// Returns the parsed claims on success.
func validateJWT(tokenStr string, pubKey *rsa.PublicKey) (map[string]interface{}, error) {
// validateAccessToken parses and validates a KeyCape-issued access token.
//
// Beyond signature and expiry it enforces the bindings the caller CLI already
// requires (KEY-WP-0016-T03): the JOSE header algorithm must be exactly RS256,
// so an "alg":"none" or HMAC-shaped token can never bypass the RSA check; the
// issuer claim must equal this issuer, so a correctly-signed token from another
// deployment is refused; and the token must be an access token.
//
// Purpose is decided on the presence of the `scope` claim, which the token
// endpoint sets on access tokens and never on ID tokens. That keeps the check
// verification-side: it does not add a claim to the issued token contract, which
// consumers pin exactly.
func validateAccessToken(tokenStr string, pubKey *rsa.PublicKey, issuer string) (map[string]interface{}, error) {
parts := strings.Split(tokenStr, ".")
if len(parts) != 3 {
return nil, errors.New("malformed JWT: expected 3 parts")
}
// Verify the JOSE header algorithm before trusting the signature check.
headerJSON, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil {
return nil, errors.New("malformed JWT: invalid header encoding")
}
var header struct {
Alg string `json:"alg"`
}
if err := json.Unmarshal(headerJSON, &header); err != nil {
return nil, errors.New("malformed JWT: header is not valid JSON")
}
if header.Alg != "RS256" {
return nil, errors.New("unsupported JWT algorithm")
}
// Verify signature over header.payload.
signingInput := parts[0] + "." + parts[1]
digest := sha256.Sum256([]byte(signingInput))
sigBytes, err := base64.RawURLEncoding.DecodeString(parts[2])
if err != nil {
sigBytes, decodeErr := base64.RawURLEncoding.DecodeString(parts[2])
if decodeErr != nil {
return nil, errors.New("malformed JWT: invalid signature encoding")
}
@ -158,8 +183,8 @@ func validateJWT(tokenStr string, pubKey *rsa.PublicKey) (map[string]interface{}
}
// Decode payload.
payloadJSON, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
payloadJSON, payloadErr := base64.RawURLEncoding.DecodeString(parts[1])
if payloadErr != nil {
return nil, errors.New("malformed JWT: invalid payload encoding")
}
@ -177,6 +202,20 @@ func validateJWT(tokenStr string, pubKey *rsa.PublicKey) (map[string]interface{}
return nil, errors.New("JWT has expired")
}
// Require this issuer. An empty configured issuer would make the check
// vacuous, so treat that as a misconfiguration rather than skipping it.
if issuer == "" {
return nil, errors.New("issuer is not configured")
}
if tokenIssuer, _ := claims["iss"].(string); tokenIssuer != issuer {
return nil, errors.New("JWT issuer mismatch")
}
// Require an access token. ID tokens carry no scope claim.
if _, ok := claims["scope"]; !ok {
return nil, errors.New("JWT is not an access token")
}
return claims, nil
}