Harden the authorization-code grant and UserInfo verification
All checks were successful
Build and Publish Container Image / build-and-push (push) Successful in 37s
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:
parent
217223b4d1
commit
139b6ff351
13 changed files with 644 additions and 25 deletions
|
|
@ -53,7 +53,9 @@ func provider(t *testing.T) (*Client, Discovery, *oidc.TokenHandler) {
|
|||
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(d) })
|
||||
mux.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
code := sessions.Create(&oidc.PKCESession{ClientID: q.Get("client_id"), Username: "test", Nonce: q.Get("nonce"), Scopes: strings.Fields(q.Get("scope")), PKCEChallenge: q.Get("code_challenge"), ExpiresAt: time.Now().Add(time.Minute)})
|
||||
// Record the redirect URI as the real /authorize does: the token
|
||||
// endpoint binds the exchange to it (KEY-WP-0016-T02).
|
||||
code := sessions.Create(&oidc.PKCESession{ClientID: q.Get("client_id"), Username: "test", Nonce: q.Get("nonce"), Scopes: strings.Fields(q.Get("scope")), PKCEChallenge: q.Get("code_challenge"), RedirectURI: q.Get("redirect_uri"), ExpiresAt: time.Now().Add(time.Minute)})
|
||||
target, _ := url.Parse(q.Get("redirect_uri"))
|
||||
params := target.Query()
|
||||
params.Set("state", q.Get("state"))
|
||||
|
|
|
|||
334
src/internal/server/oidc/hardening_test.go
Normal file
334
src/internal/server/oidc/hardening_test.go
Normal file
|
|
@ -0,0 +1,334 @@
|
|||
package oidc_test
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"keycape/internal/domain"
|
||||
"keycape/internal/server/oidc"
|
||||
)
|
||||
|
||||
// KEY-WP-0016 — negative coverage for the authorization-code protocol bindings
|
||||
// and UserInfo token verification. Each case asserts the specific rejection, so
|
||||
// a binding that stops being enforced fails here rather than passing silently.
|
||||
|
||||
func codeExchange(t *testing.T, params url.Values) *http.Request {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, "/token", strings.NewReader(params.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
return req
|
||||
}
|
||||
|
||||
func TestCodeExchangeRejectsRedirectURIMismatchAndOmission(t *testing.T) {
|
||||
for name, redirect := range map[string]string{
|
||||
"omitted": "",
|
||||
"different": "https://attacker.example.com/callback",
|
||||
"prefix": seededRedirectURI + "/../callback",
|
||||
"trailing": seededRedirectURI + "/",
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
sessions := oidc.NewSessionStore()
|
||||
h, _ := newTokenHandler(t, sessions, &mockUserRepo{users: map[string]*domain.User{"alice": aliceUser()}})
|
||||
verifier := "test-verifier"
|
||||
code := seededSession(sessions, verifier)
|
||||
params := url.Values{"grant_type": {"authorization_code"}, "client_id": {"test-client"}, "code": {code}, "code_verifier": {verifier}}
|
||||
if redirect != "" {
|
||||
params.Set("redirect_uri", redirect)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, codeExchange(t, params))
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status %d, want 400", w.Code)
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), "redirect_uri") {
|
||||
t.Fatalf("wrong rejection: %s", w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodeExchangeRejectsServiceOnlyClient(t *testing.T) {
|
||||
sessions := oidc.NewSessionStore()
|
||||
h, _ := newTokenHandler(t, sessions, &mockUserRepo{})
|
||||
h.ClientConfig["test-client"].GrantTypes = []string{"client_credentials"}
|
||||
code := seededSession(sessions, "verifier")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, codeExchange(t, url.Values{"grant_type": {"authorization_code"}, "client_id": {"test-client"}, "code": {code}, "code_verifier": {"verifier"}, "redirect_uri": {seededRedirectURI}}))
|
||||
if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "grant_type") {
|
||||
t.Fatalf("status %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// An empty grantTypes stays an implicit authorization-code client, matching
|
||||
// what config validation already assumes.
|
||||
func TestCodeExchangeAllowsImplicitAuthorizationCodeClient(t *testing.T) {
|
||||
sessions := oidc.NewSessionStore()
|
||||
h, _ := newTokenHandler(t, sessions, &mockUserRepo{users: map[string]*domain.User{"alice": aliceUser()}})
|
||||
h.ClientConfig["test-client"].GrantTypes = nil
|
||||
verifier := "test-verifier"
|
||||
code := seededSession(sessions, verifier)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, codeExchange(t, url.Values{"grant_type": {"authorization_code"}, "client_id": {"test-client"}, "code": {code}, "code_verifier": {verifier}, "redirect_uri": {seededRedirectURI}}))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfidentialCodeClientRequiresItsSecret(t *testing.T) {
|
||||
makeHandler := func(t *testing.T) (string, http.Handler) {
|
||||
sessions := oidc.NewSessionStore()
|
||||
h, _ := newTokenHandler(t, sessions, &mockUserRepo{users: map[string]*domain.User{"alice": aliceUser()}})
|
||||
h.ClientConfig["test-client"].ClientType = "confidential"
|
||||
h.ClientConfig["test-client"].ClientSecret = "human-client-secret"
|
||||
return seededSession(sessions, "test-verifier"), h
|
||||
}
|
||||
|
||||
base := func(code string) url.Values {
|
||||
return url.Values{"grant_type": {"authorization_code"}, "client_id": {"test-client"}, "code": {code}, "code_verifier": {"test-verifier"}, "redirect_uri": {seededRedirectURI}}
|
||||
}
|
||||
|
||||
t.Run("no credentials", func(t *testing.T) {
|
||||
code, h := makeHandler(t)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, codeExchange(t, base(code)))
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status %d, want 401", w.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("wrong secret", func(t *testing.T) {
|
||||
code, h := makeHandler(t)
|
||||
req := codeExchange(t, base(code))
|
||||
req.SetBasicAuth("test-client", "not-the-secret")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status %d, want 401", w.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("other client identity", func(t *testing.T) {
|
||||
code, h := makeHandler(t)
|
||||
req := codeExchange(t, base(code))
|
||||
req.SetBasicAuth("someone-else", "human-client-secret")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status %d, want 401", w.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("correct secret", func(t *testing.T) {
|
||||
code, h := makeHandler(t)
|
||||
req := codeExchange(t, base(code))
|
||||
req.SetBasicAuth("test-client", "human-client-secret")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A public client must not become "authenticated" by presenting a secret, and a
|
||||
// confidential registration with no configured secret must not accept an empty
|
||||
// one.
|
||||
func TestPublicClientSecretIsIgnoredAndEmptyConfidentialSecretIsRejected(t *testing.T) {
|
||||
sessions := oidc.NewSessionStore()
|
||||
h, _ := newTokenHandler(t, sessions, &mockUserRepo{users: map[string]*domain.User{"alice": aliceUser()}})
|
||||
code := seededSession(sessions, "test-verifier")
|
||||
req := codeExchange(t, url.Values{"grant_type": {"authorization_code"}, "client_id": {"test-client"}, "code": {code}, "code_verifier": {"test-verifier"}, "redirect_uri": {seededRedirectURI}})
|
||||
req.SetBasicAuth("test-client", "irrelevant")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("public client exchange: status %d", w.Code)
|
||||
}
|
||||
|
||||
sessions2 := oidc.NewSessionStore()
|
||||
h2, _ := newTokenHandler(t, sessions2, &mockUserRepo{users: map[string]*domain.User{"alice": aliceUser()}})
|
||||
h2.ClientConfig["test-client"].ClientType = "confidential"
|
||||
code2 := seededSession(sessions2, "test-verifier")
|
||||
req2 := codeExchange(t, url.Values{"grant_type": {"authorization_code"}, "client_id": {"test-client"}, "code": {code2}, "code_verifier": {"test-verifier"}, "redirect_uri": {seededRedirectURI}})
|
||||
req2.SetBasicAuth("test-client", "")
|
||||
w2 := httptest.NewRecorder()
|
||||
h2.ServeHTTP(w2, req2)
|
||||
if w2.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("empty configured secret accepted: status %d", w2.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Concurrent exchanges of one code must yield exactly one token: the store
|
||||
// consumes the session atomically rather than reading and deleting separately.
|
||||
func TestConcurrentCodeExchangeSucceedsExactlyOnce(t *testing.T) {
|
||||
sessions := oidc.NewSessionStore()
|
||||
h, _ := newTokenHandler(t, sessions, &mockUserRepo{users: map[string]*domain.User{"alice": aliceUser()}})
|
||||
verifier := "test-verifier"
|
||||
code := seededSession(sessions, verifier)
|
||||
|
||||
const attempts = 16
|
||||
var wg sync.WaitGroup
|
||||
codes := make([]int, attempts)
|
||||
start := make(chan struct{})
|
||||
for i := 0; i < attempts; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
req := codeExchange(t, url.Values{"grant_type": {"authorization_code"}, "client_id": {"test-client"}, "code": {code}, "code_verifier": {verifier}, "redirect_uri": {seededRedirectURI}})
|
||||
<-start
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
codes[i] = w.Code
|
||||
}(i)
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
|
||||
succeeded := 0
|
||||
for _, c := range codes {
|
||||
if c == http.StatusOK {
|
||||
succeeded++
|
||||
}
|
||||
}
|
||||
if succeeded != 1 {
|
||||
t.Fatalf("%d concurrent exchanges succeeded, want exactly 1", succeeded)
|
||||
}
|
||||
}
|
||||
|
||||
// A failed exchange must not leave the code replayable.
|
||||
func TestFailedExchangeConsumesTheCode(t *testing.T) {
|
||||
sessions := oidc.NewSessionStore()
|
||||
h, _ := newTokenHandler(t, sessions, &mockUserRepo{users: map[string]*domain.User{"alice": aliceUser()}})
|
||||
code := seededSession(sessions, "test-verifier")
|
||||
params := url.Values{"grant_type": {"authorization_code"}, "client_id": {"test-client"}, "code": {code}, "code_verifier": {"wrong-verifier"}, "redirect_uri": {seededRedirectURI}}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, codeExchange(t, params))
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("first attempt: status %d", w.Code)
|
||||
}
|
||||
params.Set("code_verifier", "test-verifier")
|
||||
w = httptest.NewRecorder()
|
||||
h.ServeHTTP(w, codeExchange(t, params))
|
||||
if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "authorization code") {
|
||||
t.Fatalf("code survived a failed exchange: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// KEY-WP-0016-T03 — UserInfo token verification bindings.
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
func TestUserinfoRejectsUnverifiedTokenShapes(t *testing.T) {
|
||||
users := &mockUserRepo{users: map[string]*domain.User{
|
||||
"user-alice": aliceUser(),
|
||||
"alice": aliceUser(),
|
||||
}}
|
||||
|
||||
valid := func() map[string]interface{} {
|
||||
now := time.Now()
|
||||
return map[string]interface{}{
|
||||
"iss": "https://auth.netkingdom.local",
|
||||
"sub": "alice",
|
||||
"aud": "test-client",
|
||||
"exp": now.Add(10 * time.Minute).Unix(),
|
||||
"iat": now.Unix(),
|
||||
"scope": "openid profile",
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("accepts a well-formed access token", func(t *testing.T) {
|
||||
h, key := newUserinfoHandler(t, users)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, userinfoRequest(buildToken(t, valid(), key)))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("foreign issuer", func(t *testing.T) {
|
||||
h, key := newUserinfoHandler(t, users)
|
||||
claims := valid()
|
||||
claims["iss"] = "https://auth.other.example"
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, userinfoRequest(buildToken(t, claims, key)))
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status %d, want 401", w.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing issuer", func(t *testing.T) {
|
||||
h, key := newUserinfoHandler(t, users)
|
||||
claims := valid()
|
||||
delete(claims, "iss")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, userinfoRequest(buildToken(t, claims, key)))
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status %d, want 401", w.Code)
|
||||
}
|
||||
})
|
||||
|
||||
// An ID token is correctly signed by this issuer but is not an access
|
||||
// token: it carries no scope claim.
|
||||
t.Run("id token presented as access token", func(t *testing.T) {
|
||||
h, key := newUserinfoHandler(t, users)
|
||||
claims := valid()
|
||||
delete(claims, "scope")
|
||||
claims["nonce"] = "nonce1"
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, userinfoRequest(buildToken(t, claims, key)))
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status %d, want 401", w.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The JOSE header algorithm is checked before the signature, so a token
|
||||
// claiming "none" or a symmetric algorithm can never reach the RSA check.
|
||||
func TestUserinfoRejectsNonRS256Algorithms(t *testing.T) {
|
||||
users := &mockUserRepo{users: map[string]*domain.User{
|
||||
"user-alice": aliceUser(),
|
||||
"alice": aliceUser(),
|
||||
}}
|
||||
h, key := newUserinfoHandler(t, users)
|
||||
now := time.Now()
|
||||
payload, err := json.Marshal(map[string]interface{}{
|
||||
"iss": "https://auth.netkingdom.local",
|
||||
"sub": "alice",
|
||||
"exp": now.Add(10 * time.Minute).Unix(),
|
||||
"scope": "openid",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
encodedPayload := base64.RawURLEncoding.EncodeToString(payload)
|
||||
|
||||
// Keep a genuine RS256 signature and only restate the algorithm, so the
|
||||
// test isolates the header check rather than relying on a broken signature.
|
||||
signed := buildToken(t, map[string]interface{}{
|
||||
"iss": "https://auth.netkingdom.local",
|
||||
"sub": "alice",
|
||||
"exp": now.Add(10 * time.Minute).Unix(),
|
||||
"scope": "openid",
|
||||
}, key)
|
||||
genuineSignature := strings.Split(signed, ".")[2]
|
||||
|
||||
for _, alg := range []string{"none", "HS256", "RS512", "rs256", ""} {
|
||||
header, err := json.Marshal(map[string]interface{}{"alg": alg, "typ": "JWT", "kid": "key-1"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(header) + "." + encodedPayload + "." + genuineSignature
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, userinfoRequest(token))
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("alg %q accepted: status %d", alg, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -69,6 +69,28 @@ func (s *SessionStore) Get(code string) (*PKCESession, bool) {
|
|||
return sess, true
|
||||
}
|
||||
|
||||
// Consume retrieves a session by code and removes it in the same critical
|
||||
// section, so exactly one caller can ever observe a given code. Returns false
|
||||
// if the code is not present or has expired. The token endpoint must use this
|
||||
// rather than Get/Delete: signing happens between those two calls, which is
|
||||
// long enough for two concurrent exchanges to both observe the same session
|
||||
// (KEY-WP-0016-T01). A consumed code is gone even if the exchange then fails,
|
||||
// which is the intended single-use semantics -- a failed attempt must not leave
|
||||
// a replayable code.
|
||||
func (s *SessionStore) Consume(code string) (*PKCESession, bool) {
|
||||
s.mu.Lock()
|
||||
sess, ok := s.sessions[code]
|
||||
if ok {
|
||||
delete(s.sessions, code)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
|
||||
if !ok || time.Now().After(sess.ExpiresAt) {
|
||||
return nil, false
|
||||
}
|
||||
return sess, true
|
||||
}
|
||||
|
||||
// Delete removes a session by code. No-op if the code is not present.
|
||||
func (s *SessionStore) Delete(code string) {
|
||||
s.mu.Lock()
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -93,13 +93,32 @@ func newTokenHandler(t *testing.T, sessions *oidc.SessionStore, users domain.Use
|
|||
return h, key
|
||||
}
|
||||
|
||||
// seededRedirectURI is the redirect stored by seededSession, and the value the
|
||||
// token endpoint now requires the exchange to repeat (KEY-WP-0016-T02).
|
||||
const seededRedirectURI = "https://app.example.com/callback"
|
||||
|
||||
func tokenRequest(params url.Values) *http.Request {
|
||||
// Supply the matching redirect_uri for code exchanges unless the test is
|
||||
// deliberately exercising a mismatch, so each case still fails for the
|
||||
// reason it is testing.
|
||||
if params.Get("grant_type") == "authorization_code" && !params.Has("redirect_uri") {
|
||||
params = cloneValues(params)
|
||||
params.Set("redirect_uri", seededRedirectURI)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/token",
|
||||
strings.NewReader(params.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
return req
|
||||
}
|
||||
|
||||
func cloneValues(params url.Values) url.Values {
|
||||
out := make(url.Values, len(params)+1)
|
||||
for key, values := range params {
|
||||
out[key] = append([]string(nil), values...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func seededSession(sessions *oidc.SessionStore, verifier string) (code string) {
|
||||
challenge := s256Challenge(verifier)
|
||||
sess := &oidc.PKCESession{
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -304,10 +304,11 @@ func TestUserinfoHandler_EmitsTelemetry(t *testing.T) {
|
|||
|
||||
now := time.Now()
|
||||
claims := map[string]interface{}{
|
||||
"iss": "https://auth.netkingdom.local",
|
||||
"sub": "alice",
|
||||
"exp": now.Add(10 * time.Minute).Unix(),
|
||||
"iat": now.Unix(),
|
||||
"iss": "https://auth.netkingdom.local",
|
||||
"sub": "alice",
|
||||
"exp": now.Add(10 * time.Minute).Unix(),
|
||||
"iat": now.Unix(),
|
||||
"scope": "openid",
|
||||
}
|
||||
token, _ := oidc.BuildJWT(claims, "key-1", key)
|
||||
|
||||
|
|
|
|||
|
|
@ -574,6 +574,8 @@ func TestCompleteTokenFlow(t *testing.T) {
|
|||
tokenForm.Set("client_id", "demo-app")
|
||||
tokenForm.Set("code", authCode)
|
||||
tokenForm.Set("code_verifier", verifier)
|
||||
// The exchange must repeat the redirect URI the code was issued for.
|
||||
tokenForm.Set("redirect_uri", "http://localhost:3000/callback")
|
||||
|
||||
tokenResp, err := http.Post(
|
||||
ts.Server.URL+"/token",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue