Reconcile the canonical model and discovery with the runtime
All checks were successful
Build and Publish Container Image / build-and-push (push) Successful in 40s

Closes gap G02 of the scope assessment for the client-registration and discovery
surface. spec/canonical-model.yaml and domain/model.go both claimed to be the
source of truth and disagreed: the spec restricted grants to authorization_code,
required redirect URIs of every client, and omitted the audience, service
subject, tenant, role, MFA and handoff fields the runtime reads.

The durable part is the link, not the edit. A two-way conformance test compares
the spec against the Go model by reflection and fails when a runtime field has
no spec entry or a spec entry is not read by the runtime, the latter unless
marked runtime: false. It found drift beyond the assessment's list on its first
run -- User.tenant was undeclared -- which is the argument for the check over a
one-time reconciliation.

Discovery now advertises the core profile claims that appear on every token and
derives scopes_supported from the registered clients rather than a fixed list.

The Go model is stated as the runtime authority and the YAML as the reviewed
contract, in both files. This covers client registration and discovery, not
schema enforcement in general, which remains G06.

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

Assistant: claude-code
Assistant-Model: opus
Assistant-Process: 713576@bnt-lap001
Assistant-Session: 384c511d-9bce-4cb8-a676-2aef6c0c8df6
This commit is contained in:
tegwick 2026-09-07 00:22:49 +02:00
parent 0d7e2f6b41
commit a770ac67d0
9 changed files with 441 additions and 15 deletions

View file

@ -141,6 +141,7 @@ func main() {
JWKSUri: issuer + "/jwks",
UserinfoEndpoint: issuer + "/userinfo",
EndSessionEndpoint: issuer + "/logout",
Clients: clients,
}))
// JWKS.

View file

@ -0,0 +1,126 @@
package domain_test
import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"gopkg.in/yaml.v3"
"keycape/internal/domain"
)
// KEY-WP-0017-T02 — the executable link between spec/canonical-model.yaml and
// the runtime model. Reconciling the two files by hand leaves them free to drift
// again immediately; this fails the build when they do, in either direction.
//
// The contract is deliberately two-way:
//
// - every YAML-serialised field of domain.Client must have a spec entry, so a
// new runtime field cannot be added without describing it; and
// - every spec field must either exist in the Go model or carry
// `runtime: false`, so declaring a field the runtime ignores is a visible,
// reviewable act rather than an omission.
//
// Fields tagged `yaml:"-"` are excluded by construction: they are runtime policy
// or secret material, not identity data the canonical model describes.
type specModel struct {
Entities map[string]struct {
Fields map[string]struct {
Runtime *bool `yaml:"runtime"`
} `yaml:"fields"`
} `yaml:"entities"`
}
func loadSpec(t *testing.T) specModel {
t.Helper()
path := filepath.Join("..", "..", "..", "spec", "canonical-model.yaml")
raw, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read canonical model: %v", err)
}
var model specModel
if err := yaml.Unmarshal(raw, &model); err != nil {
t.Fatalf("parse canonical model: %v", err)
}
if len(model.Entities) == 0 {
t.Fatal("canonical model declares no entities")
}
return model
}
// serialisedFields returns the YAML field names of a struct, skipping those
// explicitly excluded with `yaml:"-"`.
func serialisedFields(t *testing.T, v interface{}) map[string]bool {
t.Helper()
typ := reflect.TypeOf(v)
fields := make(map[string]bool, typ.NumField())
for i := 0; i < typ.NumField(); i++ {
tag := typ.Field(i).Tag.Get("yaml")
name := strings.Split(tag, ",")[0]
if name == "" || name == "-" {
continue
}
fields[name] = true
}
return fields
}
func TestCanonicalModelMatchesRuntimeClient(t *testing.T) {
spec := loadSpec(t)
entity, ok := spec.Entities["Client"]
if !ok {
t.Fatal("canonical model has no Client entity")
}
goFields := serialisedFields(t, domain.Client{})
for name := range goFields {
field, ok := entity.Fields[name]
if !ok {
t.Errorf("domain.Client field %q has no entry in spec/canonical-model.yaml", name)
continue
}
if field.Runtime != nil && !*field.Runtime {
t.Errorf("spec field %q is marked runtime:false but domain.Client reads it", name)
}
}
for name, field := range entity.Fields {
if goFields[name] {
continue
}
if field.Runtime == nil || *field.Runtime {
t.Errorf("spec field Client.%q is not read by domain.Client; add runtime: false if that is deliberate", name)
}
}
}
// The same two-way check for the directory entities the migration and validator
// paths serialise.
func TestCanonicalModelMatchesRuntimeDirectoryEntities(t *testing.T) {
spec := loadSpec(t)
for entityName, value := range map[string]interface{}{
"User": domain.User{},
"Group": domain.Group{},
"Membership": domain.Membership{},
} {
entity, ok := spec.Entities[entityName]
if !ok {
t.Errorf("canonical model has no %s entity", entityName)
continue
}
for name := range serialisedFields(t, value) {
field, ok := entity.Fields[name]
if !ok {
t.Errorf("domain.%s field %q has no entry in spec/canonical-model.yaml", entityName, name)
continue
}
if field.Runtime != nil && !*field.Runtime {
t.Errorf("spec field %s.%q is marked runtime:false but the runtime reads it", entityName, name)
}
}
}
}

View file

