From 2b4f1704ca0f46ef8f28ad51b288672236cd5039 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 22:17:15 +0800 Subject: [PATCH 1/5] test: follow nested types in the key-material field guard TestKeyHolderMatrixCoversEveryKeyField only looked at a field's own type, so a field reaching key material through a struct it points to went unseen: the federation issuers' deps field, a pointer to a Dependencies struct holding the Signer, was not flagged, although its rendering is what printed an Ed25519 key before the issuers gained their redacting Format methods. The guard now indexes the named types the guarded packages and internal/ declare and counts a field as holding key material when its type, through pointers, slices, arrays, map values, channels, generic type arguments, inline structs and those named types, reaches a field that holds it directly. Cycles end at a type already being resolved, and only an outermost negative result is memoized, so a cycle cut short cannot hide a holder found later. Such a field must be covered by a keyHolders case rendering the value that holds it, like a direct one. The newly flagged fields are covered: the issuers' deps (and the shadows their Format methods print), the signer and ephemeral key managers' maps, the client sealers' keyrings, and new cases for a KeyManager built with DeclareCustody and for the interactioncookie and sessioncookie Cookies' jars. None of them prints its key. TestKeyMaterialIndexFollowsNestedTypes checks the detection itself on a synthetic package. Co-Authored-By: Claude Opus 5.5 --- fapitest/key_rendering_guard_test.go | 397 ++++++++++++++++++++++++--- 1 file changed, 357 insertions(+), 40 deletions(-) diff --git a/fapitest/key_rendering_guard_test.go b/fapitest/key_rendering_guard_test.go index 61f5c500..b45d3ad0 100644 --- a/fapitest/key_rendering_guard_test.go +++ b/fapitest/key_rendering_guard_test.go @@ -11,6 +11,7 @@ import ( "go/ast" "go/parser" "go/token" + "io/fs" "maps" "path/filepath" "reflect" @@ -23,6 +24,7 @@ import ( fapi "github.com/idfoundry/fapigo" "github.com/idfoundry/fapigo/client" + "github.com/idfoundry/fapigo/client/sessioncookie" "github.com/idfoundry/fapigo/fapitest" "github.com/idfoundry/fapigo/federation" "github.com/idfoundry/fapigo/internal/rendertest" @@ -30,15 +32,18 @@ import ( "github.com/idfoundry/fapigo/keys/ephemeral" "github.com/idfoundry/fapigo/pairwise" "github.com/idfoundry/fapigo/server" + "github.com/idfoundry/fapigo/server/interactioncookie" ) // This file is the rendering matrix for key material, beside the // redaction guard's for the values a flow hands its caller: every // struct field of the guarded packages, exported or not, that holds a // private key, a crypto.Signer, a cipher, or bytes named as a key or -// secret is reached by one of keyHolders' cases, which builds a value -// holding real key material the way a deployment does and renders it -// through rendertest's whole matrix. A new such field fails +// secret, or whose type holds such a field at any depth (a deps pointer +// to a Dependencies struct with a Signer in it, a map of structs with a +// cipher in each), is reached by one of keyHolders' cases, which builds +// a value holding real key material the way a deployment does and +// renders it through rendertest's whole matrix. A new such field fails // TestKeyHolderMatrixCoversEveryKeyField until a case covers it, or // notKeyMaterial says why it isn't one. // @@ -80,12 +85,18 @@ var keyHolders = map[string]keyHolder{ macKey, encKey := randomBytes(t, 32), randomBytes(t, 32) return must(pairwise.NewReversible(macKey, encKey))(t), []string{string(macKey), string(encKey)} }}, - "keys.NewKeyManagerFromSigners ES256": {covers: []string{"keys.signerBackend.signer"}, + "keys.NewKeyManagerFromSigners ES256": {covers: []string{"keys.signerBackend.signer", "keys.signerKeyManager.backends"}, build: func(t *testing.T) (any, []string) { return signerKeyManager(t, fapi.ES256, ecdsaKey(t)) }}, - "keys.NewKeyManagerFromSigners PS256": {covers: []string{"keys.signerBackend.signer"}, + "keys.NewKeyManagerFromSigners PS256": {covers: []string{"keys.signerBackend.signer", "keys.signerKeyManager.backends"}, build: func(t *testing.T) (any, []string) { return signerKeyManager(t, fapi.PS256, rsaKey(t)) }}, - "keys.NewKeyManagerFromSigners EdDSA": {covers: []string{"keys.signerBackend.signer"}, + "keys.NewKeyManagerFromSigners EdDSA": {covers: []string{"keys.signerBackend.signer", "keys.signerKeyManager.backends"}, build: func(t *testing.T) (any, []string) { return signerKeyManager(t, fapi.EdDSA, ed25519Key(t)) }}, + "keys.NewKeyManagerFromSigners with DeclareCustody": {covers: []string{"keys.custodyKeyManager.signerKeyManager"}, + build: func(t *testing.T) (any, []string) { + key := ecdsaKey(t) + custody := keys.DeclareCustody(keys.KeyCustody{Durable: true}) + return must(keys.NewKeyManagerFromSigners([]keys.SignerSpec{{Purpose: keys.JARMSigning, Algorithm: fapi.ES256, Signer: key}}, custody))(t), keySecrets(key) + }}, "keys.SignerSpec ES256 and PS256": {covers: []string{"keys.SignerSpec.Signer"}, build: func(t *testing.T) (any, []string) { ec, rsa := ecdsaKey(t), rsaKey(t) @@ -123,6 +134,14 @@ var keyHolders = map[string]keyHolder{ }, keySecrets(key) }}, "federation issuers": { + covers: []string{ + "federation.HistoricalKeysIssuer.deps", "federation.ResolveIssuer.deps", "federation.SelfIssuer.deps", + "federation.SubordinateIssuer.deps", "federation.TrustMarkIssuer.deps", + // The shadows the issuers' Format methods print in their place. + "federation.historicalKeysIssuerShadow.Dependencies", "federation.resolveIssuerShadow.Dependencies", + "federation.selfIssuerShadow.Dependencies", "federation.subordinateIssuerShadow.Dependencies", + "federation.trustMarkIssuerShadow.Dependencies", + }, build: func(t *testing.T) (any, []string) { key := ed25519Key(t) return federationIssuers(t, key), keySecrets(key) @@ -137,20 +156,20 @@ var keyHolders = map[string]keyHolder{ key := must(ecdh.P256().GenerateKey(rand.Reader))(t) return must(keys.NewInMemoryECDH(key, "k"))(t), keySecrets(key) }}, - "ephemeral.NewKeyManager ES256 and PS256": {covers: []string{"ephemeral.signingKey.signer"}, + "ephemeral.NewKeyManager ES256 and PS256": {covers: []string{"ephemeral.signingKey.signer", "ephemeral.KeyManager.keys"}, build: func(t *testing.T) (any, []string) { return ephemeralKeyManager(t, map[keys.SigningPurpose]fapi.SignatureAlgorithm{keys.JARMSigning: fapi.ES256, keys.IDTokenSigning: fapi.PS256}, nil) }}, - "ephemeral.NewKeyManager EdDSA": {covers: []string{"ephemeral.signingKey.signer"}, + "ephemeral.NewKeyManager EdDSA": {covers: []string{"ephemeral.signingKey.signer", "ephemeral.KeyManager.keys"}, build: func(t *testing.T) (any, []string) { return ephemeralKeyManager(t, map[keys.SigningPurpose]fapi.SignatureAlgorithm{keys.JARMSigning: fapi.EdDSA}, nil) }}, - "ephemeral.NewKeyManagerWithDecryption": {covers: []string{"ephemeral.decryptionKeys.keys"}, + "ephemeral.NewKeyManagerWithDecryption": {covers: []string{"ephemeral.decryptionKeys.keys", "ephemeral.KeyManager.decryption", "ephemeral.KeyManager.keys"}, build: func(t *testing.T) (any, []string) { return ephemeralKeyManager(t, map[keys.SigningPurpose]fapi.SignatureAlgorithm{keys.JARMSigning: fapi.ES256}, map[keys.DecryptionPurpose]fapi.KeyManagementAlgorithm{keys.IDTokenDecryption: fapi.RSAOAEP256, keys.UserInfoDecryption: fapi.ECDHESA256KW}) }}, - "client sealers": {covers: []string{"client.sealKey.aead"}, + "client sealers": {covers: []string{"client.sealKey.aead", "client.sealKeyring.keys", "client.TokenSetSealer.keys", "client.BackchannelSessionSealer.keys"}, build: func(t *testing.T) (any, []string) { key := randomBytes(t, 32) c := fapitest.New(t, fapitest.Config{Profile: server.ProfileFAPISecurity}).Client @@ -159,6 +178,14 @@ var keyHolders = map[string]keyHolder{ Session *client.BackchannelSessionSealer }{must(client.NewTokenSetSealer(c, [][]byte{key}))(t), must(client.NewBackchannelSessionSealer(c, [][]byte{key}))(t)}, []string{string(key)} }}, + "cookie jars": {covers: []string{"interactioncookie.Cookie.jar", "sessioncookie.Cookie.jar"}, + build: func(t *testing.T) (any, []string) { + key := randomBytes(t, 32) + return struct { + Interaction *interactioncookie.Cookie + Session *sessioncookie.Cookie + }{must(interactioncookie.New([][]byte{key}, interactioncookie.Options{}))(t), must(sessioncookie.New([][]byte{key}, sessioncookie.Options{}))(t)}, []string{string(key)} + }}, } // notKeyMaterial are the fields TestKeyHolderMatrixCoversEveryKeyField @@ -197,10 +224,16 @@ var keyMaterialTypes = map[string]bool{ var keyMaterialName = regexp.MustCompile(`(?i)key|secret|seed|priv`) // TestKeyHolderMatrixCoversEveryKeyField parses the guarded packages and -// fails for a struct field holding key material (see keyMaterialTypes -// and keyMaterialName; a map or slice of them too) that no keyHolders -// case covers and notKeyMaterial doesn't excuse, and for a table entry -// naming no such field. +// fails for a struct field holding key material that no keyHolders case +// covers and notKeyMaterial doesn't excuse, and for a table entry naming +// no such field. A field holds key material directly (see +// keyMaterialTypes and keyMaterialName; a map, slice or array of them +// too), or transitively: its type, through pointers, slices, arrays, +// maps' values, channels, generic types' arguments, inline structs and +// the named types this module declares (in the guarded packages or +// internal/), reaches a field holding it directly. A case covering a +// transitive holder renders the value that holds it, so its renderings +// check the nested key too. func TestKeyHolderMatrixCoversEveryKeyField(t *testing.T) { covered := map[string]bool{} for _, tc := range keyHolders { @@ -208,13 +241,12 @@ func TestKeyHolderMatrixCoversEveryKeyField(t *testing.T) { covered[field] = true } } + ix := newTypeIndex(t) found := map[string]bool{} - for _, dir := range guardedPackages { - for _, field := range keyMaterialFields(t, dir) { - found[field] = true - if _, excused := notKeyMaterial[field]; !covered[field] && !excused { - t.Errorf("%s holds key material, and no keyHolders case covers it: add one, or say in notKeyMaterial why it isn't key material", field) - } + for _, field := range ix.keyMaterialFields() { + found[field.name] = true + if _, excused := notKeyMaterial[field.name]; !covered[field.name] && !excused { + t.Errorf("%s holds key material%s, and no keyHolders case covers it: add one, or say in notKeyMaterial why it isn't key material", field.name, field.via) } } for _, field := range append(slices.Collect(maps.Keys(covered)), slices.Collect(maps.Keys(notKeyMaterial))...) { @@ -224,49 +256,334 @@ func TestKeyHolderMatrixCoversEveryKeyField(t *testing.T) { } } -// keyMaterialFields is the key-material fields of the struct types -// declared in dir's non-test files, as package.Type.field. -func keyMaterialFields(t *testing.T, dir string) []string { +// TestKeyMaterialIndexFollowsNestedTypes checks the guard's transitive +// detection on a package of its own: through pointers, maps, slices, +// generic arguments, inline structs and another module package's type, +// across a cycle, and not into a type holding no key material. +func TestKeyMaterialIndexFollowsNestedTypes(t *testing.T) { + const other = modulePath + "/internal/other" + files := map[string][]*ast.File{ + modulePath + "/guarded": {parseSource(t, `package guarded +import ( + "crypto" + "sync/atomic" + o "github.com/idfoundry/fapigo/internal/other" +) +type W struct{ x *X } +type X struct { + y *Y + k crypto.Signer +} +type Y struct{ x *X } +type Z struct{ y map[string][]Y } +type G struct{ p atomic.Pointer[X] } +type I struct{ s struct{ secretKey []byte } } +type O struct{ j *o.Jar } +type named []*X +type N struct{ n named } +type P struct { + n int + self *P + jwks []byte +} +`)}, + other: {parseSource(t, `package other +import "crypto/cipher" +type Jar struct{ keys []key } +type key struct{ aead cipher.AEAD } +`)}, + } + var got []string + for _, field := range indexTypes(files, []string{modulePath + "/guarded"}).keyMaterialFields() { + got = append(got, field.name) + } + want := []string{"guarded.W.x", "guarded.X.y", "guarded.X.k", "guarded.Y.x", "guarded.Z.y", "guarded.G.p", "guarded.I.s", "guarded.O.j", "guarded.N.n"} + if !slices.Equal(got, want) { + t.Errorf("key-material fields\n got %v\nwant %v", got, want) + } +} + +// parseSource parses src, a Go file. +func parseSource(t *testing.T, src string) *ast.File { t.Helper() - files, err := filepath.Glob(filepath.Join(dir, "*.go")) + file, err := parser.ParseFile(token.NewFileSet(), "src.go", src, parser.SkipObjectResolution) if err != nil { t.Fatal(err) } - var out []string + return file +} + +// modulePath is the import path of the module the guarded packages are in. +const modulePath = "github.com/idfoundry/fapigo" + +// typeDecl is a named type declared in this module. +type typeDecl struct { + // name is the type as package.Type, package being its package's name. + name string + // expr is the type's definition. + expr ast.Expr + // file resolves the names expr uses. + file *fileScope +} + +// fileScope resolves the type names a file's declarations use. +type fileScope struct { + // path is the file's package's import path. + path string + // imports maps a name the file imports a package as to its path. + imports map[string]string +} + +// keyField is a field holding key material. +type keyField struct { + // name is the field as package.Type.field. + name string + // via, for a transitive holder, says through which type it does. + via string +} + +// typeIndex is the named types this module declares, by import path and +// name, and which of them reach key material. +type typeIndex struct { + decls map[string]*typeDecl + // guarded are the guarded packages' types, the ones whose fields + // the guard reports, in declaration order. + guarded []string + // reaches memoizes typeReaches's final results; visiting holds the + // types it is inside, so a cycle ends. + reaches map[string]bool + visiting map[string]bool +} + +// newTypeIndex parses the guarded packages and internal/'s. +func newTypeIndex(t *testing.T) *typeIndex { + t.Helper() + dirs := slices.Clone(guardedPackages) + err := filepath.WalkDir("../internal", func(path string, d fs.DirEntry, err error) error { + if err == nil && d.IsDir() && d.Name() != "testdata" { + dirs = append(dirs, path) + } + return err + }) + if err != nil { + t.Fatal(err) + } + parsed := map[string][]*ast.File{} + var guarded []string + for _, dir := range dirs { + path := importPath(t, dir) + parsed[path] = parseDir(t, dir) + if slices.Contains(guardedPackages, dir) { + guarded = append(guarded, path) + } + } + return indexTypes(parsed, guarded) +} + +// indexTypes indexes the type declarations of files, by import path, +// reporting the fields of guarded's. +func indexTypes(files map[string][]*ast.File, guarded []string) *typeIndex { + ix := &typeIndex{decls: map[string]*typeDecl{}, reaches: map[string]bool{}, visiting: map[string]bool{}} + names := map[string]string{} + for path, pkg := range files { + if len(pkg) > 0 { + names[path] = pkg[0].Name.Name + } + } + // Sorted paths, and each package's file order, keep the guard's + // reports in a stable order. + for _, path := range slices.Sorted(maps.Keys(files)) { + for _, file := range files[path] { + ix.add(file, &fileScope{path: path, imports: fileImports(file, names)}, slices.Contains(guarded, path)) + } + } + return ix +} + +// add indexes file's type declarations, recording them as guarded if +// guarded is set. +func (ix *typeIndex) add(file *ast.File, scope *fileScope, guarded bool) { + for _, spec := range typeSpecs(file) { + key := scope.path + "." + spec.Name.Name + ix.decls[key] = &typeDecl{name: file.Name.Name + "." + spec.Name.Name, expr: spec.Type, file: scope} + if guarded { + ix.guarded = append(ix.guarded, key) + } + } +} + +// importPath is dir's import path. +func importPath(t *testing.T, dir string) string { + t.Helper() + root, err := filepath.Abs("..") + if err != nil { + t.Fatal(err) + } + abs, err := filepath.Abs(dir) + if err != nil { + t.Fatal(err) + } + rel, err := filepath.Rel(root, abs) + if err != nil { + t.Fatal(err) + } + if rel == "." { + return modulePath + } + return modulePath + "/" + filepath.ToSlash(rel) +} + +// parseDir parses dir's non-test files. +func parseDir(t *testing.T, dir string) []*ast.File { + t.Helper() + paths, err := filepath.Glob(filepath.Join(dir, "*.go")) + if err != nil { + t.Fatal(err) + } + var files []*ast.File fset := token.NewFileSet() - for _, path := range files { + for _, path := range paths { if strings.HasSuffix(path, "_test.go") { continue } - file, err := parser.ParseFile(fset, path, nil, 0) + file, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution) if err != nil { t.Fatal(err) } - for _, spec := range typeSpecs(file) { - if st, ok := spec.Type.(*ast.StructType); ok { - out = append(out, structKeyFields(file.Name.Name+"."+spec.Name.Name, st)...) - } + files = append(files, file) + } + return files +} + +// fileImports maps the names file imports this module's packages as to +// their import paths; names holds each package's name. +func fileImports(file *ast.File, names map[string]string) map[string]string { + out := map[string]string{} + for _, imp := range file.Imports { + path := strings.Trim(imp.Path.Value, `"`) + name, ok := names[path] + if imp.Name != nil { + name = imp.Name.Name + } + if ok || imp.Name != nil { + out[name] = path + } + } + return out +} + +// keyMaterialFields is the fields of the guarded packages' struct types +// holding key material, directly or transitively. +func (ix *typeIndex) keyMaterialFields() []keyField { + var out []keyField + for _, key := range ix.guarded { + decl := ix.decls[key] + st, ok := decl.expr.(*ast.StructType) + if !ok { + continue + } + for _, field := range st.Fields.List { + out = append(out, ix.fieldKeys(decl, field)...) } } return out } -// structKeyFields is st's key-material fields, prefixed with typeName. -func structKeyFields(typeName string, st *ast.StructType) []string { - var out []string +// fieldKeys is field of decl's struct, once per name, if it holds key +// material. +func (ix *typeIndex) fieldKeys(decl *typeDecl, field *ast.Field) []keyField { + names := fieldNames(field) + var out []keyField + for _, name := range names { + if holdsKeyMaterial(typeString(field.Type), name) { + out = append(out, keyField{name: decl.name + "." + name}) + } else if ix.exprReaches(decl.file, field.Type) { + out = append(out, keyField{name: decl.name + "." + name, via: " through its type, " + typeString(field.Type)}) + } + } + return out +} + +// fieldNames is field's names, or an embedded field's type name. +func fieldNames(field *ast.Field) []string { + if len(field.Names) == 0 { + typ := strings.TrimPrefix(typeString(field.Type), "*") + return []string{typ[strings.LastIndex(typ, ".")+1:]} + } + names := make([]string, len(field.Names)) + for i, name := range field.Names { + names[i] = name.Name + } + return names +} + +// exprReaches reports whether a value of type e, resolved in scope, +// holds key material in a field, at any depth. +func (ix *typeIndex) exprReaches(scope *fileScope, e ast.Expr) bool { + switch t := e.(type) { + case *ast.StarExpr: + return ix.exprReaches(scope, t.X) + case *ast.ArrayType: + return ix.exprReaches(scope, t.Elt) + case *ast.MapType: + return ix.exprReaches(scope, t.Value) + case *ast.ChanType: + return ix.exprReaches(scope, t.Value) + case *ast.IndexExpr: + return ix.exprReaches(scope, t.X) || ix.exprReaches(scope, t.Index) + case *ast.IndexListExpr: + return ix.exprReaches(scope, t.X) || slices.ContainsFunc(t.Indices, func(e ast.Expr) bool { return ix.exprReaches(scope, e) }) + case *ast.StructType: + return ix.structReaches(scope, t) + case *ast.Ident: + return ix.typeReaches(scope.path + "." + t.Name) + case *ast.SelectorExpr: + pkg, ok := t.X.(*ast.Ident) + return ok && scope.imports[pkg.Name] != "" && ix.typeReaches(scope.imports[pkg.Name]+"."+t.Sel.Name) + } + return false +} + +// structReaches reports whether one of st's fields holds key material, +// directly or transitively. +func (ix *typeIndex) structReaches(scope *fileScope, st *ast.StructType) bool { for _, field := range st.Fields.List { - typ := typeString(field.Type) - for _, name := range field.Names { - if holdsKeyMaterial(typ, name.Name) { - out = append(out, typeName+"."+name.Name) + for _, name := range fieldNames(field) { + if holdsKeyMaterial(typeString(field.Type), name) { + return true } } + if ix.exprReaches(scope, field.Type) { + return true + } } - return out + return false +} + +// typeReaches reports whether the named type key, a module type's +// import path and name, holds key material: false for a type the module +// doesn't declare, or one already being resolved. +func (ix *typeIndex) typeReaches(key string) bool { + if reaches, done := ix.reaches[key]; done { + return reaches + } + decl := ix.decls[key] + if decl == nil || ix.visiting[key] { + return false + } + ix.visiting[key] = true + reaches := ix.exprReaches(decl.file, decl.expr) + delete(ix.visiting, key) + // A false found inside another type's resolution may be a cycle cut + // short, so only an outermost one is final. + if reaches || len(ix.visiting) == 0 { + ix.reaches[key] = reaches + } + return reaches } // holdsKeyMaterial reports whether a field of type typ named name holds -// key material. +// key material directly. func holdsKeyMaterial(typ, name string) bool { for { if keyMaterialTypes[typ] { From c198a546dca5ca7263176e52791dfc7e541dc0fd Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 22:24:52 +0800 Subject: [PATCH 2/5] feat(fapitest): add Harness.EmbedderUI, a model login and consent UI The harness's authorization endpoint approves every interaction at once, so a test of what an embedding application's UI does with the interaction had to build that UI by hand. Harness.EmbedderUI returns an http.Handler in front of the harness's server: a sign-in that sets the UI's own session cookie, an authorization endpoint that keeps the interaction in a cookie server/interactioncookie seals and renders a consent page carrying its tag, and a consent submission that completes the interaction for the signed-in subject, granting what it requested, and answers 303 to the client's redirect URI. A submission without a session the UI issued is refused. Its POSTs refuse cross-origin requests and its pages carry server.AuthorizationPageHeaders. It uses only the server's and interactioncookie's public API, so an embedder can follow the pattern. EmbedderUIOptions.OnInteraction hands a test each interaction begun, as a leaked log line would, and UnsafeRawHandleCookie, for negative tests only, keeps the raw handle in a plain cookie instead. The UI holds its interaction cookie's key, so the key-material matrix gains a case rendering one, and the redaction guard classifies the two new types. Co-Authored-By: Claude Opus 5.5 --- fapitest/doc.go | 11 + fapitest/embedderui.go | 296 +++++++++++++++++++++++++++ fapitest/embedderui_internal_test.go | 191 +++++++++++++++++ fapitest/export_internal_test.go | 7 + fapitest/key_rendering_guard_test.go | 6 + fapitest/redaction_guard_test.go | 2 +- 6 files changed, 512 insertions(+), 1 deletion(-) create mode 100644 fapitest/embedderui.go create mode 100644 fapitest/embedderui_internal_test.go create mode 100644 fapitest/export_internal_test.go diff --git a/fapitest/doc.go b/fapitest/doc.go index e7bc6eb6..87308a05 100644 --- a/fapitest/doc.go +++ b/fapitest/doc.go @@ -13,4 +13,15 @@ // wire encoding and HTTP semantics; doing so would defeat its own purpose. // This package is test-only and must not be imported by client, server, // resource or internal/. +// +// The harness's own authorization endpoint approves every interaction +// at once (AutoApprove). For a test of what an embedding application's +// login and consent UI does with the interaction, Harness.EmbedderUI +// serves a model one in front of the same server: a sign-in that sets +// the UI's own session cookie, an authorization endpoint keeping the +// interaction in a cookie server/interactioncookie seals, and a consent +// submission completing it for the signed-in subject. It uses only the +// server's and server/interactioncookie's public API, so an embedder's +// own UI can follow it; EmbedderUIOptions.UnsafeRawHandleCookie keeps +// the raw handle in a plain cookie instead, for negative tests only. package fapitest diff --git a/fapitest/embedderui.go b/fapitest/embedderui.go new file mode 100644 index 00000000..1c732e07 --- /dev/null +++ b/fapitest/embedderui.go @@ -0,0 +1,296 @@ +package fapitest + +import ( + "crypto/rand" + "encoding/base64" + "html/template" + "net/http" + "strings" + "sync" + "time" + + "github.com/idfoundry/fapigo/server" + "github.com/idfoundry/fapigo/server/interactioncookie" +) + +// The paths EmbedderUI serves. +const ( + // EmbedderUISignInPath signs the browser in: a POST whose form's + // EmbedderUISubjectField names the subject, answered 204 with the + // session cookie (EmbedderUISessionCookie) set. + EmbedderUISignInPath = "/signin" + // EmbedderUIAuthorizePath is the authorization endpoint: a GET with + // the request_uri and client_id the client's authorization URL + // carries, answered 200 with the consent page, the interaction kept + // in the browser's cookies. + EmbedderUIAuthorizePath = "/authorize" + // EmbedderUIConsentPath is the consent page's form submission: a POST + // carrying the page's interactioncookie.FormField, from a browser + // signed in, answered 303 to the client's redirect URI. + EmbedderUIConsentPath = "/consent" +) + +const ( + // EmbedderUISubjectField is the sign-in form's field naming the + // subject to sign in as. + EmbedderUISubjectField = "subject" + // EmbedderUISessionCookie is the name of the cookie EmbedderUI signs + // a browser in with: the embedder's own session, apart from the + // interaction's cookie. + EmbedderUISessionCookie = "__Host-fapitest-session" +) + +// The plain cookies an EmbedderUI with UnsafeRawHandleCookie keeps the +// interaction in. +const ( + rawHandleCookie = "fapitest-interaction-handle" + rawRequestCookie = "fapitest-interaction-request" +) + +// EmbedderUIOptions configures Harness.EmbedderUI. +type EmbedderUIOptions struct { + // OnInteraction, if set, is called with each interaction the + // authorization endpoint begins, before the page is written: a test + // can take the handle as a leaked log line would give it away. + OnInteraction func(server.InteractionRequired) + + // UnsafeRawHandleCookie keeps the raw interaction handle, and the + // encoded InteractionRequest, in plain cookies instead of sealing + // them with server/interactioncookie. The handle is then bound to the + // browser only while it stays secret: whoever learns it completes + // the interaction as themselves. Set it only for a negative test of + // that; never copy it. + UnsafeRawHandleCookie bool +} + +// EmbedderUI is a model embedding application's sign-in and consent UI +// in front of the harness's server, built from the server's and +// server/interactioncookie's public API only, so a test of an embedder +// can copy the pattern. Mount it on an httptest server (a TLS one for a +// browser-like cookie jar: its cookies are Secure) or call ServeHTTP +// directly; it serves EmbedderUISignInPath, EmbedderUIAuthorizePath and +// EmbedderUIConsentPath. +// +// It signs browsers in from its own session cookie, and keeps each +// interaction between the authorization endpoint and the consent +// submission in a cookie server/interactioncookie seals, with a key of +// its own: a consent submission completes the interaction only from +// that cookie, for the subject the browser is signed in as, granting +// what the interaction requested. Its sign-in takes the subject's name +// alone, which a real one never does, and its POSTs refuse cross-origin +// requests (net/http's CrossOriginProtection), the CSRF defence +// server.InteractionHandle's doc comment asks for. +type EmbedderUI struct { + h *Harness + opts EmbedderUIOptions + sealed *interactioncookie.Cookie + handler http.Handler + + mu sync.Mutex + // sessions maps a session cookie's value to the subject it signs + // in. + sessions map[string]string +} + +// EmbedderUI returns a new EmbedderUI completing interactions at h's +// server. +func (h *Harness) EmbedderUI(opts EmbedderUIOptions) *EmbedderUI { + h.t.Helper() + key := make([]byte, 32) + _, _ = rand.Read(key) // never fails: it crashes the program instead (Go 1.24+) + return h.embedderUI(opts, key) +} + +// embedderUI is EmbedderUI sealing its interactions with key. +func (h *Harness) embedderUI(opts EmbedderUIOptions, key []byte) *EmbedderUI { + h.t.Helper() + sealed, err := interactioncookie.New([][]byte{key}, interactioncookie.Options{}) + if err != nil { + h.t.Fatalf("fapitest: interactioncookie.New: %v", err) + } + u := &EmbedderUI{h: h, opts: opts, sealed: sealed, sessions: map[string]string{}} + protect := http.NewCrossOriginProtection() + mux := http.NewServeMux() + mux.Handle("POST "+EmbedderUISignInPath, protect.Handler(http.HandlerFunc(u.signIn))) + mux.Handle("GET "+EmbedderUIAuthorizePath, server.AuthorizationPageHeaders(http.HandlerFunc(u.authorize))) + mux.Handle("POST "+EmbedderUIConsentPath, server.AuthorizationPageHeaders(protect.Handler(http.HandlerFunc(u.consent)))) + u.handler = mux + return u +} + +// ServeHTTP implements http.Handler. +func (u *EmbedderUI) ServeHTTP(w http.ResponseWriter, r *http.Request) { + u.handler.ServeHTTP(w, r) +} + +// signIn starts a session for the form's subject. +func (u *EmbedderUI) signIn(w http.ResponseWriter, r *http.Request) { + subject := r.PostFormValue(EmbedderUISubjectField) + if subject == "" { + http.Error(w, "no subject", http.StatusBadRequest) + return + } + random := make([]byte, 32) + _, _ = rand.Read(random) + session := base64.RawURLEncoding.EncodeToString(random) + u.mu.Lock() + u.sessions[session] = subject + u.mu.Unlock() + http.SetCookie(w, &http.Cookie{Name: EmbedderUISessionCookie, Value: session, Path: "/", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode}) + w.WriteHeader(http.StatusNoContent) +} + +// signedIn is the subject r's session cookie signs in, if any. +func (u *EmbedderUI) signedIn(r *http.Request) (string, bool) { + c, err := r.Cookie(EmbedderUISessionCookie) + if err != nil { + return "", false + } + u.mu.Lock() + defer u.mu.Unlock() + subject, ok := u.sessions[c.Value] + return subject, ok +} + +var consentPage = template.Must(template.New("consent").Parse(` +Consent +

{{.ClientID}} asks for: {{.Scope}}

+
+ + +
+`)) + +// authorize begins the interaction, keeps it in the browser's cookies +// and renders the consent page. +func (u *EmbedderUI) authorize(w http.ResponseWriter, r *http.Request) { + req, err := server.BeginAuthorizationRequestFromHTTP(r) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + action, err := u.h.authServer.srv.BeginAuthorization(r.Context(), req) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + switch a := action.(type) { + case server.InteractionRequired: + if u.opts.OnInteraction != nil { + u.opts.OnInteraction(a) + } + tag, err := u.keep(w, a, u.h.Clock.Now()) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + _ = consentPage.Execute(w, map[string]string{"ClientID": string(a.Interaction.ClientID), "Scope": strings.Join(a.Interaction.Scope, " "), "Tag": tag}) + case server.RedirectResponse: + w.Header().Set("Location", a.Destination.String()) + w.WriteHeader(http.StatusFound) + case server.LocalErrorResponse: + http.Error(w, string(a.Error.Code())+": "+a.Error.PublicDescription(), a.Error.HTTPStatus()) + } +} + +// consent completes the interaction the browser's cookies carry for the +// subject it is signed in as. +func (u *EmbedderUI) consent(w http.ResponseWriter, r *http.Request) { + subject, ok := u.signedIn(r) + if !ok { + http.Error(w, "not signed in", http.StatusForbidden) + return + } + now := u.h.Clock.Now() + handle, in, ok := u.recover(r, now, r.PostFormValue(interactioncookie.FormField)) + if !ok { + http.Error(w, "this browser has no sign-in in progress", http.StatusBadRequest) + return + } + if !u.opts.UnsafeRawHandleCookie { + u.sealed.Clear(w) + } + result, err := u.complete(r, handle, in, subject, now) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + switch o := result.(type) { + case server.AuthorizationRedirect: + // The server's redirect to the client's registered redirect URI, + // 303 after a form POST. + w.Header().Set("Location", o.Destination().String()) + w.WriteHeader(http.StatusSeeOther) + case server.AuthorizationLocalError: + http.Error(w, string(o.Error.Code())+": "+o.Error.PublicDescription(), o.Error.HTTPStatus()) + } +} + +// complete approves the interaction handle names, as subject, granting +// what in requested. +func (u *EmbedderUI) complete(r *http.Request, handle server.InteractionHandle, in server.InteractionRequest, subject string, now time.Time) (server.AuthorizationResult, error) { + id, err := server.NewSubjectID(subject) + if err != nil { + return nil, err + } + authenticated, err := server.NewAuthenticatedSubject(id) + if err != nil { + return nil, err + } + authCtx, err := server.NewAuthenticationContext(now, "", nil) + if err != nil { + return nil, err + } + return u.h.authServer.srv.CompleteAuthorization(r.Context(), server.CompleteAuthorizationRequest{ + Handle: handle, + Result: server.Authorize(authenticated, authCtx, server.GrantedAuthorization{ + Scope: in.Scope, ApprovedIdentityClaims: in.RequestedClaims.Names(), + }), + }) +} + +// keep stores a in the browser's cookies on w, returning the tag the +// consent form sends back. +func (u *EmbedderUI) keep(w http.ResponseWriter, a server.InteractionRequired, now time.Time) (string, error) { + if !u.opts.UnsafeRawHandleCookie { + return u.sealed.Set(w, a, now) + } + encoded, err := a.Interaction.MarshalText() + if err != nil { + return "", err + } + http.SetCookie(w, &http.Cookie{Name: rawHandleCookie, Value: a.Handle.String(), Path: "/", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode}) + http.SetCookie(w, &http.Cookie{Name: rawRequestCookie, Value: base64.RawURLEncoding.EncodeToString(encoded), Path: "/", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode}) + return "", nil +} + +// recover reads the interaction back from r's cookies for the form's +// tag. +func (u *EmbedderUI) recover(r *http.Request, now time.Time, tag string) (server.InteractionHandle, server.InteractionRequest, bool) { + if !u.opts.UnsafeRawHandleCookie { + handle, in, err := u.sealed.Read(r, now, tag) + return handle, in, err == nil + } + return readRawInteraction(r) +} + +// readRawInteraction reads the plain cookies UnsafeRawHandleCookie keeps +// an interaction in. +func readRawInteraction(r *http.Request) (server.InteractionHandle, server.InteractionRequest, bool) { + hc, err1 := r.Cookie(rawHandleCookie) + rc, err2 := r.Cookie(rawRequestCookie) + if err1 != nil || err2 != nil { + return server.InteractionHandle{}, server.InteractionRequest{}, false + } + handle, err := server.ParseInteractionHandle(hc.Value) + if err != nil { + return server.InteractionHandle{}, server.InteractionRequest{}, false + } + text, err := base64.RawURLEncoding.DecodeString(rc.Value) + if err != nil { + return server.InteractionHandle{}, server.InteractionRequest{}, false + } + in, err := server.ParseInteractionRequest(string(text)) + return handle, in, err == nil +} diff --git a/fapitest/embedderui_internal_test.go b/fapitest/embedderui_internal_test.go new file mode 100644 index 00000000..4ad201d9 --- /dev/null +++ b/fapitest/embedderui_internal_test.go @@ -0,0 +1,191 @@ +package fapitest + +import ( + "context" + "io" + "net/http" + "net/http/cookiejar" + "net/http/httptest" + "net/url" + "regexp" + "strings" + "testing" + + "github.com/idfoundry/fapigo/client" + "github.com/idfoundry/fapigo/server" + "github.com/idfoundry/fapigo/server/interactioncookie" +) + +// consentTagField finds the consent page's tag. +var consentTagField = regexp.MustCompile(`name="` + interactioncookie.FormField + `" value="([^"]*)"`) + +// consentTag is the tag the consent page body carries. +func consentTag(t *testing.T, body string) string { + t.Helper() + m := consentTagField.FindStringSubmatch(body) + if m == nil { + t.Fatalf("the consent page has no %s field: %s", interactioncookie.FormField, body) + } + return m[1] +} + +// signInRequest is the sign-in form's submission as subject. +func signInRequest(subject string) *http.Request { + r := httptest.NewRequest(http.MethodPost, EmbedderUISignInPath, strings.NewReader(url.Values{EmbedderUISubjectField: {subject}}.Encode())) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + return r +} + +// consentRequest is the consent form's submission with tag, from a +// browser carrying cookies. +func consentRequest(tag string, cookies ...*http.Cookie) *http.Request { + r := httptest.NewRequest(http.MethodPost, EmbedderUIConsentPath, strings.NewReader(url.Values{interactioncookie.FormField: {tag}}.Encode())) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range cookies { + r.AddCookie(&http.Cookie{Name: c.Name, Value: c.Value}) + } + return r +} + +// serveUI is ui's response to r. +func serveUI(ui *EmbedderUI, r *http.Request) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + ui.ServeHTTP(w, r) + return w +} + +// beginAt starts a sign-in at h's client and has a browser reach ui's +// authorization endpoint: the client session, the cookies the browser +// is given and the consent form's tag. +func beginAt(t *testing.T, h *Harness, ui *EmbedderUI) (client.AuthorizationSession, []*http.Cookie, string) { + t.Helper() + session, err := h.Client.BeginAuthorization(context.Background(), client.BeginAuthorizationRequest{Scope: []string{"openid"}}) + if err != nil { + t.Fatalf("BeginAuthorization (client): %v", err) + } + w := serveUI(ui, httptest.NewRequest(http.MethodGet, EmbedderUIAuthorizePath+"?"+session.URL().URL().RawQuery, nil)) + if w.Code != http.StatusOK { + t.Fatalf("authorize: status %d: %s", w.Code, w.Body) + } + return session, w.Result().Cookies(), consentTag(t, w.Body.String()) +} + +// sessionCookie is the session cookie ui's sign-in gives subject. +func sessionCookie(t *testing.T, ui *EmbedderUI, subject string) *http.Cookie { + t.Helper() + for _, c := range serveUI(ui, signInRequest(subject)).Result().Cookies() { + if c.Name == EmbedderUISessionCookie { + return c + } + } + t.Fatal("sign-in set no session cookie") + return nil +} + +// TestEmbedderUICompletesForTheSignedInSubject drives the UI as a +// browser does, over TLS with a cookie jar: sign in, reach the +// authorization endpoint, submit the consent form; the redirect's code +// signs the client in as the signed-in subject. +func TestEmbedderUICompletesForTheSignedInSubject(t *testing.T) { + h := New(t, Config{Profile: server.ProfileFAPISecurity}) + ts := httptest.NewTLSServer(h.EmbedderUI(EmbedderUIOptions{})) + t.Cleanup(ts.Close) + browser := ts.Client() + browser.Jar, _ = cookiejar.New(nil) + browser.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + + res, err := browser.PostForm(ts.URL+EmbedderUISignInPath, url.Values{EmbedderUISubjectField: {"alice"}}) + if err != nil || res.StatusCode != http.StatusNoContent { + t.Fatalf("sign-in: %v, %v", res, err) + } + _ = res.Body.Close() + session, err := h.Client.BeginAuthorization(context.Background(), client.BeginAuthorizationRequest{Scope: []string{"openid"}}) + if err != nil { + t.Fatalf("BeginAuthorization (client): %v", err) + } + tag := pageTag(t, browser, ts.URL+EmbedderUIAuthorizePath+"?"+session.URL().URL().RawQuery) + res, err = browser.PostForm(ts.URL+EmbedderUIConsentPath, url.Values{interactioncookie.FormField: {tag}}) + if err != nil || res.StatusCode != http.StatusSeeOther { + t.Fatalf("consent: %v, %v", res, err) + } + _ = res.Body.Close() + redirect, err := url.Parse(res.Header.Get("Location")) + if err != nil { + t.Fatal(err) + } + tokens, err := h.RunAuthorizationCodeFlowWithCallback(context.Background(), session.Handle(), redirect.RawQuery) + if err != nil { + t.Fatalf("the client: %v", err) + } + if tokens.Subject != "alice" { + t.Errorf("signed in as %q, want alice", tokens.Subject) + } +} + +// pageTag GETs the consent page at pageURL with browser, returning its +// tag. +func pageTag(t *testing.T, browser *http.Client, pageURL string) string { + t.Helper() + res, err := browser.Get(pageURL) + if err != nil { + t.Fatalf("authorize: %v", err) + } + defer func() { _ = res.Body.Close() }() + body, err := io.ReadAll(res.Body) + if err != nil { + t.Fatal(err) + } + if res.StatusCode != http.StatusOK { + t.Fatalf("authorize: status %d: %s", res.StatusCode, body) + } + return consentTag(t, string(body)) +} + +// TestEmbedderUIRefusesConsentWithoutASession: a consent submission +// carrying the interaction's cookie and tag, but no session cookie or +// one the UI never issued, completes nothing; the same browser, signed +// in, then completes the interaction. +func TestEmbedderUIRefusesConsentWithoutASession(t *testing.T) { + h := New(t, Config{Profile: server.ProfileFAPISecurity}) + ui := h.EmbedderUI(EmbedderUIOptions{}) + _, cookies, tag := beginAt(t, h, ui) + + for name, extra := range map[string][]*http.Cookie{ + "no session": nil, + "unknown session": {{Name: EmbedderUISessionCookie, Value: "not-a-session"}}, + } { + if w := serveUI(ui, consentRequest(tag, append(extra, cookies...)...)); w.Code != http.StatusForbidden { + t.Errorf("%s: status %d, want %d", name, w.Code, http.StatusForbidden) + } + } + signedIn := append([]*http.Cookie{sessionCookie(t, ui, "alice")}, cookies...) + if w := serveUI(ui, consentRequest(tag, signedIn...)); w.Code != http.StatusSeeOther { + t.Errorf("signed in: status %d, want %d: %s", w.Code, http.StatusSeeOther, w.Body) + } +} + +// TestEmbedderUISealsTheHandleUnlessToldNotTo: by default the +// interaction is kept only in interactioncookie's sealed cookie, and a +// submission carrying it in the raw cookies is refused; +// UnsafeRawHandleCookie alone puts the raw handle in a cookie. +func TestEmbedderUISealsTheHandleUnlessToldNotTo(t *testing.T) { + h := New(t, Config{Profile: server.ProfileFAPISecurity}) + var handle string + onInteraction := func(a server.InteractionRequired) { handle = a.Handle.String() } + + sealed := h.EmbedderUI(EmbedderUIOptions{OnInteraction: onInteraction}) + _, cookies, tag := beginAt(t, h, sealed) + if len(cookies) != 1 || cookies[0].Name != interactioncookie.DefaultName || strings.Contains(cookies[0].Value, handle) { + t.Errorf("the default UI set %v, want only the sealed %s", cookies, interactioncookie.DefaultName) + } + + unsafe := h.EmbedderUI(EmbedderUIOptions{OnInteraction: onInteraction, UnsafeRawHandleCookie: true}) + _, raw, _ := beginAt(t, h, unsafe) + if len(raw) != 2 || raw[0].Name != rawHandleCookie || raw[0].Value != handle || raw[1].Name != rawRequestCookie { + t.Fatalf("UnsafeRawHandleCookie set %v, want the raw handle and request", raw) + } + session := sessionCookie(t, sealed, "alice") + if w := serveUI(sealed, consentRequest(tag, append([]*http.Cookie{session}, raw...)...)); w.Code != http.StatusBadRequest { + t.Errorf("the default UI given the raw cookies: status %d, want %d", w.Code, http.StatusBadRequest) + } +} diff --git a/fapitest/export_internal_test.go b/fapitest/export_internal_test.go new file mode 100644 index 00000000..c2cd379f --- /dev/null +++ b/fapitest/export_internal_test.go @@ -0,0 +1,7 @@ +package fapitest + +// EmbedderUIWithKey is h.EmbedderUI sealing its interactions with key, +// for the key-material matrix to render one whose key it knows. +func EmbedderUIWithKey(h *Harness, opts EmbedderUIOptions, key []byte) *EmbedderUI { + return h.embedderUI(opts, key) +} diff --git a/fapitest/key_rendering_guard_test.go b/fapitest/key_rendering_guard_test.go index b45d3ad0..ded919d7 100644 --- a/fapitest/key_rendering_guard_test.go +++ b/fapitest/key_rendering_guard_test.go @@ -178,6 +178,12 @@ var keyHolders = map[string]keyHolder{ Session *client.BackchannelSessionSealer }{must(client.NewTokenSetSealer(c, [][]byte{key}))(t), must(client.NewBackchannelSessionSealer(c, [][]byte{key}))(t)}, []string{string(key)} }}, + "fapitest.Harness.EmbedderUI": {covers: []string{"fapitest.EmbedderUI.sealed"}, + build: func(t *testing.T) (any, []string) { + key := randomBytes(t, 32) + h := fapitest.New(t, fapitest.Config{Profile: server.ProfileFAPISecurity}) + return fapitest.EmbedderUIWithKey(h, fapitest.EmbedderUIOptions{}, key), []string{string(key)} + }}, "cookie jars": {covers: []string{"interactioncookie.Cookie.jar", "sessioncookie.Cookie.jar"}, build: func(t *testing.T) (any, []string) { key := randomBytes(t, 32) diff --git a/fapitest/redaction_guard_test.go b/fapitest/redaction_guard_test.go index 26911cdb..964c4ddd 100644 --- a/fapitest/redaction_guard_test.go +++ b/fapitest/redaction_guard_test.go @@ -262,7 +262,7 @@ var exemptTypes = map[string]string{ "client.BackchannelSessionSealer": engine, "client.Client": engine, "client.DiscoveredMetadata": engine, "client.InMemoryDPoPNonceCache": engine, "client.SystemClock": engine, "client.TokenSetSealer": engine, "sessioncookie.Cookie": engine, "extension.RARRegistry": engine, "extension.Registry": engine, - "fapitest.AutoApprove": engine, "fapitest.Harness": engine, "resource.JWTAccessTokens": engine, + "fapitest.AutoApprove": engine, "fapitest.Harness": engine, "fapitest.EmbedderUI": keyMaterial, "fapitest.EmbedderUIOptions": configuration, "resource.JWTAccessTokens": engine, "resource.NoDPoPNonces": engine, "resource.NoRevocation": engine, "resource.NoRevocationUntilExpiry": engine, "resource.OpaqueAccessTokens": engine, "resource.SystemClock": engine, "resource.Verifier": engine, "server.AllowRequestedAuthorizationDetails": engine, "server.AnyAttesterLeaf": engine, "server.AttesterAnchor": engine, From 6f2eba55d5e74d3f2d27b32234f251dba1098474 Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 22:24:52 +0800 Subject: [PATCH 3/5] test: drive the interaction-handle leak tests through EmbedderUI The leak tests built their own embedder, with a plain-cookie and a sealed-cookie bridge. They now use Harness.EmbedderUI, with UnsafeRawHandleCookie for the plain cookie and OnInteraction for the leaked handle, and sign the victim and the attacker in through its sign-in. The scenarios and assertions are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../interaction_handle_leak_internal_test.go | 189 +++++------------- 1 file changed, 50 insertions(+), 139 deletions(-) diff --git a/fapitest/interaction_handle_leak_internal_test.go b/fapitest/interaction_handle_leak_internal_test.go index d58a4cc3..68b7381a 100644 --- a/fapitest/interaction_handle_leak_internal_test.go +++ b/fapitest/interaction_handle_leak_internal_test.go @@ -2,13 +2,11 @@ package fapitest import ( "context" - "crypto/rand" "encoding/base64" "encoding/json" "net/http" "net/http/httptest" "net/url" - "strings" "testing" "time" @@ -32,100 +30,51 @@ import ( // hands the resulting redirect to the user, whose client then signs the // user in to the attacker's account. With server/interactioncookie the // handle is only ever read back from a cookie the server sealed, so the -// leaked handle alone completes nothing. +// leaked handle alone completes nothing. The embedder is EmbedderUI, +// with UnsafeRawHandleCookie for the plain cookie. const ( - leakVictimSession = "victim-session" - leakAttackerSession = "attacker-session" leakVictimSubject = "victim-user" leakAttackerSubject = "attacker-user" - leakLoginCookie = "login" ) -// leakBridge is how an embedder carries the interaction from its -// authorization endpoint to the consent form's submission. -type leakBridge interface { - // keep stores a in the browser's cookies on w and returns the tag - // the consent form sends back ("" if none). - keep(w http.ResponseWriter, a server.InteractionRequired, now time.Time) string - // recover reads the interaction back from r and the form's tag. - recover(r *http.Request, now time.Time, tag string) (server.InteractionHandle, server.InteractionRequest, bool) -} - -// plainCookieBridge keeps the raw handle, and the encoded request, in -// plain cookies. -type plainCookieBridge struct{} - -func (plainCookieBridge) keep(w http.ResponseWriter, a server.InteractionRequired, _ time.Time) string { - in, _ := a.Interaction.MarshalText() - http.SetCookie(w, &http.Cookie{Name: "interaction-handle", Value: a.Handle.String(), HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode}) - http.SetCookie(w, &http.Cookie{Name: "interaction-request", Value: base64.RawURLEncoding.EncodeToString(in), HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode}) - return "" -} - -func (plainCookieBridge) recover(r *http.Request, _ time.Time, _ string) (server.InteractionHandle, server.InteractionRequest, bool) { - hc, err1 := r.Cookie("interaction-handle") - rc, err2 := r.Cookie("interaction-request") - if err1 != nil || err2 != nil { - return server.InteractionHandle{}, server.InteractionRequest{}, false - } - handle, err := server.ParseInteractionHandle(hc.Value) - if err != nil { - return server.InteractionHandle{}, server.InteractionRequest{}, false - } - text, err := base64.RawURLEncoding.DecodeString(rc.Value) - if err != nil { - return server.InteractionHandle{}, server.InteractionRequest{}, false - } - in, err := server.ParseInteractionRequest(string(text)) - return handle, in, err == nil -} - -// sealedCookieBridge is server/interactioncookie. -type sealedCookieBridge struct{ cookie *interactioncookie.Cookie } - -func (b sealedCookieBridge) keep(w http.ResponseWriter, a server.InteractionRequired, now time.Time) string { - tag, err := b.cookie.Set(w, a, now) - if err != nil { - panic(err) - } - return tag -} - -func (b sealedCookieBridge) recover(r *http.Request, now time.Time, tag string) (server.InteractionHandle, server.InteractionRequest, bool) { - handle, in, err := b.cookie.Read(r, now, tag) - return handle, in, err == nil -} - -// leakEmbedder is the embedding authorization server's login UI. +// leakEmbedder is the embedding authorization server's login UI, with +// the handle of the last interaction begun, as a log line would leak +// it. type leakEmbedder struct { t *testing.T h *Harness - bridge leakBridge - // leaked is the handle of the last interaction begun, as a log line - // would leak it. + ui *EmbedderUI leaked string } +// newLeakEmbedder is an EmbedderUI at a new harness's server, with the +// raw handle in a plain cookie if unsafe is set. +func newLeakEmbedder(t *testing.T, unsafe bool) *leakEmbedder { + t.Helper() + e := &leakEmbedder{t: t, h: New(t, Config{Profile: server.ProfileFAPISecurity})} + e.ui = e.h.EmbedderUI(EmbedderUIOptions{ + UnsafeRawHandleCookie: unsafe, + OnInteraction: func(a server.InteractionRequired) { e.leaked = a.Handle.String() }, + }) + return e +} + +// signIn is the session cookie e's sign-in gives subject. +func (e *leakEmbedder) signIn(subject string) *http.Cookie { + e.t.Helper() + return sessionCookie(e.t, e.ui, subject) +} + // authorize is the browser reaching the authorization endpoint at // authorizeURL: the cookies it is given and the consent form's tag. func (e *leakEmbedder) authorize(authorizeURL url.URL) ([]*http.Cookie, string) { e.t.Helper() - q := authorizeURL.Query() - action, err := e.h.authServer.srv.BeginAuthorization(context.Background(), server.BeginAuthorizationRequest{ - RequestURI: q.Get("request_uri"), ClientID: clientIDFromQuery(q), - }) - if err != nil { - e.t.Fatalf("BeginAuthorization: %v", err) + w := serveUI(e.ui, httptest.NewRequest(http.MethodGet, EmbedderUIAuthorizePath+"?"+authorizeURL.RawQuery, nil)) + if w.Code != http.StatusOK { + e.t.Fatalf("authorize: status %d: %s", w.Code, w.Body) } - a, ok := action.(server.InteractionRequired) - if !ok { - e.t.Fatalf("BeginAuthorization = %T, want server.InteractionRequired", action) - } - e.leaked = a.Handle.String() - w := httptest.NewRecorder() - tag := e.bridge.keep(w, a, e.h.Clock.Now()) - return w.Result().Cookies(), tag + return w.Result().Cookies(), consentTag(e.t, w.Body.String()) } // decide is a browser carrying cookies submitting the consent form @@ -133,57 +82,24 @@ func (e *leakEmbedder) authorize(authorizeURL url.URL) ([]*http.Cookie, string) // redirect's query, or "" when the embedder refuses the submission. func (e *leakEmbedder) decide(cookies []*http.Cookie, tag string) string { e.t.Helper() - r := httptest.NewRequest(http.MethodPost, "/authorize", strings.NewReader(url.Values{interactioncookie.FormField: {tag}}.Encode())) - for _, c := range cookies { - r.AddCookie(&http.Cookie{Name: c.Name, Value: c.Value}) - } - login, err := r.Cookie(leakLoginCookie) - if err != nil { + w := serveUI(e.ui, consentRequest(tag, cookies...)) + switch w.Code { + case http.StatusSeeOther: + u, err := url.Parse(w.Header().Get("Location")) + if err != nil { + e.t.Fatalf("consent redirect: %v", err) + } + return u.RawQuery + case http.StatusForbidden: e.t.Fatal("the browser has no login session") + case http.StatusInternalServerError: + e.t.Fatalf("consent: %s", w.Body) } - subject := map[string]string{leakVictimSession: leakVictimSubject, leakAttackerSession: leakAttackerSubject}[login.Value] - handle, in, ok := e.bridge.recover(r, e.h.Clock.Now(), tag) - if !ok { - return "" - } - result, err := e.h.authServer.srv.CompleteAuthorization(context.Background(), server.CompleteAuthorizationRequest{ - Handle: handle, Result: server.Authorize(leakSubject(e.t, subject), leakAuthContext(e.t, e.h.Clock.Now()), server.GrantedAuthorization{Scope: in.Scope}), - }) - if err != nil { - e.t.Fatalf("CompleteAuthorization: %v", err) - } - redirect, ok := result.(server.AuthorizationRedirect) - if !ok { - return "" - } - u := redirect.Destination().URL() - return u.RawQuery -} - -func leakSubject(t *testing.T, value string) server.AuthenticatedSubject { - t.Helper() - id, err := server.NewSubjectID(value) - if err != nil { - t.Fatalf("NewSubjectID: %v", err) - } - subject, err := server.NewAuthenticatedSubject(id) - if err != nil { - t.Fatalf("NewAuthenticatedSubject: %v", err) - } - return subject -} - -func leakAuthContext(t *testing.T, now time.Time) server.AuthenticationContext { - t.Helper() - authCtx, err := server.NewAuthenticationContext(now, "", nil) - if err != nil { - t.Fatalf("NewAuthenticationContext: %v", err) - } - return authCtx + return "" } -func withLogin(session string, cookies ...*http.Cookie) []*http.Cookie { - return append([]*http.Cookie{{Name: leakLoginCookie, Value: session}}, cookies...) +func withLogin(session *http.Cookie, cookies ...*http.Cookie) []*http.Cookie { + return append([]*http.Cookie{session}, cookies...) } // beginVictim starts the victim's sign-in at h's client and has the @@ -196,7 +112,7 @@ func beginVictim(t *testing.T, e *leakEmbedder) (client.AuthorizationSession, [] t.Fatalf("BeginAuthorization (client): %v", err) } cookies, tag := e.authorize(session.URL().URL()) - return session, withLogin(leakVictimSession, cookies...), tag + return session, withLogin(e.signIn(leakVictimSubject), cookies...), tag } // TestLeakedHandleInPlainCookieCompletesVictimsInteraction: with the @@ -206,17 +122,17 @@ func beginVictim(t *testing.T, e *leakEmbedder) (client.AuthorizationSession, [] // to the victim's browser, signs the victim's client in to the // attacker's account. func TestLeakedHandleInPlainCookieCompletesVictimsInteraction(t *testing.T) { - e := &leakEmbedder{t: t, h: New(t, Config{Profile: server.ProfileFAPISecurity}), bridge: plainCookieBridge{}} + e := newLeakEmbedder(t, true) session, victimCookies, tag := beginVictim(t, e) var requestCookie *http.Cookie for _, c := range victimCookies { - if c.Name == "interaction-request" { + if c.Name == rawRequestCookie { requestCookie = c } } - attackerCookies := withLogin(leakAttackerSession, - &http.Cookie{Name: "interaction-handle", Value: e.leaked}, requestCookie) + attackerCookies := withLogin(e.signIn(leakAttackerSubject), + &http.Cookie{Name: rawHandleCookie, Value: e.leaked}, requestCookie) callback := e.decide(attackerCookies, tag) if callback == "" { t.Fatal("the attacker's submission with the leaked handle was refused") @@ -259,13 +175,8 @@ func forgedSealedCookie(t *testing.T, sealed *http.Cookie, handle, tag string, n // — completes nothing, even with the victim's form tag, which isn't // secret; the victim's own submission then completes as the victim. func TestLeakedHandleIsUselessWithInteractionCookie(t *testing.T) { - key := make([]byte, 32) - _, _ = rand.Read(key) - cookie, err := interactioncookie.New([][]byte{key}, interactioncookie.Options{}) - if err != nil { - t.Fatalf("interactioncookie.New: %v", err) - } - e := &leakEmbedder{t: t, h: New(t, Config{Profile: server.ProfileFAPISecurity}), bridge: sealedCookieBridge{cookie}} + e := newLeakEmbedder(t, false) + attacker := e.signIn(leakAttackerSubject) session, victimCookies, tag := beginVictim(t, e) var sealed *http.Cookie @@ -278,7 +189,7 @@ func TestLeakedHandleIsUselessWithInteractionCookie(t *testing.T) { "raw handle": {Name: interactioncookie.DefaultName, Value: e.leaked}, "forged value": forgedSealedCookie(t, sealed, e.leaked, tag, e.h.Clock.Now()), } { - if callback := e.decide(withLogin(leakAttackerSession, forged), tag); callback != "" { + if callback := e.decide(withLogin(attacker, forged), tag); callback != "" { t.Errorf("%s: the attacker completed the victim's interaction: %s", name, callback) } } From 10f03a3f860a69470da9341bdaa89ff843b1e53f Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 22:25:21 +0800 Subject: [PATCH 4/5] test: add mutants for EmbedderUI's session and sealing checks Co-Authored-By: Claude Opus 5.5 --- .github/mutation/mutants.json | 48 +++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/.github/mutation/mutants.json b/.github/mutation/mutants.json index ef9c0702..8c1546ac 100644 --- a/.github/mutation/mutants.json +++ b/.github/mutation/mutants.json @@ -5995,5 +5995,53 @@ ], "run": "^TestParseClaimsRefusesDuplicateMembers$", "why": "a JARM response repeating iss with an identical value (claim and RFC 9207 parameter) is accepted" + }, + { + "id": "fapitest-embedderui-session-lookup", + "file": "fapitest/embedderui.go", + "old": "\treturn subject, ok\n}", + "new": "\treturn subject, ok || true\n}", + "module": "root", + "packages": [ + "./fapitest" + ], + "run": "^TestEmbedderUIRefusesConsentWithoutASession$", + "why": "EmbedderUI's consent accepts a session cookie it never issued" + }, + { + "id": "fapitest-embedderui-consent-needs-session", + "file": "fapitest/embedderui.go", + "old": "\tif !ok {\n\t\thttp.Error(w, \"not signed in\"", + "new": "\tif !ok && false {\n\t\thttp.Error(w, \"not signed in\"", + "module": "root", + "packages": [ + "./fapitest" + ], + "run": "^TestEmbedderUIRefusesConsentWithoutASession$", + "why": "EmbedderUI's consent completes an interaction for a browser that isn't signed in" + }, + { + "id": "fapitest-embedderui-keep-sealed", + "file": "fapitest/embedderui.go", + "old": "\tif !u.opts.UnsafeRawHandleCookie {\n\t\treturn u.sealed.Set(w, a, now)", + "new": "\tif !u.opts.UnsafeRawHandleCookie && false {\n\t\treturn u.sealed.Set(w, a, now)", + "module": "root", + "packages": [ + "./fapitest" + ], + "run": "^TestEmbedderUISealsTheHandleUnlessToldNotTo$", + "why": "EmbedderUI keeps the raw handle in a plain cookie without UnsafeRawHandleCookie" + }, + { + "id": "fapitest-embedderui-recover-sealed", + "file": "fapitest/embedderui.go", + "old": "\tif !u.opts.UnsafeRawHandleCookie {\n\t\thandle, in, err := u.sealed.Read(r, now, tag)", + "new": "\tif !u.opts.UnsafeRawHandleCookie && false {\n\t\thandle, in, err := u.sealed.Read(r, now, tag)", + "module": "root", + "packages": [ + "./fapitest" + ], + "run": "^TestEmbedderUISealsTheHandleUnlessToldNotTo$", + "why": "EmbedderUI without UnsafeRawHandleCookie completes an interaction from the raw handle in a plain cookie" } ] From eaa12126cba6a830b56e2de81ad950f3f595a2fb Mon Sep 17 00:00:00 2001 From: Oscar Sanderson Date: Thu, 26 Nov 2026 22:45:17 +0800 Subject: [PATCH 5/5] test(fapitest): cover the login UI's refusals of bad input Co-Authored-By: Claude Opus 5.5 --- fapitest/embedderui_errors_internal_test.go | 53 +++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 fapitest/embedderui_errors_internal_test.go diff --git a/fapitest/embedderui_errors_internal_test.go b/fapitest/embedderui_errors_internal_test.go new file mode 100644 index 00000000..f27538a4 --- /dev/null +++ b/fapitest/embedderui_errors_internal_test.go @@ -0,0 +1,53 @@ +package fapitest + +import ( + "encoding/base64" + "net/http" + "net/http/httptest" + "testing" + + "github.com/idfoundry/fapigo/server" +) + +// TestEmbedderUIRefusesABadSignInOrAuthorization: a sign-in naming no +// subject, and an authorization request the server can't read or +// refuses, are answered with an error, not a consent page. +func TestEmbedderUIRefusesABadSignInOrAuthorization(t *testing.T) { + h := New(t, Config{Profile: server.ProfileFAPISecurity}) + ui := h.EmbedderUI(EmbedderUIOptions{}) + if w := serveUI(ui, signInRequest("")); w.Code != http.StatusBadRequest { + t.Errorf("sign-in without a subject: status %d, want %d", w.Code, http.StatusBadRequest) + } + for name, query := range map[string]string{ + "no parameters": "", + "unknown request_uri": "client_id=" + string(ClientID) + "&request_uri=urn:ietf:params:oauth:request_uri:unknown", + "unregistered client": "client_id=nobody&request_uri=urn:ietf:params:oauth:request_uri:unknown", + "malformed query value": "client_id=%zz", + } { + w := serveUI(ui, httptest.NewRequest(http.MethodGet, EmbedderUIAuthorizePath+"?"+query, nil)) + if w.Code == http.StatusOK { + t.Errorf("%s: status 200, want an error or a redirect to the client", name) + } + } +} + +// TestEmbedderUIUnsafeModeRefusesUnreadableCookies: with +// UnsafeRawHandleCookie, a consent whose raw cookies are missing or +// don't parse is refused as having no sign-in in progress. +func TestEmbedderUIUnsafeModeRefusesUnreadableCookies(t *testing.T) { + h := New(t, Config{Profile: server.ProfileFAPISecurity}) + ui := h.EmbedderUI(EmbedderUIOptions{UnsafeRawHandleCookie: true}) + _, raw, _ := beginAt(t, h, ui) + session := sessionCookie(t, ui, "alice") + handle, request := raw[0], raw[1] + for name, cookies := range map[string][]*http.Cookie{ + "no raw cookies": {session}, + "empty handle": {session, {Name: handle.Name, Value: ""}, request}, + "request not base64": {session, handle, {Name: request.Name, Value: "!!!"}}, + "request not readable": {session, handle, {Name: request.Name, Value: base64.RawURLEncoding.EncodeToString([]byte("{"))}}, + } { + if w := serveUI(ui, consentRequest("", cookies...)); w.Code != http.StatusBadRequest { + t.Errorf("%s: status %d, want %d", name, w.Code, http.StatusBadRequest) + } + } +}