2026-03-13 01:56:57 +01:00
|
|
|
package oidc
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"crypto"
|
|
|
|
|
"crypto/rand"
|
|
|
|
|
"crypto/rsa"
|
|
|
|
|
"crypto/sha256"
|
2026-07-27 20:03:07 +02:00
|
|
|
"crypto/subtle"
|
2026-03-13 01:56:57 +01:00
|
|
|
"encoding/base64"
|
|
|
|
|
"encoding/json"
|
2026-09-09 14:40:36 +02:00
|
|
|
"fmt"
|
2026-03-13 01:56:57 +01:00
|
|
|
"net/http"
|
2026-09-05 01:08:58 +02:00
|
|
|
"net/url"
|
2026-03-13 01:56:57 +01:00
|
|
|
"strings"
|
|
|
|
|
"time"
|
|
|
|
|
|
KEY-WP-0005-T02-T03: cached tenant_roles claim, close workplan
New internal/adapters/tenantengine package, mirroring
internal/adapters/{lldap,privacyidea,authelia}'s shape: Client.Roles()
calls tenant-engine's cache-read endpoint. Fails open by construction --
unreachable, non-200, malformed body, or a nil *Client all return
(nil, false), never an error to specially handle. Wired into
TokenHandler.TenantEngine (nil by default, existing tests unaffected);
token.go stamps tenant_roles only when ok.
7 adapter tests plus 3 TokenHandler-level tests proving the actual
required behavior end-to-end: present when reachable, token issuance still
200 with every other core claim intact when unreachable (tenant_roles
simply absent -- the literal done-criteria), absent when not configured.
Real bug found and fixed at the source, not worked around: the first live
cross-process check (real flex-auth, real tenant-engine, this adapter)
returned tenant_not_found for a tenant that existed -- tenant-engine's read
endpoint was keyed by its internal tenant_id, but key-cape only ever has
the tenant's profile identifier. Fixed in tenant-engine
(ADHOC-2026-07-24), re-verified with the same live three-process chain --
roles=[IAM] ok=true.
Workplan closed: T01-T03 done. Explicitly still open: client_credentials /
service-token issuance -- no such flow exists in token.go at all, a
materially larger separate piece of work than either task here.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 00:18:17 +02:00
|
|
|
"keycape/internal/adapters/tenantengine"
|
2026-03-13 01:56:57 +01:00
|
|
|
"keycape/internal/domain"
|
|
|
|
|
profileerrors "keycape/internal/errors"
|
|
|
|
|
"keycape/internal/server/telemetry"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// TokenHandler implements POST /token.
|
|
|
|
|
type TokenHandler struct {
|
|
|
|
|
ClientConfig map[string]*domain.Client
|
|
|
|
|
Sessions *SessionStore
|
|
|
|
|
Users domain.UserRepository
|
KEY-WP-0005-T01: IAM Profile core claims for the human PKCE flow
Verified first: grant_types_supported advertises client_credentials in
discovery.go, but token.go only ever accepted authorization_code -- no
service-token issuance path exists at all. Building one from scratch is
materially bigger than extending the existing flow; explicitly not
attempted here, left open in the workplan rather than declared done.
What shipped for the human Authorization Code + PKCE flow:
- domain.User.Tenant (new, omitempty) + token.go's effectiveTenant():
falls back to tenant:coulomb (this workstation's actual tenant, ADR-0006)
when unset -- never an empty tenant claim, never a silent reassignment.
- principal_type: "human", unconditional.
- groups/roles promoted from scope-gated to unconditional core claims,
always [] not null when empty. One pre-existing test asserted the old
scope-gated groups behavior -- updated to match the new intentional
behavior, not left failing or reverted.
- assurance built from PKCESession.MFAVerified (new field, threaded
through completeAuthorization's two call sites in authorize.go) --
whether MFA was actually verified in this session, not static enrollment
state. aal2 only when required-and-passed this time, aal1 otherwise.
go build/vet clean, go test ./... green repo-wide. Two new authorize_test.go
cases assert MFAVerified on both paths. tests/profile/profile_test.go's
TestCompleteTokenFlow (the repo's own full HTTP integration test) extended
with real value assertions for all five claims, not just presence checks.
Python conformance tool not run against a live instance (needs the full
Authelia+LLDAP+privacyIDEA stack); TestCompleteTokenFlow's real HTTP round
trip covers the equivalent claim checks instead.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 00:03:31 +02:00
|
|
|
SigningKey *rsa.PrivateKey
|
2026-03-13 01:56:57 +01:00
|
|
|
Issuer string
|
|
|
|
|
TokenLifetime time.Duration
|
|
|
|
|
Emitter telemetry.Emitter
|
KEY-WP-0005-T02-T03: cached tenant_roles claim, close workplan
New internal/adapters/tenantengine package, mirroring
internal/adapters/{lldap,privacyidea,authelia}'s shape: Client.Roles()
calls tenant-engine's cache-read endpoint. Fails open by construction --
unreachable, non-200, malformed body, or a nil *Client all return
(nil, false), never an error to specially handle. Wired into
TokenHandler.TenantEngine (nil by default, existing tests unaffected);
token.go stamps tenant_roles only when ok.
7 adapter tests plus 3 TokenHandler-level tests proving the actual
required behavior end-to-end: present when reachable, token issuance still
200 with every other core claim intact when unreachable (tenant_roles
simply absent -- the literal done-criteria), absent when not configured.
Real bug found and fixed at the source, not worked around: the first live
cross-process check (real flex-auth, real tenant-engine, this adapter)
returned tenant_not_found for a tenant that existed -- tenant-engine's read
endpoint was keyed by its internal tenant_id, but key-cape only ever has
the tenant's profile identifier. Fixed in tenant-engine
(ADHOC-2026-07-24), re-verified with the same live three-process chain --
roles=[IAM] ok=true.
Workplan closed: T01-T03 done. Explicitly still open: client_credentials /
service-token issuance -- no such flow exists in token.go at all, a
materially larger separate piece of work than either task here.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 00:18:17 +02:00
|
|
|
// TenantEngine sources the optional tenant_roles claim (KEY-WP-0005-T02).
|
|
|
|
|
// Nil disables it entirely -- token issuance never depends on it.
|
|
|
|
|
TenantEngine *tenantengine.Client
|
2026-03-13 01:56:57 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// tokenResponse is the JSON body returned on a successful token exchange.
|
|
|
|
|
type tokenResponse struct {
|
|
|
|
|
AccessToken string `json:"access_token"`
|
|
|
|
|
TokenType string `json:"token_type"`
|
|
|
|
|
ExpiresIn int `json:"expires_in"`
|
2026-07-27 20:03:07 +02:00
|
|
|
IDToken string `json:"id_token,omitempty"`
|
2026-03-13 01:56:57 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ServeHTTP handles POST /token.
|
|
|
|
|
func (h *TokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
ctx := r.Context()
|
|
|
|
|
|
|
|
|
|
if err := r.ParseForm(); err != nil {
|
|
|
|
|
http.Error(w, "invalid form body", http.StatusBadRequest)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
grantType := r.FormValue("grant_type")
|
2026-07-27 20:03:07 +02:00
|
|
|
if grantType == "client_credentials" {
|
|
|
|
|
h.serveClientCredentials(w, r)
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-03-13 01:56:57 +01:00
|
|
|
clientID := r.FormValue("client_id")
|
|
|
|
|
code := r.FormValue("code")
|
|
|
|
|
codeVerifier := r.FormValue("code_verifier")
|
|
|
|
|
|
|
|
|
|
// 1. Validate grant_type.
|
|
|
|
|
if grantType != "authorization_code" {
|
|
|
|
|
profileerrors.FeatureNotSupported(
|
|
|
|
|
"only grant_type=authorization_code is supported",
|
|
|
|
|
"grant_type="+grantType,
|
|
|
|
|
).Write(w, http.StatusBadRequest)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
Harden the authorization-code grant and UserInfo verification
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
2026-09-06 22:43:47 +02:00
|
|
|
// 2. Validate client exists and may use this grant.
|
|
|
|
|
client, ok := h.ClientConfig[clientID]
|
|
|
|
|
if !ok {
|
2026-03-13 01:56:57 +01:00
|
|
|
profileerrors.InvalidProfileUsage("unknown client_id", "client_id").
|
|
|
|
|
Write(w, http.StatusBadRequest)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
Harden the authorization-code grant and UserInfo verification
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
2026-09-06 22:43:47 +02:00
|
|
|
// 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)
|
2026-03-13 01:56:57 +01:00
|
|
|
if !ok {
|
|
|
|
|
profileerrors.InvalidProfileUsage(
|
|
|
|
|
"authorization code not found or expired",
|
|
|
|
|
"code",
|
|
|
|
|
).Write(w, http.StatusBadRequest)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Verify client_id matches the session.
|
|
|
|
|
if sess.ClientID != clientID {
|
|
|
|
|
profileerrors.InvalidProfileUsage(
|
|
|
|
|
"client_id does not match the authorization code",
|
|
|
|
|
"client_id",
|
|
|
|
|
).Write(w, http.StatusBadRequest)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
Harden the authorization-code grant and UserInfo verification
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
2026-09-06 22:43:47 +02:00
|
|
|
// 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
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-05 00:41:17 +02:00
|
|
|
// Recheck grants in case the client registration changed after authorization.
|
|
|
|
|
for _, scope := range sess.Scopes {
|
|
|
|
|
if !containsString(h.ClientConfig[clientID].AllowedScopes, scope) {
|
|
|
|
|
profileerrors.InvalidProfileUsage("requested scope is not allowed", "scope").Write(w, http.StatusBadRequest)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-13 01:56:57 +01:00
|
|
|
// 4. Verify PKCE code_verifier.
|
|
|
|
|
if !verifyPKCE(codeVerifier, sess.PKCEChallenge) {
|
|
|
|
|
profileerrors.InvalidProfileUsage(
|
|
|
|
|
"code_verifier does not match code_challenge",
|
|
|
|
|
"code_verifier",
|
|
|
|
|
).Write(w, http.StatusBadRequest)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 5. Look up user.
|
|
|
|
|
user, err := h.Users.LookupUser(ctx, sess.Username)
|
|
|
|
|
if err != nil {
|
|
|
|
|
http.Error(w, "user not found", http.StatusInternalServerError)
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-07-28 01:23:22 +02:00
|
|
|
if isSuspended(user) {
|
|
|
|
|
profileerrors.RejectedForSafety(
|
|
|
|
|
"account is suspended",
|
|
|
|
|
"account_lifecycle",
|
|
|
|
|
).Write(w, http.StatusForbidden)
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-03-13 01:56:57 +01:00
|
|
|
|
|
|
|
|
// 6. Build JWT claims.
|
|
|
|
|
now := time.Now()
|
|
|
|
|
exp := now.Add(h.TokenLifetime)
|
|
|
|
|
|
|
|
|
|
claims := map[string]interface{}{
|
|
|
|
|
"iss": h.Issuer,
|
|
|
|
|
"sub": user.ID,
|
|
|
|
|
"aud": clientID,
|
|
|
|
|
"exp": exp.Unix(),
|
|
|
|
|
"iat": now.Unix(),
|
|
|
|
|
}
|
2026-06-01 21:20:54 +02:00
|
|
|
if sess.Nonce != "" {
|
|
|
|
|
claims["nonce"] = sess.Nonce
|
|
|
|
|
}
|
2026-03-13 01:56:57 +01:00
|
|
|
|
|
|
|
|
scopeSet := make(map[string]bool)
|
|
|
|
|
for _, s := range sess.Scopes {
|
|
|
|
|
scopeSet[s] = true
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if scopeSet["profile"] {
|
|
|
|
|
claims["preferred_username"] = user.Username
|
|
|
|
|
}
|
|
|
|
|
if scopeSet["email"] {
|
|
|
|
|
claims["email"] = user.Email
|
|
|
|
|
}
|
KEY-WP-0005-T01: IAM Profile core claims for the human PKCE flow
Verified first: grant_types_supported advertises client_credentials in
discovery.go, but token.go only ever accepted authorization_code -- no
service-token issuance path exists at all. Building one from scratch is
materially bigger than extending the existing flow; explicitly not
attempted here, left open in the workplan rather than declared done.
What shipped for the human Authorization Code + PKCE flow:
- domain.User.Tenant (new, omitempty) + token.go's effectiveTenant():
falls back to tenant:coulomb (this workstation's actual tenant, ADR-0006)
when unset -- never an empty tenant claim, never a silent reassignment.
- principal_type: "human", unconditional.
- groups/roles promoted from scope-gated to unconditional core claims,
always [] not null when empty. One pre-existing test asserted the old
scope-gated groups behavior -- updated to match the new intentional
behavior, not left failing or reverted.
- assurance built from PKCESession.MFAVerified (new field, threaded
through completeAuthorization's two call sites in authorize.go) --
whether MFA was actually verified in this session, not static enrollment
state. aal2 only when required-and-passed this time, aal1 otherwise.
go build/vet clean, go test ./... green repo-wide. Two new authorize_test.go
cases assert MFAVerified on both paths. tests/profile/profile_test.go's
TestCompleteTokenFlow (the repo's own full HTTP integration test) extended
with real value assertions for all five claims, not just presence checks.
Python conformance tool not run against a live instance (needs the full
Authelia+LLDAP+privacyIDEA stack); TestCompleteTokenFlow's real HTTP round
trip covers the equivalent claim checks instead.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 00:03:31 +02:00
|
|
|
|
|
|
|
|
// Core claims required by net-kingdom/canon/standards/iam-profile_v0.3.md
|
|
|
|
|
// for every production token -- not scope-gated, unlike the recommended
|
|
|
|
|
// human claims above (KEY-WP-0005-T01).
|
Carry the tenant claim's provenance, and correct a guard the ruling voided
GH-DEC-2026-013 §5 is a finding nobody asked for and ours to implement: tenant is
a bare string, so a consumer cannot tell a zone the directory asserted about the
person from one a registration supplied about the client they came through.
approval-engine exact-matches that string while its contract reads as though it
relies on the first -- the check is sound and the property a reader infers from
it is absent. gate-house named the property and left the mechanism to us.
Every token now carries tenant_source beside tenant: directory, registration or
default. Advertised in claims_supported, and asserted at the token level on both
grants rather than only in the resolution function, since the claim a consumer
reads is the thing under obligation.
Three values where the ruling names two, which is the judgement here. Labelling
an unasserted profile default as directory would reproduce the same defect one
level down -- a consumer reading an assertion the identity layer never made. The
ruling cites GH-DEC-2026-011 §3 on unknown versus absent for the case it
examined; the same rule applies to our own fallback. The agreement case resolves
to directory deliberately: if a registration declares the zone the directory also
assigned, the directory did assert it, and reporting the weaker source would
understate what is known.
Also corrects the guard shipped in 5f516a0. Its failure message offered two ways
out of adding dynamic registration, and condition (b) voids the second: admitting
dynamic registration voids the registration-bound shape that day, whatever state
the adapter is in. The message named an inadmissible resolution in the exact
place someone would read it while making that change.
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
2026-09-10 07:58:29 +02:00
|
|
|
tenant, tenantSource, err := humanTenant(h.ClientConfig[clientID], user)
|
2026-09-09 14:40:36 +02:00
|
|
|
if err != nil {
|
|
|
|
|
profileerrors.RejectedForSafety(
|
|
|
|
|
"tenant binding conflict",
|
|
|
|
|
"tenant_binding",
|
|
|
|
|
).Write(w, http.StatusForbidden)
|
|
|
|
|
return
|
|
|
|
|
}
|
KEY-WP-0005-T02-T03: cached tenant_roles claim, close workplan
New internal/adapters/tenantengine package, mirroring
internal/adapters/{lldap,privacyidea,authelia}'s shape: Client.Roles()
calls tenant-engine's cache-read endpoint. Fails open by construction --
unreachable, non-200, malformed body, or a nil *Client all return
(nil, false), never an error to specially handle. Wired into
TokenHandler.TenantEngine (nil by default, existing tests unaffected);
token.go stamps tenant_roles only when ok.
7 adapter tests plus 3 TokenHandler-level tests proving the actual
required behavior end-to-end: present when reachable, token issuance still
200 with every other core claim intact when unreachable (tenant_roles
simply absent -- the literal done-criteria), absent when not configured.
Real bug found and fixed at the source, not worked around: the first live
cross-process check (real flex-auth, real tenant-engine, this adapter)
returned tenant_not_found for a tenant that existed -- tenant-engine's read
endpoint was keyed by its internal tenant_id, but key-cape only ever has
the tenant's profile identifier. Fixed in tenant-engine
(ADHOC-2026-07-24), re-verified with the same live three-process chain --
roles=[IAM] ok=true.
Workplan closed: T01-T03 done. Explicitly still open: client_credentials /
service-token issuance -- no such flow exists in token.go at all, a
materially larger separate piece of work than either task here.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 00:18:17 +02:00
|
|
|
claims["tenant"] = tenant
|
Carry the tenant claim's provenance, and correct a guard the ruling voided
GH-DEC-2026-013 §5 is a finding nobody asked for and ours to implement: tenant is
a bare string, so a consumer cannot tell a zone the directory asserted about the
person from one a registration supplied about the client they came through.
approval-engine exact-matches that string while its contract reads as though it
relies on the first -- the check is sound and the property a reader infers from
it is absent. gate-house named the property and left the mechanism to us.
Every token now carries tenant_source beside tenant: directory, registration or
default. Advertised in claims_supported, and asserted at the token level on both
grants rather than only in the resolution function, since the claim a consumer
reads is the thing under obligation.
Three values where the ruling names two, which is the judgement here. Labelling
an unasserted profile default as directory would reproduce the same defect one
level down -- a consumer reading an assertion the identity layer never made. The
ruling cites GH-DEC-2026-011 §3 on unknown versus absent for the case it
examined; the same rule applies to our own fallback. The agreement case resolves
to directory deliberately: if a registration declares the zone the directory also
assigned, the directory did assert it, and reporting the weaker source would
understate what is known.
Also corrects the guard shipped in 5f516a0. Its failure message offered two ways
out of adding dynamic registration, and condition (b) voids the second: admitting
dynamic registration voids the registration-bound shape that day, whatever state
the adapter is in. The message named an inadmissible resolution in the exact
place someone would read it while making that change.
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
2026-09-10 07:58:29 +02:00
|
|
|
claims["tenant_source"] = tenantSource
|
KEY-WP-0005-T01: IAM Profile core claims for the human PKCE flow
Verified first: grant_types_supported advertises client_credentials in
discovery.go, but token.go only ever accepted authorization_code -- no
service-token issuance path exists at all. Building one from scratch is
materially bigger than extending the existing flow; explicitly not
attempted here, left open in the workplan rather than declared done.
What shipped for the human Authorization Code + PKCE flow:
- domain.User.Tenant (new, omitempty) + token.go's effectiveTenant():
falls back to tenant:coulomb (this workstation's actual tenant, ADR-0006)
when unset -- never an empty tenant claim, never a silent reassignment.
- principal_type: "human", unconditional.
- groups/roles promoted from scope-gated to unconditional core claims,
always [] not null when empty. One pre-existing test asserted the old
scope-gated groups behavior -- updated to match the new intentional
behavior, not left failing or reverted.
- assurance built from PKCESession.MFAVerified (new field, threaded
through completeAuthorization's two call sites in authorize.go) --
whether MFA was actually verified in this session, not static enrollment
state. aal2 only when required-and-passed this time, aal1 otherwise.
go build/vet clean, go test ./... green repo-wide. Two new authorize_test.go
cases assert MFAVerified on both paths. tests/profile/profile_test.go's
TestCompleteTokenFlow (the repo's own full HTTP integration test) extended
with real value assertions for all five claims, not just presence checks.
Python conformance tool not run against a live instance (needs the full
Authelia+LLDAP+privacyIDEA stack); TestCompleteTokenFlow's real HTTP round
trip covers the equivalent claim checks instead.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 00:03:31 +02:00
|
|
|
claims["principal_type"] = "human"
|
|
|
|
|
claims["groups"] = nonNilStrings(user.Groups)
|
|
|
|
|
claims["roles"] = nonNilStrings(user.Roles)
|
Answer the approver-client questions, and fix what checking them turned up
informed-decision and approval-engine both asked to hear problems with the human
approver registration now rather than at handover. Checking their requested shape
against the source rather than agreeing it on paper turned up three things.
Scope gap, accepted: [openid, approval:approve] cannot render a decision, since
GET /v1/approvals/{id} and /claim both need approval:read -- the surface could
submit an entry it was never able to display. Published
[openid, approval:read, approval:approve]. Reading through a service identity was
the alternative and is worse: it weakens the evidence-of-what-this-person-saw
claim the component exists to make. approval:consume stays excluded.
Assurance shape, published and a defect fixed. Both asked for a documented shape
and KeyCape already emitted one, so it is written down rather than renegotiated.
Writing it down surfaced that `at` was the token mint time rather than the
authentication time. Those differ by hours whenever a browser session is reused,
and approval-engine persists this object verbatim as the only downstream record
that MFA happened -- so a stored approval could have evidenced MFA at a moment
the person proved nothing. PKCESession.AuthTime now carries the original login
instant through session reuse, with mint time as the fallback.
Blocker found before anyone built on it: a human token cannot carry
tenant:platform. effectiveTenant resolves the human tenant from the directory
user, no adapter populates User.Tenant, and the per-client tenant field is read
only on the client_credentials path -- so every human token defaults to
tenant:coulomb, which approval-engine refuses by exact string equality. It would
have presented as a failed approval rather than a registration defect. Two
resolutions sent to the owners and neither implemented here: the choice decides
whether a human's tenant is a property of the person or of the registration, and
that is not KeyCape's alone to make.
Also recorded ops-warden's answers to KEY-WP-0014-T04, including their finding
that `warden plan` returns `autonomous` for a need containing generate and
CAS-write, because it has no read-versus-mutate intent. Their standing
instruction -- treat a warden plan verdict on any write, rotate or provision need
as unreliable until WARDEN-WP-0038 lands -- is recorded in the workplan rather
than left in an inbox.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uV8zoCKpA1WRAxsKRYbdH
Assistant: claude-code
Assistant-Model: opus
Assistant-Process: 1182213@bnt-lap001
Assistant-Session: 966597b9-ae61-46a4-8b9e-1594ab3ec4ad
2026-09-09 14:25:38 +02:00
|
|
|
claims["assurance"] = assuranceClaim(sess.MFAVerified, sess.AuthTime, now)
|
2026-03-13 01:56:57 +01:00
|
|
|
|
KEY-WP-0005-T02-T03: cached tenant_roles claim, close workplan
New internal/adapters/tenantengine package, mirroring
internal/adapters/{lldap,privacyidea,authelia}'s shape: Client.Roles()
calls tenant-engine's cache-read endpoint. Fails open by construction --
unreachable, non-200, malformed body, or a nil *Client all return
(nil, false), never an error to specially handle. Wired into
TokenHandler.TenantEngine (nil by default, existing tests unaffected);
token.go stamps tenant_roles only when ok.
7 adapter tests plus 3 TokenHandler-level tests proving the actual
required behavior end-to-end: present when reachable, token issuance still
200 with every other core claim intact when unreachable (tenant_roles
simply absent -- the literal done-criteria), absent when not configured.
Real bug found and fixed at the source, not worked around: the first live
cross-process check (real flex-auth, real tenant-engine, this adapter)
returned tenant_not_found for a tenant that existed -- tenant-engine's read
endpoint was keyed by its internal tenant_id, but key-cape only ever has
the tenant's profile identifier. Fixed in tenant-engine
(ADHOC-2026-07-24), re-verified with the same live three-process chain --
roles=[IAM] ok=true.
Workplan closed: T01-T03 done. Explicitly still open: client_credentials /
service-token issuance -- no such flow exists in token.go at all, a
materially larger separate piece of work than either task here.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 00:18:17 +02:00
|
|
|
// Optional cached tenant_roles claim (KEY-WP-0005-T02). Fails open --
|
|
|
|
|
// see internal/adapters/tenantengine's package doc for why this is the
|
|
|
|
|
// one place in the whole tenant_roles design where that's correct.
|
|
|
|
|
if roles, ok := h.TenantEngine.Roles(ctx, tenant); ok {
|
|
|
|
|
claims["tenant_roles"] = roles
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-13 01:56:57 +01:00
|
|
|
// 7. Sign JWT with RSA-SHA256.
|
|
|
|
|
kid := "key-1" // static kid for v0.1
|
|
|
|
|
jwtToken, err := buildJWT(claims, kid, h.SigningKey)
|
|
|
|
|
if err != nil {
|
|
|
|
|
http.Error(w, "failed to build JWT", http.StatusInternalServerError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-05 00:41:17 +02:00
|
|
|
// Access tokens target the statically registered resource server. ID tokens
|
|
|
|
|
// remain bound to the OIDC relying party.
|
|
|
|
|
if audience := h.ClientConfig[clientID].Audience; audience != "" {
|
|
|
|
|
claims["aud"] = audience
|
|
|
|
|
}
|
|
|
|
|
claims["scope"] = strings.Join(sess.Scopes, " ")
|
|
|
|
|
accessToken, err := buildJWT(claims, kid, h.SigningKey)
|
|
|
|
|
if err != nil {
|
|
|
|
|
http.Error(w, "failed to build JWT", http.StatusInternalServerError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
Harden the authorization-code grant and UserInfo verification
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
2026-09-06 22:43:47 +02:00
|
|
|
// 8. Build response. The session was already consumed at lookup, so no
|
|
|
|
|
// separate replay-prevention delete is needed here.
|
2026-03-13 01:56:57 +01:00
|
|
|
resp := tokenResponse{
|
2026-09-05 00:41:17 +02:00
|
|
|
AccessToken: accessToken,
|
2026-03-13 01:56:57 +01:00
|
|
|
TokenType: "Bearer",
|
|
|
|
|
ExpiresIn: int(h.TokenLifetime.Seconds()),
|
|
|
|
|
IDToken: jwtToken,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 10. Emit token_issued telemetry.
|
|
|
|
|
h.Emitter.Emit(ctx, telemetry.Event{
|
|
|
|
|
Timestamp: time.Now(),
|
|
|
|
|
EventType: telemetry.EventTokenIssued,
|
|
|
|
|
ClientID: clientID,
|
|
|
|
|
Endpoint: "/token",
|
|
|
|
|
Result: "success",
|
|
|
|
|
Scopes: sess.Scopes,
|
|
|
|
|
GrantType: grantType,
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
|
_ = json.NewEncoder(w).Encode(resp)
|
|
|
|
|
}
|
|
|
|
|
|
Harden the authorization-code grant and UserInfo verification
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
2026-09-06 22:43:47 +02:00
|
|
|
// 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
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-27 20:03:07 +02:00
|
|
|
func (h *TokenHandler) serveClientCredentials(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
ctx := r.Context()
|
|
|
|
|
clientID, clientSecret, ok := r.BasicAuth()
|
|
|
|
|
if !ok {
|
|
|
|
|
profileerrors.InvalidProfileUsage("client_secret_basic authentication required", "Authorization").
|
|
|
|
|
Write(w, http.StatusUnauthorized)
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-09-05 01:08:58 +02:00
|
|
|
clientID, idErr := url.QueryUnescape(clientID)
|
|
|
|
|
clientSecret, secretErr := url.QueryUnescape(clientSecret)
|
|
|
|
|
if idErr != nil || secretErr != nil {
|
|
|
|
|
profileerrors.InvalidProfileUsage("invalid client authentication encoding", "Authorization").Write(w, http.StatusUnauthorized)
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-07-27 20:03:07 +02:00
|
|
|
client, ok := h.ClientConfig[clientID]
|
|
|
|
|
if !ok || client.ClientType != "confidential" || !containsString(client.GrantTypes, "client_credentials") {
|
|
|
|
|
profileerrors.InvalidProfileUsage("invalid confidential client", "client_id").
|
|
|
|
|
Write(w, http.StatusUnauthorized)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
presentedDigest := sha256.Sum256([]byte(clientSecret))
|
|
|
|
|
expectedDigest := sha256.Sum256([]byte(client.ClientSecret))
|
|
|
|
|
if client.ClientSecret == "" ||
|
|
|
|
|
subtle.ConstantTimeCompare(presentedDigest[:], expectedDigest[:]) != 1 {
|
|
|
|
|
profileerrors.InvalidProfileUsage("invalid client authentication", "Authorization").
|
|
|
|
|
Write(w, http.StatusUnauthorized)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
requestedScopes := strings.Fields(r.FormValue("scope"))
|
|
|
|
|
if len(requestedScopes) == 0 {
|
|
|
|
|
requestedScopes = append([]string(nil), client.AllowedScopes...)
|
|
|
|
|
}
|
|
|
|
|
for _, scope := range requestedScopes {
|
|
|
|
|
if !containsString(client.AllowedScopes, scope) {
|
|
|
|
|
profileerrors.InvalidProfileUsage("requested scope is not allowed", "scope").
|
|
|
|
|
Write(w, http.StatusBadRequest)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
now := time.Now()
|
2026-08-23 13:10:13 +02:00
|
|
|
tokenLifetime := h.TokenLifetime
|
|
|
|
|
if client.TokenLifetime > 0 {
|
|
|
|
|
tokenLifetime = client.TokenLifetime
|
|
|
|
|
}
|
2026-07-27 20:03:07 +02:00
|
|
|
claims := map[string]interface{}{
|
Carry the tenant claim's provenance, and correct a guard the ruling voided
GH-DEC-2026-013 §5 is a finding nobody asked for and ours to implement: tenant is
a bare string, so a consumer cannot tell a zone the directory asserted about the
person from one a registration supplied about the client they came through.
approval-engine exact-matches that string while its contract reads as though it
relies on the first -- the check is sound and the property a reader infers from
it is absent. gate-house named the property and left the mechanism to us.
Every token now carries tenant_source beside tenant: directory, registration or
default. Advertised in claims_supported, and asserted at the token level on both
grants rather than only in the resolution function, since the claim a consumer
reads is the thing under obligation.
Three values where the ruling names two, which is the judgement here. Labelling
an unasserted profile default as directory would reproduce the same defect one
level down -- a consumer reading an assertion the identity layer never made. The
ruling cites GH-DEC-2026-011 §3 on unknown versus absent for the case it
examined; the same rule applies to our own fallback. The agreement case resolves
to directory deliberately: if a registration declares the zone the directory also
assigned, the directory did assert it, and reporting the weaker source would
understate what is known.
Also corrects the guard shipped in 5f516a0. Its failure message offered two ways
out of adding dynamic registration, and condition (b) voids the second: admitting
dynamic registration voids the registration-bound shape that day, whatever state
the adapter is in. The message named an inadmissible resolution in the exact
place someone would read it while making that change.
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
2026-09-10 07:58:29 +02:00
|
|
|
"iss": h.Issuer,
|
|
|
|
|
"sub": client.ServiceSubject,
|
|
|
|
|
"aud": accessAudience(client),
|
|
|
|
|
"exp": now.Add(tokenLifetime).Unix(),
|
|
|
|
|
"iat": now.Unix(),
|
|
|
|
|
"tenant": client.Tenant,
|
|
|
|
|
// A service client's tenant is always registration-supplied: there is no
|
|
|
|
|
// directory principal behind it to assert one (GH-DEC-2026-013 §5).
|
|
|
|
|
"tenant_source": TenantSourceRegistration,
|
2026-07-27 20:03:07 +02:00
|
|
|
"principal_type": "service",
|
|
|
|
|
"groups": []string{},
|
|
|
|
|
"roles": nonNilStrings(client.Roles),
|
|
|
|
|
"scope": strings.Join(requestedScopes, " "),
|
|
|
|
|
"assurance": map[string]interface{}{
|
|
|
|
|
"level": "aal1", "methods": []string{"client_secret"},
|
|
|
|
|
"mfa": false, "source": "key-cape", "at": now.Unix(),
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
if roles, ok := h.TenantEngine.Roles(ctx, client.Tenant); ok {
|
|
|
|
|
claims["tenant_roles"] = roles
|
|
|
|
|
}
|
|
|
|
|
jwtToken, err := buildJWT(claims, "key-1", h.SigningKey)
|
|
|
|
|
if err != nil {
|
|
|
|
|
http.Error(w, "failed to build JWT", http.StatusInternalServerError)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
h.Emitter.Emit(ctx, telemetry.Event{
|
|
|
|
|
Timestamp: now, EventType: telemetry.EventTokenIssued, ClientID: clientID,
|
|
|
|
|
Endpoint: "/token", Result: "success", Scopes: requestedScopes,
|
|
|
|
|
GrantType: "client_credentials",
|
|
|
|
|
})
|
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
|
_ = json.NewEncoder(w).Encode(tokenResponse{
|
|
|
|
|
AccessToken: jwtToken, TokenType: "Bearer",
|
2026-08-23 13:10:13 +02:00
|
|
|
ExpiresIn: int(tokenLifetime.Seconds()),
|
2026-07-27 20:03:07 +02:00
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func containsString(values []string, wanted string) bool {
|
|
|
|
|
for _, value := range values {
|
|
|
|
|
if value == wanted {
|
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-28 01:23:22 +02:00
|
|
|
func isSuspended(user *domain.User) bool {
|
|
|
|
|
return containsString(user.Groups, "netkingdom-suspended")
|
|
|
|
|
}
|
|
|
|
|
|
KEY-WP-0005-T01: IAM Profile core claims for the human PKCE flow
Verified first: grant_types_supported advertises client_credentials in
discovery.go, but token.go only ever accepted authorization_code -- no
service-token issuance path exists at all. Building one from scratch is
materially bigger than extending the existing flow; explicitly not
attempted here, left open in the workplan rather than declared done.
What shipped for the human Authorization Code + PKCE flow:
- domain.User.Tenant (new, omitempty) + token.go's effectiveTenant():
falls back to tenant:coulomb (this workstation's actual tenant, ADR-0006)
when unset -- never an empty tenant claim, never a silent reassignment.
- principal_type: "human", unconditional.
- groups/roles promoted from scope-gated to unconditional core claims,
always [] not null when empty. One pre-existing test asserted the old
scope-gated groups behavior -- updated to match the new intentional
behavior, not left failing or reverted.
- assurance built from PKCESession.MFAVerified (new field, threaded
through completeAuthorization's two call sites in authorize.go) --
whether MFA was actually verified in this session, not static enrollment
state. aal2 only when required-and-passed this time, aal1 otherwise.
go build/vet clean, go test ./... green repo-wide. Two new authorize_test.go
cases assert MFAVerified on both paths. tests/profile/profile_test.go's
TestCompleteTokenFlow (the repo's own full HTTP integration test) extended
with real value assertions for all five claims, not just presence checks.
Python conformance tool not run against a live instance (needs the full
Authelia+LLDAP+privacyIDEA stack); TestCompleteTokenFlow's real HTTP round
trip covers the equivalent claim checks instead.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 00:03:31 +02:00
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
// IAM Profile core claims (KEY-WP-0005-T01)
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
// defaultTenant is the fallback tenant claim for users with no explicit
|
|
|
|
|
// Tenant assignment yet. This workstation currently operates a single
|
|
|
|
|
// tenant (tenant:coulomb, ADR-0006); later tenants (e.g. tenant:friendly:binky,
|
|
|
|
|
// ADR-0013) require an explicit domain.User.Tenant value -- this default
|
|
|
|
|
// never silently assigns a user to a tenant other than the platform's
|
|
|
|
|
// original one.
|
|
|
|
|
const defaultTenant = "tenant:coulomb"
|
|
|
|
|
|
|
|
|
|
// effectiveTenant resolves the tenant claim for a user, falling back to
|
|
|
|
|
// defaultTenant when the user has no explicit tenant assignment. The IAM
|
|
|
|
|
// Profile requires a non-empty tenant claim on every token.
|
|
|
|
|
func effectiveTenant(user *domain.User) string {
|
|
|
|
|
if user.Tenant != "" {
|
|
|
|
|
return user.Tenant
|
|
|
|
|
}
|
|
|
|
|
return defaultTenant
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-09 14:40:36 +02:00
|
|
|
// humanTenant resolves the tenant claim for a human token (KEY-WP-0013-T05).
|
|
|
|
|
//
|
|
|
|
|
// A human's tenant is normally a property of the person, read from the
|
|
|
|
|
// directory. But the approval chain is bound to the landlord zone by decision
|
|
|
|
|
// 5ed3fb35-eca9-413a-82b9-95171ba85bf6, and approval-engine compares the claim
|
|
|
|
|
// by exact string equality, so an approver client has to be able to state the
|
|
|
|
|
// zone it issues into. Without this every human token fell back to
|
|
|
|
|
// defaultTenant and would have been refused downstream -- as a failed approval
|
|
|
|
|
// rather than as a registration defect.
|
|
|
|
|
//
|
|
|
|
|
// The rule is deliberately not an override:
|
|
|
|
|
//
|
|
|
|
|
// - no client tenant declared -> the directory answer, unchanged;
|
|
|
|
|
// - declared, user unassigned -> the declared zone;
|
|
|
|
|
// - declared and equal -> agreement, no ambiguity;
|
|
|
|
|
// - declared and different -> refuse to issue.
|
|
|
|
|
//
|
|
|
|
|
// So a registration can bind a zone for users the directory has not placed, and
|
|
|
|
|
// can never relabel a user the directory HAS placed into a different one. That
|
|
|
|
|
// last case fails closed rather than picking a winner, because either answer
|
|
|
|
|
// would be a silent cross-tenant assertion. It also means this stays correct if
|
|
|
|
|
// the directory later populates Tenant: the same code turns from supplying the
|
|
|
|
|
// zone into enforcing agreement with it, with no second migration.
|
|
|
|
|
//
|
|
|
|
|
// This is only safe because client registrations are static and
|
|
|
|
|
// deployment-owned; KeyCape excludes dynamic client registration by design. A
|
|
|
|
|
// self-service client that could name its users' tenant would be an escalation.
|
Carry the tenant claim's provenance, and correct a guard the ruling voided
GH-DEC-2026-013 §5 is a finding nobody asked for and ours to implement: tenant is
a bare string, so a consumer cannot tell a zone the directory asserted about the
person from one a registration supplied about the client they came through.
approval-engine exact-matches that string while its contract reads as though it
relies on the first -- the check is sound and the property a reader infers from
it is absent. gate-house named the property and left the mechanism to us.
Every token now carries tenant_source beside tenant: directory, registration or
default. Advertised in claims_supported, and asserted at the token level on both
grants rather than only in the resolution function, since the claim a consumer
reads is the thing under obligation.
Three values where the ruling names two, which is the judgement here. Labelling
an unasserted profile default as directory would reproduce the same defect one
level down -- a consumer reading an assertion the identity layer never made. The
ruling cites GH-DEC-2026-011 §3 on unknown versus absent for the case it
examined; the same rule applies to our own fallback. The agreement case resolves
to directory deliberately: if a registration declares the zone the directory also
assigned, the directory did assert it, and reporting the weaker source would
understate what is known.
Also corrects the guard shipped in 5f516a0. Its failure message offered two ways
out of adding dynamic registration, and condition (b) voids the second: admitting
dynamic registration voids the registration-bound shape that day, whatever state
the adapter is in. The message named an inadmissible resolution in the exact
place someone would read it while making that change.
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
2026-09-10 07:58:29 +02:00
|
|
|
func humanTenant(client *domain.Client, user *domain.User) (string, string, error) {
|
2026-09-09 14:40:36 +02:00
|
|
|
if client == nil || client.Tenant == "" {
|
Carry the tenant claim's provenance, and correct a guard the ruling voided
GH-DEC-2026-013 §5 is a finding nobody asked for and ours to implement: tenant is
a bare string, so a consumer cannot tell a zone the directory asserted about the
person from one a registration supplied about the client they came through.
approval-engine exact-matches that string while its contract reads as though it
relies on the first -- the check is sound and the property a reader infers from
it is absent. gate-house named the property and left the mechanism to us.
Every token now carries tenant_source beside tenant: directory, registration or
default. Advertised in claims_supported, and asserted at the token level on both
grants rather than only in the resolution function, since the claim a consumer
reads is the thing under obligation.
Three values where the ruling names two, which is the judgement here. Labelling
an unasserted profile default as directory would reproduce the same defect one
level down -- a consumer reading an assertion the identity layer never made. The
ruling cites GH-DEC-2026-011 §3 on unknown versus absent for the case it
examined; the same rule applies to our own fallback. The agreement case resolves
to directory deliberately: if a registration declares the zone the directory also
assigned, the directory did assert it, and reporting the weaker source would
understate what is known.
Also corrects the guard shipped in 5f516a0. Its failure message offered two ways
out of adding dynamic registration, and condition (b) voids the second: admitting
dynamic registration voids the registration-bound shape that day, whatever state
the adapter is in. The message named an inadmissible resolution in the exact
place someone would read it while making that change.
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
2026-09-10 07:58:29 +02:00
|
|
|
if user.Tenant != "" {
|
|
|
|
|
return user.Tenant, TenantSourceDirectory, nil
|
|
|
|
|
}
|
|
|
|
|
return defaultTenant, TenantSourceDefault, nil
|
2026-09-09 14:40:36 +02:00
|
|
|
}
|
Carry the tenant claim's provenance, and correct a guard the ruling voided
GH-DEC-2026-013 §5 is a finding nobody asked for and ours to implement: tenant is
a bare string, so a consumer cannot tell a zone the directory asserted about the
person from one a registration supplied about the client they came through.
approval-engine exact-matches that string while its contract reads as though it
relies on the first -- the check is sound and the property a reader infers from
it is absent. gate-house named the property and left the mechanism to us.
Every token now carries tenant_source beside tenant: directory, registration or
default. Advertised in claims_supported, and asserted at the token level on both
grants rather than only in the resolution function, since the claim a consumer
reads is the thing under obligation.
Three values where the ruling names two, which is the judgement here. Labelling
an unasserted profile default as directory would reproduce the same defect one
level down -- a consumer reading an assertion the identity layer never made. The
ruling cites GH-DEC-2026-011 §3 on unknown versus absent for the case it
examined; the same rule applies to our own fallback. The agreement case resolves
to directory deliberately: if a registration declares the zone the directory also
assigned, the directory did assert it, and reporting the weaker source would
understate what is known.
Also corrects the guard shipped in 5f516a0. Its failure message offered two ways
out of adding dynamic registration, and condition (b) voids the second: admitting
dynamic registration voids the registration-bound shape that day, whatever state
the adapter is in. The message named an inadmissible resolution in the exact
place someone would read it while making that change.
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
2026-09-10 07:58:29 +02:00
|
|
|
if user.Tenant != "" {
|
|
|
|
|
if user.Tenant != client.Tenant {
|
|
|
|
|
return "", "", fmt.Errorf("client %q binds tenant %q but the directory assigns this user a different tenant", client.ClientID, client.Tenant)
|
|
|
|
|
}
|
|
|
|
|
// Agreement: the directory did assert this about the person, so the
|
|
|
|
|
// stronger provenance is the true one.
|
|
|
|
|
return user.Tenant, TenantSourceDirectory, nil
|
2026-09-09 14:40:36 +02:00
|
|
|
}
|
Carry the tenant claim's provenance, and correct a guard the ruling voided
GH-DEC-2026-013 §5 is a finding nobody asked for and ours to implement: tenant is
a bare string, so a consumer cannot tell a zone the directory asserted about the
person from one a registration supplied about the client they came through.
approval-engine exact-matches that string while its contract reads as though it
relies on the first -- the check is sound and the property a reader infers from
it is absent. gate-house named the property and left the mechanism to us.
Every token now carries tenant_source beside tenant: directory, registration or
default. Advertised in claims_supported, and asserted at the token level on both
grants rather than only in the resolution function, since the claim a consumer
reads is the thing under obligation.
Three values where the ruling names two, which is the judgement here. Labelling
an unasserted profile default as directory would reproduce the same defect one
level down -- a consumer reading an assertion the identity layer never made. The
ruling cites GH-DEC-2026-011 §3 on unknown versus absent for the case it
examined; the same rule applies to our own fallback. The agreement case resolves
to directory deliberately: if a registration declares the zone the directory also
assigned, the directory did assert it, and reporting the weaker source would
understate what is known.
Also corrects the guard shipped in 5f516a0. Its failure message offered two ways
out of adding dynamic registration, and condition (b) voids the second: admitting
dynamic registration voids the registration-bound shape that day, whatever state
the adapter is in. The message named an inadmissible resolution in the exact
place someone would read it while making that change.
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
2026-09-10 07:58:29 +02:00
|
|
|
return client.Tenant, TenantSourceRegistration, nil
|
2026-09-09 14:40:36 +02:00
|
|
|
}
|
|
|
|
|
|
Carry the tenant claim's provenance, and correct a guard the ruling voided
GH-DEC-2026-013 §5 is a finding nobody asked for and ours to implement: tenant is
a bare string, so a consumer cannot tell a zone the directory asserted about the
person from one a registration supplied about the client they came through.
approval-engine exact-matches that string while its contract reads as though it
relies on the first -- the check is sound and the property a reader infers from
it is absent. gate-house named the property and left the mechanism to us.
Every token now carries tenant_source beside tenant: directory, registration or
default. Advertised in claims_supported, and asserted at the token level on both
grants rather than only in the resolution function, since the claim a consumer
reads is the thing under obligation.
Three values where the ruling names two, which is the judgement here. Labelling
an unasserted profile default as directory would reproduce the same defect one
level down -- a consumer reading an assertion the identity layer never made. The
ruling cites GH-DEC-2026-011 §3 on unknown versus absent for the case it
examined; the same rule applies to our own fallback. The agreement case resolves
to directory deliberately: if a registration declares the zone the directory also
assigned, the directory did assert it, and reporting the weaker source would
understate what is known.
Also corrects the guard shipped in 5f516a0. Its failure message offered two ways
out of adding dynamic registration, and condition (b) voids the second: admitting
dynamic registration voids the registration-bound shape that day, whatever state
the adapter is in. The message named an inadmissible resolution in the exact
place someone would read it while making that change.
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
2026-09-10 07:58:29 +02:00
|
|
|
// Tenant provenance values for the tenant_source claim (GH-DEC-2026-013 §5).
|
|
|
|
|
//
|
|
|
|
|
// A bare tenant string cannot tell a consumer whether the identity layer
|
|
|
|
|
// asserted the zone about this PERSON or a registration supplied it about the
|
|
|
|
|
// CLIENT they came through. approval-engine admits an approver by exact-matching
|
|
|
|
|
// that string while its contract reads as though it relies on the first, so the
|
|
|
|
|
// check is sound and the property a reader infers from it is absent. The ruling
|
|
|
|
|
// requires the claim to carry its provenance and forbids a consumer treating the
|
|
|
|
|
// two as equivalent for any decision turning on a fact about the person. It names
|
|
|
|
|
// the property; the field is ours.
|
|
|
|
|
//
|
|
|
|
|
// Three values, not the two the ruling names, and the third is the point. A
|
|
|
|
|
// tenant nobody asserted -- neither directory nor registration, just the
|
|
|
|
|
// profile's non-empty default -- is not directory-asserted, and labelling it so
|
|
|
|
|
// would reintroduce the same defect one level down: a consumer would read
|
|
|
|
|
// "directory" for a fact the directory never stated. That is the unknown-versus-
|
|
|
|
|
// absent distinction the ruling cites from GH-DEC-2026-011 §3, applied to our own
|
|
|
|
|
// fallback rather than only to the case we were asked about.
|
|
|
|
|
const (
|
|
|
|
|
// TenantSourceDirectory: the identity layer asserted this zone about this
|
|
|
|
|
// person. Includes the agreement case, where a registration declared the
|
|
|
|
|
// same zone the directory did -- the directory still asserted it.
|
|
|
|
|
TenantSourceDirectory = "directory"
|
|
|
|
|
|
|
|
|
|
// TenantSourceRegistration: supplied by the client registration for a person
|
|
|
|
|
// the directory has placed nowhere. A fact about the client, not the person.
|
|
|
|
|
TenantSourceRegistration = "registration"
|
|
|
|
|
|
|
|
|
|
// TenantSourceDefault: nobody asserted a zone; this is the profile default,
|
|
|
|
|
// emitted because the profile requires a non-empty tenant. Weaker than both.
|
|
|
|
|
TenantSourceDefault = "default"
|
|
|
|
|
)
|
|
|
|
|
|
KEY-WP-0005-T01: IAM Profile core claims for the human PKCE flow
Verified first: grant_types_supported advertises client_credentials in
discovery.go, but token.go only ever accepted authorization_code -- no
service-token issuance path exists at all. Building one from scratch is
materially bigger than extending the existing flow; explicitly not
attempted here, left open in the workplan rather than declared done.
What shipped for the human Authorization Code + PKCE flow:
- domain.User.Tenant (new, omitempty) + token.go's effectiveTenant():
falls back to tenant:coulomb (this workstation's actual tenant, ADR-0006)
when unset -- never an empty tenant claim, never a silent reassignment.
- principal_type: "human", unconditional.
- groups/roles promoted from scope-gated to unconditional core claims,
always [] not null when empty. One pre-existing test asserted the old
scope-gated groups behavior -- updated to match the new intentional
behavior, not left failing or reverted.
- assurance built from PKCESession.MFAVerified (new field, threaded
through completeAuthorization's two call sites in authorize.go) --
whether MFA was actually verified in this session, not static enrollment
state. aal2 only when required-and-passed this time, aal1 otherwise.
go build/vet clean, go test ./... green repo-wide. Two new authorize_test.go
cases assert MFAVerified on both paths. tests/profile/profile_test.go's
TestCompleteTokenFlow (the repo's own full HTTP integration test) extended
with real value assertions for all five claims, not just presence checks.
Python conformance tool not run against a live instance (needs the full
Authelia+LLDAP+privacyIDEA stack); TestCompleteTokenFlow's real HTTP round
trip covers the equivalent claim checks instead.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 00:03:31 +02:00
|
|
|
// nonNilStrings returns s, or an empty (non-nil) slice if s is nil, so the
|
|
|
|
|
// claim always serializes as `[]`, never `null` -- the profile requires
|
|
|
|
|
// groups/roles to be present, "possibly empty", not absent.
|
|
|
|
|
func nonNilStrings(s []string) []string {
|
|
|
|
|
if s == nil {
|
|
|
|
|
return []string{}
|
|
|
|
|
}
|
|
|
|
|
return s
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// assuranceClaim builds the profile's `assurance` object from whether MFA
|
|
|
|
|
// was actually verified during this authorization (session.MFAVerified),
|
|
|
|
|
// not from static enrollment state -- a user who has MFA enrolled but
|
|
|
|
|
// wasn't challenged for it in this particular flow gets aal1, not aal2.
|
Answer the approver-client questions, and fix what checking them turned up
informed-decision and approval-engine both asked to hear problems with the human
approver registration now rather than at handover. Checking their requested shape
against the source rather than agreeing it on paper turned up three things.
Scope gap, accepted: [openid, approval:approve] cannot render a decision, since
GET /v1/approvals/{id} and /claim both need approval:read -- the surface could
submit an entry it was never able to display. Published
[openid, approval:read, approval:approve]. Reading through a service identity was
the alternative and is worse: it weakens the evidence-of-what-this-person-saw
claim the component exists to make. approval:consume stays excluded.
Assurance shape, published and a defect fixed. Both asked for a documented shape
and KeyCape already emitted one, so it is written down rather than renegotiated.
Writing it down surfaced that `at` was the token mint time rather than the
authentication time. Those differ by hours whenever a browser session is reused,
and approval-engine persists this object verbatim as the only downstream record
that MFA happened -- so a stored approval could have evidenced MFA at a moment
the person proved nothing. PKCESession.AuthTime now carries the original login
instant through session reuse, with mint time as the fallback.
Blocker found before anyone built on it: a human token cannot carry
tenant:platform. effectiveTenant resolves the human tenant from the directory
user, no adapter populates User.Tenant, and the per-client tenant field is read
only on the client_credentials path -- so every human token defaults to
tenant:coulomb, which approval-engine refuses by exact string equality. It would
have presented as a failed approval rather than a registration defect. Two
resolutions sent to the owners and neither implemented here: the choice decides
whether a human's tenant is a property of the person or of the registration, and
that is not KeyCape's alone to make.
Also recorded ops-warden's answers to KEY-WP-0014-T04, including their finding
that `warden plan` returns `autonomous` for a need containing generate and
CAS-write, because it has no read-versus-mutate intent. Their standing
instruction -- treat a warden plan verdict on any write, rotate or provision need
as unreliable until WARDEN-WP-0038 lands -- is recorded in the workplan rather
than left in an inbox.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uV8zoCKpA1WRAxsKRYbdH
Assistant: claude-code
Assistant-Model: opus
Assistant-Process: 1182213@bnt-lap001
Assistant-Session: 966597b9-ae61-46a4-8b9e-1594ab3ec4ad
2026-09-09 14:25:38 +02:00
|
|
|
//
|
|
|
|
|
// `at` is the time the user authenticated, not the time this token was
|
|
|
|
|
// minted. Those differ whenever a browser session is reused, and the gap is
|
|
|
|
|
// the whole point: approval-engine stores this object verbatim as the only
|
|
|
|
|
// downstream record that MFA occurred (KEY-WP-0013-T05), so mint time would
|
|
|
|
|
// overstate how recently the person proved anything. issuedAt is the
|
|
|
|
|
// fallback for a session predating this field.
|
|
|
|
|
func assuranceClaim(mfaVerified bool, authTime, issuedAt time.Time) map[string]interface{} {
|
|
|
|
|
at := authTime
|
|
|
|
|
if at.IsZero() {
|
|
|
|
|
at = issuedAt
|
|
|
|
|
}
|
KEY-WP-0005-T01: IAM Profile core claims for the human PKCE flow
Verified first: grant_types_supported advertises client_credentials in
discovery.go, but token.go only ever accepted authorization_code -- no
service-token issuance path exists at all. Building one from scratch is
materially bigger than extending the existing flow; explicitly not
attempted here, left open in the workplan rather than declared done.
What shipped for the human Authorization Code + PKCE flow:
- domain.User.Tenant (new, omitempty) + token.go's effectiveTenant():
falls back to tenant:coulomb (this workstation's actual tenant, ADR-0006)
when unset -- never an empty tenant claim, never a silent reassignment.
- principal_type: "human", unconditional.
- groups/roles promoted from scope-gated to unconditional core claims,
always [] not null when empty. One pre-existing test asserted the old
scope-gated groups behavior -- updated to match the new intentional
behavior, not left failing or reverted.
- assurance built from PKCESession.MFAVerified (new field, threaded
through completeAuthorization's two call sites in authorize.go) --
whether MFA was actually verified in this session, not static enrollment
state. aal2 only when required-and-passed this time, aal1 otherwise.
go build/vet clean, go test ./... green repo-wide. Two new authorize_test.go
cases assert MFAVerified on both paths. tests/profile/profile_test.go's
TestCompleteTokenFlow (the repo's own full HTTP integration test) extended
with real value assertions for all five claims, not just presence checks.
Python conformance tool not run against a live instance (needs the full
Authelia+LLDAP+privacyIDEA stack); TestCompleteTokenFlow's real HTTP round
trip covers the equivalent claim checks instead.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 00:03:31 +02:00
|
|
|
level := "aal1"
|
|
|
|
|
methods := []string{"pwd"}
|
|
|
|
|
if mfaVerified {
|
|
|
|
|
level = "aal2"
|
|
|
|
|
methods = append(methods, "otp")
|
|
|
|
|
}
|
|
|
|
|
return map[string]interface{}{
|
|
|
|
|
"level": level,
|
|
|
|
|
"methods": methods,
|
|
|
|
|
"mfa": mfaVerified,
|
|
|
|
|
"source": "key-cape",
|
|
|
|
|
"at": at.Unix(),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-13 01:56:57 +01:00
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
// PKCE verification
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
// verifyPKCE checks BASE64URL(SHA256(verifier)) == challenge (S256 method).
|
|
|
|
|
func verifyPKCE(verifier, challenge string) bool {
|
|
|
|
|
h := sha256.New()
|
|
|
|
|
h.Write([]byte(verifier))
|
|
|
|
|
computed := base64.RawURLEncoding.EncodeToString(h.Sum(nil))
|
|
|
|
|
return computed == challenge
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
// JWT construction (stdlib only — no external JWT library)
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
type jwtHeader struct {
|
|
|
|
|
Alg string `json:"alg"`
|
|
|
|
|
Typ string `json:"typ"`
|
|
|
|
|
Kid string `json:"kid"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// buildJWT constructs and signs a JWT using RSA-SHA256 with the standard library.
|
|
|
|
|
// Format: base64url(header) + "." + base64url(payload) + "." + base64url(signature)
|
|
|
|
|
func buildJWT(claims map[string]interface{}, kid string, key *rsa.PrivateKey) (string, error) {
|
|
|
|
|
// Header.
|
|
|
|
|
hdr := jwtHeader{Alg: "RS256", Typ: "JWT", Kid: kid}
|
|
|
|
|
hdrJSON, err := json.Marshal(hdr)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return "", err
|
|
|
|
|
}
|
|
|
|
|
hdrB64 := base64.RawURLEncoding.EncodeToString(hdrJSON)
|
|
|
|
|
|
|
|
|
|
// Payload.
|
|
|
|
|
payloadJSON, err := json.Marshal(claims)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return "", err
|
|
|
|
|
}
|
|
|
|
|
payloadB64 := base64.RawURLEncoding.EncodeToString(payloadJSON)
|
|
|
|
|
|
|
|
|
|
// Signing input.
|
|
|
|
|
signingInput := hdrB64 + "." + payloadB64
|
|
|
|
|
|
|
|
|
|
// Digest.
|
|
|
|
|
digest := sha256.Sum256([]byte(signingInput))
|
|
|
|
|
|
|
|
|
|
// Sign with PKCS1v15 / SHA256.
|
|
|
|
|
sig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, digest[:])
|
|
|
|
|
if err != nil {
|
|
|
|
|
return "", err
|
|
|
|
|
}
|
|
|
|
|
sigB64 := base64.RawURLEncoding.EncodeToString(sig)
|
|
|
|
|
|
|
|
|
|
return strings.Join([]string{hdrB64, payloadB64, sigB64}, "."), nil
|
|
|
|
|
}
|
2026-09-05 00:41:17 +02:00
|
|
|
|
|
|
|
|
// accessAudience is configured by the issuer, never selected by request input.
|
|
|
|
|
func accessAudience(client *domain.Client) string {
|
|
|
|
|
if client.Audience != "" {
|
|
|
|
|
return client.Audience
|
|
|
|
|
}
|
|
|
|
|
return client.ClientID
|
|
|
|
|
}
|