diff --git a/.github/mutation/mutants.json b/.github/mutation/mutants.json index e4be4da1..87a7e20e 100644 --- a/.github/mutation/mutants.json +++ b/.github/mutation/mutants.json @@ -5178,5 +5178,425 @@ ], "run": "^TestCodeReuseWhileIssuedIsInvalidGrant$", "why": "a code exchange issuing its refresh token last answers invalid_grant when a reuse revokes the grant mid-issuance" + }, + { + "id": "keys-signer-km-signer-redacted", + "file": "keys/key_holder_render.go", + "old": "Signer: keyMask(b.signer != nil)", + "new": "Signer: redact.Hidden(fmt.Sprint(b.signer))", + "module": "root", + "packages": [ + "./keys" + ], + "run": "^(TestSignerKeyManagerPrintsNoKey|TestSignerKeyManagerLogsNoKey)$", + "why": "the signer KeyManager prints and logs [REDACTED] for each signer, an ed25519 private key included" + }, + { + "id": "keys-signer-km-format", + "file": "keys/key_holder_render.go", + "old": "func (m signerKeyManager) Format(f fmt.State, verb rune) {", + "new": "func (m signerKeyManager) format(f fmt.State, verb rune) {", + "module": "root", + "packages": [ + "./keys" + ], + "run": "^TestSignerKeyManagerPrintsNoKey$", + "why": "the signer KeyManager formats itself, so no verb reaches its signers" + }, + { + "id": "keys-signer-km-logvalue", + "file": "keys/key_holder_render.go", + "old": "func (m signerKeyManager) LogValue() slog.Value {", + "new": "func (m signerKeyManager) logValue() slog.Value {", + "module": "root", + "packages": [ + "./keys" + ], + "run": "^TestSignerKeyManagerLogsNoKey$", + "why": "log/slog logs the signer KeyManager's redacted shadow" + }, + { + "id": "keys-custody-km-format", + "file": "keys/key_holder_render.go", + "old": "func (m custodyKeyManager) Format(f fmt.State, verb rune) {", + "new": "func (m custodyKeyManager) format(f fmt.State, verb rune) {", + "module": "root", + "packages": [ + "./keys" + ], + "run": "^TestSignerKeyManagerPrintsNoKey$", + "why": "a custody-declaring signer KeyManager prints its own redacted shadow, custody included" + }, + { + "id": "keys-inmemory-ecdh-priv-redacted", + "file": "keys/key_holder_render.go", + "old": "inMemoryKeyShadow{Priv: keyMask(k.priv != nil), KeyID: k.kid}, \"keys.inMemoryKeyShadow\", \"keys.inMemoryECDH\")", + "new": "inMemoryKeyShadow{Priv: redact.Hidden(fmt.Sprint(k.priv.Bytes())), KeyID: k.kid}, \"keys.inMemoryKeyShadow\", \"keys.inMemoryECDH\")", + "module": "root", + "packages": [ + "./keys" + ], + "run": "^TestInMemoryKeysPrintNoKey$", + "why": "the in-memory ECDH backend prints [REDACTED] for its private key" + }, + { + "id": "keys-inmemory-ecdh-format", + "file": "keys/key_holder_render.go", + "old": "func (k inMemoryECDH) Format(f fmt.State, verb rune) {", + "new": "func (k inMemoryECDH) format(f fmt.State, verb rune) {", + "module": "root", + "packages": [ + "./keys" + ], + "run": "^TestInMemoryKeysPrintNoKey$", + "why": "the in-memory ECDH backend formats itself, so %s and %q don't print what its *ecdh.PrivateKey points to" + }, + { + "id": "keys-inmemory-ecdh-logvalue", + "file": "keys/key_holder_render.go", + "old": "func (k inMemoryECDH) LogValue() slog.Value {", + "new": "func (k inMemoryECDH) logValue() slog.Value {", + "module": "root", + "packages": [ + "./keys" + ], + "run": "^TestInMemoryKeysPrintNoKey$", + "why": "log/slog logs the in-memory ECDH backend's redacted shadow" + }, + { + "id": "keys-inmemory-rsa-format", + "file": "keys/key_holder_render.go", + "old": "func (k inMemoryRSA) Format(f fmt.State, verb rune) {", + "new": "func (k inMemoryRSA) format(f fmt.State, verb rune) {", + "module": "root", + "packages": [ + "./keys" + ], + "run": "^TestInMemoryKeysPrintNoKey$", + "why": "the in-memory RSA backend prints its redacted shadow" + }, + { + "id": "ephemeral-km-signing-key-redacted", + "file": "keys/ephemeral/render.go", + "old": "sh.Keys[purpose] = keyShadow{Key: keyMask(held != nil && held.signer != nil), KeyID: m.kid[purpose]}", + "new": "sh.Keys[purpose] = keyShadow{Key: redact.Hidden(fmt.Sprint(held.signer)), KeyID: m.kid[purpose]}", + "module": "root", + "packages": [ + "./keys/ephemeral" + ], + "run": "^(TestKeyManagerPrintsNoKey|TestKeyManagerLogsNoKey)$", + "why": "an ephemeral KeyManager prints and logs [REDACTED] for each signing key, an ed25519 private key included" + }, + { + "id": "ephemeral-km-decryption-key-redacted", + "file": "keys/ephemeral/render.go", + "old": "sh.Decryption[purpose] = keyShadow{Key: keyMask(priv != nil), KeyID: m.decryption.kid[purpose]}", + "new": "sh.Decryption[purpose] = keyShadow{Key: redact.Hidden(fmt.Sprint(priv)), KeyID: m.decryption.kid[purpose]}", + "module": "root", + "packages": [ + "./keys/ephemeral" + ], + "run": "^TestKeyManagerPrintsNoKey$", + "why": "an ephemeral KeyManager prints [REDACTED] for each decryption key" + }, + { + "id": "ephemeral-km-format", + "file": "keys/ephemeral/render.go", + "old": "func (m *KeyManager) Format(f fmt.State, verb rune) {", + "new": "func (m *KeyManager) format(f fmt.State, verb rune) {", + "module": "root", + "packages": [ + "./keys/ephemeral" + ], + "run": "^TestKeyManagerPrintsNoKey$", + "why": "an ephemeral KeyManager formats itself, so no verb reaches its keys" + }, + { + "id": "ephemeral-km-logvalue", + "file": "keys/ephemeral/render.go", + "old": "func (m *KeyManager) LogValue() slog.Value {", + "new": "func (m *KeyManager) logValue() slog.Value {", + "module": "root", + "packages": [ + "./keys/ephemeral" + ], + "run": "^TestKeyManagerLogsNoKey$", + "why": "log/slog logs an ephemeral KeyManager's redacted shadow" + }, + { + "id": "fed-deps-signer-redacted", + "file": "federation/dependencies_render.go", + "old": "sh := issueDependenciesShadow{Signer: signerMask(signer),", + "new": "sh := issueDependenciesShadow{Signer: redact.Hidden(fmt.Sprint(signer)),", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^(TestIssueDependenciesPrintNoKey|TestIssueDependenciesPrintTheirFields)$", + "why": "the resolve, subordinate and trust mark issuers' dependencies print [REDACTED] for their Signer" + }, + { + "id": "fed-jwks-deps-signer-redacted", + "file": "federation/dependencies_render.go", + "old": "sh := jwksIssueDependenciesShadow{Signer: signerMask(signer),", + "new": "sh := jwksIssueDependenciesShadow{Signer: redact.Hidden(fmt.Sprint(signer)),", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^(TestIssueDependenciesPrintNoKey|TestIssueDependenciesPrintTheirFields)$", + "why": "the self and historical keys issuers' dependencies print [REDACTED] for their Signer" + }, + { + "id": "fed-deps-log-signer-redacted", + "file": "federation/dependencies_render.go", + "old": "slog.String(\"Signer\", string(signerMask(signer)))", + "new": "slog.String(\"Signer\", fmt.Sprint(signer))", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^(TestIssueDependenciesPrintNoKey|TestIssueDependenciesLogNoKey)$", + "why": "log/slog logs [REDACTED] for an issuer's dependencies' Signer" + }, + { + "id": "fed-historicalkeys-deps-refuse-json", + "file": "federation/dependencies_render.go", + "old": "func (HistoricalKeysIssueDependencies) MarshalJSON() ([]byte, error) {\n\treturn nil, ErrIssueDependenciesSerialization\n}", + "new": "func (HistoricalKeysIssueDependencies) MarshalJSON() ([]byte, error) {\n\treturn []byte(\"{}\"), nil\n}", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssueDependenciesRefuseEncoding$", + "why": "encoding/json refuses HistoricalKeysIssueDependencies rather than writing its Signer" + }, + { + "id": "fed-historicalkeys-deps-refuse-text", + "file": "federation/dependencies_render.go", + "old": "func (HistoricalKeysIssueDependencies) MarshalText() ([]byte, error) {\n\treturn nil, ErrIssueDependenciesSerialization\n}", + "new": "func (HistoricalKeysIssueDependencies) MarshalText() ([]byte, error) {\n\treturn []byte(\"x\"), nil\n}", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssueDependenciesRefuseEncoding$", + "why": "encoding/xml and other TextMarshaler encoders refuse HistoricalKeysIssueDependencies rather than writing its Signer" + }, + { + "id": "fed-resolve-deps-refuse-json", + "file": "federation/dependencies_render.go", + "old": "func (ResolveIssueDependencies) MarshalJSON() ([]byte, error) {\n\treturn nil, ErrIssueDependenciesSerialization\n}", + "new": "func (ResolveIssueDependencies) MarshalJSON() ([]byte, error) {\n\treturn []byte(\"{}\"), nil\n}", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssueDependenciesRefuseEncoding$", + "why": "encoding/json refuses ResolveIssueDependencies rather than writing its Signer" + }, + { + "id": "fed-resolve-deps-refuse-text", + "file": "federation/dependencies_render.go", + "old": "func (ResolveIssueDependencies) MarshalText() ([]byte, error) {\n\treturn nil, ErrIssueDependenciesSerialization\n}", + "new": "func (ResolveIssueDependencies) MarshalText() ([]byte, error) {\n\treturn []byte(\"x\"), nil\n}", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssueDependenciesRefuseEncoding$", + "why": "encoding/xml and other TextMarshaler encoders refuse ResolveIssueDependencies rather than writing its Signer" + }, + { + "id": "fed-self-deps-refuse-json", + "file": "federation/dependencies_render.go", + "old": "func (SelfIssueDependencies) MarshalJSON() ([]byte, error) {\n\treturn nil, ErrIssueDependenciesSerialization\n}", + "new": "func (SelfIssueDependencies) MarshalJSON() ([]byte, error) {\n\treturn []byte(\"{}\"), nil\n}", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssueDependenciesRefuseEncoding$", + "why": "encoding/json refuses SelfIssueDependencies rather than writing its Signer" + }, + { + "id": "fed-self-deps-refuse-text", + "file": "federation/dependencies_render.go", + "old": "func (SelfIssueDependencies) MarshalText() ([]byte, error) {\n\treturn nil, ErrIssueDependenciesSerialization\n}", + "new": "func (SelfIssueDependencies) MarshalText() ([]byte, error) {\n\treturn []byte(\"x\"), nil\n}", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssueDependenciesRefuseEncoding$", + "why": "encoding/xml and other TextMarshaler encoders refuse SelfIssueDependencies rather than writing its Signer" + }, + { + "id": "fed-subordinate-deps-refuse-json", + "file": "federation/dependencies_render.go", + "old": "func (SubordinateIssueDependencies) MarshalJSON() ([]byte, error) {\n\treturn nil, ErrIssueDependenciesSerialization\n}", + "new": "func (SubordinateIssueDependencies) MarshalJSON() ([]byte, error) {\n\treturn []byte(\"{}\"), nil\n}", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssueDependenciesRefuseEncoding$", + "why": "encoding/json refuses SubordinateIssueDependencies rather than writing its Signer" + }, + { + "id": "fed-subordinate-deps-refuse-text", + "file": "federation/dependencies_render.go", + "old": "func (SubordinateIssueDependencies) MarshalText() ([]byte, error) {\n\treturn nil, ErrIssueDependenciesSerialization\n}", + "new": "func (SubordinateIssueDependencies) MarshalText() ([]byte, error) {\n\treturn []byte(\"x\"), nil\n}", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssueDependenciesRefuseEncoding$", + "why": "encoding/xml and other TextMarshaler encoders refuse SubordinateIssueDependencies rather than writing its Signer" + }, + { + "id": "fed-trustmark-deps-refuse-json", + "file": "federation/dependencies_render.go", + "old": "func (TrustMarkIssueDependencies) MarshalJSON() ([]byte, error) {\n\treturn nil, ErrIssueDependenciesSerialization\n}", + "new": "func (TrustMarkIssueDependencies) MarshalJSON() ([]byte, error) {\n\treturn []byte(\"{}\"), nil\n}", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssueDependenciesRefuseEncoding$", + "why": "encoding/json refuses TrustMarkIssueDependencies rather than writing its Signer" + }, + { + "id": "fed-trustmark-deps-refuse-text", + "file": "federation/dependencies_render.go", + "old": "func (TrustMarkIssueDependencies) MarshalText() ([]byte, error) {\n\treturn nil, ErrIssueDependenciesSerialization\n}", + "new": "func (TrustMarkIssueDependencies) MarshalText() ([]byte, error) {\n\treturn []byte(\"x\"), nil\n}", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssueDependenciesRefuseEncoding$", + "why": "encoding/xml and other TextMarshaler encoders refuse TrustMarkIssueDependencies rather than writing its Signer" + }, + { + "id": "fed-historicalkeys-issuer-format", + "file": "federation/issuers_render.go", + "old": "func (i HistoricalKeysIssuer) Format(f fmt.State, verb rune) {", + "new": "func (i HistoricalKeysIssuer) format(f fmt.State, verb rune) {", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssuersPrintNoKey$", + "why": "a HistoricalKeysIssuer formats itself, so no verb reaches its dependencies' Signer" + }, + { + "id": "fed-historicalkeys-issuer-logvalue", + "file": "federation/issuers_render.go", + "old": "func (i HistoricalKeysIssuer) LogValue() slog.Value {", + "new": "func (i HistoricalKeysIssuer) logValue() slog.Value {", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssuersPrintNoKey$", + "why": "log/slog logs a HistoricalKeysIssuer's redacted shadow" + }, + { + "id": "fed-resolve-issuer-format", + "file": "federation/issuers_render.go", + "old": "func (i ResolveIssuer) Format(f fmt.State, verb rune) {", + "new": "func (i ResolveIssuer) format(f fmt.State, verb rune) {", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssuersPrintNoKey$", + "why": "a ResolveIssuer formats itself, so no verb reaches its dependencies' Signer" + }, + { + "id": "fed-resolve-issuer-logvalue", + "file": "federation/issuers_render.go", + "old": "func (i ResolveIssuer) LogValue() slog.Value {", + "new": "func (i ResolveIssuer) logValue() slog.Value {", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssuersPrintNoKey$", + "why": "log/slog logs a ResolveIssuer's redacted shadow" + }, + { + "id": "fed-self-issuer-format", + "file": "federation/issuers_render.go", + "old": "func (s SelfIssuer) Format(f fmt.State, verb rune) {", + "new": "func (s SelfIssuer) format(f fmt.State, verb rune) {", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssuersPrintNoKey$", + "why": "a SelfIssuer formats itself, so no verb reaches its dependencies' Signer" + }, + { + "id": "fed-self-issuer-logvalue", + "file": "federation/issuers_render.go", + "old": "func (s SelfIssuer) LogValue() slog.Value {", + "new": "func (s SelfIssuer) logValue() slog.Value {", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssuersPrintNoKey$", + "why": "log/slog logs a SelfIssuer's redacted shadow" + }, + { + "id": "fed-subordinate-issuer-format", + "file": "federation/issuers_render.go", + "old": "func (s SubordinateIssuer) Format(f fmt.State, verb rune) {", + "new": "func (s SubordinateIssuer) format(f fmt.State, verb rune) {", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssuersPrintNoKey$", + "why": "a SubordinateIssuer formats itself, so no verb reaches its dependencies' Signer" + }, + { + "id": "fed-subordinate-issuer-logvalue", + "file": "federation/issuers_render.go", + "old": "func (s SubordinateIssuer) LogValue() slog.Value {", + "new": "func (s SubordinateIssuer) logValue() slog.Value {", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssuersPrintNoKey$", + "why": "log/slog logs a SubordinateIssuer's redacted shadow" + }, + { + "id": "fed-trustmark-issuer-format", + "file": "federation/issuers_render.go", + "old": "func (i TrustMarkIssuer) Format(f fmt.State, verb rune) {", + "new": "func (i TrustMarkIssuer) format(f fmt.State, verb rune) {", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssuersPrintNoKey$", + "why": "a TrustMarkIssuer formats itself, so no verb reaches its dependencies' Signer" + }, + { + "id": "fed-trustmark-issuer-logvalue", + "file": "federation/issuers_render.go", + "old": "func (i TrustMarkIssuer) LogValue() slog.Value {", + "new": "func (i TrustMarkIssuer) logValue() slog.Value {", + "module": "root", + "packages": [ + "./federation" + ], + "run": "^TestIssuersPrintNoKey$", + "why": "log/slog logs a TrustMarkIssuer's redacted shadow" } ] diff --git a/UPGRADING.md b/UPGRADING.md index af61d406..2e45efda 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -78,6 +78,47 @@ withdraw the token, still answers `server_error`. 500: expect a 400 `invalid_grant` instead, and the client starts a new authorization as for any other refused grant. +### Encoding a federation issuer's dependencies fails (federation) + +**Affects:** code that encodes a `federation.HistoricalKeysIssueDependencies`, +`ResolveIssueDependencies`, `SelfIssueDependencies`, +`SubordinateIssueDependencies` or `TrustMarkIssueDependencies`, or a +struct holding one, with `encoding/json`, `encoding/xml` or another +encoder that uses `MarshalText` or `MarshalJSON`. Building and running +the issuers is unchanged. + +**Why:** their `Signer` is often the private key itself, and an encoder +wrote it out: `encoding/json`, `encoding/xml` and `log/slog`'s JSON +handler encoded an ECDSA or RSA key's private exponent, into a config +dump or a log line, say. `keys.SignerSpec` already refuses encoding for +the same reason. + +**What fails:** encoding returns an error wrapping +`federation.ErrIssueDependenciesSerialization`. + +**What to change:** encode the entity's public keys instead (the +`JWKS` you pass `SelfIssueDependencies`, say), or the fields you need +without `Signer`. + +### Key holders print `[REDACTED]` for their keys (keys, federation) + +**Affects:** only code that compares the `fmt` or `log/slog` output of +the `KeyManager` `keys.NewKeyManagerFromSigners` returns, a +`keys/ephemeral.KeyManager`, the backends `keys.NewInMemoryECDH` and +`keys.NewInMemoryRSA` return, or a federation issuer or its +dependencies. + +**Why:** they printed whatever `fmt` makes of their keys, which for an +`ed25519.PrivateKey`, a byte slice, is every byte of it, and for an +`*ecdh.PrivateKey` under `%s` is what it points to. An issuer printed +its dependencies field by field, its `Signer` included. + +**What fails:** nothing fails. Each now prints its kids and the rest +of what it holds but its keys, with `[REDACTED]` for each private key +or signer, under every verb and in `log/slog`. + +**What to change:** nothing, unless a test matched the old output. + ## v0.85.0 ### Codes, refresh tokens and `auth_req_id`s are stored under digests covering the issuer (server, storage) diff --git a/fapitest/key_rendering_guard_test.go b/fapitest/key_rendering_guard_test.go index 87ec77e8..f272968d 100644 --- a/fapitest/key_rendering_guard_test.go +++ b/fapitest/key_rendering_guard_test.go @@ -18,6 +18,7 @@ import ( "slices" "strings" "testing" + "time" "unsafe" fapi "github.com/idfoundry/fapigo" @@ -43,7 +44,10 @@ import ( // // A case whose renderings print its key today is skipped, with the // reason in knownLeak, so the matrix records the gap without failing -// the build; removing knownLeak is how a fix proves itself. +// the build; removing knownLeak is how a fix proves itself. A case +// whose key sits in an exported field the caller fills, which fmt's +// reflection fallback prints as it prints any exported field, accepts +// that fallback, with the reason in inputField. // keyHolder is one case of the key-material matrix. type keyHolder struct { @@ -54,14 +58,15 @@ type keyHolder struct { build func(t *testing.T) (value any, secrets []string) // knownLeak, when set, skips the case: some rendering prints the key. knownLeak string + // inputField, when set, accepts what fmt's reflection fallback + // prints, which calls none of the value's methods: the key is in an + // exported field of an input type the caller fills. + inputField string } -// The known leaks the skipped cases record. -const ( - leaksEd25519 = "fmt's %v prints an ed25519.PrivateKey held behind crypto.Signer: it is a byte slice, which fmt prints at any depth" - leaksSignerJSON = "encoding/json, encoding/xml and slog's JSON handler encode an *ecdsa.PrivateKey held in the exported Signer field, D included" - leaksECDHBadVerb = "fmt's %s and %q print the *ecdh.PrivateKey's bytes: a verb a pointer field doesn't take makes fmt print what it points to" -) +// signerSpecEd25519 is why the keys.SignerSpec EdDSA case accepts fmt's +// reflection fallback. +const signerSpecEd25519 = "an ed25519.PrivateKey in SignerSpec's exported Signer field is a byte slice, which fmt's reflection fallback (%w outside Errorf, %p, a SignerSpec in an unexported field) prints byte by byte; an *ecdsa.PrivateKey or *rsa.PrivateKey sits behind a pointer it prints as an address" // keyHolders are the key-material matrix's cases, by name. var keyHolders = map[string]keyHolder{ @@ -79,7 +84,7 @@ var keyHolders = map[string]keyHolder{ build: func(t *testing.T) (any, []string) { return signerKeyManager(t, fapi.ES256, ecdsaKey(t)) }}, "keys.NewKeyManagerFromSigners PS256": {covers: []string{"keys.signerBackend.signer"}, build: func(t *testing.T) (any, []string) { return signerKeyManager(t, fapi.PS256, rsaKey(t)) }}, - "keys.NewKeyManagerFromSigners EdDSA": {covers: []string{"keys.signerBackend.signer"}, knownLeak: leaksEd25519, + "keys.NewKeyManagerFromSigners EdDSA": {covers: []string{"keys.signerBackend.signer"}, build: func(t *testing.T) (any, []string) { return signerKeyManager(t, fapi.EdDSA, ed25519Key(t)) }}, "keys.SignerSpec ES256 and PS256": {covers: []string{"keys.SignerSpec.Signer"}, build: func(t *testing.T) (any, []string) { @@ -89,12 +94,12 @@ var keyHolders = map[string]keyHolder{ {Purpose: keys.IDTokenSigning, Algorithm: fapi.PS256, Signer: rsa}, }, append(keySecrets(ec), keySecrets(rsa)...) }}, - "keys.SignerSpec EdDSA": {covers: []string{"keys.SignerSpec.Signer"}, knownLeak: leaksEd25519, + "keys.SignerSpec EdDSA": {covers: []string{"keys.SignerSpec.Signer"}, inputField: signerSpecEd25519, build: func(t *testing.T) (any, []string) { key := ed25519Key(t) return keys.SignerSpec{Purpose: keys.JARMSigning, Algorithm: fapi.EdDSA, Signer: key}, keySecrets(key) }}, - "federation issuers' Dependencies": {knownLeak: leaksSignerJSON, + "federation issuers' Dependencies": { covers: []string{ "federation.HistoricalKeysIssueDependencies.Signer", "federation.ResolveIssueDependencies.Signer", "federation.SelfIssueDependencies.Signer", "federation.SubordinateIssueDependencies.Signer", @@ -116,21 +121,26 @@ var keyHolders = map[string]keyHolder{ federation.TrustMarkIssueDependencies{Signer: key, Algorithm: fapi.ES256}, }, keySecrets(key) }}, + "federation issuers": { + build: func(t *testing.T) (any, []string) { + key := ed25519Key(t) + return federationIssuers(t, key), keySecrets(key) + }}, "keys.NewInMemoryRSA": {covers: []string{"keys.inMemoryRSA.priv"}, build: func(t *testing.T) (any, []string) { key := rsaKey(t) return must(keys.NewInMemoryRSA(key, "k"))(t), keySecrets(key) }}, - "keys.NewInMemoryECDH": {covers: []string{"keys.inMemoryECDH.priv"}, knownLeak: leaksECDHBadVerb, + "keys.NewInMemoryECDH": {covers: []string{"keys.inMemoryECDH.priv"}, build: func(t *testing.T) (any, []string) { 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.KeyManager.keys"}, + "ephemeral.NewKeyManager ES256 and PS256": {covers: []string{"ephemeral.signingKey.signer"}, 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.KeyManager.keys"}, knownLeak: leaksEd25519, + "ephemeral.NewKeyManager EdDSA": {covers: []string{"ephemeral.signingKey.signer"}, build: func(t *testing.T) (any, []string) { return ephemeralKeyManager(t, map[keys.SigningPurpose]fapi.SignatureAlgorithm{keys.JARMSigning: fapi.EdDSA}, nil) }}, @@ -166,7 +176,11 @@ func TestKeyHoldersDontPrintTheirKeys(t *testing.T) { t.Skip("known leak, awaiting a decision: " + tc.knownLeak) } value, secrets := tc.build(t) - rendertest.Check(t, value, secrets, rendertest.Quick()) + opts := []rendertest.Option{rendertest.Quick()} + if tc.inputField != "" { + opts = append(opts, rendertest.Allow(rendertest.Fallback)) + } + rendertest.Check(t, value, secrets, opts...) }) } } @@ -326,6 +340,32 @@ func ed25519Key(t *testing.T) ed25519.PrivateKey { return key } +// federationIssuers is one of each federation issuer, signing with key. +func federationIssuers(t *testing.T, key ed25519.PrivateKey) any { + t.Helper() + const id = "https://entity.example" + clock := federation.SystemClock{} + jwks := []byte(`{"keys":[]}`) + return struct { + Historical *federation.HistoricalKeysIssuer + Resolve *federation.ResolveIssuer + Self *federation.SelfIssuer + Subordinate *federation.SubordinateIssuer + TrustMark *federation.TrustMarkIssuer + }{ + must(federation.NewHistoricalKeysIssuer(federation.HistoricalKeysIssueConfig{EntityID: id}, + federation.HistoricalKeysIssueDependencies{Signer: key, Algorithm: fapi.EdDSA, KeyID: "k", Clock: clock}))(t), + must(federation.NewResolveIssuer(federation.ResolveIssueConfig{EntityID: id}, + federation.ResolveIssueDependencies{Signer: key, Algorithm: fapi.EdDSA, KeyID: "k", Clock: clock}))(t), + must(federation.NewSelfIssuer(federation.SelfIssueConfig{EntityID: id, Lifetime: time.Hour}, + federation.SelfIssueDependencies{Signer: key, Algorithm: fapi.EdDSA, KeyID: "k", JWKS: jwks, Clock: clock}))(t), + must(federation.NewSubordinateIssuer(federation.SubordinateIssueConfig{EntityID: id, Lifetime: time.Hour}, + federation.SubordinateIssueDependencies{Signer: key, Algorithm: fapi.EdDSA, KeyID: "k", Clock: clock}))(t), + must(federation.NewTrustMarkIssuer(federation.TrustMarkIssueConfig{EntityID: id}, + federation.TrustMarkIssueDependencies{Signer: key, Algorithm: fapi.EdDSA, KeyID: "k", Clock: clock}))(t), + } +} + // signerKeyManager is keys.NewKeyManagerFromSigners over signer, with // the key material it holds. func signerKeyManager(t *testing.T, alg fapi.SignatureAlgorithm, signer crypto.Signer) (any, []string) { @@ -356,10 +396,14 @@ func unexportedField(v reflect.Value, name string) reflect.Value { return reflect.NewAt(f.Type(), unsafe.Pointer(f.UnsafeAddr())).Elem() } -// mapKeySecrets is the key material of m's values. +// mapKeySecrets is the key material of m's values: a key, or a pointer +// to a struct holding one in its signer field. func mapKeySecrets(m reflect.Value) []string { var secrets []string for _, v := range m.Seq2() { + if v.Kind() == reflect.Pointer && v.Elem().Kind() == reflect.Struct { + v = unexportedField(v.Elem(), "signer") + } secrets = append(secrets, keySecrets(v.Interface())...) } return secrets diff --git a/federation/dependencies_render.go b/federation/dependencies_render.go new file mode 100644 index 00000000..e66f3c6f --- /dev/null +++ b/federation/dependencies_render.go @@ -0,0 +1,198 @@ +package federation + +import ( + "crypto" + "encoding/json" + "errors" + "fmt" + "log/slog" + + fapi "github.com/idfoundry/fapigo" + "github.com/idfoundry/fapigo/internal/redact" +) + +// The issuers' *IssueDependencies hold the Signer that signs the +// issuer's statements, often the private key itself, in an exported +// field. So each prints a shadow of itself in which Signer is only +// [REDACTED], under every fmt verb and flag and in log/slog (see +// package redact), and refuses encoding/json, encoding/xml and every +// other encoder that takes an encoding.TextMarshaler: see +// ErrIssueDependenciesSerialization. fmt's reflection fallback, for a +// value in an unexported field, still sees Signer as the exported field +// it is: an *ecdsa.PrivateKey or *rsa.PrivateKey sits behind a pointer +// it prints as an address, but an ed25519.PrivateKey is a byte slice. + +// ErrIssueDependenciesSerialization is returned by the MarshalText and +// MarshalJSON methods of HistoricalKeysIssueDependencies, +// ResolveIssueDependencies, SelfIssueDependencies, +// SubordinateIssueDependencies and TrustMarkIssueDependencies, so a +// Signer, often the private key itself, is never serialized (into a +// JSON response, a config dump, a log line) by an encoder that doesn't +// know what it holds. Publish the entity's public keys as its JWKS +// instead. +var ErrIssueDependenciesSerialization = errors.New("federation: issuer dependencies cannot be marshaled, since their Signer may be the private key") + +// issueDependenciesShadow is what ResolveIssueDependencies, +// SubordinateIssueDependencies and TrustMarkIssueDependencies print. +type issueDependenciesShadow struct { + Signer redact.Hidden + Algorithm fapi.SignatureAlgorithm + KeyID string + Clock Clock +} + +// jwksIssueDependenciesShadow is what HistoricalKeysIssueDependencies +// and SelfIssueDependencies print. +type jwksIssueDependenciesShadow struct { + Signer redact.Hidden + Algorithm fapi.SignatureAlgorithm + KeyID string + JWKS json.RawMessage + Clock Clock +} + +func signerMask(signer crypto.Signer) redact.Hidden { + if signer == nil { + return "" + } + return redact.Redacted +} + +func formatDependencies(f fmt.State, verb rune, signer crypto.Signer, alg fapi.SignatureAlgorithm, kid string, clock Clock, typeName string) { + sh := issueDependenciesShadow{Signer: signerMask(signer), Algorithm: alg, KeyID: kid, Clock: clock} + redact.Format(f, verb, sh, "federation.issueDependenciesShadow", typeName) +} + +func formatJWKSDependencies(f fmt.State, verb rune, signer crypto.Signer, alg fapi.SignatureAlgorithm, kid string, jwks json.RawMessage, clock Clock, typeName string) { + sh := jwksIssueDependenciesShadow{Signer: signerMask(signer), Algorithm: alg, KeyID: kid, JWKS: jwks, Clock: clock} + redact.Format(f, verb, sh, "federation.jwksIssueDependenciesShadow", typeName) +} + +func dependenciesLogValue(signer crypto.Signer, alg fapi.SignatureAlgorithm, kid string, clock Clock, extra ...slog.Attr) slog.Value { + attrs := []slog.Attr{ + slog.String("Signer", string(signerMask(signer))), slog.String("Algorithm", alg.String()), + slog.String("KeyID", kid), + } + attrs = append(attrs, extra...) + return slog.GroupValue(append(attrs, slog.Any("Clock", clock))...) +} + +// Format implements fmt.Formatter: d prints its fields, with only +// [REDACTED] for Signer, under every verb and flag. +func (d HistoricalKeysIssueDependencies) Format(f fmt.State, verb rune) { + formatJWKSDependencies(f, verb, d.Signer, d.Algorithm, d.KeyID, d.JWKS, d.Clock, "federation.HistoricalKeysIssueDependencies") +} + +// LogValue implements slog.LogValuer: d's fields, with only +// [REDACTED] for Signer. +func (d HistoricalKeysIssueDependencies) LogValue() slog.Value { + return dependenciesLogValue(d.Signer, d.Algorithm, d.KeyID, d.Clock, slog.Any("JWKS", d.JWKS)) +} + +// MarshalText implements encoding.TextMarshaler by refusing: see +// ErrIssueDependenciesSerialization. +func (HistoricalKeysIssueDependencies) MarshalText() ([]byte, error) { + return nil, ErrIssueDependenciesSerialization +} + +// MarshalJSON implements json.Marshaler by refusing: see +// ErrIssueDependenciesSerialization. +func (HistoricalKeysIssueDependencies) MarshalJSON() ([]byte, error) { + return nil, ErrIssueDependenciesSerialization +} + +// Format implements fmt.Formatter: d prints its fields, with only +// [REDACTED] for Signer, under every verb and flag. +func (d ResolveIssueDependencies) Format(f fmt.State, verb rune) { + formatDependencies(f, verb, d.Signer, d.Algorithm, d.KeyID, d.Clock, "federation.ResolveIssueDependencies") +} + +// LogValue implements slog.LogValuer: d's fields, with only +// [REDACTED] for Signer. +func (d ResolveIssueDependencies) LogValue() slog.Value { + return dependenciesLogValue(d.Signer, d.Algorithm, d.KeyID, d.Clock) +} + +// MarshalText implements encoding.TextMarshaler by refusing: see +// ErrIssueDependenciesSerialization. +func (ResolveIssueDependencies) MarshalText() ([]byte, error) { + return nil, ErrIssueDependenciesSerialization +} + +// MarshalJSON implements json.Marshaler by refusing: see +// ErrIssueDependenciesSerialization. +func (ResolveIssueDependencies) MarshalJSON() ([]byte, error) { + return nil, ErrIssueDependenciesSerialization +} + +// Format implements fmt.Formatter: d prints its fields, with only +// [REDACTED] for Signer, under every verb and flag. +func (d SelfIssueDependencies) Format(f fmt.State, verb rune) { + formatJWKSDependencies(f, verb, d.Signer, d.Algorithm, d.KeyID, d.JWKS, d.Clock, "federation.SelfIssueDependencies") +} + +// LogValue implements slog.LogValuer: d's fields, with only +// [REDACTED] for Signer. +func (d SelfIssueDependencies) LogValue() slog.Value { + return dependenciesLogValue(d.Signer, d.Algorithm, d.KeyID, d.Clock, slog.Any("JWKS", d.JWKS)) +} + +// MarshalText implements encoding.TextMarshaler by refusing: see +// ErrIssueDependenciesSerialization. +func (SelfIssueDependencies) MarshalText() ([]byte, error) { + return nil, ErrIssueDependenciesSerialization +} + +// MarshalJSON implements json.Marshaler by refusing: see +// ErrIssueDependenciesSerialization. +func (SelfIssueDependencies) MarshalJSON() ([]byte, error) { + return nil, ErrIssueDependenciesSerialization +} + +// Format implements fmt.Formatter: d prints its fields, with only +// [REDACTED] for Signer, under every verb and flag. +func (d SubordinateIssueDependencies) Format(f fmt.State, verb rune) { + formatDependencies(f, verb, d.Signer, d.Algorithm, d.KeyID, d.Clock, "federation.SubordinateIssueDependencies") +} + +// LogValue implements slog.LogValuer: d's fields, with only +// [REDACTED] for Signer. +func (d SubordinateIssueDependencies) LogValue() slog.Value { + return dependenciesLogValue(d.Signer, d.Algorithm, d.KeyID, d.Clock) +} + +// MarshalText implements encoding.TextMarshaler by refusing: see +// ErrIssueDependenciesSerialization. +func (SubordinateIssueDependencies) MarshalText() ([]byte, error) { + return nil, ErrIssueDependenciesSerialization +} + +// MarshalJSON implements json.Marshaler by refusing: see +// ErrIssueDependenciesSerialization. +func (SubordinateIssueDependencies) MarshalJSON() ([]byte, error) { + return nil, ErrIssueDependenciesSerialization +} + +// Format implements fmt.Formatter: d prints its fields, with only +// [REDACTED] for Signer, under every verb and flag. +func (d TrustMarkIssueDependencies) Format(f fmt.State, verb rune) { + formatDependencies(f, verb, d.Signer, d.Algorithm, d.KeyID, d.Clock, "federation.TrustMarkIssueDependencies") +} + +// LogValue implements slog.LogValuer: d's fields, with only +// [REDACTED] for Signer. +func (d TrustMarkIssueDependencies) LogValue() slog.Value { + return dependenciesLogValue(d.Signer, d.Algorithm, d.KeyID, d.Clock) +} + +// MarshalText implements encoding.TextMarshaler by refusing: see +// ErrIssueDependenciesSerialization. +func (TrustMarkIssueDependencies) MarshalText() ([]byte, error) { + return nil, ErrIssueDependenciesSerialization +} + +// MarshalJSON implements json.Marshaler by refusing: see +// ErrIssueDependenciesSerialization. +func (TrustMarkIssueDependencies) MarshalJSON() ([]byte, error) { + return nil, ErrIssueDependenciesSerialization +} diff --git a/federation/dependencies_render_internal_test.go b/federation/dependencies_render_internal_test.go new file mode 100644 index 00000000..78085994 --- /dev/null +++ b/federation/dependencies_render_internal_test.go @@ -0,0 +1,173 @@ +package federation + +import ( + "bytes" + "crypto" + "crypto/ecdsa" + "crypto/ed25519" + "crypto/elliptic" + "crypto/rand" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "log/slog" + "reflect" + "strings" + "testing" + + fapi "github.com/idfoundry/fapigo" + "github.com/idfoundry/fapigo/internal/rendertest" +) + +var testJWKS = json.RawMessage(`{"keys":[]}`) + +// checkAllDependencies runs check on one of each issuer's dependencies, +// signing with signer. +func checkAllDependencies(signer crypto.Signer, check func(name string, deps any, run func(func(any)))) { + h := HistoricalKeysIssueDependencies{Signer: signer, Algorithm: fapi.ES256, KeyID: "k1", JWKS: testJWKS, Clock: SystemClock{}} + r := ResolveIssueDependencies{Signer: signer, Algorithm: fapi.ES256, KeyID: "k1", Clock: SystemClock{}} + s := SelfIssueDependencies{Signer: signer, Algorithm: fapi.ES256, KeyID: "k1", JWKS: testJWKS, Clock: SystemClock{}} + sub := SubordinateIssueDependencies{Signer: signer, Algorithm: fapi.ES256, KeyID: "k1", Clock: SystemClock{}} + tm := TrustMarkIssueDependencies{Signer: signer, Algorithm: fapi.ES256, KeyID: "k1", Clock: SystemClock{}} + check("HistoricalKeysIssueDependencies", h, func(f func(any)) { f(h); f(&h) }) + check("ResolveIssueDependencies", r, func(f func(any)) { f(r); f(&r) }) + check("SelfIssueDependencies", s, func(f func(any)) { f(s); f(&s) }) + check("SubordinateIssueDependencies", sub, func(f func(any)) { f(sub); f(&sub) }) + check("TrustMarkIssueDependencies", tm, func(f func(any)) { f(tm); f(&tm) }) +} + +// TestIssueDependenciesPrintNoKey: each issuer's dependencies print +// [REDACTED] for their Signer, whatever prints them through their own +// methods, and the encoders refuse them. fmt's reflection fallback sees +// Signer as the exported field it is, so it's allowed for an +// ed25519.PrivateKey, a byte slice it prints whole; an +// *ecdsa.PrivateKey sits behind a pointer it prints as an address. +func TestIssueDependenciesPrintNoKey(t *testing.T) { + ec, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + _, ed, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + ecSecrets := []string{string(ec.D.FillBytes(make([]byte, 32))), ec.D.String()} + rendertest.Check(t, HistoricalKeysIssueDependencies{Signer: ec, Algorithm: fapi.ES256, JWKS: testJWKS}, ecSecrets) + rendertest.Check(t, ResolveIssueDependencies{Signer: ec, Algorithm: fapi.ES256}, ecSecrets) + rendertest.Check(t, SelfIssueDependencies{Signer: ec, Algorithm: fapi.ES256, JWKS: testJWKS}, ecSecrets) + rendertest.Check(t, SubordinateIssueDependencies{Signer: ec, Algorithm: fapi.ES256}, ecSecrets) + rendertest.Check(t, TrustMarkIssueDependencies{Signer: ec, Algorithm: fapi.ES256}, ecSecrets) + + edSecrets, fallback := []string{string(ed.Seed())}, rendertest.Allow(rendertest.Fallback) + quick := rendertest.Quick() + rendertest.Check(t, HistoricalKeysIssueDependencies{Signer: ed, Algorithm: fapi.EdDSA, JWKS: testJWKS}, edSecrets, fallback, quick) + rendertest.Check(t, ResolveIssueDependencies{Signer: ed, Algorithm: fapi.EdDSA}, edSecrets, fallback, quick) + rendertest.Check(t, SelfIssueDependencies{Signer: ed, Algorithm: fapi.EdDSA, JWKS: testJWKS}, edSecrets, fallback, quick) + rendertest.Check(t, SubordinateIssueDependencies{Signer: ed, Algorithm: fapi.EdDSA}, edSecrets, fallback, quick) + rendertest.Check(t, TrustMarkIssueDependencies{Signer: ed, Algorithm: fapi.EdDSA}, edSecrets, fallback, quick) +} + +// TestIssueDependenciesPrintTheirFields: under %+v and %#v each +// issuer's dependencies print every field but Signer as fmt would, and +// a dependencies value without a Signer prints no placeholder. +func TestIssueDependenciesPrintTheirFields(t *testing.T) { + ec, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + checkAllDependencies(ec, func(name string, deps any, _ func(func(any))) { + want := "{Signer:[REDACTED] Algorithm:ES256 KeyID:k1 Clock:{}}" + if strings.HasPrefix(name, "Historical") || strings.HasPrefix(name, "Self") { + want = "{Signer:[REDACTED] Algorithm:ES256 KeyID:k1 JWKS:" + fmt.Sprintf("%+v", testJWKS) + " Clock:{}}" + } + if got := fmt.Sprintf("%+v", deps); got != want { + t.Errorf("%s: %%+v = %q, want %q", name, got, want) + } + if got := fmt.Sprintf("%#v", deps); !strings.HasPrefix(got, "federation."+name+"{") || strings.Contains(got, "Shadow") { + t.Errorf("%s: %%#v = %q, want the real type's name", name, got) + } + }) + checkAllDependencies(nil, func(name string, deps any, _ func(func(any))) { + if got := fmt.Sprint(deps); strings.Contains(got, "REDACTED") { + t.Errorf("%s without a Signer prints %q, want no placeholder", name, got) + } + }) +} + +// TestIssueDependenciesLogNoKey: log/slog's JSON handler logs each +// issuer's dependencies' fields, with [REDACTED] for Signer. +func TestIssueDependenciesLogNoKey(t *testing.T) { + ec, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + checkAllDependencies(ec, func(name string, deps any, _ func(func(any))) { + var buf bytes.Buffer + slog.New(slog.NewJSONHandler(&buf, nil)).Info("deps", "v", deps) + want := `"v":{"Signer":"[REDACTED]","Algorithm":"ES256","KeyID":"k1","Clock":{}}` + if strings.HasPrefix(name, "Historical") || strings.HasPrefix(name, "Self") { + want = `"v":{"Signer":"[REDACTED]","Algorithm":"ES256","KeyID":"k1","JWKS":{"keys":[]},"Clock":{}}` + } + if got := buf.String(); !strings.Contains(got, want) { + t.Errorf("%s: slog JSON logged %s, want it to hold %s", name, got, want) + } + }) +} + +// TestIssueDependenciesShadowsMatch keeps each issuer's dependencies' +// shadow in step with it. +func TestIssueDependenciesShadowsMatch(t *testing.T) { + plain, withJWKS := reflect.TypeFor[issueDependenciesShadow](), reflect.TypeFor[jwksIssueDependenciesShadow]() + rendertest.CheckShadow(t, reflect.TypeFor[HistoricalKeysIssueDependencies](), withJWKS) + rendertest.CheckShadow(t, reflect.TypeFor[ResolveIssueDependencies](), plain) + rendertest.CheckShadow(t, reflect.TypeFor[SelfIssueDependencies](), withJWKS) + rendertest.CheckShadow(t, reflect.TypeFor[SubordinateIssueDependencies](), plain) + rendertest.CheckShadow(t, reflect.TypeFor[TrustMarkIssueDependencies](), plain) +} + +// xmlHolder holds dependencies in a field, as a configuration struct +// encoding/xml can name would. +type xmlHolder struct{ Deps any } + +// TestIssueDependenciesRefuseEncoding: encoding/json and encoding/xml, +// given each issuer's dependencies as a value, a pointer, or a field of +// a struct, and the dependencies' own MarshalText and MarshalJSON, all +// fail with ErrIssueDependenciesSerialization rather than writing the +// Signer. +func TestIssueDependenciesRefuseEncoding(t *testing.T) { + ec, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + checkAllDependencies(ec, func(name string, deps any, run func(func(any))) { + run(func(v any) { checkEncodersRefuse(t, name, v) }) + m := deps.(interface { + MarshalText() ([]byte, error) + MarshalJSON() ([]byte, error) + }) + if out, err := m.MarshalText(); !errors.Is(err, ErrIssueDependenciesSerialization) || out != nil { + t.Errorf("%s.MarshalText = %q, %v; want ErrIssueDependenciesSerialization", name, out, err) + } + if out, err := m.MarshalJSON(); !errors.Is(err, ErrIssueDependenciesSerialization) || out != nil { + t.Errorf("%s.MarshalJSON = %q, %v; want ErrIssueDependenciesSerialization", name, out, err) + } + }) +} + +// checkEncodersRefuse fails t unless encoding/json refuses v, name's +// dependencies, alone, in a struct and in a slice, and encoding/xml +// refuses it alone and in a struct. +func checkEncodersRefuse(t *testing.T, name string, v any) { + t.Helper() + for _, shape := range []any{v, struct{ Deps any }{v}, []any{v}} { + if out, err := json.Marshal(shape); !errors.Is(err, ErrIssueDependenciesSerialization) { + t.Errorf("json.Marshal(%T holding %s) = %s, %v; want ErrIssueDependenciesSerialization", shape, name, out, err) + } + } + for _, shape := range []any{v, xmlHolder{Deps: v}} { + if out, err := xml.Marshal(shape); !errors.Is(err, ErrIssueDependenciesSerialization) { + t.Errorf("xml.Marshal(%T holding %s) = %s, %v; want ErrIssueDependenciesSerialization", shape, name, out, err) + } + } +} diff --git a/federation/historical_keys_issue.go b/federation/historical_keys_issue.go index 81c65aca..aa7a3f19 100644 --- a/federation/historical_keys_issue.go +++ b/federation/historical_keys_issue.go @@ -81,6 +81,9 @@ type HistoricalKeysIssueDependencies struct { // Resolver.FetchHistoricalKeys verifies against after resolving this // entity's Trust Chain. Never one of the retired keys the response // reports on: Response refuses to publish Signer's own key. + // + // The dependencies print [REDACTED] for Signer and refuse to be + // encoded: see ErrIssueDependenciesSerialization. Signer crypto.Signer // Algorithm Signer signs with. @@ -128,7 +131,7 @@ type HistoricalKeysIssueDependencies struct { // supplies Response's input. type HistoricalKeysIssuer struct { cfg HistoricalKeysIssueConfig - deps HistoricalKeysIssueDependencies + deps *HistoricalKeysIssueDependencies active []jose.ParsedJWK } @@ -162,7 +165,7 @@ func NewHistoricalKeysIssuer(cfg HistoricalKeysIssueConfig, deps HistoricalKeysI active = parsed } cfg.AdditionalRevocationReasons = slices.Clone(cfg.AdditionalRevocationReasons) - return &HistoricalKeysIssuer{cfg: cfg, deps: deps, active: active}, nil + return &HistoricalKeysIssuer{cfg: cfg, deps: &deps, active: active}, nil } // Response signs and returns a Federation Historical Keys response diff --git a/federation/issuers_render.go b/federation/issuers_render.go new file mode 100644 index 00000000..ef60cac4 --- /dev/null +++ b/federation/issuers_render.go @@ -0,0 +1,113 @@ +package federation + +import ( + "fmt" + "log/slog" + + "github.com/idfoundry/fapigo/internal/jose" + "github.com/idfoundry/fapigo/internal/redact" +) + +// Each issuer holds its dependencies, Signer included, so it prints a +// shadow of itself in which they print as their own Format does, with +// [REDACTED] for Signer (see dependencies_render.go), under every verb +// and flag and in log/slog. The dependencies are held behind a pointer, +// so fmt's reflection fallback, which calls no Format method (%w outside +// Errorf, say), prints only an address where Signer is: an +// ed25519.PrivateKey is a byte slice it would print whole. + +type historicalKeysIssuerShadow struct { + Config HistoricalKeysIssueConfig + Dependencies HistoricalKeysIssueDependencies + Active []jose.ParsedJWK +} + +type resolveIssuerShadow struct { + Config ResolveIssueConfig + Dependencies ResolveIssueDependencies +} + +type selfIssuerShadow struct { + Config SelfIssueConfig + Dependencies SelfIssueDependencies +} + +type subordinateIssuerShadow struct { + Config SubordinateIssueConfig + Dependencies SubordinateIssueDependencies +} + +type trustMarkIssuerShadow struct { + Config TrustMarkIssueConfig + Dependencies TrustMarkIssueDependencies +} + +// deref is *p, or the zero value for a nil p. +func deref[T any](p *T) T { + if p == nil { + var zero T + return zero + } + return *p +} + +// Format implements fmt.Formatter: i prints its config and +// dependencies, with [REDACTED] for Signer, under every verb and flag. +func (i HistoricalKeysIssuer) Format(f fmt.State, verb rune) { + redact.Format(f, verb, historicalKeysIssuerShadow{Config: i.cfg, Dependencies: deref(i.deps), Active: i.active}, + "federation.historicalKeysIssuerShadow", "federation.HistoricalKeysIssuer") +} + +// LogValue implements slog.LogValuer: i's config and dependencies, with +// [REDACTED] for Signer. +func (i HistoricalKeysIssuer) LogValue() slog.Value { + return slog.GroupValue(slog.Any("Config", i.cfg), slog.Any("Dependencies", deref(i.deps).LogValue()), slog.Any("Active", i.active)) +} + +// Format implements fmt.Formatter: i prints its config and +// dependencies, with [REDACTED] for Signer, under every verb and flag. +func (i ResolveIssuer) Format(f fmt.State, verb rune) { + redact.Format(f, verb, resolveIssuerShadow{Config: i.cfg, Dependencies: deref(i.deps)}, "federation.resolveIssuerShadow", "federation.ResolveIssuer") +} + +// LogValue implements slog.LogValuer: i's config and dependencies, with +// [REDACTED] for Signer. +func (i ResolveIssuer) LogValue() slog.Value { + return slog.GroupValue(slog.Any("Config", i.cfg), slog.Any("Dependencies", deref(i.deps).LogValue())) +} + +// Format implements fmt.Formatter: i prints its config and +// dependencies, with [REDACTED] for Signer, under every verb and flag. +func (s SelfIssuer) Format(f fmt.State, verb rune) { + redact.Format(f, verb, selfIssuerShadow{Config: s.cfg, Dependencies: deref(s.deps)}, "federation.selfIssuerShadow", "federation.SelfIssuer") +} + +// LogValue implements slog.LogValuer: i's config and dependencies, with +// [REDACTED] for Signer. +func (s SelfIssuer) LogValue() slog.Value { + return slog.GroupValue(slog.Any("Config", s.cfg), slog.Any("Dependencies", deref(s.deps).LogValue())) +} + +// Format implements fmt.Formatter: i prints its config and +// dependencies, with [REDACTED] for Signer, under every verb and flag. +func (s SubordinateIssuer) Format(f fmt.State, verb rune) { + redact.Format(f, verb, subordinateIssuerShadow{Config: s.cfg, Dependencies: deref(s.deps)}, "federation.subordinateIssuerShadow", "federation.SubordinateIssuer") +} + +// LogValue implements slog.LogValuer: i's config and dependencies, with +// [REDACTED] for Signer. +func (s SubordinateIssuer) LogValue() slog.Value { + return slog.GroupValue(slog.Any("Config", s.cfg), slog.Any("Dependencies", deref(s.deps).LogValue())) +} + +// Format implements fmt.Formatter: i prints its config and +// dependencies, with [REDACTED] for Signer, under every verb and flag. +func (i TrustMarkIssuer) Format(f fmt.State, verb rune) { + redact.Format(f, verb, trustMarkIssuerShadow{Config: i.cfg, Dependencies: deref(i.deps)}, "federation.trustMarkIssuerShadow", "federation.TrustMarkIssuer") +} + +// LogValue implements slog.LogValuer: i's config and dependencies, with +// [REDACTED] for Signer. +func (i TrustMarkIssuer) LogValue() slog.Value { + return slog.GroupValue(slog.Any("Config", i.cfg), slog.Any("Dependencies", deref(i.deps).LogValue())) +} diff --git a/federation/issuers_render_test.go b/federation/issuers_render_test.go new file mode 100644 index 00000000..515b5f6c --- /dev/null +++ b/federation/issuers_render_test.go @@ -0,0 +1,82 @@ +package federation_test + +import ( + "bytes" + "crypto/ed25519" + "crypto/rand" + "encoding/base64" + "encoding/json" + "fmt" + "log/slog" + "strings" + "testing" + "time" + + fapi "github.com/idfoundry/fapigo" + "github.com/idfoundry/fapigo/federation" + "github.com/idfoundry/fapigo/internal/rendertest" +) + +// ed25519Issuers is one of each issuer, signing with a fresh +// ed25519.PrivateKey, and that key's seed. +func ed25519Issuers(t *testing.T) (map[string]any, string) { + t.Helper() + pub, key, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + jwks, err := json.Marshal(map[string]any{"keys": []any{map[string]any{"kty": "OKP", "crv": "Ed25519", "kid": "k1", "alg": "EdDSA", "x": base64.RawURLEncoding.EncodeToString(pub)}}}) + if err != nil { + t.Fatal(err) + } + const id = "https://entity.example" + clock := federation.SystemClock{} + issuers := map[string]any{} + add := func(name string, v any, err error) { + t.Helper() + if err != nil { + t.Fatalf("New%s: %v", name, err) + } + issuers[name] = v + } + h, err := federation.NewHistoricalKeysIssuer(federation.HistoricalKeysIssueConfig{EntityID: id}, + federation.HistoricalKeysIssueDependencies{Signer: key, Algorithm: fapi.EdDSA, KeyID: "k1", Clock: clock}) + add("HistoricalKeysIssuer", h, err) + r, err := federation.NewResolveIssuer(federation.ResolveIssueConfig{EntityID: id}, + federation.ResolveIssueDependencies{Signer: key, Algorithm: fapi.EdDSA, KeyID: "k1", Clock: clock}) + add("ResolveIssuer", r, err) + s, err := federation.NewSelfIssuer(federation.SelfIssueConfig{EntityID: id, Lifetime: time.Hour}, + federation.SelfIssueDependencies{Signer: key, Algorithm: fapi.EdDSA, KeyID: "k1", JWKS: jwks, Clock: clock}) + add("SelfIssuer", s, err) + sub, err := federation.NewSubordinateIssuer(federation.SubordinateIssueConfig{EntityID: id, Lifetime: time.Hour}, + federation.SubordinateIssueDependencies{Signer: key, Algorithm: fapi.EdDSA, KeyID: "k1", Clock: clock}) + add("SubordinateIssuer", sub, err) + tm, err := federation.NewTrustMarkIssuer(federation.TrustMarkIssueConfig{EntityID: id}, + federation.TrustMarkIssueDependencies{Signer: key, Algorithm: fapi.EdDSA, KeyID: "k1", Clock: clock}) + add("TrustMarkIssuer", tm, err) + return issuers, string(key.Seed()) +} + +// TestIssuersPrintNoKey: each issuer, signing with an +// ed25519.PrivateKey, a byte slice fmt would print whole, prints and +// logs its config and dependencies with [REDACTED] for the Signer, +// under every rendering the matrix makes, fmt's reflection fallback +// included. +func TestIssuersPrintNoKey(t *testing.T) { + issuers, seed := ed25519Issuers(t) + for name, issuer := range issuers { + rendertest.Check(t, issuer, []string{seed}, rendertest.Quick()) + out := fmt.Sprintf("%+v", issuer) + if !strings.Contains(out, "Dependencies:{Signer:[REDACTED] Algorithm:EdDSA KeyID:k1") || !strings.Contains(out, "Config:{EntityID:https://entity.example") { + t.Errorf("%s: %%+v = %q, want its config and redacted dependencies", name, out) + } + if got := fmt.Sprintf("%#v", issuer); !strings.HasPrefix(got, "federation."+name+"{") { + t.Errorf("%s: %%#v = %q, want the real type's name", name, got) + } + var buf bytes.Buffer + slog.New(slog.NewJSONHandler(&buf, nil)).Info("issuer", "v", issuer) + if got := buf.String(); !strings.Contains(got, `"Dependencies":{"Signer":"[REDACTED]","Algorithm":"EdDSA","KeyID":"k1"`) { + t.Errorf("%s: slog JSON logged %s, want its redacted dependencies", name, got) + } + } +} diff --git a/federation/resolve_issue.go b/federation/resolve_issue.go index 50d6f727..9b338189 100644 --- a/federation/resolve_issue.go +++ b/federation/resolve_issue.go @@ -29,6 +29,9 @@ type ResolveIssueConfig struct { type ResolveIssueDependencies struct { // Signer produces every Resolve Response's signature — this // entity's own federation key. + // + // The dependencies print [REDACTED] for Signer and refuse to be + // encoded: see ErrIssueDependenciesSerialization. Signer crypto.Signer // Algorithm Signer signs with. @@ -60,7 +63,7 @@ type ResolveIssueDependencies struct { // it never resolves a Trust Chain itself — see its own doc comment. type ResolveIssuer struct { cfg ResolveIssueConfig - deps ResolveIssueDependencies + deps *ResolveIssueDependencies } // NewResolveIssuer validates cfg and deps and returns a ResolveIssuer. @@ -80,7 +83,7 @@ func NewResolveIssuer(cfg ResolveIssueConfig, deps ResolveIssueDependencies) (*R if deps.Clock == nil { return nil, fmt.Errorf("federation: dependencies: clock is required") } - return &ResolveIssuer{cfg: cfg, deps: deps}, nil + return &ResolveIssuer{cfg: cfg, deps: &deps}, nil } // VerifiedTrustMark pairs an already-verified Trust Mark's own wire diff --git a/federation/self_issue.go b/federation/self_issue.go index 16c8d8c6..e6a627b0 100644 --- a/federation/self_issue.go +++ b/federation/self_issue.go @@ -60,6 +60,9 @@ type SelfIssueDependencies struct { // signs OAuth/OIDC artifacts with, matching this module's existing // key-separation precedent for every other signing use // (ARCHITECTURE.md). + // + // The dependencies print [REDACTED] for Signer and refuse to be + // encoded: see ErrIssueDependenciesSerialization. Signer crypto.Signer // Algorithm Signer signs with. @@ -87,7 +90,7 @@ type SelfIssueDependencies struct { // capability. Construct one with NewSelfIssuer. type SelfIssuer struct { cfg SelfIssueConfig - deps SelfIssueDependencies + deps *SelfIssueDependencies } // NewSelfIssuer validates cfg and deps and returns a SelfIssuer. @@ -118,7 +121,7 @@ func NewSelfIssuer(cfg SelfIssueConfig, deps SelfIssueDependencies) (*SelfIssuer if deps.Clock == nil { return nil, fmt.Errorf("federation: dependencies: clock is required") } - return &SelfIssuer{cfg: cfg, deps: deps}, nil + return &SelfIssuer{cfg: cfg, deps: &deps}, nil } // clone returns c with a copy of AuthorityHints and of TrustMarkIssuers, diff --git a/federation/subordinate_issue.go b/federation/subordinate_issue.go index 855eb799..583717eb 100644 --- a/federation/subordinate_issue.go +++ b/federation/subordinate_issue.go @@ -40,6 +40,9 @@ type SubordinateIssueDependencies struct { // entity's own federation signing key, the same one // SelfIssueDependencies.Signer would use for its own Entity // Configuration when this entity also self-issues one. + // + // The dependencies print [REDACTED] for Signer and refuse to be + // encoded: see ErrIssueDependenciesSerialization. Signer crypto.Signer // Algorithm Signer signs with. @@ -65,7 +68,7 @@ type SubordinateIssueDependencies struct { // WellKnownPath. type SubordinateIssuer struct { cfg SubordinateIssueConfig - deps SubordinateIssueDependencies + deps *SubordinateIssueDependencies } // NewSubordinateIssuer validates cfg and deps and returns a @@ -86,7 +89,7 @@ func NewSubordinateIssuer(cfg SubordinateIssueConfig, deps SubordinateIssueDepen if deps.Clock == nil { return nil, fmt.Errorf("federation: dependencies: clock is required") } - return &SubordinateIssuer{cfg: cfg, deps: deps}, nil + return &SubordinateIssuer{cfg: cfg, deps: &deps}, nil } // SubordinateStatementParams describes one Subordinate Statement to diff --git a/federation/trustmark_issue.go b/federation/trustmark_issue.go index d68fe544..7ec4c5c6 100644 --- a/federation/trustmark_issue.go +++ b/federation/trustmark_issue.go @@ -31,6 +31,9 @@ type TrustMarkIssueConfig struct { type TrustMarkIssueDependencies struct { // Signer produces every Trust Mark/Delegation's signature — this // entity's own federation signing key. + // + // The dependencies print [REDACTED] for Signer and refuse to be + // encoded: see ErrIssueDependenciesSerialization. Signer crypto.Signer // Algorithm Signer signs with. @@ -74,7 +77,7 @@ const TrustMarkContentType = "application/trust-mark+jwt" // an HTTPStatus to. type TrustMarkIssuer struct { cfg TrustMarkIssueConfig - deps TrustMarkIssueDependencies + deps *TrustMarkIssueDependencies } // NewTrustMarkIssuer validates cfg and deps and returns a @@ -95,7 +98,7 @@ func NewTrustMarkIssuer(cfg TrustMarkIssueConfig, deps TrustMarkIssueDependencie if deps.Clock == nil { return nil, fmt.Errorf("federation: dependencies: clock is required") } - return &TrustMarkIssuer{cfg: cfg, deps: deps}, nil + return &TrustMarkIssuer{cfg: cfg, deps: &deps}, nil } // TrustMarkParams describes one Trust Mark to issue. diff --git a/keys/ephemeral/keymanager.go b/keys/ephemeral/keymanager.go index 11d9df2a..f1dba800 100644 --- a/keys/ephemeral/keymanager.go +++ b/keys/ephemeral/keymanager.go @@ -24,19 +24,30 @@ import ( // since most callers never need it, and decryption is not merely an // addition to keys.KeyManager (the underlying key types and use cases // differ), so plain NewKeyManager leaves the decryption field nil. +// +// A KeyManager prints [REDACTED] for its keys, under every fmt verb and +// in log/slog (see render.go). type KeyManager struct { mu sync.Mutex - keys map[keys.SigningPurpose]crypto.Signer + keys map[keys.SigningPurpose]*signingKey kid map[keys.SigningPurpose]string decryption *decryptionKeys } +// signingKey holds one purpose's signer behind a pointer, so fmt's +// reflection fallback, which calls no Format method (%w outside Errorf, +// say), prints an address where the key is, not the bytes of an +// ed25519.PrivateKey. +type signingKey struct { + signer crypto.Signer +} + // NewKeyManager generates one key per purpose in purposes, sized for // the paired algorithm (ECDSA P-256 for ES256, RSA-2048 for PS256, // Ed25519 for EdDSA — the three algorithms this module supports). func NewKeyManager(purposes map[keys.SigningPurpose]fapi.SignatureAlgorithm) (*KeyManager, error) { m := &KeyManager{ - keys: make(map[keys.SigningPurpose]crypto.Signer, len(purposes)), + keys: make(map[keys.SigningPurpose]*signingKey, len(purposes)), kid: make(map[keys.SigningPurpose]string, len(purposes)), } for purpose, alg := range purposes { @@ -44,7 +55,7 @@ func NewKeyManager(purposes map[keys.SigningPurpose]fapi.SignatureAlgorithm) (*K if err != nil { return nil, fmt.Errorf("generate key for purpose %v: %w", purpose, err) } - m.keys[purpose] = signer + m.keys[purpose] = &signingKey{signer: signer} m.kid[purpose] = fmt.Sprintf("ephemeral-%d-%s", purpose, alg.String()) } return m, nil @@ -73,12 +84,13 @@ func GenerateSigner(alg fapi.SignatureAlgorithm) (crypto.Signer, error) { // Sign implements keys.KeyManager. func (m *KeyManager) Sign(_ context.Context, req keys.SigningRequest) (keys.Signature, error) { m.mu.Lock() - signer, ok := m.keys[req.Purpose] + held, ok := m.keys[req.Purpose] kid := m.kid[req.Purpose] m.mu.Unlock() if !ok { return keys.Signature{}, fmt.Errorf("ephemeral: no key for purpose %v", req.Purpose) } + signer := held.signer switch key := signer.(type) { case *ecdsa.PrivateKey: @@ -109,11 +121,11 @@ func (m *KeyManager) Sign(_ context.Context, req keys.SigningRequest) (keys.Sign // PublicKey implements keys.KeyManager. func (m *KeyManager) PublicKey(_ context.Context, purpose keys.SigningPurpose, _ fapi.SignatureAlgorithm) (keys.PublicKeyInfo, error) { m.mu.Lock() - signer, ok := m.keys[purpose] + held, ok := m.keys[purpose] kid := m.kid[purpose] m.mu.Unlock() if !ok { return keys.PublicKeyInfo{}, fmt.Errorf("ephemeral: no key for purpose %v", purpose) } - return keys.PublicKeyInfo{KeyID: kid, PublicKey: signer.Public()}, nil + return keys.PublicKeyInfo{KeyID: kid, PublicKey: held.signer.Public()}, nil } diff --git a/keys/ephemeral/render.go b/keys/ephemeral/render.go new file mode 100644 index 00000000..6ae269cd --- /dev/null +++ b/keys/ephemeral/render.go @@ -0,0 +1,78 @@ +package ephemeral + +import ( + "fmt" + "log/slog" + + "github.com/idfoundry/fapigo/internal/redact" + "github.com/idfoundry/fapigo/keys" +) + +// A KeyManager holds the private keys it generated, so it prints a +// shadow of itself in which each key is only [REDACTED], under every +// verb and flag and in log/slog (see package redact). Without it fmt +// prints an ed25519.PrivateKey, a byte slice, byte by byte. + +type keyManagerShadow struct { + Keys map[keys.SigningPurpose]keyShadow + Decryption map[keys.DecryptionPurpose]keyShadow +} + +type keyShadow struct { + Key redact.Hidden + KeyID string +} + +func (m *KeyManager) shadow() keyManagerShadow { + m.mu.Lock() + defer m.mu.Unlock() + var sh keyManagerShadow + if m.keys != nil { + sh.Keys = make(map[keys.SigningPurpose]keyShadow, len(m.keys)) + for purpose, held := range m.keys { + sh.Keys[purpose] = keyShadow{Key: keyMask(held != nil && held.signer != nil), KeyID: m.kid[purpose]} + } + } + if m.decryption != nil { + sh.Decryption = make(map[keys.DecryptionPurpose]keyShadow, len(m.decryption.keys)) + for purpose, priv := range m.decryption.keys { + sh.Decryption[purpose] = keyShadow{Key: keyMask(priv != nil), KeyID: m.decryption.kid[purpose]} + } + } + return sh +} + +// keyMask is the placeholder for a held key: [REDACTED], or "" for +// none. +func keyMask(present bool) redact.Hidden { + if !present { + return "" + } + return redact.Redacted +} + +// Format implements fmt.Formatter: m prints each purpose's kid, and +// [REDACTED] for its key, signing and decryption keys alike, under +// every verb and flag. +func (m *KeyManager) Format(f fmt.State, verb rune) { + redact.Format(f, verb, m.shadow(), "ephemeral.keyManagerShadow", "ephemeral.KeyManager") +} + +// LogValue implements slog.LogValuer: each purpose's kid, and +// [REDACTED] for its key, signing and decryption keys alike. +func (m *KeyManager) LogValue() slog.Value { + sh := m.shadow() + signing := make([]any, 0, len(sh.Keys)) + for purpose, k := range sh.Keys { + signing = append(signing, keyAttr(purpose.String(), k)) + } + decryption := make([]any, 0, len(sh.Decryption)) + for purpose, k := range sh.Decryption { + decryption = append(decryption, keyAttr(fmt.Sprint(purpose), k)) + } + return slog.GroupValue(slog.Group("Keys", signing...), slog.Group("Decryption", decryption...)) +} + +func keyAttr(name string, k keyShadow) slog.Attr { + return slog.Group(name, slog.String("Key", string(k.Key)), slog.String("KeyID", k.KeyID)) +} diff --git a/keys/ephemeral/render_internal_test.go b/keys/ephemeral/render_internal_test.go new file mode 100644 index 00000000..64cca8df --- /dev/null +++ b/keys/ephemeral/render_internal_test.go @@ -0,0 +1,65 @@ +package ephemeral + +import ( + "bytes" + "crypto/ecdh" + "crypto/ed25519" + "fmt" + "log/slog" + "strings" + "testing" + + fapi "github.com/idfoundry/fapigo" + "github.com/idfoundry/fapigo/internal/rendertest" + "github.com/idfoundry/fapigo/keys" +) + +// TestKeyManagerPrintsNoKey: a KeyManager prints each purpose's kid, +// and [REDACTED] for its key, under every rendering the matrix makes, +// fmt's reflection fallback included: an ed25519.PrivateKey is a byte +// slice, which fmt would otherwise print byte by byte. +func TestKeyManagerPrintsNoKey(t *testing.T) { + m, err := NewKeyManagerWithDecryption( + map[keys.SigningPurpose]fapi.SignatureAlgorithm{keys.JARMSigning: fapi.EdDSA}, + map[keys.DecryptionPurpose]fapi.KeyManagementAlgorithm{keys.IDTokenDecryption: fapi.ECDHESA256KW}) + if err != nil { + t.Fatal(err) + } + signing, ok := m.keys[keys.JARMSigning].signer.(ed25519.PrivateKey) + if !ok { + t.Fatalf("the EdDSA key is a %T", m.keys[keys.JARMSigning].signer) + } + decryption, ok := m.decryption.keys[keys.IDTokenDecryption].(*ecdh.PrivateKey) + if !ok { + t.Fatalf("the ECDH-ES key is a %T", m.decryption.keys[keys.IDTokenDecryption]) + } + rendertest.Check(t, m, []string{string(signing.Seed()), string(decryption.Bytes())}) + + const want = "{Keys:map[jarm_signing:{Key:[REDACTED] KeyID:ephemeral-1-EdDSA}] Decryption:map[1:{Key:[REDACTED] KeyID:ephemeral-dec-1-ECDH-ES+A256KW}]}" + if got := fmt.Sprintf("%+v", m); got != want { + t.Errorf("%%+v = %q, want %q", got, want) + } + if got := fmt.Sprintf("%#v", m); !strings.HasPrefix(got, "ephemeral.KeyManager{") { + t.Errorf("%%#v = %q, want an ephemeral.KeyManager", got) + } + if got := fmt.Sprintf("%v", &KeyManager{kid: map[keys.SigningPurpose]string{}}); strings.Contains(got, "REDACTED") { + t.Errorf("%%v of a KeyManager without keys = %q, want no placeholder", got) + } +} + +// TestKeyManagerLogsNoKey: log/slog's JSON handler logs each purpose's +// kid, and [REDACTED] for its key. +func TestKeyManagerLogsNoKey(t *testing.T) { + m, err := NewKeyManagerWithDecryption( + map[keys.SigningPurpose]fapi.SignatureAlgorithm{keys.JARMSigning: fapi.EdDSA}, + map[keys.DecryptionPurpose]fapi.KeyManagementAlgorithm{keys.IDTokenDecryption: fapi.RSAOAEP256}) + if err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + slog.New(slog.NewJSONHandler(&buf, nil)).Info("km", "v", m) + const want = `"v":{"Keys":{"jarm_signing":{"Key":"[REDACTED]","KeyID":"ephemeral-1-EdDSA"}},"Decryption":{"1":{"Key":"[REDACTED]","KeyID":"ephemeral-dec-1-RSA-OAEP-256"}}}` + if got := buf.String(); !strings.Contains(got, want) { + t.Errorf("slog JSON logged %s, want it to hold %s", got, want) + } +} diff --git a/keys/key_holder_render.go b/keys/key_holder_render.go new file mode 100644 index 00000000..dfc3d8a8 --- /dev/null +++ b/keys/key_holder_render.go @@ -0,0 +1,129 @@ +package keys + +import ( + "fmt" + "log/slog" + + "github.com/idfoundry/fapigo/internal/redact" +) + +// The KeyManager NewKeyManagerFromSigners builds, and the in-memory +// ECDHAgreer and KeyDecrypter, hold private keys, so each prints a +// shadow of itself in which a key is only [REDACTED], under every verb +// and flag and in log/slog (see package redact). Without it fmt prints +// an ed25519.PrivateKey, a byte slice, byte by byte, and a verb a +// pointer doesn't take, such as %s, makes it print what an +// *ecdh.PrivateKey points to. signerKeyManager also holds each backend +// behind a pointer, so fmt's reflection fallback (%w, say, which calls +// no method) prints only an address where the signer is. + +type signerKeyManagerShadow struct { + Backends map[SigningPurpose]signerBackendShadow +} + +type signerBackendShadow struct { + Signer redact.Hidden + Algorithm string + KeyID string + Previous []PublicKeyInfo +} + +type custodyKeyManagerShadow struct { + Backends map[SigningPurpose]signerBackendShadow + Custody KeyCustody +} + +type inMemoryKeyShadow struct { + Priv redact.Hidden + KeyID string +} + +// keyMask is the placeholder for a held key: [REDACTED], or "" for +// none. +func keyMask(present bool) redact.Hidden { + if !present { + return "" + } + return redact.Redacted +} + +func (m signerKeyManager) shadow() signerKeyManagerShadow { + backends := make(map[SigningPurpose]signerBackendShadow, len(m.backends)) + for purpose, b := range m.backends { + backends[purpose] = signerBackendShadow{Signer: keyMask(b.signer != nil), Algorithm: b.algorithm.String(), KeyID: b.kid, Previous: b.previous} + } + return signerKeyManagerShadow{Backends: backends} +} + +// Format implements fmt.Formatter: m prints each purpose's algorithm, +// kid and previous public keys, and [REDACTED] for its signer, under +// every verb and flag. +func (m signerKeyManager) Format(f fmt.State, verb rune) { + redact.Format(f, verb, m.shadow(), "keys.signerKeyManagerShadow", "keys.signerKeyManager", "keys.signerBackendShadow", "keys.signerBackend") +} + +// LogValue implements slog.LogValuer: each purpose's algorithm, kid +// and previous public keys, and [REDACTED] for its signer. +func (m signerKeyManager) LogValue() slog.Value { + return slog.GroupValue(backendsAttr(m.shadow().Backends)) +} + +// Format implements fmt.Formatter: m prints as its signerKeyManager +// does, with its declared custody. +func (m custodyKeyManager) Format(f fmt.State, verb rune) { + var backends map[SigningPurpose]signerBackendShadow + if m.signerKeyManager != nil { + backends = m.shadow().Backends + } + redact.Format(f, verb, custodyKeyManagerShadow{Backends: backends, Custody: m.custody}, "keys.custodyKeyManagerShadow", "keys.custodyKeyManager", "keys.signerBackendShadow", "keys.signerBackend") +} + +// LogValue implements slog.LogValuer: m logs as its signerKeyManager +// does, with its declared custody. +func (m custodyKeyManager) LogValue() slog.Value { + var backends map[SigningPurpose]signerBackendShadow + if m.signerKeyManager != nil { + backends = m.shadow().Backends + } + return slog.GroupValue(backendsAttr(backends), slog.Any("Custody", m.custody)) +} + +// backendsAttr is a group of backends' shadows, one per purpose. +func backendsAttr(backends map[SigningPurpose]signerBackendShadow) slog.Attr { + attrs := make([]any, 0, len(backends)) + for purpose, b := range backends { + attrs = append(attrs, slog.Group(purpose.String(), + slog.String("Signer", string(b.Signer)), slog.String("Algorithm", b.Algorithm), + slog.String("KeyID", b.KeyID), slog.Any("Previous", b.Previous), + )) + } + return slog.Group("Backends", attrs...) +} + +// Format implements fmt.Formatter: k prints its kid, and [REDACTED] +// for its private key, under every verb and flag. +func (k inMemoryECDH) Format(f fmt.State, verb rune) { + redact.Format(f, verb, inMemoryKeyShadow{Priv: keyMask(k.priv != nil), KeyID: k.kid}, "keys.inMemoryKeyShadow", "keys.inMemoryECDH") +} + +// LogValue implements slog.LogValuer: k's kid, and [REDACTED] for its +// private key. +func (k inMemoryECDH) LogValue() slog.Value { + return inMemoryKeyLogValue(k.priv != nil, k.kid) +} + +// Format implements fmt.Formatter: k prints its kid, and [REDACTED] +// for its private key, under every verb and flag. +func (k inMemoryRSA) Format(f fmt.State, verb rune) { + redact.Format(f, verb, inMemoryKeyShadow{Priv: keyMask(k.priv != nil), KeyID: k.kid}, "keys.inMemoryKeyShadow", "keys.inMemoryRSA") +} + +// LogValue implements slog.LogValuer: k's kid, and [REDACTED] for its +// private key. +func (k inMemoryRSA) LogValue() slog.Value { + return inMemoryKeyLogValue(k.priv != nil, k.kid) +} + +func inMemoryKeyLogValue(present bool, kid string) slog.Value { + return slog.GroupValue(slog.String("Priv", string(keyMask(present))), slog.String("KeyID", kid)) +} diff --git a/keys/key_holder_render_internal_test.go b/keys/key_holder_render_internal_test.go new file mode 100644 index 00000000..3cf1a0b8 --- /dev/null +++ b/keys/key_holder_render_internal_test.go @@ -0,0 +1,148 @@ +package keys + +import ( + "bytes" + "crypto/ecdh" + "crypto/ed25519" + "crypto/rand" + "crypto/rsa" + "fmt" + "log/slog" + "strings" + "testing" + + fapi "github.com/idfoundry/fapigo" + "github.com/idfoundry/fapigo/internal/rendertest" +) + +func ed25519TestKey(t *testing.T) ed25519.PrivateKey { + t.Helper() + _, key, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + return key +} + +// TestSignerKeyManagerPrintsNoKey: the KeyManager +// NewKeyManagerFromSigners builds, custody declared or not, prints +// [REDACTED] for an ed25519.PrivateKey signer, which fmt would +// otherwise print byte by byte, under every rendering the matrix makes, +// its reflection fallback included. +func TestSignerKeyManagerPrintsNoKey(t *testing.T) { + key := ed25519TestKey(t) + specs := []SignerSpec{{Purpose: JARMSigning, Algorithm: fapi.EdDSA, Signer: key, KeyID: "k1"}} + plain, err := NewKeyManagerFromSigners(specs) + if err != nil { + t.Fatal(err) + } + custody, err := NewKeyManagerFromSigners(specs, DeclareCustody(KeyCustody{Durable: true})) + if err != nil { + t.Fatal(err) + } + secrets := []string{string(key.Seed())} + rendertest.Check(t, plain, secrets) + rendertest.Check(t, custody, secrets) + + const backends = "Backends:map[jarm_signing:{Signer:[REDACTED] Algorithm:EdDSA KeyID:k1 Previous:[]}]" + if got, want := fmt.Sprintf("%+v", plain), "{"+backends+"}"; got != want { + t.Errorf("%%+v = %q, want %q", got, want) + } + if got, want := fmt.Sprintf("%+v", custody), "{"+backends+" Custody:{Durable:true CrossInstanceConsistent:false}}"; got != want { + t.Errorf("%%+v with custody = %q, want %q", got, want) + } + if got := fmt.Sprintf("%#v", plain); !strings.HasPrefix(got, "keys.signerKeyManager{") || !strings.Contains(got, "keys.signerBackend{") || strings.Contains(got, "Shadow") { + t.Errorf("%%#v = %q, want the real type names", got) + } + if got := fmt.Sprintf("%#v", custody); !strings.HasPrefix(got, "keys.custodyKeyManager{") { + t.Errorf("%%#v with custody = %q, want keys.custodyKeyManager", got) + } + if got := fmt.Sprintf("%v", custodyKeyManager{}); strings.Contains(got, "REDACTED") { + t.Errorf("%%v of a custodyKeyManager without signers = %q, want no placeholder", got) + } +} + +// TestSignerKeyManagerLogsNoKey: log/slog's handlers log each purpose's +// algorithm and kid, and [REDACTED] for its signer. +func TestSignerKeyManagerLogsNoKey(t *testing.T) { + key := ed25519TestKey(t) + km, err := NewKeyManagerFromSigners([]SignerSpec{{Purpose: JARMSigning, Algorithm: fapi.EdDSA, Signer: key, KeyID: "k1"}}, DeclareCustody(KeyCustody{Durable: true})) + if err != nil { + t.Fatal(err) + } + plain := custodyKeyManagerOf(t, km).signerKeyManager + for v, want := range map[any]string{ + plain: `{"Backends":{"jarm_signing":{"Signer":"[REDACTED]","Algorithm":"EdDSA","KeyID":"k1","Previous":[]}}}`, + km: `{"Backends":{"jarm_signing":{"Signer":"[REDACTED]","Algorithm":"EdDSA","KeyID":"k1","Previous":[]}},"Custody":{"Durable":true,"CrossInstanceConsistent":false}}`, + } { + if got := jsonLogged(v); got != want { + t.Errorf("slog JSON logged %s, want %s", got, want) + } + } +} + +func custodyKeyManagerOf(t *testing.T, km KeyManager) custodyKeyManager { + t.Helper() + c, ok := km.(custodyKeyManager) + if !ok { + t.Fatalf("NewKeyManagerFromSigners with custody returned %T", km) + } + return c +} + +// jsonLogged is what log/slog's JSON handler logs of v, as the value of +// an attribute. +func jsonLogged(v any) string { + var buf bytes.Buffer + slog.New(slog.NewJSONHandler(&buf, &slog.HandlerOptions{ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { + if len(groups) == 0 && a.Key != "v" { + return slog.Attr{} + } + return a + }})).Info("", "v", v) + out := strings.TrimSpace(buf.String()) + return strings.TrimSuffix(strings.TrimPrefix(out, `{"v":`), "}") +} + +// TestInMemoryKeysPrintNoKey: NewInMemoryECDH's and NewInMemoryRSA's +// backends print their kid, and [REDACTED] for the private key, under +// every rendering, %s and %q among them, which would otherwise make +// fmt print what an *ecdh.PrivateKey points to. +func TestInMemoryKeysPrintNoKey(t *testing.T) { + ec, err := ecdh.P256().GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + agreer, err := NewInMemoryECDH(ec, "e1") + if err != nil { + t.Fatal(err) + } + rk, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + decrypter, err := NewInMemoryRSA(rk, "r1") + if err != nil { + t.Fatal(err) + } + rendertest.Check(t, agreer, []string{string(ec.Bytes())}) + rendertest.Check(t, decrypter, []string{string(rk.D.Bytes()), rk.D.String(), rk.Primes[0].String()}) + + for v, want := range map[any]string{agreer: "{Priv:[REDACTED] KeyID:e1}", decrypter: "{Priv:[REDACTED] KeyID:r1}"} { + if got := fmt.Sprintf("%+v", v); got != want { + t.Errorf("%%+v = %q, want %q", got, want) + } + if got, want := jsonLogged(v), `{"Priv":"[REDACTED]","KeyID":"`+want[len(want)-3:len(want)-1]+`"}`; got != want { + t.Errorf("slog JSON logged %s, want %s", got, want) + } + } + if got := fmt.Sprintf("%#v", agreer); got != `keys.inMemoryECDH{Priv:"[REDACTED]", KeyID:"e1"}` { + t.Errorf("%%#v = %q", got) + } + if got := fmt.Sprintf("%#v", decrypter); got != `keys.inMemoryRSA{Priv:"[REDACTED]", KeyID:"r1"}` { + t.Errorf("%%#v = %q", got) + } + if got := fmt.Sprintf("%v", inMemoryECDH{kid: "e1"}); got != "{ e1}" { + t.Errorf("%%v of a backend without a key = %q, want no placeholder", got) + } +} diff --git a/keys/signer_keymanager.go b/keys/signer_keymanager.go index 18deee10..8c9dd732 100644 --- a/keys/signer_keymanager.go +++ b/keys/signer_keymanager.go @@ -62,9 +62,13 @@ type signerBackend struct { } // signerKeyManager implements RotatingKeyManager over a caller-supplied -// crypto.Signer per SigningPurpose. See NewKeyManagerFromSigners. +// crypto.Signer per SigningPurpose. See NewKeyManagerFromSigners. Each +// backend is held behind a pointer, so fmt's reflection fallback, which +// calls no Format method, prints an address where the signer is, not +// the key an ed25519.PrivateKey carries in its bytes (see +// key_holder_render.go). type signerKeyManager struct { - backends map[SigningPurpose]signerBackend + backends map[SigningPurpose]*signerBackend } // NewKeyManagerFromSigners builds a KeyManager over specs, one per @@ -109,7 +113,7 @@ func NewKeyManagerFromSigners(specs []SignerSpec, opts ...CustodyOption) (KeyMan if len(specs) == 0 { return nil, fmt.Errorf("keys: NewKeyManagerFromSigners requires at least one SignerSpec") } - backends := make(map[SigningPurpose]signerBackend, len(specs)) + backends := make(map[SigningPurpose]*signerBackend, len(specs)) kids := make(map[string]crypto.PublicKey) for _, spec := range specs { backend, err := newSignerBackend(spec) @@ -127,7 +131,7 @@ func NewKeyManagerFromSigners(specs []SignerSpec, opts ...CustodyOption) (KeyMan return nil, err } } - backends[spec.Purpose] = backend + backends[spec.Purpose] = &backend } km := &signerKeyManager{backends: backends} if d := applyCustodyOptions(opts); d.declared {