@ -1,6 +1,13 @@
// Package domain contains the canonical identity model for KeyCape.
// This is the source of truth for all user, group, client, and MFA data.
// All provisioning, tests, and migrations derive from these types.
//
// These types are the runtime authority for all user, group, client and MFA
// data: the server reads them, not spec/canonical-model.yaml. That YAML is the
// reviewed contract, and conformance_test.go holds the two together — adding a
// serialised field here without describing it there fails the build, and so
// does describing a field there that nothing here reads (KEY-WP-0017).
//
// Fields tagged `yaml:"-"` are outside the canonical model by construction:
// they are runtime policy or secret material, not identity data.
package domain
import "time"

View file

@ -6,6 +6,9 @@ package oidc
import (
"encoding/json"
"net/http"
"sort"
"keycape/internal/domain"
)
// DiscoveryConfig holds the issuer and endpoint URLs for the discovery document.
@ -17,6 +20,11 @@ type DiscoveryConfig struct {
JWKSUri string
UserinfoEndpoint string // optional, empty = not advertised
EndSessionEndpoint string // optional, empty = not advertised
// 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.
@ -62,11 +70,16 @@ func NewDiscoveryHandler(cfg DiscoveryConfig) http.Handler {
GrantTypesSupported: []string{"authorization_code", "client_credentials"},
CodeChallengeMethodsSupported: []string{"S256"},
IDTokenSigningAlgValuesSupported: []string{"RS256"},
ScopesSupported: []string{"openid", "profile", "email", "groups"},
ScopesSupported: supportedScopes(cfg.Clients),
TokenEndpointAuthMethodsSupported: []string{"client_secret_basic", "none"},
// 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",
"preferred_username", "email", "name", "groups", "roles",
"tenant", "principal_type", "roles", "groups", "assurance", "scope",
"nonce", "preferred_username", "email", "name", "tenant_roles",
},
SubjectTypesSupported: []string{"public"},
RequestParameterSupported: false,
@ -87,3 +100,28 @@ func (h *discoveryHandler) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write(h.doc)
}
// 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...)
}

View file

@ -6,6 +6,7 @@ import (
"net/http/httptest"
"testing"
"keycape/internal/domain"
"keycape/internal/server/oidc"
)
@ -290,7 +291,61 @@ func TestDiscoveryHandler_Claims(t *testing.T) {
}
doc := discoveryDoc(t, cfg)
assertStringSlice(t, doc, "claims_supported",
[]string{"sub", "iss", "aud", "exp", "iat", "preferred_username", "email", "name", "groups", "roles"})
[]string{"sub", "iss", "aud", "exp", "iat", "tenant", "principal_type", "roles", "groups",
"assurance", "scope", "nonce", "preferred_username", "email", "name", "tenant_roles"})
}
// KEY-WP-0017-T03. The token endpoint puts these on every token it issues, so an
// omission here is a contract defect rather than missing optional metadata --
// unlike, say, an unadvertised optional endpoint.
func TestDiscoveryAdvertisesEveryCoreProfileClaim(t *testing.T) {
cfg := oidc.DiscoveryConfig{
Issuer: "https://auth.netkingdom.local",
AuthorizationEndpoint: "https://auth.netkingdom.local/authorize",
TokenEndpoint: "https://auth.netkingdom.local/token",
JWKSUri: "https://auth.netkingdom.local/jwks",
}
doc := discoveryDoc(t, cfg)
advertised := map[string]bool{}
for _, claim := range doc["claims_supported"].([]interface{}) {
advertised[claim.(string)] = true
}
for _, claim := range []string{"iss", "sub", "aud", "exp", "iat", "tenant", "principal_type", "roles", "groups", "assurance"} {
if !advertised[claim] {
t.Errorf("core profile claim %q is emitted on every token but not advertised", claim)
}
}
}
// scopes_supported must describe what this deployment can actually grant.
func TestDiscoveryScopesIncludeConfiguredResourceScopes(t *testing.T) {
cfg := oidc.DiscoveryConfig{
Issuer: "https://auth.netkingdom.local",
AuthorizationEndpoint: "https://auth.netkingdom.local/authorize",
TokenEndpoint: "https://auth.netkingdom.local/token",
JWKSUri: "https://auth.netkingdom.local/jwks",
Clients: map[string]*domain.Client{
"approval": {ClientID: "approval", AllowedScopes: []string{"approval:read", "approval:consume", "openid"}},
"openbao": {ClientID: "openbao", AllowedScopes: []string{"openbao:login"}},
},
}
doc := discoveryDoc(t, cfg)
// Baseline first, then configured resource scopes sorted for a stable
// document regardless of client map iteration order.
assertStringSlice(t, doc, "scopes_supported",
[]string{"openid", "profile", "email", "groups", "approval:consume", "approval:read", "openbao:login"})
}
// With no clients configured the baseline profile scopes are still advertised.
func TestDiscoveryScopesFallBackToBaseline(t *testing.T) {
cfg := oidc.DiscoveryConfig{
Issuer: "https://auth.netkingdom.local",
AuthorizationEndpoint: "https://auth.netkingdom.local/authorize",
TokenEndpoint: "https://auth.netkingdom.local/token",
JWKSUri: "https://auth.netkingdom.local/jwks",
}
doc := discoveryDoc(t, cfg)
assertStringSlice(t, doc, "scopes_supported", []string{"openid", "profile", "email", "groups"})
}
func TestDiscoveryHandler_SubjectTypes(t *testing.T) {