key-cape/src/internal/server/oidc/discovery.go

128 lines
5.4 KiB
Go
Raw Normal View History

// Package oidc implements OIDC profile endpoints for KeyCape.
// Only profile-supported features are advertised — no implicit flow,
// no dynamic registration, no request objects.
package oidc
import (
"encoding/json"
"net/http"
2026-09-07 00:22:49 +02:00
"sort"
"keycape/internal/domain"
)
// DiscoveryConfig holds the issuer and endpoint URLs for the discovery document.
// UserinfoEndpoint is optional; if empty it is omitted from the document.
type DiscoveryConfig struct {
Issuer string // e.g. "https://auth.netkingdom.local"
AuthorizationEndpoint string
TokenEndpoint string
JWKSUri string
UserinfoEndpoint string // optional, empty = not advertised
EndSessionEndpoint string // optional, empty = not advertised
2026-09-07 00:22:49 +02:00
// Clients supplies the registered clients so scopes_supported reflects the
// scopes this deployment can actually grant, rather than a fixed list that
// omits every configured resource scope (KEY-WP-0017-T03). Nil or empty
// leaves only the baseline OIDC scopes advertised.
Clients map[string]*domain.Client
}
// discoveryDocument is the JSON shape of /.well-known/openid-configuration.
// Fields are ordered to match common OIDC implementations for readability.
// registration_endpoint is intentionally absent — no dynamic client registration.
type discoveryDocument struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
JWKSUri string `json:"jwks_uri"`
UserinfoEndpoint string `json:"userinfo_endpoint,omitempty"`
EndSessionEndpoint string `json:"end_session_endpoint,omitempty"`
ResponseTypesSupported []string `json:"response_types_supported"`
GrantTypesSupported []string `json:"grant_types_supported"`
CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported"`
IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"`
ScopesSupported []string `json:"scopes_supported"`
TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported"`
ClaimsSupported []string `json:"claims_supported"`
SubjectTypesSupported []string `json:"subject_types_supported"`
RequestParameterSupported bool `json:"request_parameter_supported"`
ClaimsParameterSupported bool `json:"claims_parameter_supported"`
}
// discoveryHandler implements http.Handler for GET /.well-known/openid-configuration.
type discoveryHandler struct {
doc []byte
}
// NewDiscoveryHandler returns an http.Handler that serves the OIDC discovery document.
// The document is pre-serialised at construction time so every request is a cheap copy.
func NewDiscoveryHandler(cfg DiscoveryConfig) http.Handler {
d := discoveryDocument{
Issuer: cfg.Issuer,
AuthorizationEndpoint: cfg.AuthorizationEndpoint,
TokenEndpoint: cfg.TokenEndpoint,
JWKSUri: cfg.JWKSUri,
UserinfoEndpoint: cfg.UserinfoEndpoint,
EndSessionEndpoint: cfg.EndSessionEndpoint,
// Profile-locked values — not negotiable.
ResponseTypesSupported: []string{"code"},
GrantTypesSupported: []string{"authorization_code", "client_credentials"},
CodeChallengeMethodsSupported: []string{"S256"},
IDTokenSigningAlgValuesSupported: []string{"RS256"},
2026-09-07 00:22:49 +02:00
ScopesSupported: supportedScopes(cfg.Clients),
TokenEndpointAuthMethodsSupported: []string{"client_secret_basic", "none"},
2026-09-07 00:22:49 +02:00
// Core profile claims are emitted on every token, so omitting one here
// is a contract defect rather than missing optional metadata. The
// scope-gated human claims and the optional cached tenant_roles claim
// follow them.
ClaimsSupported: []string{
"sub", "iss", "aud", "exp", "iat",
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", "tenant_source", "principal_type", "roles", "groups", "assurance", "scope",
2026-09-07 00:22:49 +02:00
"nonce", "preferred_username", "email", "name", "tenant_roles",
},
SubjectTypesSupported: []string{"public"},
RequestParameterSupported: false,
ClaimsParameterSupported: false,
}
b, err := json.Marshal(d)
if err != nil {
// This can only fail if the struct contains un-marshallable types, which it does not.
panic("oidc: failed to marshal discovery document: " + err.Error())
}
return &discoveryHandler{doc: b}
}
func (h *discoveryHandler) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "max-age=3600")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(h.doc)
}
2026-09-07 00:22:49 +02:00
// supportedScopes returns the baseline OIDC scopes plus every scope any
// registered client is allowed to request, sorted for a stable document. The
// baseline is advertised even with no clients configured, since it describes the
// profile rather than a particular deployment.
func supportedScopes(clients map[string]*domain.Client) []string {
seen := map[string]bool{}
scopes := []string{}
for _, scope := range []string{"openid", "profile", "email", "groups"} {
seen[scope] = true
scopes = append(scopes, scope)
}
extra := []string{}
for _, client := range clients {
for _, scope := range client.AllowedScopes {
if scope == "" || seen[scope] {
continue
}
seen[scope] = true
extra = append(extra, scope)
}
}
sort.Strings(extra)
return append(scopes, extra...)
}