diff --git a/.env.example b/.env.example index 11543628d2..d42e61fa8b 100644 --- a/.env.example +++ b/.env.example @@ -73,18 +73,18 @@ RELAY_URL=ws://localhost:3000 # requires authenticated requests to present a valid corporate JWT, then binds # the configured uid claim to the Nostr pubkey proven by NIP-42/NIP-98. The JWT # may be injected by a trusted proxy or attached by a first-party client; the -# relay treats both as the same header. Client token forwarding and admin -# revocation/rotation workflows are separate follow-up features. +# relay treats both as the same header. Clients must forward the configured +# token header on every authenticated HTTP request and session handshake. # # Operational notes for the initial implementation: # - When a trusted proxy injects this header, it MUST overwrite any inbound # client-supplied value before forwarding to the relay. -# - A uid/pubkey conflict is a hard lockout until an operator resolves the -# binding out of band; admin revocation/rotation endpoints are not in this PR. +# - Revocation and rotation are explicit database lifecycle operations; +# ordinary authentication never silently replaces a key. # - JWKS outages fail closed for human JWT authentication. Delegated agent # admission can still work when the owner binding is already present. -# - DISPLAY_CLAIM is stored in identity_bindings.display_name. Using email here -# stores corporate PII and PR2 may surface it in clients. +# - DISPLAY_CLAIM is private binding metadata. It is never projected publicly +# unless PUBLIC_DISPLAY_CLAIM is separately configured. # BUZZ_REQUIRE_CORPORATE_IDENTITY=false # BUZZ_CORPORATE_IDENTITY_JWT_HEADER=x-forwarded-identity-token # BUZZ_ALLOW_CORPORATE_IDENTITY_DELEGATION=true @@ -98,6 +98,8 @@ RELAY_URL=ws://localhost:3000 # BUZZ_CORPORATE_IDENTITY_AUDIENCE=buzz-relay # BUZZ_CORPORATE_IDENTITY_UID_CLAIM=sub # BUZZ_CORPORATE_IDENTITY_DISPLAY_CLAIM=email +# Optional, public NIP-85 label. Unset by default to keep identity claims private. +# BUZZ_CORPORATE_IDENTITY_PUBLIC_DISPLAY_CLAIM=display_name # BUZZ_CORPORATE_IDENTITY_NPUB_CLAIM=buzz_npub # ----------------------------------------------------------------------------- diff --git a/Cargo.lock b/Cargo.lock index 4e4fea2ad9..2eb2c0a206 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -567,6 +567,12 @@ dependencies = [ "tokio", ] +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + [[package]] name = "base16ct" version = "1.0.0" @@ -1159,7 +1165,7 @@ dependencies = [ "metrics-exporter-prometheus", "minicbor", "nostr", - "p256", + "p256 0.14.0", "proptest", "rand 0.10.1", "reqwest 0.13.4", @@ -1718,6 +1724,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "const-oid" version = "0.10.2" @@ -1991,6 +2003,18 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + [[package]] name = "crypto-bigint" version = "0.7.5" @@ -2133,6 +2157,7 @@ dependencies = [ "cfg-if 1.0.4", "cpufeatures 0.2.17", "curve25519-dalek-derive", + "digest 0.10.7", "fiat-crypto 0.2.9", "rustc_version", "subtle", @@ -2352,14 +2377,25 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5729f5117e208430e437df2f4843f5e5952997175992d1414f94c57d61e270b4" +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468 0.7.0", + "zeroize", +] + [[package]] name = "der" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "71fd89660b2dc699704064e59e9dba0147b903e85319429e131620d022be411b" dependencies = [ - "const-oid", - "pem-rfc7468", + "const-oid 0.10.2", + "pem-rfc7468 1.0.0", "zeroize", ] @@ -2460,6 +2496,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", + "const-oid 0.9.6", "crypto-common 0.1.7", "subtle", ] @@ -2471,7 +2508,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.0", - "const-oid", + "const-oid 0.10.2", "crypto-common 0.2.2", "ctutils", ] @@ -2582,30 +2619,68 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der 0.7.10", + "digest 0.10.7", + "elliptic-curve 0.13.8", + "rfc6979 0.4.0", + "signature 2.2.0", + "spki 0.7.3", +] + [[package]] name = "ecdsa" version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" dependencies = [ - "der", + "der 0.8.0", "digest 0.11.3", - "elliptic-curve", - "rfc6979", - "signature", - "spki", + "elliptic-curve 0.14.1", + "rfc6979 0.6.0", + "signature 3.0.0", + "spki 0.8.0", "zeroize", ] +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8 0.10.2", + "signature 2.2.0", +] + [[package]] name = "ed25519" version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a" dependencies = [ - "pkcs8", + "pkcs8 0.11.0", "serdect", - "signature", + "signature 3.0.0", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek 4.1.3", + "ed25519 2.2.3", + "serde", + "sha2 0.10.9", + "subtle", + "zeroize", ] [[package]] @@ -2615,11 +2690,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b011170fe4f04665565b4110afef66774fe9ffff278f3eb5b81cc73d26e27d60" dependencies = [ "curve25519-dalek 5.0.0-rc.0", - "ed25519", + "ed25519 3.0.0", "rand_core 0.10.1", "serde", "sha2 0.11.0", - "signature", + "signature 3.0.0", "subtle", "zeroize", ] @@ -2633,23 +2708,44 @@ dependencies = [ "serde", ] +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct 0.2.0", + "crypto-bigint 0.5.5", + "digest 0.10.7", + "ff 0.13.1", + "generic-array", + "group 0.13.0", + "hkdf 0.12.4", + "pem-rfc7468 0.7.0", + "pkcs8 0.10.2", + "rand_core 0.6.4", + "sec1 0.7.3", + "subtle", + "zeroize", +] + [[package]] name = "elliptic-curve" version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d65aa39b3a5c1c9c1b745c9a019234bb7a21b77abcb4f4d266d706e2d577d65" dependencies = [ - "base16ct", - "crypto-bigint", + "base16ct 1.0.0", + "crypto-bigint 0.7.5", "crypto-common 0.2.2", "digest 0.11.3", - "ff", - "group", + "ff 0.14.0", + "group 0.14.0", "hybrid-array", - "pem-rfc7468", - "pkcs8", + "pem-rfc7468 1.0.0", + "pkcs8 0.11.0", "rand_core 0.10.1", - "sec1", + "sec1 0.8.1", "subtle", "zeroize", ] @@ -2846,6 +2942,16 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "ff" version = "0.14.0" @@ -3280,13 +3386,24 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff 0.13.1", + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "group" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" dependencies = [ - "ff", + "ff 0.14.0", "rand_core 0.10.1", "subtle", ] @@ -4044,7 +4161,7 @@ dependencies = [ "ctutils", "data-encoding", "derive_more", - "ed25519-dalek", + "ed25519-dalek 3.0.0-rc.0", "futures-util", "getrandom 0.4.3", "hickory-resolver", @@ -4092,7 +4209,7 @@ dependencies = [ "data-encoding", "data-encoding-macro", "derive_more", - "ed25519-dalek", + "ed25519-dalek 3.0.0-rc.0", "getrandom 0.4.3", "n0-error", "rand 0.10.1", @@ -4352,17 +4469,24 @@ dependencies = [ [[package]] name = "jsonwebtoken" -version = "9.3.1" +version = "10.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" +checksum = "eba32bfb4ffdeaca3e34431072faf01745c9b26d25504aa7a6cf5684334fc4fc" dependencies = [ "base64 0.22.1", + "ed25519-dalek 2.2.0", + "getrandom 0.2.17", + "hmac 0.12.1", "js-sys", - "pem", - "ring", + "p256 0.13.2", + "p384", + "rand 0.8.6", + "rsa", "serde", "serde_json", - "simple_asn1", + "sha2 0.10.9", + "signature 2.2.0", + "zeroize", ] [[package]] @@ -4485,6 +4609,9 @@ name = "lazy_static" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +dependencies = [ + "spin 0.9.8", +] [[package]] name = "left-right" @@ -4828,7 +4955,7 @@ dependencies = [ "base64 0.22.1", "bytes", "crypto_box", - "ed25519-dalek", + "ed25519-dalek 3.0.0-rc.0", "hex", "httparse", "iroh", @@ -4935,7 +5062,7 @@ dependencies = [ "crossterm 0.28.1", "crypto_box", "dirs", - "ed25519-dalek", + "ed25519-dalek 3.0.0-rc.0", "flate2", "futures-util", "hex", @@ -5022,7 +5149,7 @@ dependencies = [ "chrono", "crypto_box", "dirs", - "ed25519-dalek", + "ed25519-dalek 3.0.0-rc.0", "hex", "keyring", "rand 0.10.1", @@ -5942,6 +6069,22 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.6", + "smallvec", + "zeroize", +] + [[package]] name = "num-complex" version = "0.4.6" @@ -6007,6 +6150,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -6465,19 +6609,43 @@ dependencies = [ "memchr", ] +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa 0.16.9", + "elliptic-curve 0.13.8", + "primeorder 0.13.6", + "sha2 0.10.9", +] + [[package]] name = "p256" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" dependencies = [ - "ecdsa", - "elliptic-curve", + "ecdsa 0.17.0", + "elliptic-curve 0.14.1", "primefield", - "primeorder", + "primeorder 0.14.0", "sha2 0.11.0", ] +[[package]] +name = "p384" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +dependencies = [ + "ecdsa 0.16.9", + "elliptic-curve 0.13.8", + "primeorder 0.13.6", + "sha2 0.10.9", +] + [[package]] name = "palette" version = "0.7.6" @@ -6590,6 +6758,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "pem-rfc7468" version = "1.0.0" @@ -6767,14 +6944,35 @@ dependencies = [ "futures-io", ] +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der 0.7.10", + "pkcs8 0.10.2", + "spki 0.7.3", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der 0.7.10", + "spki 0.7.3", +] + [[package]] name = "pkcs8" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" dependencies = [ - "der", - "spki", + "der 0.8.0", + "spki 0.8.0", ] [[package]] @@ -6968,21 +7166,30 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" dependencies = [ - "crypto-bigint", + "crypto-bigint 0.7.5", "crypto-common 0.2.2", - "ff", + "ff 0.14.0", "rand_core 0.10.1", "subtle", "zeroize", ] +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve 0.13.8", +] + [[package]] name = "primeorder" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" dependencies = [ - "elliptic-curve", + "elliptic-curve 0.14.1", "once_cell", "primefield", "serdect", @@ -7892,13 +8099,23 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7" +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac 0.12.1", + "subtle", +] + [[package]] name = "rfc6979" version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" dependencies = [ - "crypto-bigint", + "crypto-bigint 0.7.5", "hmac 0.13.0", ] @@ -7972,6 +8189,26 @@ dependencies = [ "winapi", ] +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid 0.9.6", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8 0.10.2", + "rand_core 0.6.4", + "signature 2.2.0", + "spki 0.7.3", + "subtle", + "zeroize", +] + [[package]] name = "rust-ini" version = "0.21.3" @@ -8261,15 +8498,29 @@ dependencies = [ "sha2 0.10.9", ] +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct 0.2.0", + "der 0.7.10", + "generic-array", + "pkcs8 0.10.2", + "subtle", + "zeroize", +] + [[package]] name = "sec1" version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" dependencies = [ - "base16ct", + "base16ct 1.0.0", "ctutils", - "der", + "der 0.8.0", "hybrid-array", "subtle", "zeroize", @@ -8549,7 +8800,7 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" dependencies = [ - "base16ct", + "base16ct 1.0.0", "serde", ] @@ -8692,6 +8943,16 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + [[package]] name = "signature" version = "3.0.0" @@ -8742,18 +9003,6 @@ dependencies = [ "bitflags 2.13.0", ] -[[package]] -name = "simple_asn1" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" -dependencies = [ - "num-bigint", - "num-traits", - "thiserror 2.0.18", - "time", -] - [[package]] name = "siphasher" version = "1.0.3" @@ -8928,6 +9177,16 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d5fe4ccb98d9c292d56fec89a5e07da7fc4cf0dc11e156b41793132775d3e591" +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der 0.7.10", +] + [[package]] name = "spki" version = "0.8.0" @@ -8935,7 +9194,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d9efca8738c78ee9484207732f728b1ef517bbb1833d6fc0879ca898a522f6f" dependencies = [ "base64ct", - "der", + "der 0.8.0", ] [[package]] @@ -11332,8 +11591,8 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab12e7090f27e2ffd9322651492942d50c2926094af30601e1964337db39daf1" dependencies = [ - "ff", - "group", + "ff 0.14.0", + "group 0.14.0", "hybrid-array", ] diff --git a/Cargo.toml b/Cargo.toml index 5afaa847f3..f1500b5e50 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -77,7 +77,7 @@ postcard = { version = "1", default-features = false, features = ["use-std"] iroh = { version = "1.0.0-rc.0", default-features = false, features = ["tls-ring"] } serde_json = "1" serde_yaml = "0.9" -jsonwebtoken = "9" +jsonwebtoken = { version = "10.3", default-features = false, features = ["rust_crypto"] } evalexpr = "11" cron = "0.16" # Observability diff --git a/crates/buzz-db/src/identity_binding.rs b/crates/buzz-db/src/identity_binding.rs index 25cb9b72ff..743e81dcea 100644 --- a/crates/buzz-db/src/identity_binding.rs +++ b/crates/buzz-db/src/identity_binding.rs @@ -3,8 +3,9 @@ //! Bindings map an issuer-qualified IdP uid to the currently authorized Nostr //! pubkey inside one Buzz community. The active uniqueness indexes deliberately //! model one active pubkey per `(issuer, uid)` principal and one active principal -//! per pubkey. Rotation/revocation flows clear that active state in a follow-up -//! lifecycle layer rather than silently rewriting it during authentication. +//! per pubkey. Explicit lifecycle operations distinguish principal disablement, +//! single-key revocation, and authorized rotation; authentication never +//! silently rewrites those states. use chrono::{DateTime, Utc}; use sqlx::{PgPool, Postgres, Row, Transaction}; @@ -64,6 +65,21 @@ pub enum BindIdentityResult { Revoked, } +/// Corporate identity data staged for an atomic admission transaction. +#[derive(Debug, Clone, Copy)] +pub struct IdentityBindingInput<'a> { + /// Validated identity-provider issuer. + pub issuer: &'a str, + /// Stable issuer-qualified principal identifier. + pub uid: &'a str, + /// Authenticated Nostr pubkey bytes. + pub pubkey: &'a [u8], + /// Private display attribute retained in the binding table. + pub display_name: Option<&'a str>, + /// Binding source (`jwt_npub` or `db_binding`). + pub source: &'a str, +} + fn validate_inputs(issuer: &str, uid: &str, pubkey: &[u8], source: &str) -> Result<()> { if issuer.trim().is_empty() { return Err(DbError::InvalidData( @@ -93,6 +109,23 @@ fn validate_pubkey(pubkey: &[u8]) -> Result<()> { Ok(()) } +pub(crate) fn validate_membership_identity_key( + member_pubkey_hex: &str, + identity: Option<&IdentityBindingInput<'_>>, +) -> Result<()> { + let Some(identity) = identity else { + return Ok(()); + }; + let member_pubkey = hex::decode(member_pubkey_hex) + .map_err(|_| DbError::InvalidData("membership pubkey must be 32-byte hex".to_string()))?; + if member_pubkey.len() != 32 || member_pubkey.as_slice() != identity.pubkey { + return Err(DbError::InvalidData( + "membership pubkey does not match staged identity key".to_string(), + )); + } + Ok(()) +} + fn row_to_binding(row: sqlx::postgres::PgRow) -> Result { Ok(IdentityBinding { issuer: row.try_get("issuer")?, @@ -176,6 +209,81 @@ async fn revoked_pair_exists_tx( Ok(row.is_some()) } +async fn principal_disabled_tx( + tx: &mut Transaction<'_, Postgres>, + community_id: CommunityId, + issuer: &str, + uid: &str, +) -> Result { + let row = sqlx::query( + r#" + SELECT 1 FROM identity_principals + WHERE community_id = $1 AND issuer = $2 AND uid = $3 + AND disabled_at IS NOT NULL + UNION ALL + SELECT 1 FROM identity_bindings + WHERE community_id = $1 AND issuer = $2 AND uid = $3 + AND revoked_at IS NOT NULL AND revocation_scope = 'principal' + LIMIT 1 + "#, + ) + .bind(community_id.as_uuid()) + .bind(issuer) + .bind(uid) + .fetch_optional(&mut **tx) + .await?; + Ok(row.is_some()) +} + +async fn key_revoked_tx( + tx: &mut Transaction<'_, Postgres>, + community_id: CommunityId, + pubkey: &[u8], +) -> Result { + let row = sqlx::query( + r#" + SELECT 1 FROM identity_revoked_keys + WHERE community_id = $1 AND pubkey = $2 + UNION ALL + SELECT 1 FROM identity_bindings + WHERE community_id = $1 AND pubkey = $2 AND revoked_at IS NOT NULL + LIMIT 1 + "#, + ) + .bind(community_id.as_uuid()) + .bind(pubkey) + .fetch_optional(&mut **tx) + .await?; + Ok(row.is_some()) +} + +async fn principal_requires_rotation_tx( + tx: &mut Transaction<'_, Postgres>, + community_id: CommunityId, + issuer: &str, + uid: &str, +) -> Result { + let row = sqlx::query( + r#" + SELECT 1 + FROM identity_bindings + WHERE community_id = $1 + AND issuer = $2 + AND uid = $3 + AND revoked_at IS NOT NULL + AND revocation_scope = 'key' + AND rotation_completed_at IS NULL + LIMIT 1 + "#, + ) + .bind(community_id.as_uuid()) + .bind(issuer) + .bind(uid) + .fetch_optional(&mut **tx) + .await?; + Ok(row.is_some()) +} + fn conflict_from(binding: IdentityBinding) -> IdentityBindingConflict { IdentityBindingConflict { issuer: binding.issuer, @@ -185,18 +293,12 @@ fn conflict_from(binding: IdentityBinding) -> IdentityBindingConflict { } } -async fn lock_identity_keys_tx( +async fn lock_identity_key_strings_tx( tx: &mut Transaction<'_, Postgres>, - community_id: CommunityId, - issuer: &str, - uid: &str, - pubkey: &[u8], + mut keys: Vec, ) -> Result<()> { - let mut keys = [ - format!("{}:principal:{issuer}:{uid}", community_id.as_uuid()), - format!("{}:pubkey:{}", community_id.as_uuid(), hex::encode(pubkey)), - ]; keys.sort(); + keys.dedup(); for key in keys { sqlx::query("SELECT pg_advisory_xact_lock(hashtext('identity_bindings'), hashtext($1))") .bind(key) @@ -206,12 +308,30 @@ async fn lock_identity_keys_tx( Ok(()) } +async fn lock_identity_keys_tx( + tx: &mut Transaction<'_, Postgres>, + community_id: CommunityId, + issuer: &str, + uid: &str, + pubkey: &[u8], +) -> Result<()> { + lock_identity_key_strings_tx( + tx, + vec![ + format!("{}:principal:{issuer}:{uid}", community_id.as_uuid()), + format!("{}:pubkey:{}", community_id.as_uuid(), hex::encode(pubkey)), + ], + ) + .await +} + /// Create or validate an active corporate identity binding. /// /// This is a fail-closed auth-time operation: /// - same issuer + uid + pubkey updates display/last_seen and succeeds; /// - same issuer + uid with a different pubkey conflicts; /// - same pubkey with a different issuer-qualified principal conflicts; +/// - principal disablement and unresolved key revocation reject every key; /// - a previously revoked issuer/uid/pubkey tuple remains revoked; /// - no active row creates a new binding. pub async fn bind_or_validate_identity( @@ -223,18 +343,56 @@ pub async fn bind_or_validate_identity( display_name: Option<&str>, source: &str, ) -> Result { + let mut tx = pool.begin().await?; + let result = bind_or_validate_identity_tx( + &mut tx, + community_id, + &IdentityBindingInput { + issuer, + uid, + pubkey, + display_name, + source, + }, + ) + .await?; + tx.commit().await?; + Ok(result) +} + +/// Create or validate a binding inside a caller-owned admission transaction. +pub(crate) async fn bind_or_validate_identity_tx( + tx: &mut Transaction<'_, Postgres>, + community_id: CommunityId, + identity: &IdentityBindingInput<'_>, +) -> Result { + let IdentityBindingInput { + issuer, + uid, + pubkey, + display_name, + source, + } = *identity; validate_inputs(issuer, uid, pubkey, source)?; - let mut tx = pool.begin().await?; sqlx::query("SET LOCAL lock_timeout = '3s'") - .execute(&mut *tx) + .execute(&mut **tx) .await?; - lock_identity_keys_tx(&mut tx, community_id, issuer, uid, pubkey).await?; + lock_identity_keys_tx(tx, community_id, issuer, uid, pubkey).await?; - let active_principal = active_by_principal_tx(&mut tx, community_id, issuer, uid).await?; + if principal_disabled_tx(tx, community_id, issuer, uid).await? { + return Ok(BindIdentityResult::Revoked); + } + if key_revoked_tx(tx, community_id, pubkey).await? { + return Ok(BindIdentityResult::Revoked); + } + if principal_requires_rotation_tx(tx, community_id, issuer, uid).await? { + return Ok(BindIdentityResult::Revoked); + } + + let active_principal = active_by_principal_tx(tx, community_id, issuer, uid).await?; if let Some(binding) = active_principal { if binding.pubkey != pubkey { - tx.rollback().await?; return Ok(BindIdentityResult::Conflict(conflict_from(binding))); } @@ -261,22 +419,19 @@ pub async fn bind_or_validate_identity( .bind(pubkey) .bind(display_name) .bind(source) - .execute(&mut *tx) + .execute(&mut **tx) .await?; - tx.commit().await?; return Ok(BindIdentityResult::Matched); } - let active_pubkey = active_by_pubkey_tx(&mut tx, community_id, pubkey).await?; + let active_pubkey = active_by_pubkey_tx(tx, community_id, pubkey).await?; if let Some(binding) = active_pubkey { if binding.issuer != issuer || binding.uid != uid { - tx.rollback().await?; return Ok(BindIdentityResult::Conflict(conflict_from(binding))); } } - if revoked_pair_exists_tx(&mut tx, community_id, issuer, uid, pubkey).await? { - tx.rollback().await?; + if revoked_pair_exists_tx(tx, community_id, issuer, uid, pubkey).await? { return Ok(BindIdentityResult::Revoked); } @@ -292,9 +447,8 @@ pub async fn bind_or_validate_identity( .bind(pubkey) .bind(display_name) .bind(source) - .execute(&mut *tx) + .execute(&mut **tx) .await?; - tx.commit().await?; Ok(BindIdentityResult::Created) } @@ -319,6 +473,319 @@ pub async fn get_active_identity_binding_by_pubkey( row.map(row_to_binding).transpose() } +/// Disable an issuer-qualified principal and revoke its active key. +/// +/// A principal disablement is durable: normal authentication with any new key +/// returns [`BindIdentityResult::Revoked`]. Re-enablement requires a separate, +/// explicit operator lifecycle operation rather than first-use enrollment. +pub async fn revoke_identity_principal( + pool: &PgPool, + community_id: CommunityId, + issuer: &str, + uid: &str, + revoked_by: Option<&[u8]>, + reason: &str, +) -> Result { + if issuer.trim().is_empty() || uid.trim().is_empty() || reason.trim().is_empty() { + return Err(DbError::InvalidData( + "identity principal revocation requires issuer, uid, and reason".to_string(), + )); + } + if let Some(pubkey) = revoked_by { + validate_pubkey(pubkey)?; + } + let mut tx = pool.begin().await?; + sqlx::query("SET LOCAL lock_timeout = '3s'") + .execute(&mut *tx) + .await?; + // Enrollment and rotation take the principal lock first. Take it before + // discovering the current key so a concurrent first enrollment cannot + // slip between the lookup and the durable principal tombstone. + lock_identity_key_strings_tx( + &mut tx, + vec![format!( + "{}:principal:{issuer}:{uid}", + community_id.as_uuid() + )], + ) + .await?; + let active_pubkey: Option> = sqlx::query_scalar( + "SELECT pubkey FROM identity_bindings WHERE community_id = $1 AND issuer = $2 AND uid = $3 AND revoked_at IS NULL", + ) + .bind(community_id.as_uuid()) + .bind(issuer) + .bind(uid) + .fetch_optional(&mut *tx) + .await?; + if let Some(pubkey) = active_pubkey.as_ref() { + lock_identity_key_strings_tx( + &mut tx, + vec![format!( + "{}:pubkey:{}", + community_id.as_uuid(), + hex::encode(pubkey) + )], + ) + .await?; + } + + sqlx::query( + r#" + INSERT INTO identity_principals + (community_id, issuer, uid, disabled_at, disabled_by, disabled_reason) + VALUES ($1, $2, $3, NOW(), $4, $5) + ON CONFLICT (community_id, issuer, uid) DO NOTHING + "#, + ) + .bind(community_id.as_uuid()) + .bind(issuer) + .bind(uid) + .bind(revoked_by) + .bind(reason) + .execute(&mut *tx) + .await?; + sqlx::query( + r#" + UPDATE identity_bindings + SET revoked_at = NOW(), revoked_by = $4, revoked_reason = $5, + revocation_scope = 'principal', updated_at = NOW() + WHERE community_id = $1 AND issuer = $2 AND uid = $3 AND revoked_at IS NULL + "#, + ) + .bind(community_id.as_uuid()) + .bind(issuer) + .bind(uid) + .bind(revoked_by) + .bind(reason) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok(true) +} + +/// Revoke one active key without disabling the issuer-qualified principal. +/// A replacement key must still be installed through [`rotate_identity_binding`]. +pub async fn revoke_identity_key( + pool: &PgPool, + community_id: CommunityId, + pubkey: &[u8], + revoked_by: Option<&[u8]>, + reason: &str, +) -> Result { + validate_pubkey(pubkey)?; + if let Some(operator) = revoked_by { + validate_pubkey(operator)?; + } + if reason.trim().is_empty() { + return Err(DbError::InvalidData( + "identity key revocation reason must not be empty".to_string(), + )); + } + let mut tx = pool.begin().await?; + sqlx::query("SET LOCAL lock_timeout = '3s'") + .execute(&mut *tx) + .await?; + // A community-scoped key tombstone is the entire correctness boundary. + // Do not acquire a principal lock after it: enrollment and rotation use + // principal→key ordering, and reversing that order can deadlock. + lock_identity_key_strings_tx( + &mut tx, + vec![format!( + "{}:pubkey:{}", + community_id.as_uuid(), + hex::encode(pubkey) + )], + ) + .await?; + sqlx::query( + r#" + INSERT INTO identity_revoked_keys + (community_id, pubkey, revoked_at, revoked_by, reason) + VALUES ($1, $2, NOW(), $3, $4) + ON CONFLICT (community_id, pubkey) DO NOTHING + "#, + ) + .bind(community_id.as_uuid()) + .bind(pubkey) + .bind(revoked_by) + .bind(reason) + .execute(&mut *tx) + .await?; + sqlx::query( + r#" + UPDATE identity_bindings + SET revoked_at = NOW(), revoked_by = $3, revoked_reason = $4, + revocation_scope = 'key', updated_at = NOW() + WHERE community_id = $1 AND pubkey = $2 AND revoked_at IS NULL + "#, + ) + .bind(community_id.as_uuid()) + .bind(pubkey) + .bind(revoked_by) + .bind(reason) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok(true) +} + +/// Atomically retire an active key and install an operator-authorized replacement. +#[allow(clippy::too_many_arguments)] +pub async fn rotate_identity_binding( + pool: &PgPool, + community_id: CommunityId, + issuer: &str, + uid: &str, + old_pubkey: &[u8], + new_pubkey: &[u8], + display_name: Option<&str>, + source: &str, + rotated_by: Option<&[u8]>, + reason: &str, +) -> Result<()> { + validate_inputs(issuer, uid, old_pubkey, source)?; + validate_pubkey(new_pubkey)?; + if old_pubkey == new_pubkey { + return Err(DbError::InvalidData( + "identity rotation requires a different replacement key".to_string(), + )); + } + if let Some(operator) = rotated_by { + validate_pubkey(operator)?; + } + if reason.trim().is_empty() { + return Err(DbError::InvalidData( + "identity rotation reason must not be empty".to_string(), + )); + } + + let mut tx = pool.begin().await?; + sqlx::query("SET LOCAL lock_timeout = '3s'") + .execute(&mut *tx) + .await?; + lock_identity_key_strings_tx( + &mut tx, + vec![ + format!("{}:principal:{issuer}:{uid}", community_id.as_uuid()), + format!( + "{}:pubkey:{}", + community_id.as_uuid(), + hex::encode(old_pubkey) + ), + format!( + "{}:pubkey:{}", + community_id.as_uuid(), + hex::encode(new_pubkey) + ), + ], + ) + .await?; + if principal_disabled_tx(&mut tx, community_id, issuer, uid).await? { + return Err(DbError::InvalidData( + "disabled identity principal cannot be rotated".to_string(), + )); + } + if key_revoked_tx(&mut tx, community_id, new_pubkey).await? { + return Err(DbError::InvalidData( + "identity rotation replacement key is revoked".to_string(), + )); + } + let active = active_by_principal_tx(&mut tx, community_id, issuer, uid).await?; + if active + .as_ref() + .is_some_and(|binding| binding.pubkey != old_pubkey) + { + return Err(DbError::InvalidData( + "identity rotation source key does not match active binding".to_string(), + )); + } + if active.is_none() { + let revoked_key = sqlx::query( + r#" + SELECT 1 FROM identity_bindings + WHERE community_id = $1 AND issuer = $2 AND uid = $3 + AND pubkey = $4 AND revoked_at IS NOT NULL + AND revocation_scope = 'key' + FOR UPDATE + "#, + ) + .bind(community_id.as_uuid()) + .bind(issuer) + .bind(uid) + .bind(old_pubkey) + .fetch_optional(&mut *tx) + .await?; + if revoked_key.is_none() { + return Err(DbError::InvalidData( + "identity rotation source is neither active nor key-revoked".to_string(), + )); + } + } + if active_by_pubkey_tx(&mut tx, community_id, new_pubkey) + .await? + .is_some() + { + return Err(DbError::InvalidData( + "identity rotation replacement key is already bound".to_string(), + )); + } + + sqlx::query( + r#" + UPDATE identity_bindings + SET revoked_at = COALESCE(revoked_at, NOW()), + revoked_by = CASE WHEN revoked_at IS NULL THEN $5 ELSE revoked_by END, + revoked_reason = CASE WHEN revoked_at IS NULL THEN $6 ELSE revoked_reason END, + revocation_scope = CASE WHEN revoked_at IS NULL THEN 'rotation' ELSE revocation_scope END, + rotation_completed_at = NOW(), rotated_to_pubkey = $7, + rotation_by = $5, rotation_reason = $6, updated_at = NOW() + WHERE community_id = $1 AND issuer = $2 AND uid = $3 + AND pubkey = $4 + AND (revoked_at IS NULL OR revocation_scope = 'key') + "#, + ) + .bind(community_id.as_uuid()) + .bind(issuer) + .bind(uid) + .bind(old_pubkey) + .bind(rotated_by) + .bind(reason) + .bind(new_pubkey) + .execute(&mut *tx) + .await?; + sqlx::query( + r#" + INSERT INTO identity_revoked_keys + (community_id, pubkey, revoked_at, revoked_by, reason) + VALUES ($1, $2, NOW(), $3, $4) + ON CONFLICT (community_id, pubkey) DO NOTHING + "#, + ) + .bind(community_id.as_uuid()) + .bind(old_pubkey) + .bind(rotated_by) + .bind(reason) + .execute(&mut *tx) + .await?; + sqlx::query( + r#" + INSERT INTO identity_bindings + (community_id, issuer, uid, pubkey, display_name, source) + VALUES ($1, $2, $3, $4, $5, $6) + "#, + ) + .bind(community_id.as_uuid()) + .bind(issuer) + .bind(uid) + .bind(new_pubkey) + .bind(display_name) + .bind(source) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -357,6 +824,26 @@ mod tests { Keys::generate().public_key().to_bytes().to_vec() } + #[test] + fn staged_identity_key_must_match_membership_key() { + let identity_key = [7_u8; 32]; + let other_key = [8_u8; 32]; + let identity = IdentityBindingInput { + issuer: TEST_ISSUER, + uid: "user-1", + pubkey: &identity_key, + display_name: None, + source: SOURCE_JWT_NPUB, + }; + + validate_membership_identity_key(&hex::encode(identity_key), Some(&identity)) + .expect("matching key"); + assert!( + validate_membership_identity_key(&hex::encode(other_key), Some(&identity)).is_err() + ); + assert!(validate_membership_identity_key("not-hex", Some(&identity)).is_err()); + } + #[tokio::test] #[ignore = "requires Postgres"] async fn bind_identity_creates_then_matches_idempotently() { @@ -577,6 +1064,300 @@ mod tests { .expect("lookup binding") .is_none() ); + + let replacement = random_pubkey(); + let replacement_result = bind_or_validate_identity( + &pool, + community, + TEST_ISSUER, + "user-1", + &replacement, + Some("user@example.com"), + SOURCE_JWT_NPUB, + ) + .await + .expect("principal revocation is a binding result"); + assert_eq!(replacement_result, BindIdentityResult::Revoked); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn authorized_rotation_retires_old_key_and_installs_replacement() { + let pool = setup_pool().await; + let community = make_community(&pool).await; + let old_pubkey = random_pubkey(); + let new_pubkey = random_pubkey(); + bind_or_validate_identity( + &pool, + community, + TEST_ISSUER, + "rotating-user", + &old_pubkey, + Some("user@example.com"), + SOURCE_JWT_NPUB, + ) + .await + .expect("create binding"); + + rotate_identity_binding( + &pool, + community, + TEST_ISSUER, + "rotating-user", + &old_pubkey, + &new_pubkey, + Some("user@example.com"), + SOURCE_JWT_NPUB, + None, + "device replacement", + ) + .await + .expect("authorized rotation"); + + assert!( + get_active_identity_binding_by_pubkey(&pool, community, &old_pubkey) + .await + .expect("old lookup") + .is_none() + ); + assert_eq!( + get_active_identity_binding_by_pubkey(&pool, community, &new_pubkey) + .await + .expect("new lookup") + .expect("replacement active") + .uid, + "rotating-user" + ); + assert_eq!( + bind_or_validate_identity( + &pool, + community, + TEST_ISSUER, + "rotating-user", + &old_pubkey, + Some("user@example.com"), + SOURCE_JWT_NPUB, + ) + .await + .expect("old key result"), + BindIdentityResult::Conflict(IdentityBindingConflict { + issuer: TEST_ISSUER.to_string(), + uid: "rotating-user".to_string(), + pubkey: new_pubkey, + source: SOURCE_JWT_NPUB.to_string(), + }) + ); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn key_revocation_requires_explicit_rotation_for_replacement() { + let pool = setup_pool().await; + let community = make_community(&pool).await; + let old_pubkey = random_pubkey(); + let new_pubkey = random_pubkey(); + bind_or_validate_identity( + &pool, + community, + TEST_ISSUER, + "key-revoked-user", + &old_pubkey, + None, + SOURCE_DB_BINDING, + ) + .await + .expect("create binding"); + assert!( + revoke_identity_key(&pool, community, &old_pubkey, None, "lost device",) + .await + .expect("revoke key") + ); + + assert_eq!( + bind_or_validate_identity( + &pool, + community, + TEST_ISSUER, + "key-revoked-user", + &new_pubkey, + None, + SOURCE_DB_BINDING, + ) + .await + .expect("automatic replacement result"), + BindIdentityResult::Revoked + ); + + rotate_identity_binding( + &pool, + community, + TEST_ISSUER, + "key-revoked-user", + &old_pubkey, + &new_pubkey, + None, + SOURCE_DB_BINDING, + None, + "approved replacement", + ) + .await + .expect("explicit rotation after key revocation"); + assert!( + get_active_identity_binding_by_pubkey(&pool, community, &new_pubkey) + .await + .expect("replacement lookup") + .is_some() + ); + let retired = sqlx::query( + "SELECT revoked_reason, revocation_scope, rotation_reason, rotated_to_pubkey \ + FROM identity_bindings \ + WHERE community_id = $1 AND issuer = $2 AND uid = $3 AND pubkey = $4", + ) + .bind(community.as_uuid()) + .bind(TEST_ISSUER) + .bind("key-revoked-user") + .bind(&old_pubkey) + .fetch_one(&pool) + .await + .expect("retired binding provenance"); + assert_eq!( + retired.try_get::("revoked_reason").unwrap(), + "lost device" + ); + assert_eq!( + retired.try_get::("revocation_scope").unwrap(), + "key" + ); + assert_eq!( + retired.try_get::("rotation_reason").unwrap(), + "approved replacement" + ); + assert_eq!( + retired.try_get::, _>("rotated_to_pubkey").unwrap(), + new_pubkey + ); + let tombstone_reason: String = sqlx::query_scalar( + "SELECT reason FROM identity_revoked_keys WHERE community_id = $1 AND pubkey = $2", + ) + .bind(community.as_uuid()) + .bind(&old_pubkey) + .fetch_one(&pool) + .await + .expect("key tombstone provenance"); + assert_eq!(tombstone_reason, "lost device"); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn principal_can_be_disabled_before_first_enrollment() { + let pool = setup_pool().await; + let community = make_community(&pool).await; + assert!(revoke_identity_principal( + &pool, + community, + TEST_ISSUER, + "never-enrolled", + None, + "employment ended", + ) + .await + .expect("persist principal tombstone")); + assert_eq!( + bind_or_validate_identity( + &pool, + community, + TEST_ISSUER, + "never-enrolled", + &random_pubkey(), + None, + SOURCE_DB_BINDING, + ) + .await + .expect("disabled principal result"), + BindIdentityResult::Revoked + ); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn revoked_key_cannot_rebind_to_another_principal() { + let pool = setup_pool().await; + let community = make_community(&pool).await; + let pubkey = random_pubkey(); + bind_or_validate_identity( + &pool, + community, + TEST_ISSUER, + "first-principal", + &pubkey, + None, + SOURCE_DB_BINDING, + ) + .await + .expect("create binding"); + revoke_identity_key(&pool, community, &pubkey, None, "compromised key") + .await + .expect("revoke key"); + + assert_eq!( + bind_or_validate_identity( + &pool, + community, + TEST_ISSUER, + "different-principal", + &pubkey, + None, + SOURCE_DB_BINDING, + ) + .await + .expect("revoked key result"), + BindIdentityResult::Revoked + ); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn legacy_revoked_key_history_blocks_cross_principal_rebind() { + let pool = setup_pool().await; + let community = make_community(&pool).await; + let pubkey = random_pubkey(); + bind_or_validate_identity( + &pool, + community, + TEST_ISSUER, + "legacy-principal", + &pubkey, + None, + SOURCE_DB_BINDING, + ) + .await + .expect("create binding"); + sqlx::query( + "UPDATE identity_bindings SET revoked_at = NOW(), revoked_reason = 'legacy revoke' \ + WHERE community_id = $1 AND issuer = $2 AND uid = $3 AND pubkey = $4", + ) + .bind(community.as_uuid()) + .bind(TEST_ISSUER) + .bind("legacy-principal") + .bind(&pubkey) + .execute(&pool) + .await + .expect("simulate pre-lifecycle revocation"); + + assert_eq!( + bind_or_validate_identity( + &pool, + community, + "https://other-idp.example", + "different-principal", + &pubkey, + None, + SOURCE_DB_BINDING, + ) + .await + .expect("legacy key tombstone result"), + BindIdentityResult::Revoked + ); } #[tokio::test] diff --git a/crates/buzz-db/src/lib.rs b/crates/buzz-db/src/lib.rs index 0786b4451e..337d5022bb 100644 --- a/crates/buzz-db/src/lib.rs +++ b/crates/buzz-db/src/lib.rs @@ -2569,6 +2569,67 @@ impl Db { .await } + /// Disable a corporate principal and revoke its active key. + pub async fn revoke_identity_principal( + &self, + community_id: CommunityId, + issuer: &str, + uid: &str, + revoked_by: Option<&[u8]>, + reason: &str, + ) -> Result { + identity_binding::revoke_identity_principal( + &self.pool, + community_id, + issuer, + uid, + revoked_by, + reason, + ) + .await + } + + /// Revoke one corporate identity key without disabling its principal. + pub async fn revoke_identity_key( + &self, + community_id: CommunityId, + pubkey: &[u8], + revoked_by: Option<&[u8]>, + reason: &str, + ) -> Result { + identity_binding::revoke_identity_key(&self.pool, community_id, pubkey, revoked_by, reason) + .await + } + + /// Atomically rotate a corporate principal to a replacement key. + #[allow(clippy::too_many_arguments)] + pub async fn rotate_identity_binding( + &self, + community_id: CommunityId, + issuer: &str, + uid: &str, + old_pubkey: &[u8], + new_pubkey: &[u8], + display_name: Option<&str>, + source: &str, + rotated_by: Option<&[u8]>, + reason: &str, + ) -> Result<()> { + identity_binding::rotate_identity_binding( + &self.pool, + community_id, + issuer, + uid, + old_pubkey, + new_pubkey, + display_name, + source, + rotated_by, + reason, + ) + .await + } + /// Atomically set agent owner — only if no owner is currently assigned. /// Returns Ok(true) if set, Ok(false) if an owner already exists. pub async fn set_agent_owner( @@ -4106,6 +4167,27 @@ impl Db { .await } + /// Claims invite membership and an optional corporate identity binding in + /// one transaction. + pub async fn claim_relay_membership_with_identity( + &self, + community: CommunityId, + pubkey: &str, + role: &str, + policy_version: Option<&str>, + identity: Option<&identity_binding::IdentityBindingInput<'_>>, + ) -> Result { + relay_members::claim_relay_membership_with_identity( + &self.pool, + community, + pubkey, + role, + policy_version, + identity, + ) + .await + } + /// Returns whether a member has persisted acceptance evidence for a policy version. pub async fn has_join_policy_acceptance( &self, @@ -4233,6 +4315,27 @@ impl Db { .await } + /// Atomically claims a v2 invite and commits the staged corporate identity + /// binding in the same transaction as membership and invite consumption. + pub async fn claim_relay_invite_with_identity( + &self, + community: CommunityId, + token_hash: &[u8; 32], + claimer_pubkey: &str, + policy_version: Option<&str>, + identity: Option<&identity_binding::IdentityBindingInput<'_>>, + ) -> Result { + relay_invite::claim_relay_invite_with_identity( + &self.pool, + community, + token_hash, + claimer_pubkey, + policy_version, + identity, + ) + .await + } + /// Sidecar an accepted product-feedback event, idempotent by event id. pub async fn insert_product_feedback( &self, diff --git a/crates/buzz-db/src/migration.rs b/crates/buzz-db/src/migration.rs index 56501b7a8f..615f71f41a 100644 --- a/crates/buzz-db/src/migration.rs +++ b/crates/buzz-db/src/migration.rs @@ -561,7 +561,7 @@ mod tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 26); + assert_eq!(migrations.len(), 28); assert_eq!(migrations[0].version, 1); assert_eq!(&*migrations[0].description, "initial schema"); assert!(migrations[0] @@ -927,6 +927,32 @@ mod tests { .sql .as_str() .contains("idx_identity_bindings_active_principal")); + assert_eq!(migrations[27].version, 28); + assert!(migrations[27].sql.as_str().contains("revocation_scope")); + assert!(migrations[27] + .sql + .as_str() + .contains("idx_identity_bindings_revoked_principal")); + assert!(migrations[27] + .sql + .as_str() + .contains("CREATE TABLE identity_principals")); + assert!(migrations[27] + .sql + .as_str() + .contains("INSERT INTO identity_principals")); + assert!(migrations[27] + .sql + .as_str() + .contains("INSERT INTO identity_revoked_keys")); + assert!(migrations[27] + .sql + .as_str() + .contains("rotation_completed_at")); + assert!(migrations[27] + .sql + .as_str() + .contains("CREATE TABLE identity_revoked_keys")); } #[test] @@ -1169,7 +1195,7 @@ mod tests { run_migrations(&pool) .await .expect("retry succeeds after operator repair"); - assert_eq!(applied_versions(&pool).await.last().copied(), Some(26)); + assert_eq!(applied_versions(&pool).await.last().copied(), Some(28)); } #[tokio::test] diff --git a/crates/buzz-db/src/relay_invite.rs b/crates/buzz-db/src/relay_invite.rs index 82b71b07bb..b617732681 100644 --- a/crates/buzz-db/src/relay_invite.rs +++ b/crates/buzz-db/src/relay_invite.rs @@ -25,6 +25,7 @@ use chrono::{DateTime, Utc}; use sqlx::{PgPool, Row as _}; use crate::error::Result; +use crate::identity_binding::{BindIdentityResult, IdentityBindingConflict, IdentityBindingInput}; use crate::CommunityId; /// Outcome of a v2 invite claim. Expected invalid/expired/exhausted states are @@ -39,6 +40,8 @@ pub enum ClaimOutcome { use_count: i32, /// Remaining slots, or `None` when the invite is unlimited. uses_remaining: Option, + /// Binding committed in the same transaction, when one was staged. + identity_binding: Option, }, /// The claimer was already a member. `use_count` was NOT incremented. AlreadyMember { @@ -46,6 +49,8 @@ pub enum ClaimOutcome { use_count: i32, /// Remaining slots, or `None` when the invite is unlimited. uses_remaining: Option, + /// Binding committed in the same transaction, when one was staged. + identity_binding: Option, }, /// The invite's `expires_at` has passed. Expired, @@ -53,6 +58,10 @@ pub enum ClaimOutcome { Exhausted, /// No invite row matches `(community_id, token_hash)`. Invalid, + /// The staged identity conflicts with another active principal or pubkey. + IdentityConflict(IdentityBindingConflict), + /// The staged identity principal or key is revoked. + IdentityRevoked, } /// A freshly minted v2 invite, including the plaintext code and metadata. @@ -198,14 +207,19 @@ pub async fn reap_expired_relay_invites(pool: &PgPool, cutoff: DateTime) -> /// `FOR UPDATE` serializes concurrent claims so exactly one claimant wins the /// final slot. Membership insertion, policy evidence, and consumption share /// one commit — a failure in any rolls back all. -pub async fn claim_relay_invite( +pub async fn claim_relay_invite_with_identity( pool: &PgPool, community: CommunityId, token_hash: &[u8; 32], claimer_pubkey: &str, policy_version: Option<&str>, + identity: Option<&IdentityBindingInput<'_>>, ) -> Result { + crate::identity_binding::validate_membership_identity_key(claimer_pubkey, identity)?; let mut tx = pool.begin().await?; + sqlx::query("SET LOCAL lock_timeout = '3s'") + .execute(&mut *tx) + .await?; // 2. SELECT FOR UPDATE — lock the invite row for the duration of this txn. let row = sqlx::query( @@ -246,6 +260,38 @@ pub async fn claim_relay_invite( return Ok(ClaimOutcome::Expired); } + let identity_binding = if let Some(identity) = identity { + match crate::identity_binding::bind_or_validate_identity_tx(&mut tx, community, identity) + .await? + { + binding @ (BindIdentityResult::Created | BindIdentityResult::Matched) => Some(binding), + BindIdentityResult::Conflict(conflict) => { + tx.rollback().await?; + log_claim_outcome( + community, + Some(invite_id), + "identity_conflict", + max_uses, + Some(use_count), + ); + return Ok(ClaimOutcome::IdentityConflict(conflict)); + } + BindIdentityResult::Revoked => { + tx.rollback().await?; + log_claim_outcome( + community, + Some(invite_id), + "identity_revoked", + max_uses, + Some(use_count), + ); + return Ok(ClaimOutcome::IdentityRevoked); + } + } + } else { + None + }; + let uses_remaining = || max_uses.map(|mu| mu - use_count); // 5. Check existing membership. @@ -280,6 +326,7 @@ pub async fn claim_relay_invite( return Ok(ClaimOutcome::AlreadyMember { use_count, uses_remaining: uses_remaining(), + identity_binding, }); } @@ -339,6 +386,7 @@ pub async fn claim_relay_invite( return Ok(ClaimOutcome::AlreadyMember { use_count, uses_remaining: uses_remaining(), + identity_binding, }); } @@ -367,9 +415,29 @@ pub async fn claim_relay_invite( Ok(ClaimOutcome::Joined { use_count: new_use_count, uses_remaining: new_uses_remaining, + identity_binding, }) } +/// Atomically claim a v2 invite without a corporate identity binding. +pub async fn claim_relay_invite( + pool: &PgPool, + community: CommunityId, + token_hash: &[u8; 32], + claimer_pubkey: &str, + policy_version: Option<&str>, +) -> Result { + claim_relay_invite_with_identity( + pool, + community, + token_hash, + claimer_pubkey, + policy_version, + None, + ) + .await +} + #[cfg(test)] mod tests { use super::*; @@ -401,6 +469,21 @@ mod tests { async fn delete_test_community(pool: &PgPool, community: CommunityId) { let mut tx = pool.begin().await.expect("begin test cleanup"); + sqlx::query("DELETE FROM identity_revoked_keys WHERE community_id = $1") + .bind(community.as_uuid()) + .execute(&mut *tx) + .await + .expect("delete test revoked keys"); + sqlx::query("DELETE FROM identity_bindings WHERE community_id = $1") + .bind(community.as_uuid()) + .execute(&mut *tx) + .await + .expect("delete test identity bindings"); + sqlx::query("DELETE FROM identity_principals WHERE community_id = $1") + .bind(community.as_uuid()) + .execute(&mut *tx) + .await + .expect("delete test identity principals"); sqlx::query("DELETE FROM relay_invites WHERE community_id = $1") .bind(community.as_uuid()) .execute(&mut *tx) @@ -467,6 +550,7 @@ mod tests { ClaimOutcome::Joined { use_count: 1, uses_remaining: Some(0), + identity_binding: None, } ); assert_eq!( @@ -476,6 +560,7 @@ mod tests { ClaimOutcome::AlreadyMember { use_count: 1, uses_remaining: Some(0), + identity_binding: None, } ); assert_eq!( @@ -539,6 +624,77 @@ mod tests { delete_test_community(&pool, community).await; } + #[tokio::test] + #[ignore = "requires Postgres"] + async fn invite_claim_commits_identity_and_membership_atomically() { + let pool = setup_pool().await; + let community = make_test_community(&pool).await; + let claimer = test_pubkey(); + let pubkey = hex::decode(&claimer).expect("test pubkey hex"); + let identity = IdentityBindingInput { + issuer: "https://idp.example", + uid: "atomic-user", + pubkey: &pubkey, + display_name: Some("private@example.com"), + source: crate::identity_binding::SOURCE_JWT_NPUB, + }; + let invalid_hash = [7_u8; 32]; + + assert_eq!( + claim_relay_invite_with_identity( + &pool, + community, + &invalid_hash, + &claimer, + None, + Some(&identity), + ) + .await + .expect("invalid claim result"), + ClaimOutcome::Invalid + ); + assert!( + crate::identity_binding::get_active_identity_binding_by_pubkey( + &pool, community, &pubkey, + ) + .await + .expect("binding lookup after invalid claim") + .is_none() + ); + + let invite = mint_relay_invite(&pool, community, "owner", 3600, Some(1)) + .await + .expect("mint invite"); + let hash = hash_v2_code(&invite.code); + assert!(matches!( + claim_relay_invite_with_identity( + &pool, + community, + &hash, + &claimer, + None, + Some(&identity), + ) + .await + .expect("valid atomic claim"), + ClaimOutcome::Joined { .. } + )); + assert!(is_relay_member(&pool, community, &claimer) + .await + .expect("membership committed")); + assert_eq!( + crate::identity_binding::get_active_identity_binding_by_pubkey( + &pool, community, &pubkey, + ) + .await + .expect("binding lookup") + .expect("binding committed") + .uid, + "atomic-user" + ); + delete_test_community(&pool, community).await; + } + #[tokio::test] #[ignore = "requires Postgres"] async fn expiry_and_tenant_scope_return_typed_failures() { @@ -633,6 +789,7 @@ mod tests { ClaimOutcome::Joined { use_count: expected_count, uses_remaining: None, + identity_binding: None, } ); } diff --git a/crates/buzz-db/src/relay_members.rs b/crates/buzz-db/src/relay_members.rs index 402229cdec..afb31bc890 100644 --- a/crates/buzz-db/src/relay_members.rs +++ b/crates/buzz-db/src/relay_members.rs @@ -10,6 +10,7 @@ use chrono::{DateTime, Utc}; use sqlx::{PgPool, Row as _}; use crate::error::Result; +use crate::identity_binding::{BindIdentityResult, IdentityBindingConflict, IdentityBindingInput}; use crate::CommunityId; /// A single relay member record. @@ -153,7 +154,62 @@ pub async fn claim_relay_membership( role: &str, policy_version: Option<&str>, ) -> Result { + match claim_relay_membership_with_identity(pool, community, pubkey, role, policy_version, None) + .await? + { + MembershipClaimOutcome::Joined { inserted, .. } => Ok(inserted), + MembershipClaimOutcome::IdentityConflict(_) | MembershipClaimOutcome::IdentityRevoked => { + Err(crate::DbError::InvalidData( + "unexpected corporate identity result without staged identity".to_string(), + )) + } + } +} + +/// Outcome of an atomic membership and optional identity claim. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MembershipClaimOutcome { + /// Membership and any staged binding committed together. + Joined { + /// Whether the membership row was newly inserted. + inserted: bool, + /// Binding committed in the same transaction, when one was staged. + identity_binding: Option, + }, + /// The staged identity conflicts with an active binding. + IdentityConflict(IdentityBindingConflict), + /// The staged identity is revoked. + IdentityRevoked, +} + +/// Claims relay membership and an optional corporate identity in one transaction. +pub async fn claim_relay_membership_with_identity( + pool: &PgPool, + community: CommunityId, + pubkey: &str, + role: &str, + policy_version: Option<&str>, + identity: Option<&IdentityBindingInput<'_>>, +) -> Result { + crate::identity_binding::validate_membership_identity_key(pubkey, identity)?; let mut tx = pool.begin().await?; + let identity_binding = if let Some(identity) = identity { + match crate::identity_binding::bind_or_validate_identity_tx(&mut tx, community, identity) + .await? + { + binding @ (BindIdentityResult::Created | BindIdentityResult::Matched) => Some(binding), + BindIdentityResult::Conflict(conflict) => { + tx.rollback().await?; + return Ok(MembershipClaimOutcome::IdentityConflict(conflict)); + } + BindIdentityResult::Revoked => { + tx.rollback().await?; + return Ok(MembershipClaimOutcome::IdentityRevoked); + } + } + } else { + None + }; let inserted = sqlx::query( "INSERT INTO relay_members (community_id, pubkey, role, added_by) \ VALUES ($1, $2, $3, 'invite') \ @@ -180,7 +236,10 @@ pub async fn claim_relay_membership( } tx.commit().await?; - Ok(inserted) + Ok(MembershipClaimOutcome::Joined { + inserted, + identity_binding, + }) } /// Returns whether a member has persisted acceptance evidence for a policy version. diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index 4ffaa21a99..5a8f24df89 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -182,18 +182,18 @@ async fn check_nip98_replay_with_guard( } } -async fn enforce_bridge_corporate_identity( +async fn verify_bridge_corporate_identity( state: &AppState, tenant: &TenantContext, headers: &HeaderMap, pubkey: nostr::PublicKey, auth_tag: Option<&str>, -) -> Result<(), (StatusCode, Json)> { +) -> Result)> { let identity_jwt = crate::corporate_identity::identity_jwt_from_headers( headers, &state.config.corporate_identity, ); - crate::corporate_identity::enforce_corporate_identity( + crate::corporate_identity::verify_corporate_identity( state, tenant.community(), pubkey, @@ -201,10 +201,21 @@ async fn enforce_bridge_corporate_identity( auth_tag, ) .await - .map(|_| ()) .map_err(|e| e.into_api_error()) } +async fn finalize_bridge_corporate_identity( + state: &AppState, + tenant: &TenantContext, + pubkey: nostr::PublicKey, + proof: crate::corporate_identity::CorporateIdentityProof, +) -> Result<(), (StatusCode, Json)> { + crate::corporate_identity::finalize_corporate_identity(state, tenant.community(), pubkey, proof) + .await + .map(|_| ()) + .map_err(|e| e.into_api_error()) +} + /// Construct the NIP-98 `u`-tag expected URL for a request bound to `tenant`. /// /// Conformance row 44 obligation: "NIP-98 `u` URL host must match @@ -834,14 +845,16 @@ async fn submit_event_authed( // Enforce relay membership (with NIP-OA fallback via x-auth-tag header). let auth_tag = headers.get("x-auth-tag").and_then(|v| v.to_str().ok()); - if let Err(e) = - enforce_bridge_corporate_identity(state, tenant, headers, pubkey, auth_tag).await - { - return SubmitOutcome::Err { - status: e.0, - response: e, + let identity_proof = + match verify_bridge_corporate_identity(state, tenant, headers, pubkey, auth_tag).await { + Ok(proof) => proof, + Err(e) => { + return SubmitOutcome::Err { + status: e.0, + response: e, + }; + } }; - } let nip_oa_owner = match super::relay_members::enforce_relay_membership( state, tenant.community(), @@ -864,6 +877,13 @@ async fn submit_event_authed( }; } }; + if let Err(e) = finalize_bridge_corporate_identity(state, tenant, pubkey, identity_proof).await + { + return SubmitOutcome::Err { + status: e.0, + response: e, + }; + } if let Some(owner) = nip_oa_owner { super::relay_members::materialize_nip_oa_owner(state, tenant, &pubkey, &owner).await; } @@ -1005,7 +1025,8 @@ async fn query_events_authed( let pubkey_bytes = pubkey.to_bytes().to_vec(); let auth_tag = headers.get("x-auth-tag").and_then(|v| v.to_str().ok()); - enforce_bridge_corporate_identity(state, tenant, headers, pubkey, auth_tag).await?; + let identity_proof = + verify_bridge_corporate_identity(state, tenant, headers, pubkey, auth_tag).await?; super::relay_members::enforce_relay_membership( state, tenant.community(), @@ -1013,7 +1034,6 @@ async fn query_events_authed( auth_tag, ) .await?; - // Two-pass parse: preserve raw JSON for custom extension fields (before_id, // depth_limit, feed_types) that nostr::Filter silently drops. let raw_filters: Vec = serde_json::from_slice(body) @@ -1051,6 +1071,7 @@ async fn query_events_authed( .get_accessible_channel_ids_cached(tenant.community(), &pubkey_bytes) .await .map_err(|e| internal_error(&format!("channel access lookup: {e}")))?; + finalize_bridge_corporate_identity(state, tenant, pubkey, identity_proof).await?; if filters.iter().any(|f| f.search.is_some()) { if has_mixed_search_filters(&filters) { @@ -1450,7 +1471,8 @@ async fn count_events_authed( let pubkey_bytes = pubkey.to_bytes().to_vec(); let auth_tag = headers.get("x-auth-tag").and_then(|v| v.to_str().ok()); - enforce_bridge_corporate_identity(state, tenant, headers, pubkey, auth_tag).await?; + let identity_proof = + verify_bridge_corporate_identity(state, tenant, headers, pubkey, auth_tag).await?; super::relay_members::enforce_relay_membership( state, tenant.community(), @@ -1458,7 +1480,6 @@ async fn count_events_authed( auth_tag, ) .await?; - let filters: Vec = serde_json::from_slice(body) .map_err(|e| api_error(StatusCode::BAD_REQUEST, &format!("invalid filters: {e}")))?; @@ -1488,6 +1509,7 @@ async fn count_events_authed( .get_accessible_channel_ids_cached(tenant.community(), &pubkey_bytes) .await .map_err(|e| internal_error(&format!("channel access lookup: {e}")))?; + finalize_bridge_corporate_identity(state, tenant, pubkey, identity_proof).await?; let mut total: u64 = 0; for filter in &filters { @@ -2150,7 +2172,8 @@ async fn authorize_moderation_read( let pubkey_bytes = pubkey.to_bytes().to_vec(); let auth_tag = headers.get("x-auth-tag").and_then(|v| v.to_str().ok()); - enforce_bridge_corporate_identity(state, &tenant, headers, pubkey, auth_tag).await?; + let identity_proof = + verify_bridge_corporate_identity(state, &tenant, headers, pubkey, auth_tag).await?; crate::handlers::moderation_authz::authorize_moderation_action( &tenant, @@ -2167,6 +2190,7 @@ async fn authorize_moderation_read( "restricted: moderator access required", ) })?; + finalize_bridge_corporate_identity(state, &tenant, pubkey, identity_proof).await?; Ok(tenant) } diff --git a/crates/buzz-relay/src/api/git/transport.rs b/crates/buzz-relay/src/api/git/transport.rs index 44c85a636e..d525cd33f5 100644 --- a/crates/buzz-relay/src/api/git/transport.rs +++ b/crates/buzz-relay/src/api/git/transport.rs @@ -74,6 +74,9 @@ pub struct GitAuth { pub pubkey: nostr::PublicKey, /// Server-resolved tenant bound from the request Host before auth checks. pub tenant: TenantContext, + /// Cryptographically verified identity staged until repository policy + /// authorization succeeds. + identity_proof: crate::corporate_identity::CorporateIdentityProof, } impl axum::extract::FromRequestParts> for GitAuth { @@ -215,7 +218,7 @@ impl axum::extract::FromRequestParts> for GitAuth { &parts.headers, &state.config.corporate_identity, ); - if let Err(e) = crate::corporate_identity::enforce_corporate_identity( + let identity_proof = match crate::corporate_identity::verify_corporate_identity( state, tenant.community(), pubkey, @@ -224,9 +227,12 @@ impl axum::extract::FromRequestParts> for GitAuth { ) .await { - warn!(pubkey = %pubkey.to_hex(), error = %e, "git: corporate identity denied"); - return Err((e.status_code(), e.public_message()).into_response()); - } + Ok(proof) => proof, + Err(e) => { + warn!(pubkey = %pubkey.to_hex(), error = %e, "git: corporate identity denied"); + return Err((e.status_code(), e.public_message()).into_response()); + } + }; if crate::api::relay_members::enforce_relay_membership( state, tenant.community(), @@ -239,11 +245,29 @@ impl axum::extract::FromRequestParts> for GitAuth { warn!(pubkey = %pubkey.to_hex(), "git: relay membership denied"); return Err((StatusCode::FORBIDDEN, "restricted: not a relay member").into_response()); } - - Ok(GitAuth { pubkey, tenant }) + Ok(GitAuth { + pubkey, + tenant, + identity_proof, + }) } } +async fn finalize_git_corporate_identity(state: &AppState, auth: &GitAuth) -> Result<(), Response> { + crate::corporate_identity::finalize_corporate_identity( + state, + auth.tenant.community(), + auth.pubkey, + auth.identity_proof.clone(), + ) + .await + .map(|_| ()) + .map_err(|e| { + warn!(pubkey = %auth.pubkey.to_hex(), error = %e, "git: corporate identity finalization denied"); + (e.status_code(), e.public_message()).into_response() + }) +} + /// Construct the repo-root NIP-98 `u` URL expected for a git HTTP request. /// /// The host is always the server-resolved tenant host. `config_relay_url` only @@ -700,6 +724,7 @@ pub async fn info_refs( repo_name, ) .await?; + finalize_git_corporate_identity(&state, &auth).await?; // Track C fast path: only for clone advertisement. The receive-pack // advertisement carries a different capability set (report-status, @@ -956,6 +981,7 @@ pub async fn upload_pack( repo_name, ) .await?; + finalize_git_corporate_identity(&state, &auth).await?; let body = decode_git_request_body(&headers, body, UPLOAD_PACK_MAX_DECODED_BYTES); let permit = acquire_git_permit(&state, "upload_pack")?; @@ -1117,6 +1143,7 @@ pub async fn receive_pack( repo_id: repo_name.to_string(), pusher: auth.pubkey, tenant: auth.tenant, + identity_proof: auth.identity_proof, repo_handle: repo, }; Ok(finalize_push(&state, ctx).await) @@ -1708,6 +1735,8 @@ pub(crate) struct PushContext { /// Server-resolved tenant that selected the pointer namespace and owns /// any derived kind:30618 event from this push. pub tenant: TenantContext, + /// Identity proof finalized only after the pre-receive policy hook accepts. + pub identity_proof: crate::corporate_identity::CorporateIdentityProof, /// The hydrated workspace handle. Held until response construction /// (which happens *after* `cas_publish` returns) so the tempdir /// outlives the receive-pack subprocess and the CAS publish. @@ -1754,6 +1783,18 @@ async fn finalize_push(state: &Arc, ctx: PushContext) -> Response { return response; } + if let Err(error) = crate::corporate_identity::finalize_corporate_identity( + state, + ctx.tenant.community(), + ctx.pusher, + ctx.identity_proof.clone(), + ) + .await + { + warn!(pusher = %ctx.pusher.to_hex(), error = %error, "git: post-policy corporate identity finalization denied"); + return (error.status_code(), error.public_message()).into_response(); + } + // Step 7 (CAS). The PushContext binds `parent_state` (observed at // hydrate) to the CAS predicate here — no re-reading of the pointer // between hydrate and CAS. diff --git a/crates/buzz-relay/src/api/invites.rs b/crates/buzz-relay/src/api/invites.rs index 6104171cca..83ecb2fcc3 100644 --- a/crates/buzz-relay/src/api/invites.rs +++ b/crates/buzz-relay/src/api/invites.rs @@ -232,7 +232,14 @@ async fn authenticate( headers: &HeaderMap, path: &str, body: &[u8], -) -> Result<(buzz_core::TenantContext, nostr::PublicKey), (StatusCode, Json)> { +) -> Result< + ( + buzz_core::TenantContext, + nostr::PublicKey, + crate::corporate_identity::CorporateIdentityProof, + ), + (StatusCode, Json), +> { let raw_host = headers .get(axum::http::header::HOST) .and_then(|v| v.to_str().ok()) @@ -257,7 +264,45 @@ async fn authenticate( )?; bridge::check_nip98_replay(state, &tenant, event_id_bytes).await?; - Ok((tenant, pubkey)) + let identity_jwt = crate::corporate_identity::identity_jwt_from_headers( + headers, + &state.config.corporate_identity, + ); + let auth_tag = headers + .get("x-auth-tag") + .and_then(|value| value.to_str().ok()); + let identity_proof = crate::corporate_identity::verify_corporate_identity( + state, + tenant.community(), + pubkey, + identity_jwt.as_deref(), + auth_tag, + ) + .await + .map_err(|error| error.into_api_error())?; + + Ok((tenant, pubkey, identity_proof)) +} + +async fn record_atomic_identity_rejection( + state: &AppState, + community_id: buzz_core::CommunityId, + pubkey: nostr::PublicKey, + proof: crate::corporate_identity::CorporateIdentityProof, + binding: buzz_db::identity_binding::BindIdentityResult, +) -> (StatusCode, Json) { + match crate::corporate_identity::finalize_atomic_corporate_identity_result( + state, + community_id, + pubkey, + proof, + Some(binding), + ) + .await + { + Err(error) => error.into_api_error(), + Ok(_) => internal_error("atomic invite identity rejection was unexpectedly accepted"), + } } /// Mint an invite code — `POST /api/invites`, NIP-98 signed by an owner/admin. @@ -269,7 +314,8 @@ pub async fn mint_invite( headers: HeaderMap, body: axum::body::Bytes, ) -> Result, (StatusCode, Json)> { - let (tenant, pubkey) = authenticate(&state, &headers, "/api/invites", &body).await?; + let (tenant, pubkey, identity_proof) = + authenticate(&state, &headers, "/api/invites", &body).await?; // Authz mirrors kind:9030 (add member): owner or admin only. let sender_hex = pubkey.to_hex(); @@ -298,6 +344,14 @@ pub async fn mint_invite( }; let (ttl, max_uses) = validate_mint_request(&request)?; + crate::corporate_identity::finalize_corporate_identity( + &state, + tenant.community(), + pubkey, + identity_proof, + ) + .await + .map_err(|error| error.into_api_error())?; // Mint a v2 opaque, database-backed invite. let invite = state @@ -349,7 +403,8 @@ pub async fn claim_invite( headers: HeaderMap, body: axum::body::Bytes, ) -> Result, (StatusCode, Json)> { - let (tenant, pubkey) = authenticate(&state, &headers, "/api/invites/claim", &body).await?; + let (tenant, pubkey, identity_proof) = + authenticate(&state, &headers, "/api/invites/claim", &body).await?; if claim_rate_limited(&state, tenant.community(), &pubkey) { return Err(api_error( @@ -360,6 +415,15 @@ pub async fn claim_invite( let request: ClaimInviteRequest = serde_json::from_slice(&body) .map_err(|e| api_error(StatusCode::BAD_REQUEST, &format!("invalid claim JSON: {e}")))?; + // Invite admission must be coupled to the identity being admitted. A + // delegated owner proof can become stale between verification and the + // invite transaction, so bootstrap claims require the joiner's direct JWT. + if crate::corporate_identity::proof_is_delegated(&identity_proof) { + return Err(api_error( + StatusCode::FORBIDDEN, + "direct relay identity required for invite claim", + )); + } let claimer_hex = pubkey.to_hex(); let key = invite_token::derive_invite_key(&state.relay_keypair); @@ -384,9 +448,11 @@ pub async fn claim_invite( } let token_hash = hash_v2_code(&request.code); + let identity_binding = + crate::corporate_identity::binding_input_for_proof(&identity_proof, &pubkey); let outcome = state .db - .claim_relay_invite( + .claim_relay_invite_with_identity( tenant.community(), &token_hash, &claimer_hex, @@ -395,12 +461,24 @@ pub async fn claim_invite( .join_policy .as_ref() .map(|policy| policy.version.as_str()), + identity_binding.as_ref(), ) .await .map_err(|e| internal_error(&format!("v2 invite claim: {e}")))?; return match outcome { - buzz_db::relay_invite::ClaimOutcome::Joined { .. } => { + buzz_db::relay_invite::ClaimOutcome::Joined { + identity_binding, .. + } => { + crate::corporate_identity::finalize_atomic_corporate_identity_result( + &state, + tenant.community(), + pubkey, + identity_proof, + identity_binding, + ) + .await + .map_err(|error| error.into_api_error())?; tracing::info!( community = %tenant.community(), member = %claimer_hex, @@ -422,7 +500,18 @@ pub async fn claim_invite( "role": "member", }))) } - buzz_db::relay_invite::ClaimOutcome::AlreadyMember { .. } => { + buzz_db::relay_invite::ClaimOutcome::AlreadyMember { + identity_binding, .. + } => { + crate::corporate_identity::finalize_atomic_corporate_identity_result( + &state, + tenant.community(), + pubkey, + identity_proof, + identity_binding, + ) + .await + .map_err(|error| error.into_api_error())?; Ok(Json(serde_json::json!({ "status": "already_member", "community_id": tenant.community().to_string(), @@ -439,6 +528,26 @@ pub async fn claim_invite( buzz_db::relay_invite::ClaimOutcome::Invalid => { Err(api_error(StatusCode::FORBIDDEN, "invite_invalid")) } + buzz_db::relay_invite::ClaimOutcome::IdentityConflict(conflict) => { + Err(record_atomic_identity_rejection( + &state, + tenant.community(), + pubkey, + identity_proof, + buzz_db::identity_binding::BindIdentityResult::Conflict(conflict), + ) + .await) + } + buzz_db::relay_invite::ClaimOutcome::IdentityRevoked => { + Err(record_atomic_identity_rejection( + &state, + tenant.community(), + pubkey, + identity_proof, + buzz_db::identity_binding::BindIdentityResult::Revoked, + ) + .await) + } }; } @@ -463,9 +572,11 @@ pub async fn claim_invite( .map_err(|_| api_error(StatusCode::FORBIDDEN, "join_policy_required"))?; } - let was_inserted = state + let identity_binding = + crate::corporate_identity::binding_input_for_proof(&identity_proof, &pubkey); + let claim_outcome = state .db - .claim_relay_membership( + .claim_relay_membership_with_identity( tenant.community(), &claimer_hex, &payload.r, @@ -474,9 +585,45 @@ pub async fn claim_invite( .join_policy .as_ref() .map(|policy| policy.version.as_str()), + identity_binding.as_ref(), ) .await .map_err(|e| internal_error(&format!("invite claim insert: {e}")))?; + let (was_inserted, identity_binding) = match claim_outcome { + buzz_db::relay_members::MembershipClaimOutcome::Joined { + inserted, + identity_binding, + } => (inserted, identity_binding), + buzz_db::relay_members::MembershipClaimOutcome::IdentityConflict(conflict) => { + return Err(record_atomic_identity_rejection( + &state, + tenant.community(), + pubkey, + identity_proof, + buzz_db::identity_binding::BindIdentityResult::Conflict(conflict), + ) + .await); + } + buzz_db::relay_members::MembershipClaimOutcome::IdentityRevoked => { + return Err(record_atomic_identity_rejection( + &state, + tenant.community(), + pubkey, + identity_proof, + buzz_db::identity_binding::BindIdentityResult::Revoked, + ) + .await); + } + }; + crate::corporate_identity::finalize_atomic_corporate_identity_result( + &state, + tenant.community(), + pubkey, + identity_proof, + identity_binding, + ) + .await + .map_err(|error| error.into_api_error())?; if was_inserted { tracing::info!( diff --git a/crates/buzz-relay/src/api/media.rs b/crates/buzz-relay/src/api/media.rs index 8d560371e3..b2f633b33e 100644 --- a/crates/buzz-relay/src/api/media.rs +++ b/crates/buzz-relay/src/api/media.rs @@ -63,18 +63,18 @@ struct MediaReadAuth { tenant: TenantContext, } -async fn enforce_media_corporate_identity( +async fn verify_media_corporate_identity( state: &AppState, tenant: &TenantContext, headers: &HeaderMap, pubkey: nostr::PublicKey, -) -> Result<(), MediaError> { +) -> Result { let auth_tag = headers.get("x-auth-tag").and_then(|v| v.to_str().ok()); let identity_jwt = crate::corporate_identity::identity_jwt_from_headers( headers, &state.config.corporate_identity, ); - crate::corporate_identity::enforce_corporate_identity( + crate::corporate_identity::verify_corporate_identity( state, tenant.community(), pubkey, @@ -82,7 +82,6 @@ async fn enforce_media_corporate_identity( auth_tag, ) .await - .map(|_| ()) .map_err(|e| { tracing::warn!(pubkey = %pubkey.to_hex(), error = %e, "media: corporate identity denied"); if e.status_code() == StatusCode::UNAUTHORIZED { @@ -93,6 +92,30 @@ async fn enforce_media_corporate_identity( }) } +async fn finalize_media_corporate_identity( + state: &AppState, + tenant: &TenantContext, + pubkey: nostr::PublicKey, + proof: crate::corporate_identity::CorporateIdentityProof, +) -> Result<(), MediaError> { + crate::corporate_identity::finalize_corporate_identity( + state, + tenant.community(), + pubkey, + proof, + ) + .await + .map(|_| ()) + .map_err(|e| { + tracing::warn!(pubkey = %pubkey.to_hex(), error = %e, "media: corporate identity finalization denied"); + if e.status_code() == StatusCode::UNAUTHORIZED { + MediaError::Unauthorized + } else { + MediaError::RelayMembershipRequired + } + }) +} + const MEDIA_UPLOAD_RATE_WINDOW: Duration = Duration::from_secs(60); struct UploadPermit { @@ -238,7 +261,8 @@ impl FromRequestParts> for AuthenticatedUpload { // media). On open relays (membership disabled) any valid Blossom signer // may upload, matching the WS door's admission policy. let auth_tag = headers.get("x-auth-tag").and_then(|v| v.to_str().ok()); - enforce_media_corporate_identity(state, &tenant, headers, auth_event.pubkey).await?; + let identity_proof = + verify_media_corporate_identity(state, &tenant, headers, auth_event.pubkey).await?; crate::api::relay_members::enforce_relay_membership( state, @@ -248,7 +272,6 @@ impl FromRequestParts> for AuthenticatedUpload { ) .await .map_err(|_| MediaError::RelayMembershipRequired)?; - if upload_rate_limited(state, tenant.community(), &auth_event.pubkey) { metrics::counter!("buzz_media_upload_rejections_total", "reason" => "rate_limit") .increment(1); @@ -259,6 +282,8 @@ impl FromRequestParts> for AuthenticatedUpload { metrics::counter!("buzz_media_upload_rejections_total", "reason" => "concurrency") .increment(1); })?; + finalize_media_corporate_identity(state, &tenant, auth_event.pubkey, identity_proof) + .await?; Ok(AuthenticatedUpload { auth_event, @@ -534,7 +559,8 @@ async fn authenticate_media_read( buzz_media::auth::verify_blossom_get_auth(&auth_event, sha256, Some(tenant.host()), 3600)?; let auth_tag = headers.get("x-auth-tag").and_then(|v| v.to_str().ok()); - enforce_media_corporate_identity(state, &tenant, headers, auth_event.pubkey).await?; + let identity_proof = + verify_media_corporate_identity(state, &tenant, headers, auth_event.pubkey).await?; crate::api::relay_members::enforce_relay_membership( state, tenant.community(), @@ -543,6 +569,7 @@ async fn authenticate_media_read( ) .await .map_err(|_| MediaError::RelayMembershipRequired)?; + finalize_media_corporate_identity(state, &tenant, auth_event.pubkey, identity_proof).await?; Ok(MediaReadAuth { tenant }) } @@ -1134,6 +1161,7 @@ mod tests { } #[tokio::test] + #[ignore = "requires Postgres"] async fn protected_media_reads_require_corporate_identity_for_get_and_head() { let keys = Keys::generate(); diff --git a/crates/buzz-relay/src/audio/handler.rs b/crates/buzz-relay/src/audio/handler.rs index 349099a668..5adfe42b7e 100644 --- a/crates/buzz-relay/src/audio/handler.rs +++ b/crates/buzz-relay/src/audio/handler.rs @@ -262,7 +262,7 @@ async fn handle_active_audio_connection( let pubkey_bytes = pubkey.to_bytes().to_vec(); let parent_channel_id = auth_msg.parent_channel_id; - if let Err(e) = crate::corporate_identity::enforce_corporate_identity( + let identity_proof = match crate::corporate_identity::verify_corporate_identity( &state, tenant.community(), pubkey, @@ -271,16 +271,19 @@ async fn handle_active_audio_connection( ) .await { - warn!(channel_id = %channel_id, pubkey = %pubkey_hex, error = %e, "audio: corporate identity denied"); - let _ = ws_send - .send(WsMessage::Text( - serde_json::json!({"type": "error", "message": e.public_message()}) - .to_string() - .into(), - )) - .await; - return; - } + Ok(proof) => proof, + Err(e) => { + warn!(channel_id = %channel_id, pubkey = %pubkey_hex, error = %e, "audio: corporate identity denied"); + let _ = ws_send + .send(WsMessage::Text( + serde_json::json!({"type": "error", "message": e.public_message()}) + .to_string() + .into(), + )) + .await; + return; + } + }; if crate::api::relay_members::enforce_relay_membership( &state, @@ -303,7 +306,7 @@ async fn handle_active_audio_connection( } // ── Step 3: membership check / auto-add ─────────────────────────────────── - let parent_id_for_event = match ensure_membership( + let (parent_id_for_event, auto_add_member_by) = match ensure_membership( &state, &tenant, channel_id, @@ -326,6 +329,60 @@ async fn handle_active_audio_connection( } }; + let identity_decision = match crate::corporate_identity::finalize_corporate_identity( + &state, + tenant.community(), + pubkey, + identity_proof, + ) + .await + { + Ok(decision) => decision, + Err(e) => { + warn!(channel_id = %channel_id, pubkey = %pubkey_hex, error = %e, "audio: corporate identity finalization denied"); + let _ = ws_send + .send(WsMessage::Text( + serde_json::json!({"type": "error", "message": e.public_message()}) + .to_string() + .into(), + )) + .await; + return; + } + }; + crate::corporate_identity::spawn_session_revalidation( + Arc::clone(&state), + tenant.community(), + pubkey, + identity_decision, + cancel.clone(), + ); + if let Some(added_by) = auto_add_member_by { + if let Err(e) = state + .db + .add_member( + tenant.community(), + channel_id, + &pubkey_bytes, + MemberRole::Member, + Some(&added_by), + ) + .await + { + warn!(channel_id = %channel_id, pubkey = %pubkey_hex, "audio membership auto-add failed: {e}"); + let _ = ws_send + .send(WsMessage::Text( + serde_json::json!({"type":"error","message":"not a member"}) + .to_string() + .into(), + )) + .await; + cancel.cancel(); + return; + } + state.invalidate_membership(&tenant, channel_id, &pubkey_bytes); + } + // Huddle cross-pod routing (mesh) OR single-pod guardrail. // // When the mesh is live (`state.mesh()` is `Some`), a huddle can span pods: @@ -1197,7 +1254,7 @@ async fn ensure_membership( channel_id: Uuid, pubkey_bytes: &[u8], parent_channel_id: Option, -) -> Result { +) -> Result<(Uuid, Option>), String> { // Load channel first — reject archived channels before any membership check. // This ensures auto-ended huddles can't be rejoined by existing members. let channel = state @@ -1240,11 +1297,11 @@ async fn ensure_membership( .map_err(|e| format!("db error: {e}"))?; if is_member { - return Ok(lifecycle_parent_id); + return Ok((lifecycle_parent_id, None)); } if channel.visibility == "open" { - return Ok(lifecycle_parent_id); + return Ok((lifecycle_parent_id, None)); } // Auto-add path: private ephemeral channel + caller is member of parent. @@ -1255,20 +1312,7 @@ async fn ensure_membership( .map_err(|e| format!("db error: {e}"))?; if parent_member { - state - .db - .add_member( - tenant.community(), - channel_id, - pubkey_bytes, - MemberRole::Member, - Some(&channel.created_by), - ) - .await - .map_err(|e| format!("auto-add failed: {e}"))?; - state.invalidate_membership(tenant, channel_id, pubkey_bytes); - - return Ok(lifecycle_parent_id); + return Ok((lifecycle_parent_id, Some(channel.created_by))); } } diff --git a/crates/buzz-relay/src/config.rs b/crates/buzz-relay/src/config.rs index 284013a26d..e0b10a91d2 100644 --- a/crates/buzz-relay/src/config.rs +++ b/crates/buzz-relay/src/config.rs @@ -89,7 +89,14 @@ pub struct CorporateIdentityConfig { /// Claim name used as Buzz's stable corporate uid. pub uid_claim: String, /// Claim name used for verified display. + /// + /// This value is stored only in the private relay binding table. It is + /// never projected into a public Nostr event unless + /// `public_display_claim` is configured separately. pub display_claim: String, + /// Optional claim name explicitly approved for public NIP-85 projection. + /// Unset by default so private corporate attributes stay private. + pub public_display_claim: Option, /// Optional claim name carrying a hex pubkey or `npub1...`. pub npub_claim: Option, } @@ -106,6 +113,7 @@ impl Default for CorporateIdentityConfig { audience: String::new(), uid_claim: DEFAULT_CORPORATE_IDENTITY_UID_CLAIM.to_string(), display_claim: DEFAULT_CORPORATE_IDENTITY_DISPLAY_CLAIM.to_string(), + public_display_claim: None, npub_claim: None, } } @@ -485,55 +493,70 @@ fn ensure_git_path( Ok(git_repo_path) } -fn env_bool(name: &str, default: bool) -> bool { - std::env::var(name) - .map(|v| { - matches!( - v.trim().to_ascii_lowercase().as_str(), - "true" | "1" | "yes" | "on" - ) - }) - .unwrap_or(default) +fn corporate_env_trimmed(name: &str) -> Result, ConfigError> { + match std::env::var(name) { + Err(std::env::VarError::NotPresent) => Ok(None), + Err(std::env::VarError::NotUnicode(_)) => Err(ConfigError::InvalidValue(format!( + "{name} must be valid UTF-8" + ))), + Ok(value) => { + let value = value.trim(); + if value.is_empty() { + return Err(ConfigError::InvalidValue(format!( + "{name} must not be empty when set" + ))); + } + Ok(Some(value.to_string())) + } + } } -fn env_trimmed(name: &str) -> Option { - std::env::var(name) - .ok() - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()) +fn parse_corporate_bool(name: &str, default: bool) -> Result { + match corporate_env_trimmed(name)? { + None => Ok(default), + Some(value) => match value.to_ascii_lowercase().as_str() { + "true" | "1" | "on" => Ok(true), + "false" | "0" | "off" => Ok(false), + _ => Err(ConfigError::InvalidValue(format!( + "{name} must be true or false" + ))), + }, + } } fn load_corporate_identity_config() -> Result { let mut config = CorporateIdentityConfig::default(); - config.require = env_bool("BUZZ_REQUIRE_CORPORATE_IDENTITY", config.require); - config.jwt_header = env_trimmed("BUZZ_CORPORATE_IDENTITY_JWT_HEADER") + config.require = parse_corporate_bool("BUZZ_REQUIRE_CORPORATE_IDENTITY", config.require)?; + config.jwt_header = corporate_env_trimmed("BUZZ_CORPORATE_IDENTITY_JWT_HEADER")? .unwrap_or_else(|| config.jwt_header.clone()) .to_ascii_lowercase(); - config.allow_delegation = env_bool( + config.allow_delegation = parse_corporate_bool( "BUZZ_ALLOW_CORPORATE_IDENTITY_DELEGATION", config.allow_delegation, - ); - config.auth_precedence = match env_trimmed("BUZZ_CORPORATE_IDENTITY_AUTH_PRECEDENCE").as_deref() - { - None | Some("direct") => CorporateIdentityAuthPrecedence::Direct, - Some("delegated") => CorporateIdentityAuthPrecedence::Delegated, - Some(value) => { - return Err(ConfigError::InvalidValue(format!( + )?; + config.auth_precedence = + match corporate_env_trimmed("BUZZ_CORPORATE_IDENTITY_AUTH_PRECEDENCE")?.as_deref() { + None | Some("direct") => CorporateIdentityAuthPrecedence::Direct, + Some("delegated") => CorporateIdentityAuthPrecedence::Delegated, + Some(value) => { + return Err(ConfigError::InvalidValue(format!( "BUZZ_CORPORATE_IDENTITY_AUTH_PRECEDENCE must be direct or delegated, got {value}" ))); - } - }; - config.jwks_uri = - env_trimmed("BUZZ_CORPORATE_IDENTITY_JWKS_URI").unwrap_or_else(|| config.jwks_uri.clone()); - config.issuer = - env_trimmed("BUZZ_CORPORATE_IDENTITY_ISSUER").unwrap_or_else(|| config.issuer.clone()); - config.audience = - env_trimmed("BUZZ_CORPORATE_IDENTITY_AUDIENCE").unwrap_or_else(|| config.audience.clone()); - config.uid_claim = env_trimmed("BUZZ_CORPORATE_IDENTITY_UID_CLAIM") + } + }; + config.jwks_uri = corporate_env_trimmed("BUZZ_CORPORATE_IDENTITY_JWKS_URI")? + .unwrap_or_else(|| config.jwks_uri.clone()); + config.issuer = corporate_env_trimmed("BUZZ_CORPORATE_IDENTITY_ISSUER")? + .unwrap_or_else(|| config.issuer.clone()); + config.audience = corporate_env_trimmed("BUZZ_CORPORATE_IDENTITY_AUDIENCE")? + .unwrap_or_else(|| config.audience.clone()); + config.uid_claim = corporate_env_trimmed("BUZZ_CORPORATE_IDENTITY_UID_CLAIM")? .unwrap_or_else(|| config.uid_claim.clone()); - config.display_claim = env_trimmed("BUZZ_CORPORATE_IDENTITY_DISPLAY_CLAIM") + config.display_claim = corporate_env_trimmed("BUZZ_CORPORATE_IDENTITY_DISPLAY_CLAIM")? .unwrap_or_else(|| config.display_claim.clone()); - config.npub_claim = env_trimmed("BUZZ_CORPORATE_IDENTITY_NPUB_CLAIM"); + config.public_display_claim = + corporate_env_trimmed("BUZZ_CORPORATE_IDENTITY_PUBLIC_DISPLAY_CLAIM")?; + config.npub_claim = corporate_env_trimmed("BUZZ_CORPORATE_IDENTITY_NPUB_CLAIM")?; if config.require { let mut missing = Vec::new(); @@ -561,6 +584,22 @@ fn load_corporate_identity_config() -> Result, /// Optional pubkey carried by the IdP. pub pubkey: Option, + /// JWT expiration as a Unix timestamp. + pub expires_at: u64, } #[derive(Debug, Deserialize)] @@ -61,17 +72,25 @@ struct RawJwtClaims { #[derive(Debug)] pub struct CorporateIdentityService { config: CorporateIdentityConfig, - http: reqwest::Client, + http: Result, jwks: RwLock>, + refresh: Mutex<()>, } impl CorporateIdentityService { /// Build a corporate identity verifier from relay config. pub fn new(config: CorporateIdentityConfig) -> Self { + let http = reqwest::Client::builder() + .connect_timeout(JWKS_CONNECT_TIMEOUT) + .timeout(JWKS_REQUEST_TIMEOUT) + .redirect(reqwest::redirect::Policy::none()) + .build() + .map_err(|error| error.to_string()); Self { config, - http: reqwest::Client::new(), + http, jwks: RwLock::new(None), + refresh: Mutex::new(()), } } @@ -93,6 +112,7 @@ impl CorporateIdentityService { .as_deref() .ok_or(CorporateIdentityError::MissingKid)?; let jwk = self.jwk_for_kid(kid).await?; + validate_jwk_signature_metadata(&jwk, header.alg)?; let decoding_key = DecodingKey::from_jwk(&jwk).map_err(|e| { CorporateIdentityError::InvalidJwt(format!("invalid JWK for kid {kid}: {e}")) })?; @@ -105,14 +125,23 @@ impl CorporateIdentityService { let issuer = claim_string(&decoded.claims.claims, "iss")?; let uid = claim_string(&decoded.claims.claims, &self.config.uid_claim)?; let display_name = claim_string(&decoded.claims.claims, &self.config.display_claim)?; + let public_display_name = self + .config + .public_display_claim + .as_deref() + .map(|claim| claim_string(&decoded.claims.claims, claim)) + .transpose()?; let pubkey = - optional_pubkey_claim(&decoded.claims.claims, self.config.npub_claim.as_deref())?; + configured_pubkey_claim(&decoded.claims.claims, self.config.npub_claim.as_deref())?; + let expires_at = claim_u64(&decoded.claims.claims, "exp")?; Ok(CorporateJwtClaims { issuer, uid, display_name, + public_display_name, pubkey, + expires_at, }) } @@ -132,6 +161,23 @@ impl CorporateIdentityService { } } + // Only one request may refresh at a time. Re-check after acquiring the + // mutex because another waiter may already have populated the cache. + let _refresh = self.refresh.lock().await; + let now = Instant::now(); + { + let cache = self.jwks.read().await; + if let Some(cached) = cache.as_ref() { + if cached.expires_at > now { + return cached.set.find(kid).cloned().ok_or_else(|| { + CorporateIdentityError::Jwks(format!( + "kid not found in fresh JWKS cache: {kid}" + )) + }); + } + } + } + let set = self.fetch_jwks().await?; let jwk = set.find(kid).cloned(); *self.jwks.write().await = Some(CachedJwks { @@ -142,32 +188,106 @@ impl CorporateIdentityService { } async fn fetch_jwks(&self) -> Result { - let response = self + let client = self .http + .as_ref() + .map_err(|error| CorporateIdentityError::Jwks(error.clone()))?; + let mut response = client .get(&self.config.jwks_uri) .send() .await .map_err(|e| CorporateIdentityError::Jwks(e.to_string()))? .error_for_status() .map_err(|e| CorporateIdentityError::Jwks(e.to_string()))?; - response - .json::() + if response + .content_length() + .is_some_and(|length| length > JWKS_MAX_RESPONSE_BYTES as u64) + { + return Err(CorporateIdentityError::Jwks( + "JWKS response exceeds size limit".to_string(), + )); + } + + let mut body = Vec::new(); + while let Some(chunk) = response + .chunk() .await + .map_err(|e| CorporateIdentityError::Jwks(e.to_string()))? + { + if body.len().saturating_add(chunk.len()) > JWKS_MAX_RESPONSE_BYTES { + return Err(CorporateIdentityError::Jwks( + "JWKS response exceeds size limit".to_string(), + )); + } + body.extend_from_slice(&chunk); + } + serde_json::from_slice::(&body) .map_err(|e| CorporateIdentityError::Jwks(e.to_string())) } } fn jwt_validation(algorithm: Algorithm, config: &CorporateIdentityConfig) -> Validation { let mut validation = Validation::new(algorithm); + validation.leeway = JWT_CLOCK_SKEW_LEEWAY_SECS; validation.set_issuer(&[config.issuer.as_str()]); validation.set_audience(&[config.audience.as_str()]); - // jsonwebtoken only validates `aud` when the claim is present unless it is - // also listed as required. A correctly signed token minted for some other - // service must not be able to omit `aud` and enroll a Buzz identity binding. - validation.required_spec_claims.insert("aud".to_string()); + validation.set_required_spec_claims(&["exp", "iss", "aud"]); + validation.validate_exp = true; + validation.validate_nbf = true; validation } +/// Read-only result of cryptographically validating corporate identity. +/// +/// Callers must complete admission/authorization before passing this proof to +/// [`finalize_corporate_identity`]. This ordering prevents rejected requests +/// from creating identity bindings or public assertions. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CorporateIdentityProof { + /// Corporate identity is disabled for this relay. + NotRequired, + /// A JWT was validated, but no binding mutation has occurred yet. + Direct { + /// Validated claims staged for post-authorization binding. + claims: CorporateJwtClaims, + /// Binding source selected from the configured npub policy. + source: &'static str, + }, + /// A NIP-OA owner with an active binding authorized this agent. + Delegated { + /// Bound owner pubkey. + owner_pubkey: PublicKey, + /// Expected issuer of the owner's active binding. + owner_issuer: String, + /// Expected uid of the owner's active binding. + owner_uid: String, + }, +} + +/// Borrow staged direct-identity data for an atomic admission transaction. +pub fn binding_input_for_proof<'a>( + proof: &'a CorporateIdentityProof, + signer: &'a PublicKey, +) -> Option> { + match proof { + CorporateIdentityProof::Direct { claims, source } => { + Some(buzz_db::identity_binding::IdentityBindingInput { + issuer: &claims.issuer, + uid: &claims.uid, + pubkey: signer.as_bytes(), + display_name: Some(&claims.display_name), + source, + }) + } + CorporateIdentityProof::NotRequired | CorporateIdentityProof::Delegated { .. } => None, + } +} + +/// Whether this proof relies on a delegated owner rather than a direct JWT. +pub fn proof_is_delegated(proof: &CorporateIdentityProof) -> bool { + matches!(proof, CorporateIdentityProof::Delegated { .. }) +} + /// Outcome of corporate identity enforcement. #[derive(Debug, Clone, PartialEq, Eq)] pub enum CorporateIdentityDecision { @@ -181,6 +301,8 @@ pub enum CorporateIdentityDecision { uid: String, /// Verified display claim. display_name: String, + /// JWT expiration used to bound long-lived sessions. + expires_at: u64, /// Binding operation outcome. binding: BindIdentityResult, }, @@ -188,9 +310,160 @@ pub enum CorporateIdentityDecision { Delegated { /// NIP-OA owner pubkey that already has an active corporate binding. owner_pubkey: PublicKey, + /// Expected issuer of the owner's active binding. + owner_issuer: String, + /// Expected uid of the owner's active binding. + owner_uid: String, }, } +struct SessionRevalidationPlan { + binding_pubkey: PublicKey, + expected_issuer: String, + expected_uid: String, + expires_at: Option, +} + +fn session_revalidation_plan( + signer: PublicKey, + decision: CorporateIdentityDecision, +) -> Option { + match decision { + CorporateIdentityDecision::NotRequired => None, + CorporateIdentityDecision::Direct { + issuer, + uid, + expires_at, + .. + } => Some(SessionRevalidationPlan { + binding_pubkey: signer, + expected_issuer: issuer, + expected_uid: uid, + expires_at: Some(expires_at), + }), + CorporateIdentityDecision::Delegated { + owner_pubkey, + owner_issuer, + owner_uid, + } => Some(SessionRevalidationPlan { + binding_pubkey: owner_pubkey, + expected_issuer: owner_issuer, + expected_uid: owner_uid, + expires_at: None, + }), + } +} + +async fn cancel_session_at_expiry( + expires_at: u64, + now_secs: u64, + cancel: tokio_util::sync::CancellationToken, +) { + let delay = Duration::from_secs(expires_at.saturating_sub(now_secs)); + tokio::select! { + _ = cancel.cancelled() => {} + _ = tokio::time::sleep(delay) => cancel.cancel(), + } +} + +async fn run_session_binding_revalidation( + interval: Duration, + signer: PublicKey, + binding_pubkey: PublicKey, + expected_issuer: String, + expected_uid: String, + cancel: tokio_util::sync::CancellationToken, + mut lookup: F, +) where + F: FnMut() -> Fut, + Fut: + std::future::Future, E>>, + E: std::fmt::Display, +{ + let mut interval = tokio::time::interval(interval); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + + loop { + tokio::select! { + _ = cancel.cancelled() => return, + _ = interval.tick() => { + match lookup().await { + Ok(Some(binding)) + if binding.issuer == expected_issuer && binding.uid == expected_uid => {} + Ok(Some(_)) | Ok(None) => { + warn!( + signer = %signer.to_hex(), + binding_pubkey = %binding_pubkey.to_hex(), + "corporate identity session evicted after binding revocation" + ); + cancel.cancel(); + return; + } + Err(error) => { + warn!( + signer = %signer.to_hex(), + error = %error, + "corporate identity session revalidation failed closed" + ); + cancel.cancel(); + return; + } + } + } + } + } +} + +/// Revalidate a long-lived corporate identity session until it closes. +/// +/// Direct sessions are cancelled at JWT expiry and when their binding stops +/// being active. Delegated sessions re-check the owner binding, so revoking an +/// owner also evicts every agent session within one bounded interval. +pub fn spawn_session_revalidation( + state: Arc, + community_id: CommunityId, + signer: PublicKey, + decision: CorporateIdentityDecision, + cancel: tokio_util::sync::CancellationToken, +) { + let Some(plan) = session_revalidation_plan(signer, decision) else { + return; + }; + let SessionRevalidationPlan { + binding_pubkey, + expected_issuer, + expected_uid, + expires_at, + } = plan; + + if let Some(expires_at) = expires_at { + let expiry_cancel = cancel.clone(); + tokio::spawn(async move { + cancel_session_at_expiry(expires_at, Timestamp::now().as_secs(), expiry_cancel).await; + }); + } + + let lookup_state = Arc::clone(&state); + let lookup_pubkey = binding_pubkey; + tokio::spawn(run_session_binding_revalidation( + IDENTITY_SESSION_REVALIDATION_INTERVAL, + signer, + binding_pubkey, + expected_issuer, + expected_uid, + cancel, + move || { + let state = Arc::clone(&lookup_state); + async move { + state + .db + .get_active_identity_binding_by_pubkey(community_id, lookup_pubkey.as_bytes()) + .await + } + }, + )); +} + /// Errors produced by corporate identity verification. #[derive(Debug, Error)] pub enum CorporateIdentityError { @@ -295,16 +568,16 @@ pub fn identity_jwt_from_headers( .map(str::to_string) } -/// Enforce corporate identity for an already NIP-authenticated signer. -pub async fn enforce_corporate_identity( +/// Validate corporate identity without creating bindings or assertions. +pub async fn verify_corporate_identity( state: &AppState, community_id: CommunityId, signer: PublicKey, identity_jwt: Option<&str>, auth_tag_json: Option<&str>, -) -> Result { +) -> Result { let result = - enforce_corporate_identity_inner(state, community_id, signer, identity_jwt, auth_tag_json) + verify_corporate_identity_inner(state, community_id, signer, identity_jwt, auth_tag_json) .await; if let Err(error) = &result { record_corporate_identity_denial(error); @@ -312,15 +585,15 @@ pub async fn enforce_corporate_identity( result } -async fn enforce_corporate_identity_inner( +async fn verify_corporate_identity_inner( state: &AppState, community_id: CommunityId, signer: PublicKey, identity_jwt: Option<&str>, auth_tag_json: Option<&str>, -) -> Result { +) -> Result { let Some(service) = state.corporate_identity.as_ref() else { - return Ok(CorporateIdentityDecision::NotRequired); + return Ok(CorporateIdentityProof::NotRequired); }; // Requests can carry both a direct identity JWT and a cryptographically @@ -331,7 +604,7 @@ async fn enforce_corporate_identity_inner( if select_identity_auth_path(&service.config, identity_jwt, auth_tag_json) == IdentityAuthPath::Delegated { - return enforce_delegated_corporate_identity( + return verify_delegated_corporate_identity( &state.db, &service.config, community_id, @@ -344,111 +617,10 @@ async fn enforce_corporate_identity_inner( if let Some(token) = identity_jwt { let claims = service.validate_jwt(token).await?; let source = binding_source_for_signer(claims.pubkey, signer)?; - - let binding = state - .db - .bind_or_validate_identity( - community_id, - &claims.issuer, - &claims.uid, - signer.as_bytes(), - Some(&claims.display_name), - source, - ) - .await?; - let binding = match binding { - BindIdentityResult::Conflict(conflict) => { - metrics::counter!("buzz_corporate_identity_bindings_total", "result" => "conflict") - .increment(1); - record_identity_binding_audit( - state, - community_id, - buzz_audit::AuditAction::CorporateIdentityBindingConflict, - signer, - &claims.issuer, - &claims.uid, - serde_json::json!({ - "source": source, - "issuer": claims.issuer, - "existing_uid": conflict.uid, - "existing_issuer": conflict.issuer, - "existing_pubkey": hex::encode(conflict.pubkey), - "existing_source": conflict.source, - }), - ) - .await; - warn!( - uid = %claims.uid, - signer = %signer.to_hex(), - "corporate identity binding conflict" - ); - return Err(CorporateIdentityError::BindingConflict); - } - BindIdentityResult::Revoked => { - metrics::counter!("buzz_corporate_identity_bindings_total", "result" => "revoked") - .increment(1); - record_identity_binding_audit( - state, - community_id, - buzz_audit::AuditAction::CorporateIdentityBindingRevokedAttempt, - signer, - &claims.issuer, - &claims.uid, - serde_json::json!({ "source": source, "issuer": claims.issuer }), - ) - .await; - warn!( - uid = %claims.uid, - signer = %signer.to_hex(), - "corporate identity binding was previously revoked" - ); - return Err(CorporateIdentityError::BindingRevoked); - } - binding => binding, - }; - record_identity_binding_metric(&binding); - if matches!(binding, BindIdentityResult::Created) { - record_identity_binding_audit( - state, - community_id, - buzz_audit::AuditAction::CorporateIdentityBindingCreated, - signer, - &claims.issuer, - &claims.uid, - serde_json::json!({ "source": source, "issuer": claims.issuer }), - ) - .await; - } - if let Err(error) = - ensure_identity_assertion(state, community_id, signer, &claims.display_name).await - { - // The binding remains the authorization authority. A projection - // failure removes the verified affordance but must not lock an - // otherwise authorized user out of the relay. - warn!( - signer = %signer.to_hex(), - error = %error, - "failed to publish corporate identity assertion" - ); - metrics::counter!("buzz_corporate_identity_assertions_total", "result" => "error") - .increment(1); - } - - debug!( - uid = %claims.uid, - signer = %signer.to_hex(), - source, - "corporate identity verified" - ); - return Ok(CorporateIdentityDecision::Direct { - issuer: claims.issuer, - uid: claims.uid, - display_name: claims.display_name, - binding, - }); + return Ok(CorporateIdentityProof::Direct { claims, source }); } - enforce_delegated_corporate_identity( + verify_delegated_corporate_identity( &state.db, &service.config, community_id, @@ -458,22 +630,219 @@ async fn enforce_corporate_identity_inner( .await } +/// Commit a previously validated proof after request authorization succeeds. +pub async fn finalize_corporate_identity( + state: &AppState, + community_id: CommunityId, + signer: PublicKey, + proof: CorporateIdentityProof, +) -> Result { + let result = finalize_corporate_identity_inner(state, community_id, signer, proof).await; + if let Err(error) = &result { + record_corporate_identity_denial(error); + } + result +} + +/// Complete metrics/assertion/audit work for an identity result produced by an +/// atomic admission transaction. Rejected results were rolled back, but still +/// need the same denial audit as the ordinary finalization path. +pub async fn finalize_atomic_corporate_identity_result( + state: &AppState, + community_id: CommunityId, + signer: PublicKey, + proof: CorporateIdentityProof, + committed_binding: Option, +) -> Result { + let result = match proof { + CorporateIdentityProof::NotRequired => Ok(CorporateIdentityDecision::NotRequired), + CorporateIdentityProof::Delegated { .. } => Err(CorporateIdentityError::DelegationDenied), + CorporateIdentityProof::Direct { claims, source } => { + let binding = committed_binding.ok_or_else(|| { + buzz_db::DbError::InvalidData( + "atomic identity admission did not return a binding result".to_string(), + ) + })?; + complete_direct_corporate_identity(state, community_id, signer, claims, source, binding) + .await + } + }; + if let Err(error) = &result { + record_corporate_identity_denial(error); + } + result +} + +async fn finalize_corporate_identity_inner( + state: &AppState, + community_id: CommunityId, + signer: PublicKey, + proof: CorporateIdentityProof, +) -> Result { + match proof { + CorporateIdentityProof::NotRequired => Ok(CorporateIdentityDecision::NotRequired), + CorporateIdentityProof::Delegated { + owner_pubkey, + owner_issuer, + owner_uid, + } => Ok(CorporateIdentityDecision::Delegated { + owner_pubkey, + owner_issuer, + owner_uid, + }), + CorporateIdentityProof::Direct { claims, source } => { + let binding = state + .db + .bind_or_validate_identity( + community_id, + &claims.issuer, + &claims.uid, + signer.as_bytes(), + Some(&claims.display_name), + source, + ) + .await?; + complete_direct_corporate_identity(state, community_id, signer, claims, source, binding) + .await + } + } +} + +async fn complete_direct_corporate_identity( + state: &AppState, + community_id: CommunityId, + signer: PublicKey, + claims: CorporateJwtClaims, + source: &'static str, + binding: BindIdentityResult, +) -> Result { + let binding = match binding { + BindIdentityResult::Conflict(conflict) => { + metrics::counter!("buzz_corporate_identity_bindings_total", "result" => "conflict") + .increment(1); + record_identity_binding_audit( + state, + community_id, + buzz_audit::AuditAction::CorporateIdentityBindingConflict, + signer, + &claims.issuer, + &claims.uid, + serde_json::json!({ + "source": source, + "issuer": claims.issuer, + "existing_uid": conflict.uid, + "existing_issuer": conflict.issuer, + "existing_pubkey": hex::encode(conflict.pubkey), + "existing_source": conflict.source, + }), + ) + .await; + warn!( + uid = %claims.uid, + signer = %signer.to_hex(), + "corporate identity binding conflict" + ); + return Err(CorporateIdentityError::BindingConflict); + } + BindIdentityResult::Revoked => { + metrics::counter!("buzz_corporate_identity_bindings_total", "result" => "revoked") + .increment(1); + record_identity_binding_audit( + state, + community_id, + buzz_audit::AuditAction::CorporateIdentityBindingRevokedAttempt, + signer, + &claims.issuer, + &claims.uid, + serde_json::json!({ "source": source, "issuer": claims.issuer }), + ) + .await; + warn!( + uid = %claims.uid, + signer = %signer.to_hex(), + "corporate identity binding was previously revoked" + ); + return Err(CorporateIdentityError::BindingRevoked); + } + binding => binding, + }; + record_identity_binding_metric(&binding); + if matches!(binding, BindIdentityResult::Created) { + record_identity_binding_audit( + state, + community_id, + buzz_audit::AuditAction::CorporateIdentityBindingCreated, + signer, + &claims.issuer, + &claims.uid, + serde_json::json!({ "source": source, "issuer": claims.issuer }), + ) + .await; + } + if let Err(error) = ensure_identity_assertion( + state, + community_id, + signer, + claims.public_display_name.as_deref(), + claims.expires_at, + ) + .await + { + // The binding remains the authorization authority. A projection + // failure removes the verified affordance but must not lock an + // otherwise authorized user out of the relay. + warn!( + signer = %signer.to_hex(), + error = %error, + "failed to publish corporate identity assertion" + ); + metrics::counter!("buzz_corporate_identity_assertions_total", "result" => "error") + .increment(1); + } + + debug!( + uid = %claims.uid, + signer = %signer.to_hex(), + source, + "corporate identity verified" + ); + Ok(CorporateIdentityDecision::Direct { + issuer: claims.issuer, + uid: claims.uid, + display_name: claims.display_name, + expires_at: claims.expires_at, + binding, + }) +} + fn build_identity_assertion( relay_keypair: &nostr::Keys, subject: PublicKey, - display_name: &str, + display_name: Option<&str>, + expires_at: u64, created_at: Timestamp, ) -> Result { let subject = subject.to_hex(); - let tags = [ + let active = if display_name.is_some() { + "true" + } else { + "false" + }; + let expires_at = expires_at.to_string(); + let mut tags = vec![ Tag::parse(["d", subject.as_str()]), Tag::parse(["p", subject.as_str()]), Tag::parse(["verified", "relay"]), - Tag::parse(["display_name", display_name]), - ] - .into_iter() - .collect::, _>>() - .map_err(|error| format!("invalid corporate identity assertion tag: {error}"))?; + Tag::parse(["active", active]), + Tag::parse(["expiration", expires_at.as_str()]), + ]; + if let Some(display_name) = display_name { + tags.push(Tag::parse(["display_name", display_name])); + } + let tags = tags + .into_iter() + .collect::, _>>() + .map_err(|error| format!("invalid corporate identity assertion tag: {error}"))?; EventBuilder::new(Kind::Custom(KIND_USER_TRUSTED_ASSERTION as u16), "") .tags(tags) @@ -482,7 +851,12 @@ fn build_identity_assertion( .map_err(|error| format!("failed to sign corporate identity assertion: {error}")) } -fn identity_assertion_matches(event: &Event, subject: &str, display_name: &str) -> bool { +fn identity_assertion_matches( + event: &Event, + subject: &str, + display_name: Option<&str>, + expires_at: u64, +) -> bool { let has_tag = |name: &str, value: &str| { event.tags.iter().any(|tag| { let parts = tag.as_slice(); @@ -492,14 +866,24 @@ fn identity_assertion_matches(event: &Event, subject: &str, display_name: &str) has_tag("d", subject) && has_tag("p", subject) && has_tag("verified", "relay") - && has_tag("display_name", display_name) + && has_tag( + "active", + if display_name.is_some() { + "true" + } else { + "false" + }, + ) + && has_tag("expiration", &expires_at.to_string()) + && display_name.is_none_or(|name| has_tag("display_name", name)) } async fn ensure_identity_assertion( state: &AppState, community_id: CommunityId, subject: PublicKey, - display_name: &str, + display_name: Option<&str>, + jwt_expires_at: u64, ) -> Result<(), String> { let subject_hex = subject.to_hex(); let existing = state @@ -517,14 +901,21 @@ async fn ensure_identity_assertion( .into_iter() .next(); - if existing - .as_ref() - .is_some_and(|stored| identity_assertion_matches(&stored.event, &subject_hex, display_name)) - { + // Privacy default: do not publish any assertion unless the operator opted + // into a public label. An inactive replacement is emitted only to retire a + // previously published assertion after that opt-in is removed. + if display_name.is_none() && existing.is_none() { return Ok(()); } let now = Timestamp::now().as_secs(); + let expires_at = identity_assertion_expiration(display_name, jwt_expires_at, now); + if existing.as_ref().is_some_and(|stored| { + identity_assertion_matches(&stored.event, &subject_hex, display_name, expires_at) + }) { + return Ok(()); + } + let created_at = existing .as_ref() .map(|stored| stored.event.created_at.as_secs().saturating_add(1)) @@ -534,6 +925,7 @@ async fn ensure_identity_assertion( &state.relay_keypair, subject, display_name, + expires_at, Timestamp::from(created_at), )?; @@ -547,6 +939,14 @@ async fn ensure_identity_assertion( Ok(()) } +fn identity_assertion_expiration(display_name: Option<&str>, jwt_expires_at: u64, now: u64) -> u64 { + if display_name.is_some() { + jwt_expires_at.min(now.saturating_add(IDENTITY_ASSERTION_MAX_TTL_SECS)) + } else { + 0 + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum IdentityAuthPath { Direct, @@ -568,27 +968,29 @@ fn select_identity_auth_path( } } -async fn enforce_delegated_corporate_identity( +async fn verify_delegated_corporate_identity( db: &buzz_db::Db, config: &CorporateIdentityConfig, community_id: CommunityId, signer: PublicKey, auth_tag_json: Option<&str>, -) -> Result { +) -> Result { if config.allow_delegation { - if let Some(owner_pubkey) = - crate::api::relay_members::extract_nip_oa_owner(signer.as_bytes(), auth_tag_json) - { + if let Some(owner_pubkey) = extract_unconditional_nip_oa_owner(signer, auth_tag_json) { let owner_binding = db .get_active_identity_binding_by_pubkey(community_id, owner_pubkey.as_bytes()) .await?; - if owner_binding.is_some() { + if let Some(owner_binding) = owner_binding { debug!( agent = %signer.to_hex(), owner = %owner_pubkey.to_hex(), "corporate identity granted via NIP-OA owner binding" ); - return Ok(CorporateIdentityDecision::Delegated { owner_pubkey }); + return Ok(CorporateIdentityProof::Delegated { + owner_pubkey, + owner_issuer: owner_binding.issuer, + owner_uid: owner_binding.uid, + }); } } } @@ -599,6 +1001,18 @@ async fn enforce_delegated_corporate_identity( } } +fn extract_unconditional_nip_oa_owner( + signer: PublicKey, + auth_tag_json: Option<&str>, +) -> Option { + let tag_json = auth_tag_json?; + let tag: Vec = serde_json::from_str(tag_json).ok()?; + if tag.len() != 4 || tag.get(2).and_then(Value::as_str) != Some("") { + return None; + } + buzz_sdk::nip_oa::verify_auth_tag(tag_json, &signer).ok() +} + fn is_allowed_jwt_algorithm(algorithm: Algorithm) -> bool { matches!( algorithm, @@ -614,6 +1028,57 @@ fn is_allowed_jwt_algorithm(algorithm: Algorithm) -> bool { ) } +fn validate_jwk_signature_metadata( + jwk: &Jwk, + token_algorithm: Algorithm, +) -> Result<(), CorporateIdentityError> { + if jwk + .common + .public_key_use + .as_ref() + .is_some_and(|key_use| key_use != &PublicKeyUse::Signature) + { + return Err(CorporateIdentityError::InvalidJwt( + "JWK use must be sig for JWT verification".to_string(), + )); + } + if jwk + .common + .key_operations + .as_ref() + .is_some_and(|operations| !operations.contains(&KeyOperations::Verify)) + { + return Err(CorporateIdentityError::InvalidJwt( + "JWK key_ops must include verify for JWT verification".to_string(), + )); + } + if jwk + .common + .key_algorithm + .is_some_and(|algorithm| !jwk_algorithm_matches(algorithm, token_algorithm)) + { + return Err(CorporateIdentityError::InvalidJwt(format!( + "JWT algorithm {token_algorithm:?} does not match JWK algorithm" + ))); + } + Ok(()) +} + +fn jwk_algorithm_matches(key: KeyAlgorithm, token: Algorithm) -> bool { + matches!( + (key, token), + (KeyAlgorithm::RS256, Algorithm::RS256) + | (KeyAlgorithm::RS384, Algorithm::RS384) + | (KeyAlgorithm::RS512, Algorithm::RS512) + | (KeyAlgorithm::PS256, Algorithm::PS256) + | (KeyAlgorithm::PS384, Algorithm::PS384) + | (KeyAlgorithm::PS512, Algorithm::PS512) + | (KeyAlgorithm::ES256, Algorithm::ES256) + | (KeyAlgorithm::ES384, Algorithm::ES384) + | (KeyAlgorithm::EdDSA, Algorithm::EdDSA) + ) +} + fn binding_source_for_signer( claim_pubkey: Option, signer: PublicKey, @@ -655,37 +1120,28 @@ fn claim_string( Ok(value.to_string()) } -fn optional_claim_string( - claims: &Map, - claim: &str, -) -> Result, CorporateIdentityError> { - let Some(value) = claims.get(claim) else { - return Ok(None); - }; - let value = value - .as_str() - .map(str::trim) - .filter(|s| !s.is_empty()) - .ok_or_else(|| CorporateIdentityError::InvalidClaim { - claim: claim.to_string(), - reason: "must be a non-empty string".to_string(), - })?; - Ok(Some(value.to_string())) -} - -fn optional_pubkey_claim( +fn configured_pubkey_claim( claims: &Map, claim: Option<&str>, ) -> Result, CorporateIdentityError> { match claim { - Some(claim) => optional_claim_string(claims, claim)? - .as_deref() - .map(|raw| parse_pubkey_claim(claim, raw)) - .transpose(), + Some(claim) => claim_string(claims, claim) + .and_then(|raw| parse_pubkey_claim(claim, &raw)) + .map(Some), None => Ok(None), } } +fn claim_u64(claims: &Map, claim: &str) -> Result { + claims + .get(claim) + .and_then(Value::as_u64) + .ok_or_else(|| CorporateIdentityError::InvalidClaim { + claim: claim.to_string(), + reason: "must be an unsigned integer".to_string(), + }) +} + fn parse_pubkey_claim(claim: &str, value: &str) -> Result { if value.starts_with("npub1") { PublicKey::from_bech32(value).map_err(|e| CorporateIdentityError::InvalidClaim { @@ -767,11 +1223,19 @@ async fn record_identity_binding_audit( #[cfg(test)] mod tests { use super::*; + use std::sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, + }; + use axum::http::{HeaderMap, HeaderName, HeaderValue}; + use base64::Engine as _; use jsonwebtoken::jwk::JwkSet; use jsonwebtoken::{encode, EncodingKey, Header}; use nostr::Keys; use sqlx::PgPool; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::TcpListener; use uuid::Uuid; const TEST_DB_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; @@ -787,16 +1251,165 @@ mod tests { audience: "buzz-relay".to_string(), uid_claim: "sub".to_string(), display_claim: "email".to_string(), + public_display_claim: None, npub_claim: Some("buzz_npub".to_string()), } } + fn test_identity_binding( + issuer: &str, + uid: &str, + pubkey: PublicKey, + ) -> buzz_db::identity_binding::IdentityBinding { + let now = chrono::Utc::now(); + buzz_db::identity_binding::IdentityBinding { + issuer: issuer.to_string(), + uid: uid.to_string(), + pubkey: pubkey.to_bytes().to_vec(), + display_name: None, + source: SOURCE_DB_BINDING.to_string(), + created_at: now, + updated_at: now, + last_seen_at: now, + } + } + + fn spawn_test_revalidation( + signer: PublicKey, + plan: SessionRevalidationPlan, + cancel: tokio_util::sync::CancellationToken, + result: Result, &'static str>, + ) -> (tokio::task::JoinHandle<()>, Arc) { + let lookups = Arc::new(AtomicUsize::new(0)); + let task_lookups = Arc::clone(&lookups); + let task = tokio::spawn(run_session_binding_revalidation( + IDENTITY_SESSION_REVALIDATION_INTERVAL, + signer, + plan.binding_pubkey, + plan.expected_issuer, + plan.expected_uid, + cancel, + move || { + task_lookups.fetch_add(1, Ordering::SeqCst); + let result = result.clone(); + async move { result } + }, + )); + (task, lookups) + } + + #[tokio::test(start_paused = true)] + async fn direct_session_stays_live_before_expiry_and_cancels_at_expiry() { + let cancel = tokio_util::sync::CancellationToken::new(); + let task = tokio::spawn(cancel_session_at_expiry(110, 100, cancel.clone())); + tokio::task::yield_now().await; + + tokio::time::advance(Duration::from_secs(9)).await; + tokio::task::yield_now().await; + assert!(!cancel.is_cancelled()); + + tokio::time::advance(Duration::from_secs(1)).await; + cancel.cancelled().await; + task.await.expect("expiry task"); + } + + #[tokio::test(start_paused = true)] + async fn matching_session_binding_stays_live() { + let signer = Keys::generate().public_key(); + let plan = SessionRevalidationPlan { + binding_pubkey: signer, + expected_issuer: "https://idp.example".to_string(), + expected_uid: "user-1".to_string(), + expires_at: None, + }; + let binding = test_identity_binding("https://idp.example", "user-1", signer); + let cancel = tokio_util::sync::CancellationToken::new(); + let (task, lookups) = + spawn_test_revalidation(signer, plan, cancel.clone(), Ok(Some(binding))); + + while lookups.load(Ordering::SeqCst) == 0 { + tokio::task::yield_now().await; + } + assert!(!cancel.is_cancelled()); + cancel.cancel(); + task.await.expect("revalidation task"); + } + + #[tokio::test(start_paused = true)] + async fn missing_or_mismatched_session_binding_cancels() { + for binding in [ + None, + Some(test_identity_binding( + "https://idp.example", + "different-user", + Keys::generate().public_key(), + )), + ] { + let signer = Keys::generate().public_key(); + let plan = SessionRevalidationPlan { + binding_pubkey: signer, + expected_issuer: "https://idp.example".to_string(), + expected_uid: "user-1".to_string(), + expires_at: None, + }; + let cancel = tokio_util::sync::CancellationToken::new(); + let (task, _) = spawn_test_revalidation(signer, plan, cancel.clone(), Ok(binding)); + + cancel.cancelled().await; + task.await.expect("revalidation task"); + } + } + + #[tokio::test(start_paused = true)] + async fn delegated_session_cancels_when_owner_binding_is_revoked() { + let signer = Keys::generate().public_key(); + let owner = Keys::generate().public_key(); + let plan = session_revalidation_plan( + signer, + CorporateIdentityDecision::Delegated { + owner_pubkey: owner, + owner_issuer: "https://idp.example".to_string(), + owner_uid: "owner-1".to_string(), + }, + ) + .expect("delegated session plan"); + assert_eq!(plan.binding_pubkey, owner); + let cancel = tokio_util::sync::CancellationToken::new(); + let (task, _) = spawn_test_revalidation(signer, plan, cancel.clone(), Ok(None)); + + cancel.cancelled().await; + task.await.expect("revalidation task"); + } + + #[tokio::test(start_paused = true)] + async fn session_revalidation_database_error_cancels_fail_closed() { + let signer = Keys::generate().public_key(); + let plan = SessionRevalidationPlan { + binding_pubkey: signer, + expected_issuer: "https://idp.example".to_string(), + expected_uid: "user-1".to_string(), + expires_at: None, + }; + let cancel = tokio_util::sync::CancellationToken::new(); + let (task, _) = + spawn_test_revalidation(signer, plan, cancel.clone(), Err("database unavailable")); + + cancel.cancelled().await; + task.await.expect("revalidation task"); + } + #[test] fn identity_projects_as_relay_signed_nip85_assertion_without_provider_details() { let relay = Keys::generate(); let subject = Keys::generate().public_key(); - let event = build_identity_assertion(&relay, subject, "Example User", Timestamp::from(123)) - .unwrap(); + let event = build_identity_assertion( + &relay, + subject, + Some("Example User"), + 456, + Timestamp::from(123), + ) + .unwrap(); assert_eq!(event.kind.as_u16() as u32, KIND_USER_TRUSTED_ASSERTION); assert_eq!(event.pubkey, relay.public_key()); @@ -805,7 +1418,8 @@ mod tests { assert!(identity_assertion_matches( &event, &subject.to_hex(), - "Example User", + Some("Example User"), + 456, )); assert!( !event @@ -823,6 +1437,45 @@ mod tests { ); } + #[test] + fn identity_assertions_are_bounded_and_can_be_retired() { + let relay = Keys::generate(); + let subject = Keys::generate().public_key(); + let now = 1_000; + + assert_eq!( + identity_assertion_expiration( + Some("Example User"), + now + IDENTITY_ASSERTION_MAX_TTL_SECS + 1, + now, + ), + now + IDENTITY_ASSERTION_MAX_TTL_SECS, + ); + assert_eq!( + identity_assertion_expiration(Some("Example User"), now + 60, now), + now + 60, + ); + assert_eq!(identity_assertion_expiration(None, u64::MAX, now), 0); + + let retired = build_identity_assertion(&relay, subject, None, 0, Timestamp::from(now)) + .expect("build inactive assertion"); + assert!(identity_assertion_matches( + &retired, + &subject.to_hex(), + None, + 0, + )); + assert!(retired.tags.iter().any(|tag| { + tag.as_slice().first().is_some_and(|part| part == "active") + && tag.as_slice().get(1).is_some_and(|part| part == "false") + })); + assert!(!retired.tags.iter().any(|tag| { + tag.as_slice() + .first() + .is_some_and(|part| part == "display_name") + })); + } + #[test] fn direct_jwt_precedes_delegation_by_default() { let config = test_config(); @@ -878,32 +1531,226 @@ mod tests { assert!(matches!(err, CorporateIdentityError::InvalidJwt(_))); } - #[test] - fn jwt_validation_rejects_token_without_audience_claim() { - let secret = b"test-secret"; - let header = Header::new(Algorithm::HS256); - let token = encode( - &header, - &serde_json::json!({ - "iss": "https://idp.example", - "sub": "user-1", - "email": "user@example.com", - "exp": 4_102_444_800_u64 - }), - &EncodingKey::from_secret(secret), - ) - .expect("encode test JWT"); + #[tokio::test] + async fn validate_jwt_accepts_matching_rs256_jwk() { + let key = rsa_private_key(include_str!("testdata/rsa_private_key_1.der.b64")); + let token = rsa_test_jwt(&key, "rsa-key"); + let claims = validate_rsa_jwt(&token, rsa_test_jwk(&key, "rsa-key")) + .await + .expect("matching RSA JWT must validate"); - let err = decode::( - &token, - &DecodingKey::from_secret(secret), - &jwt_validation(Algorithm::HS256, &test_config()), + assert_eq!(claims.uid, "user-1"); + assert_eq!(claims.display_name, "user@example.com"); + } + + #[tokio::test] + async fn validate_jwt_rejects_rs256_token_signed_by_wrong_key() { + let signing_key = rsa_private_key(include_str!("testdata/rsa_private_key_1.der.b64")); + let advertised_key = rsa_private_key(include_str!("testdata/rsa_private_key_2.der.b64")); + let token = rsa_test_jwt(&signing_key, "rsa-key"); + + let error = validate_rsa_jwt(&token, rsa_test_jwk(&advertised_key, "rsa-key")) + .await + .expect_err("JWT signed by another RSA key must fail"); + assert!(matches!(error, CorporateIdentityError::InvalidJwt(_))); + } + + #[tokio::test] + async fn validate_jwt_rejects_jwk_advertised_algorithm_mismatch() { + let key = rsa_private_key(include_str!("testdata/rsa_private_key_1.der.b64")); + let token = rsa_test_jwt(&key, "rsa-key"); + let mut jwk = rsa_test_jwk(&key, "rsa-key"); + jwk.common.key_algorithm = Some(KeyAlgorithm::RS512); + + let error = validate_rsa_jwt(&token, jwk) + .await + .expect_err("JWK alg must agree with JWT alg"); + assert!(matches!( + error, + CorporateIdentityError::InvalidJwt(ref message) + if message.contains("does not match JWK algorithm") + )); + } + + #[tokio::test] + async fn validate_jwt_accepts_jwk_with_omitted_algorithm() { + let key = rsa_private_key(include_str!("testdata/rsa_private_key_1.der.b64")); + let token = rsa_test_jwt(&key, "rsa-key"); + let mut jwk = rsa_test_jwk(&key, "rsa-key"); + jwk.common.key_algorithm = None; + + validate_rsa_jwt(&token, jwk) + .await + .expect("an omitted optional JWK alg must not prevent RSA verification"); + } + + #[test] + fn validate_jwk_requires_signature_use_and_verify_operation_when_present() { + let key = rsa_private_key(include_str!("testdata/rsa_private_key_1.der.b64")); + let mut jwk = rsa_test_jwk(&key, "rsa-key"); + jwk.common.public_key_use = Some(PublicKeyUse::Encryption); + assert!(matches!( + validate_jwk_signature_metadata(&jwk, Algorithm::RS256), + Err(CorporateIdentityError::InvalidJwt(ref message)) + if message.contains("use must be sig") + )); + + jwk.common.public_key_use = Some(PublicKeyUse::Signature); + jwk.common.key_operations = Some(vec![KeyOperations::Sign]); + assert!(matches!( + validate_jwk_signature_metadata(&jwk, Algorithm::RS256), + Err(CorporateIdentityError::InvalidJwt(ref message)) + if message.contains("key_ops must include verify") + )); + + jwk.common.key_operations = Some(vec![KeyOperations::Sign, KeyOperations::Verify]); + validate_jwk_signature_metadata(&jwk, Algorithm::RS256) + .expect("JWK key_ops containing verify must be accepted"); + } + + #[test] + fn jwt_validation_rejects_missing_and_malformed_audience_claims() { + let now = Timestamp::now().as_secs(); + let missing = serde_json::json!({ + "iss": "https://idp.example", + "sub": "user-1", + "email": "user@example.com", + "exp": now + 3_600, + }); + let malformed = serde_json::json!({ + "iss": "https://idp.example", + "aud": 42, + "sub": "user-1", + "email": "user@example.com", + "exp": now + 3_600, + }); + + for claims in [missing, malformed] { + decode_test_jwt(claims, Algorithm::HS256, b"test-secret", b"test-secret") + .expect_err("invalid audience must not enroll an identity binding"); + } + } + + #[test] + fn jwt_validation_requires_expiration_issuer_and_audience() { + let now = Timestamp::now().as_secs(); + for claim in ["exp", "iss", "aud"] { + let mut claims = valid_test_claims(now) + .as_object() + .expect("claims object") + .clone(); + claims.remove(claim); + assert!( + decode_test_jwt( + Value::Object(claims), + Algorithm::HS256, + b"test-secret", + b"test-secret", + ) + .is_err(), + "missing {claim} must fail closed", + ); + } + } + + #[test] + fn jwt_validation_pins_clock_skew_leeway() { + let validation = jwt_validation(Algorithm::RS256, &test_config()); + assert_eq!(validation.leeway, JWT_CLOCK_SKEW_LEEWAY_SECS); + } + + #[test] + fn jwt_validation_rejects_malformed_registered_claim_types() { + let now = Timestamp::now().as_secs(); + for (claim, value) in [ + ("iss", Value::from(42)), + ("aud", Value::from(42)), + ("exp", Value::String("tomorrow".to_string())), + ("nbf", Value::String("tomorrow".to_string())), + ] { + let mut claims = valid_test_claims(now) + .as_object() + .expect("claims object") + .clone(); + claims.insert(claim.to_string(), value); + assert!( + decode_test_jwt( + Value::Object(claims), + Algorithm::HS256, + b"test-secret", + b"test-secret", + ) + .is_err(), + "malformed {claim} must fail closed", + ); + } + } + + #[test] + fn jwt_validation_rejects_future_and_malformed_not_before_claims() { + let now = Timestamp::now().as_secs(); + let mut future = valid_test_claims(now) + .as_object() + .expect("claims object") + .clone(); + future.insert("nbf".to_string(), Value::from(now + 3_600)); + + let mut malformed = valid_test_claims(now) + .as_object() + .expect("claims object") + .clone(); + malformed.insert("nbf".to_string(), Value::String("tomorrow".to_string())); + + for claims in [Value::Object(future), Value::Object(malformed)] { + decode_test_jwt(claims, Algorithm::HS256, b"test-secret", b"test-secret") + .expect_err("invalid nbf must fail closed"); + } + } + + #[test] + fn jwt_validation_rejects_wrong_issuer_audience_and_expiry() { + let now = Timestamp::now().as_secs(); + for (claim, value) in [ + ("iss", Value::String("https://attacker.example".to_string())), + ("aud", Value::String("some-other-service".to_string())), + ("exp", Value::from(now.saturating_sub(3_600))), + ] { + let mut claims = valid_test_claims(now) + .as_object() + .expect("claims object") + .clone(); + claims.insert(claim.to_string(), value); + assert!( + decode_test_jwt( + Value::Object(claims), + Algorithm::HS256, + b"test-secret", + b"test-secret", + ) + .is_err(), + "invalid {claim} must fail closed", + ); + } + } + + #[test] + fn jwt_validation_rejects_algorithm_and_key_mismatch() { + let claims = valid_test_claims(Timestamp::now().as_secs()); + + decode_test_jwt( + claims.clone(), + Algorithm::HS384, + b"test-secret", + b"test-secret", ) - .expect_err("a token without aud must not enroll an identity binding"); - assert!( - err.to_string().contains("aud"), - "unexpected validation error: {err}" - ); + .expect_err("the token algorithm must match verifier policy"); + decode_test_jwt( + claims, + Algorithm::HS256, + b"signing-secret", + b"different-verification-secret", + ) + .expect_err("a token signed by a different key must fail"); } #[test] @@ -932,18 +1779,20 @@ mod tests { } #[test] - fn configured_npub_claim_is_optional_but_malformed_value_is_invalid() { + fn configured_npub_claim_is_required_and_malformed_value_is_invalid() { let mut claims = Map::new(); - assert_eq!( - optional_pubkey_claim(&claims, Some("buzz_npub")).expect("missing is optional"), - None - ); + let missing = configured_pubkey_claim(&claims, Some("buzz_npub")) + .expect_err("configured claim must be present"); + assert!(matches!( + missing, + CorporateIdentityError::InvalidClaim { ref claim, .. } if claim == "buzz_npub" + )); claims.insert( "buzz_npub".to_string(), Value::String("not-an-npub".to_string()), ); - let err = optional_pubkey_claim(&claims, Some("buzz_npub")) + let err = configured_pubkey_claim(&claims, Some("buzz_npub")) .expect_err("present malformed claim must fail"); assert!(matches!( err, @@ -988,6 +1837,206 @@ mod tests { )); } + #[tokio::test] + async fn jwks_refresh_is_single_flight() { + let body = r#"{"keys":[{"kty":"RSA","n":"AQAB","e":"AQAB","kid":"test-kid","alg":"RS256","use":"sig"}]}"#; + let response = http_response("200 OK", &["Content-Type: application/json"], body); + let (uri, requests, server) = spawn_http_server(response).await; + let mut config = test_config(); + config.jwks_uri = uri; + let service = CorporateIdentityService::new(config); + + let (first, second, third, fourth) = tokio::join!( + service.jwk_for_kid("test-kid"), + service.jwk_for_kid("test-kid"), + service.jwk_for_kid("test-kid"), + service.jwk_for_kid("test-kid"), + ); + for result in [first, second, third, fourth] { + result.expect("all waiters should reuse the refreshed JWKS"); + } + assert_eq!(requests.load(Ordering::SeqCst), 1); + server.abort(); + } + + #[tokio::test] + async fn jwks_response_content_length_is_capped_before_buffering() { + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + JWKS_MAX_RESPONSE_BYTES + 1, + ); + let (uri, _requests, server) = spawn_http_server(response).await; + let mut config = test_config(); + config.jwks_uri = uri; + let service = CorporateIdentityService::new(config); + + let error = service + .fetch_jwks() + .await + .expect_err("oversized JWKS must fail before buffering the body"); + assert!(matches!( + error, + CorporateIdentityError::Jwks(ref message) if message.contains("size limit") + )); + server.abort(); + } + + #[tokio::test] + async fn jwks_streaming_response_is_capped_without_content_length() { + let response = format!( + "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n{}", + " ".repeat(JWKS_MAX_RESPONSE_BYTES + 1), + ); + let (uri, _requests, server) = spawn_http_server(response).await; + let mut config = test_config(); + config.jwks_uri = uri; + let service = CorporateIdentityService::new(config); + + let error = service + .fetch_jwks() + .await + .expect_err("streamed oversized JWKS must stop at the cap"); + assert!(matches!( + error, + CorporateIdentityError::Jwks(ref message) if message.contains("size limit") + )); + server.abort(); + } + + #[test] + fn transport_wide_delegation_rejects_conditional_nip_oa_tags() { + let owner = Keys::generate(); + let agent = Keys::generate().public_key(); + let unconditional = + buzz_sdk::nip_oa::compute_auth_tag(&owner, &agent, "").expect("unconditional auth tag"); + let conditional = buzz_sdk::nip_oa::compute_auth_tag(&owner, &agent, "kind=1") + .expect("conditional auth tag"); + + assert_eq!( + extract_unconditional_nip_oa_owner(agent, Some(&unconditional)), + Some(owner.public_key()), + ); + assert_eq!( + extract_unconditional_nip_oa_owner(agent, Some(&conditional)), + None, + ); + } + + fn valid_test_claims(now: u64) -> Value { + serde_json::json!({ + "iss": "https://idp.example", + "aud": "buzz-relay", + "sub": "user-1", + "email": "user@example.com", + "exp": now + 3_600, + }) + } + + fn decode_test_jwt( + claims: Value, + signing_algorithm: Algorithm, + signing_key: &[u8], + verification_key: &[u8], + ) -> Result<(), jsonwebtoken::errors::Error> { + let token = encode( + &Header::new(signing_algorithm), + &claims, + &EncodingKey::from_secret(signing_key), + )?; + decode::( + &token, + &DecodingKey::from_secret(verification_key), + &jwt_validation(Algorithm::HS256, &test_config()), + )?; + Ok(()) + } + + fn rsa_private_key(encoded: &str) -> Vec { + base64::engine::general_purpose::STANDARD + .decode(encoded.trim()) + .expect("decode RSA test key") + } + + fn rsa_test_jwk(private_key: &[u8], kid: &str) -> Jwk { + let encoding_key = EncodingKey::from_rsa_der(private_key); + let mut jwk = Jwk::from_encoding_key(&encoding_key, Algorithm::RS256) + .expect("derive RSA JWK from test key"); + jwk.common.key_id = Some(kid.to_string()); + jwk.common.public_key_use = Some(PublicKeyUse::Signature); + jwk.common.key_operations = Some(vec![KeyOperations::Verify]); + jwk + } + + fn rsa_test_jwt(private_key: &[u8], kid: &str) -> String { + let mut header = Header::new(Algorithm::RS256); + header.kid = Some(kid.to_string()); + encode( + &header, + &valid_test_claims(Timestamp::now().as_secs()), + &EncodingKey::from_rsa_der(private_key), + ) + .expect("encode RSA test JWT") + } + + async fn validate_rsa_jwt( + token: &str, + jwk: Jwk, + ) -> Result { + let body = + serde_json::to_string(&JwkSet { keys: vec![jwk] }).expect("serialize RSA test JWKS"); + let response = http_response("200 OK", &["Content-Type: application/json"], &body); + let (uri, _requests, server) = spawn_http_server(response).await; + let mut config = test_config(); + config.jwks_uri = uri; + config.npub_claim = None; + let result = CorporateIdentityService::new(config) + .validate_jwt(token) + .await; + server.abort(); + result + } + + fn http_response(status: &str, headers: &[&str], body: &str) -> String { + format!( + "HTTP/1.1 {status}\r\n{}Content-Length: {}\r\nConnection: close\r\n\r\n{body}", + headers + .iter() + .map(|header| format!("{header}\r\n")) + .collect::(), + body.len(), + ) + } + + async fn spawn_http_server( + response: String, + ) -> (String, Arc, tokio::task::JoinHandle<()>) { + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("bind test HTTP server"); + let address = listener.local_addr().expect("test server address"); + let requests = Arc::new(AtomicUsize::new(0)); + let request_count = requests.clone(); + let server = tokio::spawn(async move { + loop { + let Ok((mut stream, _)) = listener.accept().await else { + return; + }; + request_count.fetch_add(1, Ordering::SeqCst); + let mut request = [0_u8; 2_048]; + let Ok(bytes_read) = stream.read(&mut request).await else { + return; + }; + if bytes_read == 0 { + return; + } + if stream.write_all(response.as_bytes()).await.is_err() { + return; + } + } + }); + (format!("http://{address}/jwks"), requests, server) + } + async fn setup_db() -> (buzz_db::Db, PgPool) { let database_url = std::env::var("BUZZ_TEST_DATABASE_URL") .or_else(|_| std::env::var("DATABASE_URL")) @@ -1023,7 +2072,7 @@ mod tests { let auth_tag = buzz_sdk::nip_oa::compute_auth_tag(&owner_keys, &agent_pubkey, "").unwrap(); let config = test_config(); - let err = enforce_delegated_corporate_identity( + let err = verify_delegated_corporate_identity( &db, &config, community, @@ -1045,7 +2094,7 @@ mod tests { .await .expect("create owner binding"); - let decision = enforce_delegated_corporate_identity( + let decision = verify_delegated_corporate_identity( &db, &config, community, @@ -1056,8 +2105,10 @@ mod tests { .expect("owner binding admits agent"); assert_eq!( decision, - CorporateIdentityDecision::Delegated { - owner_pubkey: owner_keys.public_key() + CorporateIdentityProof::Delegated { + owner_pubkey: owner_keys.public_key(), + owner_issuer: config.issuer.clone(), + owner_uid: "owner-uid".to_string(), } ); } @@ -1070,7 +2121,7 @@ mod tests { let signer = Keys::generate().public_key(); let config = test_config(); - let err = enforce_delegated_corporate_identity(&db, &config, community, signer, None) + let err = verify_delegated_corporate_identity(&db, &config, community, signer, None) .await .expect_err("no JWT and no delegation tag"); assert!(matches!(err, CorporateIdentityError::MissingJwt)); diff --git a/crates/buzz-relay/src/handlers/auth.rs b/crates/buzz-relay/src/handlers/auth.rs index c042533930..1aa79aafea 100644 --- a/crates/buzz-relay/src/handlers/auth.rs +++ b/crates/buzz-relay/src/handlers/auth.rs @@ -183,7 +183,7 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: } } - match crate::corporate_identity::enforce_corporate_identity( + let identity_proof = match crate::corporate_identity::verify_corporate_identity( &state, conn.tenant.community(), pubkey, @@ -192,12 +192,7 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: ) .await { - Ok(crate::corporate_identity::CorporateIdentityDecision::Delegated { - owner_pubkey, - }) => { - auth_ctx.agent_owner_pubkey = Some(owner_pubkey); - } - Ok(_) => {} + Ok(proof) => proof, Err(e) => { warn!(conn_id = %conn_id, pubkey = %pubkey.to_hex(), error = %e, "corporate identity denied"); *conn.auth_state.write().await = AuthState::Failed; @@ -208,7 +203,7 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: )); return; } - } + }; // Pubkey allowlist gate — only for pubkey-only auth. if state.config.pubkey_allowlist_enabled @@ -264,6 +259,34 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: } }; + let identity_decision = match crate::corporate_identity::finalize_corporate_identity( + &state, + conn.tenant.community(), + pubkey, + identity_proof, + ) + .await + { + Ok(decision) => decision, + Err(e) => { + warn!(conn_id = %conn_id, pubkey = %pubkey.to_hex(), error = %e, "corporate identity finalization denied"); + *conn.auth_state.write().await = AuthState::Failed; + conn.send(RelayMessage::ok( + &event_id_hex, + false, + &format!("restricted: {}", e.public_message()), + )); + return; + } + }; + if let crate::corporate_identity::CorporateIdentityDecision::Delegated { + owner_pubkey, + .. + } = &identity_decision + { + auth_ctx.agent_owner_pubkey = Some(*owner_pubkey); + } + // Open relay NIP-OA backfill: extract owner for agent→owner DB mapping // (needed for observer frame auth). Only runs on open relays — on closed // relays, enforce_relay_membership already handles NIP-OA delegation. @@ -306,6 +329,13 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: state .conn_manager .set_authenticated_pubkey(conn_id, pubkey.to_bytes().to_vec()); + crate::corporate_identity::spawn_session_revalidation( + Arc::clone(&state), + conn.tenant.community(), + pubkey, + identity_decision, + conn.cancel.clone(), + ); conn.send(RelayMessage::ok(&event_id_hex, true, "")); } Err(e) => { diff --git a/crates/buzz-relay/src/router.rs b/crates/buzz-relay/src/router.rs index 4e34652c82..7737604495 100644 --- a/crates/buzz-relay/src/router.rs +++ b/crates/buzz-relay/src/router.rs @@ -1,13 +1,15 @@ //! axum routers — app (WebSocket + REST), health (K8s probes), metrics (Prometheus). +mod route_policy; + use std::sync::atomic::Ordering; use std::sync::Arc; use axum::{ body::Body, - extract::{ConnectInfo, FromRequest, State, WebSocketUpgrade}, + extract::{ConnectInfo, FromRequest, MatchedPath, State, WebSocketUpgrade}, http::{HeaderMap, Request, StatusCode}, - middleware, + middleware::{self, Next}, response::{IntoResponse, Json}, routing::{get, post, put}, Router, @@ -187,21 +189,83 @@ pub fn build_router(state: Arc) -> Router { } merged + // Every registered route must be present in the centralized policy + // inventory. When the gate is enabled, an unclassified route fails + // before its handler can perform reads or writes. + .route_layer(middleware::from_fn_with_state( + state.clone(), + enforce_corporate_identity_route_inventory, + )) .layer(middleware::from_fn(track_metrics)) .layer(http_trace_layer()) .layer(build_cors_layer(&state.config.cors_origins)) } +async fn enforce_corporate_identity_route_inventory( + State(state): State>, + request: Request, + next: Next, +) -> axum::response::Response { + enforce_route_inventory_for_requirement(state.config.corporate_identity.require, request, next) + .await +} + +async fn enforce_route_inventory_for_requirement( + corporate_identity_required: bool, + request: Request, + next: Next, +) -> axum::response::Response { + if !corporate_identity_required { + return next.run(request).await; + } + let matched_path = request.extensions().get::(); + let policy = matched_path + .and_then(|path| route_policy::classify_matched_route(request.method(), path.as_str())); + if policy.is_some() { + return next.run(request).await; + } + if matched_path.is_some_and(|path| route_policy::is_known_matched_path(path.as_str())) { + // Axum's method fallback also runs route layers. Return its semantic + // equivalent directly, while still preventing an accidentally added + // unclassified method handler from executing. + let allow = matched_path + .and_then(|path| route_policy::allowed_methods(path.as_str())) + .unwrap_or_default(); + return axum::response::Response::builder() + .status(StatusCode::METHOD_NOT_ALLOWED) + .header(axum::http::header::ALLOW, allow) + .body(Body::empty()) + .unwrap_or_else(|_| StatusCode::METHOD_NOT_ALLOWED.into_response()); + } + tracing::error!( + method = %request.method(), + matched_path = matched_path.map(|path| path.as_str()).unwrap_or(""), + "rejecting route missing corporate identity policy classification" + ); + ( + StatusCode::SERVICE_UNAVAILABLE, + "route unavailable: identity policy is not configured", + ) + .into_response() +} + fn http_trace_layer() -> TraceLayer) -> tracing::Span> { TraceLayer::new_for_http().make_span_with(make_http_span as fn(&Request) -> tracing::Span) } fn make_http_span(request: &Request) -> tracing::Span { + let corporate_identity_policy = request + .extensions() + .get::() + .and_then(|path| route_policy::classify_matched_route(request.method(), path.as_str())) + .map(route_policy::CorporateIdentityRoutePolicy::trace_label) + .unwrap_or("unclassified"); tracing::info_span!( target: "buzz_relay", "http.request", otel.kind = "server", http.request.method = %request.method(), + buzz.corporate_identity.route_policy = corporate_identity_policy, ) } @@ -453,7 +517,10 @@ fn build_cors_layer(cors_origins: &[String]) -> CorsLayer { #[cfg(test)] mod tests { - use axum::{routing::get, Router}; + use axum::{ + routing::{get, post}, + Router, + }; use futures_util::SinkExt; use opentelemetry::trace::TracerProvider as _; use opentelemetry_sdk::trace::{InMemorySpanExporter, SdkTracerProvider}; @@ -466,6 +533,49 @@ mod tests { use super::*; + async fn require_route_inventory( + request: Request, + next: Next, + ) -> axum::response::Response { + enforce_route_inventory_for_requirement(true, request, next).await + } + + #[tokio::test] + async fn route_inventory_preserves_405_and_rejects_new_unclassified_handlers() { + let app = Router::new() + .route("/events", post(|| async { StatusCode::OK })) + .route("/new-unclassified-route", get(|| async { StatusCode::OK })) + .route_layer(middleware::from_fn(require_route_inventory)); + + let allowed = app + .clone() + .oneshot(Request::post("/events").body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(allowed.status(), StatusCode::OK); + + let unsupported = app + .clone() + .oneshot(Request::delete("/events").body(Body::empty()).unwrap()) + .await + .unwrap(); + assert_eq!(unsupported.status(), StatusCode::METHOD_NOT_ALLOWED); + assert_eq!( + unsupported.headers().get(axum::http::header::ALLOW), + Some(&axum::http::HeaderValue::from_static("POST")) + ); + + let unclassified = app + .oneshot( + Request::get("/new-unclassified-route") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(unclassified.status(), StatusCode::SERVICE_UNAVAILABLE); + } + #[test] fn invite_landing_path_requires_exactly_one_nonempty_code_segment() { assert!(is_invite_landing_path("/invite/payload.mac")); diff --git a/crates/buzz-relay/src/router/route_policy.rs b/crates/buzz-relay/src/router/route_policy.rs new file mode 100644 index 0000000000..38859e10a9 --- /dev/null +++ b/crates/buzz-relay/src/router/route_policy.rs @@ -0,0 +1,499 @@ +//! Central inventory of corporate-identity policy at the HTTP routing boundary. +//! +//! This module classifies axum's *matched route template* (for example, +//! `/media/{sha256_ext}`), not an untrusted literal request path. Keeping the +//! complete inventory here makes every authenticated surface and every +//! deliberate exemption reviewable in one place. The handlers remain the +//! enforcement point because they have the authenticated principal, resolved +//! tenant, and admission result needed to finalize an identity safely. + +use axum::http::Method; + +/// Why a route deliberately does not use tenant corporate-identity auth. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) enum CorporateIdentityExemption { + /// Public relay metadata (NIP-05, NIP-11-adjacent information). + PublicMetadata, + /// Kubernetes/service health endpoint. + HealthProbe, + /// Public pre-membership policy and policy-acceptance bootstrap. + JoinBootstrap, + /// Deployment-global operator NIP-98 allowlist, outside tenant auth. + OperatorAuth, + /// Deployment-admin host/session authentication, outside tenant auth. + AdminAuth, + /// Per-workflow secret authentication. + WebhookSecret, + /// Loopback-only, HMAC-authenticated Git hook callback. + LocalHookCallback, + /// Disabled-by-default mesh testbed endpoint. + TestbedOnly, +} + +/// Corporate-identity policy for a registered route. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) enum CorporateIdentityRoutePolicy { + /// Authenticate and enforce corporate identity during this HTTP request. + Required, + /// Enforce when the upgraded WebSocket performs its protocol auth flow. + RequiredAtSessionAuth, + /// Public only when protected media reads are disabled; otherwise required. + RequiredWhenMediaReadsProtected, + /// Deliberately outside tenant corporate-identity authentication. + Exempt(CorporateIdentityExemption), +} + +impl CorporateIdentityRoutePolicy { + /// Stable, low-cardinality label used on HTTP trace spans. + pub(super) const fn trace_label(self) -> &'static str { + match self { + Self::Required => "required", + Self::RequiredAtSessionAuth => "required_at_session_auth", + Self::RequiredWhenMediaReadsProtected => "required_when_media_reads_protected", + Self::Exempt(CorporateIdentityExemption::PublicMetadata) => "exempt_public_metadata", + Self::Exempt(CorporateIdentityExemption::HealthProbe) => "exempt_health_probe", + Self::Exempt(CorporateIdentityExemption::JoinBootstrap) => "exempt_join_bootstrap", + Self::Exempt(CorporateIdentityExemption::OperatorAuth) => "exempt_operator_auth", + Self::Exempt(CorporateIdentityExemption::AdminAuth) => "exempt_admin_auth", + Self::Exempt(CorporateIdentityExemption::WebhookSecret) => "exempt_webhook_secret", + Self::Exempt(CorporateIdentityExemption::LocalHookCallback) => { + "exempt_local_hook_callback" + } + Self::Exempt(CorporateIdentityExemption::TestbedOnly) => "exempt_testbed_only", + } + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct RoutePolicyRule { + method: &'static str, + matched_path: &'static str, + policy: CorporateIdentityRoutePolicy, +} + +const REQUIRED: CorporateIdentityRoutePolicy = CorporateIdentityRoutePolicy::Required; +const SESSION: CorporateIdentityRoutePolicy = CorporateIdentityRoutePolicy::RequiredAtSessionAuth; +const PROTECTED_MEDIA: CorporateIdentityRoutePolicy = + CorporateIdentityRoutePolicy::RequiredWhenMediaReadsProtected; + +const fn exempt(exemption: CorporateIdentityExemption) -> CorporateIdentityRoutePolicy { + CorporateIdentityRoutePolicy::Exempt(exemption) +} + +/// Exhaustive inventory of registered relay routes. +/// +/// Static UI fallback paths are intentionally absent: they do not have an +/// axum `MatchedPath` and cannot reach an API handler. A missing API entry is +/// visible as `unclassified` in the HTTP trace span and must be added here as +/// part of registering the route. +const ROUTE_POLICY_RULES: &[RoutePolicyRule] = &[ + // Protocol and public metadata. + RoutePolicyRule { + method: "GET", + matched_path: "/", + policy: SESSION, + }, + RoutePolicyRule { + method: "GET", + matched_path: "/info", + policy: exempt(CorporateIdentityExemption::PublicMetadata), + }, + RoutePolicyRule { + method: "GET", + matched_path: "/.well-known/nostr.json", + policy: exempt(CorporateIdentityExemption::PublicMetadata), + }, + // Health routes on the primary and health-only listeners. + RoutePolicyRule { + method: "GET", + matched_path: "/health", + policy: exempt(CorporateIdentityExemption::HealthProbe), + }, + RoutePolicyRule { + method: "GET", + matched_path: "/_liveness", + policy: exempt(CorporateIdentityExemption::HealthProbe), + }, + RoutePolicyRule { + method: "GET", + matched_path: "/_readiness", + policy: exempt(CorporateIdentityExemption::HealthProbe), + }, + RoutePolicyRule { + method: "GET", + matched_path: "/_status", + policy: exempt(CorporateIdentityExemption::HealthProbe), + }, + RoutePolicyRule { + method: "GET", + matched_path: "/_mesh", + policy: exempt(CorporateIdentityExemption::HealthProbe), + }, + // NIP-98 HTTP bridge. + RoutePolicyRule { + method: "POST", + matched_path: "/events", + policy: REQUIRED, + }, + RoutePolicyRule { + method: "POST", + matched_path: "/query", + policy: REQUIRED, + }, + RoutePolicyRule { + method: "POST", + matched_path: "/count", + policy: REQUIRED, + }, + // Deployment-global operator control plane. + RoutePolicyRule { + method: "GET", + matched_path: "/operator/communities", + policy: exempt(CorporateIdentityExemption::OperatorAuth), + }, + RoutePolicyRule { + method: "POST", + matched_path: "/operator/communities", + policy: exempt(CorporateIdentityExemption::OperatorAuth), + }, + RoutePolicyRule { + method: "POST", + matched_path: "/operator/communities/archive", + policy: exempt(CorporateIdentityExemption::OperatorAuth), + }, + RoutePolicyRule { + method: "POST", + matched_path: "/operator/communities/unarchive", + policy: exempt(CorporateIdentityExemption::OperatorAuth), + }, + RoutePolicyRule { + method: "GET", + matched_path: "/operator/communities/availability", + policy: exempt(CorporateIdentityExemption::OperatorAuth), + }, + RoutePolicyRule { + method: "POST", + matched_path: "/operator/communities/transfer", + policy: exempt(CorporateIdentityExemption::OperatorAuth), + }, + // Invite admission and its deliberately public pre-join policy surface. + RoutePolicyRule { + method: "POST", + matched_path: "/api/invites", + policy: REQUIRED, + }, + RoutePolicyRule { + method: "POST", + matched_path: "/api/invites/claim", + policy: REQUIRED, + }, + RoutePolicyRule { + method: "GET", + matched_path: "/api/join-policy", + policy: exempt(CorporateIdentityExemption::JoinBootstrap), + }, + RoutePolicyRule { + method: "GET", + matched_path: "/api/join-policy/terms", + policy: exempt(CorporateIdentityExemption::JoinBootstrap), + }, + RoutePolicyRule { + method: "GET", + matched_path: "/api/join-policy/privacy", + policy: exempt(CorporateIdentityExemption::JoinBootstrap), + }, + RoutePolicyRule { + method: "POST", + matched_path: "/api/invites/accept-policy", + policy: exempt(CorporateIdentityExemption::JoinBootstrap), + }, + // Moderation data is tenant-authenticated even though it is not event data. + RoutePolicyRule { + method: "GET", + matched_path: "/moderation/reports", + policy: REQUIRED, + }, + RoutePolicyRule { + method: "GET", + matched_path: "/moderation/audit", + policy: REQUIRED, + }, + RoutePolicyRule { + method: "GET", + matched_path: "/moderation/restricted", + policy: REQUIRED, + }, + // Alternate-auth and test-only callbacks. + RoutePolicyRule { + method: "POST", + matched_path: "/hooks/{id}", + policy: exempt(CorporateIdentityExemption::WebhookSecret), + }, + RoutePolicyRule { + method: "POST", + matched_path: "/_mesh/demo/echo", + policy: exempt(CorporateIdentityExemption::TestbedOnly), + }, + RoutePolicyRule { + method: "POST", + matched_path: "/internal/git/policy", + policy: exempt(CorporateIdentityExemption::LocalHookCallback), + }, + // Huddle authentication is performed inside the upgraded socket. + RoutePolicyRule { + method: "GET", + matched_path: "/huddle/{channel_id}/audio", + policy: SESSION, + }, + // Blossom media: writes are always authenticated; reads are configurable. + RoutePolicyRule { + method: "PUT", + matched_path: "/upload", + policy: REQUIRED, + }, + RoutePolicyRule { + method: "PUT", + matched_path: "/media/upload", + policy: REQUIRED, + }, + RoutePolicyRule { + method: "GET", + matched_path: "/media/{sha256_ext}", + policy: PROTECTED_MEDIA, + }, + RoutePolicyRule { + method: "HEAD", + matched_path: "/media/{sha256_ext}", + policy: PROTECTED_MEDIA, + }, + // Git smart HTTP is tenant-authenticated on every request. + RoutePolicyRule { + method: "GET", + matched_path: "/git/{owner}/{repo}/info/refs", + policy: REQUIRED, + }, + RoutePolicyRule { + method: "POST", + matched_path: "/git/{owner}/{repo}/git-upload-pack", + policy: REQUIRED, + }, + RoutePolicyRule { + method: "POST", + matched_path: "/git/{owner}/{repo}/git-receive-pack", + policy: REQUIRED, + }, + // Deployment-admin APIs use the dedicated admin-host auth middleware. + RoutePolicyRule { + method: "GET", + matched_path: "/api/admin/v1/reports", + policy: exempt(CorporateIdentityExemption::AdminAuth), + }, + RoutePolicyRule { + method: "GET", + matched_path: "/api/admin/v1/reports/{id}", + policy: exempt(CorporateIdentityExemption::AdminAuth), + }, + RoutePolicyRule { + method: "GET", + matched_path: "/api/admin/v1/feedback", + policy: exempt(CorporateIdentityExemption::AdminAuth), + }, + RoutePolicyRule { + method: "GET", + matched_path: "/api/admin/v1/feedback/{id}", + policy: exempt(CorporateIdentityExemption::AdminAuth), + }, + RoutePolicyRule { + method: "GET", + matched_path: "/api/admin/v1/feedback/{id}/attachments/{sha256}", + policy: exempt(CorporateIdentityExemption::AdminAuth), + }, +]; + +/// Classify a registered method and axum matched-path template. +pub(super) fn classify_matched_route( + method: &Method, + matched_path: &str, +) -> Option { + let exact = ROUTE_POLICY_RULES + .iter() + .find(|rule| rule.method == method.as_str() && rule.matched_path == matched_path) + .map(|rule| rule.policy); + if exact.is_some() || method != Method::HEAD { + return exact; + } + + // axum automatically serves HEAD through GET routes when no explicit HEAD + // handler is registered. Mirror that routing fallback so those requests + // cannot appear unclassified. The explicit protected-media HEAD rule above + // wins before this branch. + ROUTE_POLICY_RULES + .iter() + .find(|rule| rule.method == "GET" && rule.matched_path == matched_path) + .map(|rule| rule.policy) +} + +/// Whether this matched template is registered in the inventory for any +/// method. An unknown method on a known template is a 405, not a new route. +pub(super) fn is_known_matched_path(matched_path: &str) -> bool { + ROUTE_POLICY_RULES + .iter() + .any(|rule| rule.matched_path == matched_path) +} + +/// RFC 9110 `Allow` value for a known matched template. GET routes include +/// Axum's implicit HEAD support. +pub(super) fn allowed_methods(matched_path: &str) -> Option { + let mut methods = Vec::new(); + for rule in ROUTE_POLICY_RULES + .iter() + .filter(|rule| rule.matched_path == matched_path) + { + if !methods.contains(&rule.method) { + methods.push(rule.method); + } + if rule.method == "GET" && !methods.contains(&"HEAD") { + methods.push("HEAD"); + } + } + (!methods.is_empty()).then(|| methods.join(", ")) +} + +#[cfg(test)] +mod tests { + use std::collections::HashSet; + + use super::*; + + fn policy(method: Method, path: &str) -> CorporateIdentityRoutePolicy { + classify_matched_route(&method, path) + .unwrap_or_else(|| panic!("missing route policy for {method} {path}")) + } + + #[test] + fn every_policy_rule_has_a_unique_method_and_path() { + let mut seen = HashSet::new(); + for rule in ROUTE_POLICY_RULES { + assert!( + seen.insert((rule.method, rule.matched_path)), + "duplicate route policy for {} {}", + rule.method, + rule.matched_path + ); + } + } + + #[test] + fn every_tenant_authenticated_http_route_requires_corporate_identity() { + let routes = [ + (Method::POST, "/events"), + (Method::POST, "/query"), + (Method::POST, "/count"), + (Method::POST, "/api/invites"), + (Method::POST, "/api/invites/claim"), + (Method::GET, "/moderation/reports"), + (Method::GET, "/moderation/audit"), + (Method::GET, "/moderation/restricted"), + (Method::PUT, "/upload"), + (Method::PUT, "/media/upload"), + (Method::GET, "/git/{owner}/{repo}/info/refs"), + (Method::POST, "/git/{owner}/{repo}/git-upload-pack"), + (Method::POST, "/git/{owner}/{repo}/git-receive-pack"), + ]; + for (method, path) in routes { + assert_eq!(policy(method, path), CorporateIdentityRoutePolicy::Required); + } + } + + #[test] + fn websocket_and_media_policies_capture_deferred_and_conditional_auth() { + assert_eq!( + policy(Method::GET, "/"), + CorporateIdentityRoutePolicy::RequiredAtSessionAuth + ); + assert_eq!( + policy(Method::GET, "/huddle/{channel_id}/audio"), + CorporateIdentityRoutePolicy::RequiredAtSessionAuth + ); + for method in [Method::GET, Method::HEAD] { + assert_eq!( + policy(method, "/media/{sha256_ext}"), + CorporateIdentityRoutePolicy::RequiredWhenMediaReadsProtected + ); + } + } + + #[test] + fn privileged_non_tenant_surfaces_have_narrow_named_exemptions() { + let routes = [ + ( + Method::POST, + "/operator/communities/archive", + CorporateIdentityExemption::OperatorAuth, + ), + ( + Method::GET, + "/api/admin/v1/reports", + CorporateIdentityExemption::AdminAuth, + ), + ( + Method::POST, + "/hooks/{id}", + CorporateIdentityExemption::WebhookSecret, + ), + ( + Method::POST, + "/internal/git/policy", + CorporateIdentityExemption::LocalHookCallback, + ), + ]; + for (method, path, exemption) in routes { + assert_eq!( + policy(method, path), + CorporateIdentityRoutePolicy::Exempt(exemption) + ); + } + } + + #[test] + fn public_routes_are_explicit_and_unknown_routes_are_unclassified() { + assert_eq!( + policy(Method::GET, "/.well-known/nostr.json"), + CorporateIdentityRoutePolicy::Exempt(CorporateIdentityExemption::PublicMetadata) + ); + assert_eq!( + policy(Method::GET, "/_readiness"), + CorporateIdentityRoutePolicy::Exempt(CorporateIdentityExemption::HealthProbe) + ); + assert_eq!( + policy(Method::GET, "/api/join-policy"), + CorporateIdentityRoutePolicy::Exempt(CorporateIdentityExemption::JoinBootstrap) + ); + assert_eq!( + policy(Method::POST, "/_mesh/demo/echo"), + CorporateIdentityRoutePolicy::Exempt(CorporateIdentityExemption::TestbedOnly) + ); + assert_eq!( + policy(Method::HEAD, "/info"), + CorporateIdentityRoutePolicy::Exempt(CorporateIdentityExemption::PublicMetadata), + "axum's automatic GET-to-HEAD fallback inherits the GET policy" + ); + assert_eq!(classify_matched_route(&Method::GET, "/events"), None); + assert_eq!(classify_matched_route(&Method::GET, "/unknown"), None); + assert_eq!( + classify_matched_route(&Method::GET, "/media/literal-sha"), + None, + "the classifier accepts trusted matched templates, not literal paths" + ); + } + + #[test] + fn known_path_detection_distinguishes_method_fallbacks_from_new_routes() { + assert!(is_known_matched_path("/events")); + assert!(is_known_matched_path("/health")); + assert!(!is_known_matched_path("/new-unclassified-route")); + assert_eq!(allowed_methods("/events").as_deref(), Some("POST")); + assert_eq!(allowed_methods("/info").as_deref(), Some("GET, HEAD")); + assert_eq!(allowed_methods("/new-unclassified-route"), None); + } +} diff --git a/crates/buzz-relay/src/testdata/rsa_private_key_1.der.b64 b/crates/buzz-relay/src/testdata/rsa_private_key_1.der.b64 new file mode 100644 index 0000000000..a7c7aba310 --- /dev/null +++ b/crates/buzz-relay/src/testdata/rsa_private_key_1.der.b64 @@ -0,0 +1 @@ +MIIEpAIBAAKCAQEAyRE6rHuNR0QbHO3H3Kt2pOKGVhQqGZXInOduQNxXzuKlvQTLUTv4l4sggh5/CYYi/cvI+SXVT9kPWSKXxJXBXd/4LkvcPuUakBoAkfh+eiFVMh2VrUyWyj3MFl0HTVF9KwRXLAcwkREiS3npThHRyIxuy0ZMeZfxVL5arMhw1SRELB8HoGfG/AtH89BIE9jDBHZ9dLelK9a184zAf8LwoPLxvJb3Il5nncqPcSfKDDodMFBIMc4lQzDKL5gvmiXLXB1AGLm8KBjfE8s3L5xqi+yUod+j8MtvIj812dkS4QMiRVN/by2h3ZY8LYVGrqZXZTcgn2ujn8uKjXLZVD5TdQIDAQABAoIBAHREk0I0O9DvECKdWUpAmF3mY7oY9PNQiu44Yaf+AoSuyRpRUGTMIgc3u3eivOE8ALX0BmYUO5JtuRNZDpvt4SAwqCnVUinIf6C+eH/wSurCpapSM0BAHp4aOA7igptyOMgMPYBHNA1e9A7jE0dCxKWMl3DSWNyjQTk4zeRGEAEfbNjHrq6YCtjHSZSLmWiG80hnfnYos9hOr5JnLnyS7ZmFE/5P3XVrxLc/tQ5zum0R4cbrgzHiQP5RgfxGJaEi7XcgherCCOgurJSSbYH29Gz8u5fFbS+Yg8s+OiCss3cs1rSgJ9/eHZuzGEdUZVARH6hVMjSuwvqVTFaE8AgtleECgYEA+uLMn4kNqHlJS2A5uAnCkj90ZxEtNm3E8hAxUrhssktY5XSOAPBlxyf5RuRGIImGtUVIr4HuJSa5TX48n3Vdt9MYCprO/iYl6moNRSPt5qowIIOJmIjY2mqPDfDt/zw+fcDD3lmCJrFlzcnh0uea1CohxEbQnL3cypeLt+WbU6kCgYEAzSp19m1ajieFkqgoB0YTpt/OroDx38vvI5unInJlEeOjQ+oIAQdN2wpxBvTrRorMU6P07mFUbt1j+Co6CbNiw+X8HcCaqYLR5clbJOOWNR36PuzOpQLkfK8woupBxzW9B8gZmY8rB1mbJ+/WTPrEJy6YGmIEBkWylQ2VpW8O4O0CgYEApdbvvfFBlwD9YxbrcGz7MeNCFbMz+MucqQntIKoKJ91ImPxvtc0y6e/Rhnv0oyNlaUOwJVu0yNgNG117w0g4t/+Q38mvVC5xV7/cn7x9UMFk6MkqVir3dYGEqIl/OP1grY2Tq9HtB5iyG9L8NIamQOLMyUqqMUILxdthHyFmiGkCgYEAn9+PjpjGMPHxL0gj8Q8VbzsFtou6b1deIRRA2CHmSltltR1gYVTMwXxQeUhPMmgkMqUXzs4/WijgpthY44hK1TaZEKIuoxrS70nJ4WQLf5a9k1065fDsFZD6yGjdGxvwEmlGMZgTwqV7t1I4X0Ilqhav5hcs5apYL7gnPYPeRz0CgYALHCj/Ji8XSsDoF/MhVhnGdIs2P99NNdmo3R2Pv0CuZbDKMU559LJHUvrKS8WkuWRDuKrz1W/EQKApFjDGpdqToZqriUFQzwy7mR3ayIiogzNtHcvbDHx8oFnGY0OFksX/ye0/XGpy2SFxYRwGU98HPYeBvAQQrVjdkzfy7BmXQQ== diff --git a/crates/buzz-relay/src/testdata/rsa_private_key_2.der.b64 b/crates/buzz-relay/src/testdata/rsa_private_key_2.der.b64 new file mode 100644 index 0000000000..90ada9a41f --- /dev/null +++ b/crates/buzz-relay/src/testdata/rsa_private_key_2.der.b64 @@ -0,0 +1 @@ +MIIEpAIBAAKCAQEAuJHF+YJVeiqBYJOXwH2dVRc6KX1gnugROTfrMyIrZJqocAVn2NZE88/yMc2hyh1wKYMQeQlduezrXlTGDLw/d6Ujut9L3ORz8FaaCreIKnwzKCyMjLYW4hjkUwBA0kaUcZPNaBJF7wdB76nI5NV4pXCKaJWyYdVVsj0ygDJGMzwBiYmptBw+HFrDEuR6v30ffU99ACYtAbrcmC+VFApFnEcZmITDXBc+zfYGI6v1k3YIvTDXuIc9/817hfmgHBvJ7bxDWu0aJOi7giP0oyXUtXO/vmgSuyPq4kNJJzTrMeW3lCx++Xda6TGwoLOIUoWS8VfdJh9pCDemoXshUhh4WQIDAQABAoIBABzCHfJUJARuhg0pwh3slKyy+02GqxzndPOQ6nVjsBYzYOZfeUBYlpLUxlyLOVfYQWc+dD0fv/pd14ixtdA7LrpyQUB3VYc8E3KR09uyoCVah9ANLPMp1iPxk/X41qDM/Yk66ej62+m0HEp/Dn3VY0CH6hEErjA/QOSOU4WVD8ogniilnE6//a3dAvRSpd7bJawvzb/zR0G9Eg6LQa2IDZ4gTvBA7dKpY06FPJrnCcxlgkZzLKQY6kCcj/Ln+R2KyQyYwTZCELXlbKmRTaZFxiugMEskB4ffjDJTVO1D62twltX4TsRpfBnS+6sw9n5arKo7EGMLa5wNmCQS1WlBdJ8CgYEA4Gxzzpa/VMaXDT7WZwqhrtQwoLXy0rddTEsw2qITwfvZKEmpYXA6w4Pqxv4JcaBYWnq4pNRr0VGD19uGPZdNJOAEzpdbdwAD5S4Wxj2oDztihARvaESVnobyYKvNDszjbdaK8A6mYMrIat6O8WqvzO5VGF9iF7v8SZR6elFatJMCgYEA0onOZUpOOOw0E9tPZDSWVaO7LBFqts9go81bYXC0I2Ea5bloJbn+ACyCud9ivtPiQtL8SgYM2aiQWNvAnJrlaxhgTktG9Ii7G2u7EoEh9GwoOWyffQbOLJ8d1a1i2tgA9wi5V/I+QX9Kj+xE9mNv9vNJTK1GAbOwkoU5rIdOfuMCgYEAi8sijAIc5nrZppeIyCC4PAXS0Jjly9oKVLbVlKq28fOl/lF8H8Tf5d/rQ88EJPJDdwDQuWPUUUuce74zrXPsytZ8SA/CGqs4we5mo0/OusY8BI4as3FdXaUjn5IEpn58AHROkWAexVYrZ16A3eKd5WJkQU1Q9gXUDiVd8Ylxnd8CgYEAwfLrLMpP1wZZTzWIJIKBPzFO2uDMks3lc+BY3yGpALKSya+MLrzxLY3Te5E68RpV5ENi4HpEWjp7hzAhduMGlyrkhRu5qMlQvIj406ob8oO0ZnoXTmD3i4mlPVO1rm6wLOJfg5IIIeQ2dvEr8mJWIYOrMbSpuiWjcsbCA5q+CAsCgYBjGyJnqilCJ547DIZrW1D5MK1pMGGqdJInmhleHEH8ES/2/O/PnCM5ilxBKjSoSFw8p1Zz0M7QCbVs/wjyCIQfsRvbw/IdyMr2VSL89iMCG/VPls/u403NDH8aeWDChcbkAbEq8BLHT0km0BM9M3HFPjMIQ1xoQvwZWE4GcRWeFQ== diff --git a/desktop/src-tauri/src/commands/profile.rs b/desktop/src-tauri/src/commands/profile.rs index ffc7b1be1e..c870c8f280 100644 --- a/desktop/src-tauri/src/commands/profile.rs +++ b/desktop/src-tauri/src/commands/profile.rs @@ -40,14 +40,21 @@ async fn query_profiles_with_assertions( Ok((query_relay(state, &filters).await?, relay_self)) } +#[derive(Clone, Debug, Eq, PartialEq)] +struct VerifiedIdentity { + display_name: String, + expires_at: u64, +} + fn verified_identities( events: &[nostr::Event], relay_self: Option<&str>, -) -> HashMap { +) -> HashMap { let Some(relay_self) = relay_self else { return HashMap::new(); }; - let mut verified = HashMap::::new(); + let mut verified = HashMap::)>::new(); + let now = nostr::Timestamp::now().as_secs(); for event in events { if event.kind.as_u16() as u32 != KIND_USER_TRUSTED_ASSERTION || !event.pubkey.to_hex().eq_ignore_ascii_case(relay_self) @@ -56,39 +63,91 @@ fn verified_identities( { continue; } + // The coordinate is recoverable even when the newer payload is + // malformed (for example, an overlong `d` tag). That malformed head + // must suppress the prior assertion rather than being skipped. + let Some(subject) = event.tags.iter().find_map(|tag| { + let parts = tag.as_slice(); + (parts.first().is_some_and(|part| part == "d")) + .then(|| parts.get(1).map(|part| part.as_str())) + .flatten() + }) else { + continue; + }; + if subject.len() != 64 || !subject.chars().all(|value| value.is_ascii_hexdigit()) { + continue; + } let tag_value = |name: &str| { - event.tags.iter().find_map(|tag| { + let mut matches = event.tags.iter().filter(|tag| { let parts = tag.as_slice(); - (parts.len() == 2 && parts[0] == name).then(|| parts[1].as_str()) - }) + parts.first().is_some_and(|part| part == name) + }); + let tag = matches.next()?; + if matches.next().is_some() { + return None; + } + let parts = tag.as_slice(); + (parts.len() == 2).then(|| parts[1].as_str()) }; - if tag_value("verified") != Some("relay") { - continue; - } - let (Some(subject), Some(display_name)) = (tag_value("d"), tag_value("display_name")) - else { - continue; + // Select the signed replaceable-event head before validating its + // payload. Otherwise a newer malformed assertion could be skipped and + // silently resurrect the older active label returned alongside it. + let identity = match (tag_value("d"), tag_value("verified"), tag_value("p")) { + (Some(assertion_d), Some("relay"), Some(asserted_subject)) + if assertion_d == subject && asserted_subject == subject => + { + match tag_value("active") { + Some("false") => None, + Some("true") => match ( + tag_value("expiration") + .and_then(|value| value.parse::().ok()) + .filter(|expiration| *expiration > now), + tag_value("display_name") + .map(str::trim) + .filter(|value| !value.is_empty()), + ) { + (Some(expires_at), Some(display_name)) => Some(VerifiedIdentity { + display_name: display_name.to_string(), + expires_at, + }), + _ => None, + }, + _ => None, + } + } + _ => None, }; - if tag_value("p") != Some(subject) - || subject.len() != 64 - || !subject.chars().all(|value| value.is_ascii_hexdigit()) - || display_name.trim().is_empty() - { - continue; - } - let entry = verified - .entry(subject.to_ascii_lowercase()) - .or_insert_with(|| (0, String::new())); - if event.created_at.as_secs() >= entry.0 { - *entry = (event.created_at.as_secs(), display_name.to_string()); + let created_at = event.created_at.as_secs(); + let event_id = event.id.to_hex(); + // NIP-01 replaceable-event ordering: greatest timestamp wins; equal + // timestamps are resolved by the lowest event id. This stays stable + // regardless of relay response order. + match verified.entry(subject.to_ascii_lowercase()) { + std::collections::hash_map::Entry::Vacant(entry) => { + entry.insert((created_at, event_id, identity)); + } + std::collections::hash_map::Entry::Occupied(mut entry) + if created_at > entry.get().0 + || (created_at == entry.get().0 && event_id < entry.get().1) => + { + entry.insert((created_at, event_id, identity)); + } + std::collections::hash_map::Entry::Occupied(_) => {} } } verified .into_iter() - .map(|(pubkey, (_, display_name))| (pubkey, display_name)) + .filter_map(|(pubkey, (_, _, identity))| identity.map(|value| (pubkey, value))) .collect() } +fn apply_verified_identity(profile: &mut ProfileInfo, identity: Option) { + profile.verified_name = identity + .as_ref() + .map(|value| value.display_name.to_string()); + profile.verified_name_expires_at = identity.map(|value| value.expires_at); +} + #[tauri::command] pub async fn get_profile(state: State<'_, AppState>) -> Result { let my_pubkey = current_pubkey_hex(&state)?; @@ -101,8 +160,8 @@ pub async fn get_profile(state: State<'_, AppState>) -> Result ProfileInfo { pubkey: pubkey.to_string(), display_name: None, verified_name: None, + verified_name_expires_at: None, avatar_url: None, about: None, nip05_handle: None, @@ -488,12 +551,15 @@ mod tests { fn verified_identity_requires_relay_signed_nip85_assertion() { let relay = nostr::Keys::generate(); let subject = nostr::Keys::generate().public_key().to_hex(); + let expires_at = nostr::Timestamp::now().as_secs() + 60; let event = nostr::EventBuilder::new(nostr::Kind::Custom(KIND_USER_TRUSTED_ASSERTION as u16), "") .tags([ nostr::Tag::parse(["d", subject.as_str()]).unwrap(), nostr::Tag::parse(["p", subject.as_str()]).unwrap(), nostr::Tag::parse(["verified", "relay"]).unwrap(), + nostr::Tag::parse(["active", "true"]).unwrap(), + nostr::Tag::parse(["expiration", &expires_at.to_string()]).unwrap(), nostr::Tag::parse(["display_name", "Example User"]).unwrap(), ]) .sign_with_keys(&relay) @@ -501,11 +567,190 @@ mod tests { let verified = verified_identities(&[event], Some(&relay.public_key().to_hex())); assert_eq!( - verified.get(&subject).map(String::as_str), - Some("Example User") + verified.get(&subject), + Some(&VerifiedIdentity { + display_name: "Example User".to_string(), + expires_at, + }) ); } + #[test] + fn expired_verified_identity_is_rejected() { + let relay = nostr::Keys::generate(); + let subject = nostr::Keys::generate().public_key().to_hex(); + let created_at = nostr::Timestamp::now().as_secs(); + let expires_at = nostr::Timestamp::now().as_secs().saturating_sub(1); + let prior_expiration = created_at + 120; + let prior = + nostr::EventBuilder::new(nostr::Kind::Custom(KIND_USER_TRUSTED_ASSERTION as u16), "") + .tags([ + nostr::Tag::parse(["d", subject.as_str()]).unwrap(), + nostr::Tag::parse(["p", subject.as_str()]).unwrap(), + nostr::Tag::parse(["verified", "relay"]).unwrap(), + nostr::Tag::parse(["active", "true"]).unwrap(), + nostr::Tag::parse(["expiration", &prior_expiration.to_string()]).unwrap(), + nostr::Tag::parse(["display_name", "Prior User"]).unwrap(), + ]) + .custom_created_at(nostr::Timestamp::from(created_at)) + .sign_with_keys(&relay) + .unwrap(); + let expired = + nostr::EventBuilder::new(nostr::Kind::Custom(KIND_USER_TRUSTED_ASSERTION as u16), "") + .tags([ + nostr::Tag::parse(["d", subject.as_str()]).unwrap(), + nostr::Tag::parse(["p", subject.as_str()]).unwrap(), + nostr::Tag::parse(["verified", "relay"]).unwrap(), + nostr::Tag::parse(["active", "true"]).unwrap(), + nostr::Tag::parse(["expiration", &expires_at.to_string()]).unwrap(), + nostr::Tag::parse(["display_name", "Expired User"]).unwrap(), + ]) + .custom_created_at(nostr::Timestamp::from(created_at + 1)) + .sign_with_keys(&relay) + .unwrap(); + + assert!( + verified_identities(&[prior, expired], Some(&relay.public_key().to_hex())).is_empty() + ); + } + + #[test] + fn newer_inactive_assertion_removes_verified_identity() { + let relay = nostr::Keys::generate(); + let subject = nostr::Keys::generate().public_key().to_hex(); + let created_at = nostr::Timestamp::now().as_secs(); + let expires_at = created_at + 60; + let active = + nostr::EventBuilder::new(nostr::Kind::Custom(KIND_USER_TRUSTED_ASSERTION as u16), "") + .tags([ + nostr::Tag::parse(["d", subject.as_str()]).unwrap(), + nostr::Tag::parse(["p", subject.as_str()]).unwrap(), + nostr::Tag::parse(["verified", "relay"]).unwrap(), + nostr::Tag::parse(["active", "true"]).unwrap(), + nostr::Tag::parse(["expiration", &expires_at.to_string()]).unwrap(), + nostr::Tag::parse(["display_name", "Example User"]).unwrap(), + ]) + .custom_created_at(nostr::Timestamp::from(created_at)) + .sign_with_keys(&relay) + .unwrap(); + let inactive = + nostr::EventBuilder::new(nostr::Kind::Custom(KIND_USER_TRUSTED_ASSERTION as u16), "") + .tags([ + nostr::Tag::parse(["d", subject.as_str()]).unwrap(), + nostr::Tag::parse(["p", subject.as_str()]).unwrap(), + nostr::Tag::parse(["verified", "relay"]).unwrap(), + nostr::Tag::parse(["active", "false"]).unwrap(), + ]) + .custom_created_at(nostr::Timestamp::from(created_at + 1)) + .sign_with_keys(&relay) + .unwrap(); + + assert!( + verified_identities(&[active, inactive], Some(&relay.public_key().to_hex())).is_empty() + ); + } + + #[test] + fn newer_malformed_assertion_does_not_resurrect_older_identity() { + let relay = nostr::Keys::generate(); + let subject = nostr::Keys::generate().public_key().to_hex(); + let wrong_subject = nostr::Keys::generate().public_key().to_hex(); + let created_at = nostr::Timestamp::now().as_secs(); + let expires_at = created_at + 60; + let active = + nostr::EventBuilder::new(nostr::Kind::Custom(KIND_USER_TRUSTED_ASSERTION as u16), "") + .tags([ + nostr::Tag::parse(["d", subject.as_str()]).unwrap(), + nostr::Tag::parse(["p", subject.as_str()]).unwrap(), + nostr::Tag::parse(["verified", "relay"]).unwrap(), + nostr::Tag::parse(["active", "true"]).unwrap(), + nostr::Tag::parse(["expiration", &expires_at.to_string()]).unwrap(), + nostr::Tag::parse(["display_name", "Example User"]).unwrap(), + ]) + .custom_created_at(nostr::Timestamp::from(created_at)) + .sign_with_keys(&relay) + .unwrap(); + let malformed = + nostr::EventBuilder::new(nostr::Kind::Custom(KIND_USER_TRUSTED_ASSERTION as u16), "") + .tags([ + nostr::Tag::parse(["d", subject.as_str()]).unwrap(), + nostr::Tag::parse(["p", wrong_subject.as_str()]).unwrap(), + nostr::Tag::parse(["verified", "relay"]).unwrap(), + nostr::Tag::parse(["active", "true"]).unwrap(), + nostr::Tag::parse(["expiration", &expires_at.to_string()]).unwrap(), + nostr::Tag::parse(["display_name", "Malformed User"]).unwrap(), + ]) + .custom_created_at(nostr::Timestamp::from(created_at + 1)) + .sign_with_keys(&relay) + .unwrap(); + + assert!(verified_identities( + &[active.clone(), malformed], + Some(&relay.public_key().to_hex()) + ) + .is_empty()); + + let overlong_d = + nostr::EventBuilder::new(nostr::Kind::Custom(KIND_USER_TRUSTED_ASSERTION as u16), "") + .tags([ + nostr::Tag::parse(["d", subject.as_str(), "unexpected"]).unwrap(), + nostr::Tag::parse(["p", subject.as_str()]).unwrap(), + nostr::Tag::parse(["verified", "relay"]).unwrap(), + nostr::Tag::parse(["active", "true"]).unwrap(), + nostr::Tag::parse(["expiration", &expires_at.to_string()]).unwrap(), + nostr::Tag::parse(["display_name", "Malformed User"]).unwrap(), + ]) + .custom_created_at(nostr::Timestamp::from(created_at + 1)) + .sign_with_keys(&relay) + .unwrap(); + assert!( + verified_identities(&[active, overlong_d], Some(&relay.public_key().to_hex())) + .is_empty() + ); + } + + #[test] + fn equal_timestamp_assertions_use_lowest_event_id_independent_of_response_order() { + let relay = nostr::Keys::generate(); + let subject = nostr::Keys::generate().public_key().to_hex(); + let created_at = nostr::Timestamp::now().as_secs(); + let expires_at = created_at + 60; + let active = + nostr::EventBuilder::new(nostr::Kind::Custom(KIND_USER_TRUSTED_ASSERTION as u16), "") + .tags([ + nostr::Tag::parse(["d", subject.as_str()]).unwrap(), + nostr::Tag::parse(["p", subject.as_str()]).unwrap(), + nostr::Tag::parse(["verified", "relay"]).unwrap(), + nostr::Tag::parse(["active", "true"]).unwrap(), + nostr::Tag::parse(["expiration", &expires_at.to_string()]).unwrap(), + nostr::Tag::parse(["display_name", "Example User"]).unwrap(), + ]) + .custom_created_at(nostr::Timestamp::from(created_at)) + .sign_with_keys(&relay) + .unwrap(); + let inactive = + nostr::EventBuilder::new(nostr::Kind::Custom(KIND_USER_TRUSTED_ASSERTION as u16), "") + .tags([ + nostr::Tag::parse(["d", subject.as_str()]).unwrap(), + nostr::Tag::parse(["p", subject.as_str()]).unwrap(), + nostr::Tag::parse(["verified", "relay"]).unwrap(), + nostr::Tag::parse(["active", "false"]).unwrap(), + ]) + .custom_created_at(nostr::Timestamp::from(created_at)) + .sign_with_keys(&relay) + .unwrap(); + let relay_pubkey = relay.public_key().to_hex(); + let expected_active = active.id.to_hex() < inactive.id.to_hex(); + + for events in [ + vec![active.clone(), inactive.clone()], + vec![inactive.clone(), active.clone()], + ] { + let actual = verified_identities(&events, Some(&relay_pubkey)); + assert_eq!(actual.contains_key(&subject), expected_active); + } + } + #[test] fn deferred_profile_signer_is_captured_and_rejects_wrong_identity() { let state = crate::app_state::build_app_state(); diff --git a/desktop/src-tauri/src/models.rs b/desktop/src-tauri/src/models.rs index 61b39844ea..c284c0da22 100644 --- a/desktop/src-tauri/src/models.rs +++ b/desktop/src-tauri/src/models.rs @@ -32,6 +32,9 @@ pub struct ProfileInfo { pub display_name: Option, #[serde(default)] pub verified_name: Option, + /// Unix timestamp (seconds) after which `verified_name` must not be shown. + #[serde(default)] + pub verified_name_expires_at: Option, pub avatar_url: Option, pub about: Option, pub nip05_handle: Option, @@ -48,6 +51,9 @@ pub struct UserProfileSummaryInfo { pub display_name: Option, #[serde(default)] pub verified_name: Option, + /// Unix timestamp (seconds) after which `verified_name` must not be shown. + #[serde(default)] + pub verified_name_expires_at: Option, /// Kind-0 `name` field, carried separately from `display_name` so clients /// can match @mention text against either alias (agents and the CLI /// resolve mentions server-side against `display_name` *or* `name`). @@ -72,6 +78,9 @@ pub struct UserSearchResultInfo { pub display_name: Option, #[serde(default)] pub verified_name: Option, + /// Unix timestamp (seconds) after which `verified_name` must not be shown. + #[serde(default)] + pub verified_name_expires_at: Option, pub avatar_url: Option, pub nip05_handle: Option, pub owner_pubkey: Option, diff --git a/desktop/src-tauri/src/nostr_convert.rs b/desktop/src-tauri/src/nostr_convert.rs index cebb575c96..5453e92f5a 100644 --- a/desktop/src-tauri/src/nostr_convert.rs +++ b/desktop/src-tauri/src/nostr_convert.rs @@ -298,6 +298,7 @@ pub fn profile_info_from_event(event: &Event) -> Result { pubkey: event.pubkey.to_hex(), display_name, verified_name: None, + verified_name_expires_at: None, avatar_url, about, nip05_handle, @@ -339,6 +340,7 @@ pub fn users_batch_from_events( .or_else(|| v.get("name").and_then(Value::as_str)) .map(str::to_string), verified_name: None, + verified_name_expires_at: None, name: v.get("name").and_then(Value::as_str).map(str::to_string), avatar_url: v.get("picture").and_then(Value::as_str).map(str::to_string), nip05_handle: v.get("nip05").and_then(Value::as_str).map(str::to_string), diff --git a/desktop/src-tauri/src/nostr_convert/user_search.rs b/desktop/src-tauri/src/nostr_convert/user_search.rs index 6dbc6faff1..fef06e66c8 100644 --- a/desktop/src-tauri/src/nostr_convert/user_search.rs +++ b/desktop/src-tauri/src/nostr_convert/user_search.rs @@ -19,6 +19,7 @@ pub fn user_search_result_from_event(ev: &Event) -> UserSearchResultInfo { .or_else(|| v.get("name").and_then(Value::as_str)) .map(str::to_string), verified_name: None, + verified_name_expires_at: None, avatar_url: v.get("picture").and_then(Value::as_str).map(str::to_string), nip05_handle: v.get("nip05").and_then(Value::as_str).map(str::to_string), is_agent: owner_pubkey.is_some(), diff --git a/desktop/src/features/messages/ui/MessageRow.tsx b/desktop/src/features/messages/ui/MessageRow.tsx index ed264224a2..09f4f2e096 100644 --- a/desktop/src/features/messages/ui/MessageRow.tsx +++ b/desktop/src/features/messages/ui/MessageRow.tsx @@ -579,7 +579,17 @@ export const MessageRow = React.memo( ) : ( authorNode )} - {verifiedName ? : null} + {verifiedName ? ( + + ) : null} {agentOwnerNode} {inlineMetadataNode} {message.personaDisplayName && diff --git a/desktop/src/features/profile/hooks.ts b/desktop/src/features/profile/hooks.ts index 04546804eb..18c6d511af 100644 --- a/desktop/src/features/profile/hooks.ts +++ b/desktop/src/features/profile/hooks.ts @@ -43,12 +43,77 @@ import { } from "@/features/profile/lib/selfProfileStorage"; import { useCommunities } from "@/features/communities/useCommunities"; import { updateCachedChannelMemberDisplayName } from "@/features/channels/channelMemberProfileCache"; +import { useVerifiedIdentityExpiryRevision } from "@/shared/hooks/useVerifiedIdentityExpiry"; +import { + type VerifiedIdentityFields, + withCurrentVerifiedIdentity, +} from "@/shared/lib/verifiedIdentity"; export const profileQueryKey = ["profile"] as const; export const contactListQueryKey = (pubkey: string) => ["contact-list", pubkey] as const; export const allPulseTimelinesQueryKey = ["pulse-timeline"] as const; +function useCurrentVerifiedIdentity( + identity: T | undefined, +): T | undefined { + const revision = useVerifiedIdentityExpiryRevision([ + identity?.verifiedNameExpiresAt, + ]); + return React.useMemo(() => { + // `revision` is the timer-driven cache key for an otherwise unchanged + // React Query value. + void revision; + return identity ? withCurrentVerifiedIdentity(identity) : undefined; + }, [identity, revision]); +} + +function useCurrentVerifiedIdentityRecord( + identities: Record | undefined, +): Record | undefined { + const revision = useVerifiedIdentityExpiryRevision( + identities + ? Object.values(identities).map( + (identity) => identity.verifiedNameExpiresAt, + ) + : [], + ); + return React.useMemo(() => { + void revision; + if (!identities) return undefined; + + let changed = false; + const current = Object.fromEntries( + Object.entries(identities).map(([pubkey, identity]) => { + const next = withCurrentVerifiedIdentity(identity); + changed ||= next !== identity; + return [pubkey, next]; + }), + ); + return changed ? current : identities; + }, [identities, revision]); +} + +function useCurrentVerifiedIdentityList( + identities: T[] | undefined, +): T[] | undefined { + const revision = useVerifiedIdentityExpiryRevision( + identities?.map((identity) => identity.verifiedNameExpiresAt) ?? [], + ); + return React.useMemo(() => { + void revision; + if (!identities) return undefined; + + let changed = false; + const current = identities.map((identity) => { + const next = withCurrentVerifiedIdentity(identity); + changed ||= next !== identity; + return next; + }); + return changed ? current : identities; + }, [identities, revision]); +} + /** * Persists a freshly-fetched profile to localStorage as the offline fallback. * Reuses an existing avatar data URL when the avatar URL is unchanged to avoid @@ -137,7 +202,7 @@ export function useProfileQuery(enabled = true) { ? { initialData, initialDataUpdatedAt: cached?.updatedAt } : {}; - return useQuery({ + const query = useQuery({ enabled, queryKey: profileQueryKey, queryFn: async () => { @@ -150,6 +215,8 @@ export function useProfileQuery(enabled = true) { staleTime: 30_000, ...seedOptions, }); + const profile = useCurrentVerifiedIdentity(query.data); + return profile === query.data ? query : { ...query, data: profile }; } /** @@ -271,12 +338,14 @@ export function useUnfollowMutation(currentPubkey?: string) { } export function useUserProfileQuery(pubkey?: string) { - return useQuery({ + const query = useQuery({ enabled: typeof pubkey === "string" && pubkey.length > 0, queryKey: ["user-profile", pubkey?.toLowerCase() ?? ""], queryFn: () => getUserProfile(pubkey), staleTime: 60_000, }); + const profile = useCurrentVerifiedIdentity(query.data); + return profile === query.data ? query : { ...query, data: profile }; } // Per-pubkey resolution cache backing `useUsersBatchQuery`'s delta fetch. @@ -393,7 +462,15 @@ export function useUsersBatchQuery( } }, [query.data, queryClient]); - return query; + const profiles = useCurrentVerifiedIdentityRecord(query.data?.profiles); + return profiles === query.data?.profiles + ? query + : { + ...query, + data: query.data + ? { ...query.data, profiles: profiles ?? {} } + : query.data, + }; } export function useUserSearchQuery( @@ -409,7 +486,7 @@ export function useUserSearchQuery( (options?.enabled ?? true) && (options?.allowEmpty === true || normalizedQuery.length > 0); - return useQuery({ + const searchQuery = useQuery({ enabled, queryKey: ["user-search", normalizedQuery, options?.limit ?? 8], queryFn: async () => @@ -417,6 +494,10 @@ export function useUserSearchQuery( staleTime: 30_000, gcTime: 5 * 60 * 1_000, }); + const users = useCurrentVerifiedIdentityList(searchQuery.data); + return users === searchQuery.data + ? searchQuery + : { ...searchQuery, data: users }; } export function useInfiniteUserSearchQuery( diff --git a/desktop/src/features/profile/lib/identity.test.mjs b/desktop/src/features/profile/lib/identity.test.mjs index 71e18c53ce..126eb195d2 100644 --- a/desktop/src/features/profile/lib/identity.test.mjs +++ b/desktop/src/features/profile/lib/identity.test.mjs @@ -11,6 +11,8 @@ import { const OWNER_PUBKEY = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; const USER_PUBKEY = "11".repeat(32); +const NOW_MS = 1_800_000_000_000; +const FUTURE_EXPIRATION = NOW_MS / 1_000 + 60; const summary = (over = {}) => ({ displayName: "Ada", @@ -65,6 +67,7 @@ test("profileLookupsEqual: a changed field is not equal", () => { for (const field of [ "displayName", "verifiedName", + "verifiedNameExpiresAt", "avatarUrl", "nip05Handle", "ownerPubkey", @@ -130,13 +133,23 @@ test("stabiliser: a real profile change swaps the reference (re-render fires)", test("formats a chosen name followed by the authoritative display name", () => { assert.equal( - formatVerifiedUserLabel("Example", "example"), + formatVerifiedUserLabel("Example", "example", FUTURE_EXPIRATION, NOW_MS), "Example (example)", ); }); test("does not duplicate equal chosen and authoritative names", () => { - assert.equal(formatVerifiedUserLabel("example", "example"), "example"); + assert.equal( + formatVerifiedUserLabel("example", "example", FUTURE_EXPIRATION, NOW_MS), + "example", + ); +}); + +test("expired authoritative names fail closed", () => { + assert.equal( + formatVerifiedUserLabel("Example", "example", NOW_MS / 1_000, NOW_MS), + "Example", + ); }); test("resolved user labels keep the chosen name first", () => { @@ -147,6 +160,7 @@ test("resolved user labels keep the chosen name first", () => { [USER_PUBKEY]: summary({ displayName: "Example", verifiedName: "example", + verifiedNameExpiresAt: Math.floor(Date.now() / 1_000) + 60, }), }, }), diff --git a/desktop/src/features/profile/lib/identity.ts b/desktop/src/features/profile/lib/identity.ts index 9bfad6a49a..45866ec3cd 100644 --- a/desktop/src/features/profile/lib/identity.ts +++ b/desktop/src/features/profile/lib/identity.ts @@ -1,5 +1,6 @@ import type { Profile, UserProfileSummary } from "@/shared/api/types"; import { normalizePubkey, truncatePubkey } from "@/shared/lib/pubkey"; +import { getCurrentVerifiedName } from "@/shared/lib/verifiedIdentity"; export type UserProfileLookup = Record; @@ -8,9 +9,15 @@ export { truncatePubkey }; export function formatVerifiedUserLabel( chosenName: string | null | undefined, verifiedName: string | null | undefined, + verifiedNameExpiresAt: number | null | undefined, + nowMs = Date.now(), ): string | null { const chosen = chosenName?.trim(); - const verified = verifiedName?.trim(); + const verified = getCurrentVerifiedName( + verifiedName, + verifiedNameExpiresAt, + nowMs, + ); if (chosen && verified && chosen !== verified) { return `${chosen} (${verified})`; @@ -52,6 +59,7 @@ export function profileLookupsEqual( next === undefined || prev.displayName !== next.displayName || prev.verifiedName !== next.verifiedName || + prev.verifiedNameExpiresAt !== next.verifiedNameExpiresAt || prev.name !== next.name || prev.avatarUrl !== next.avatarUrl || prev.nip05Handle !== next.nip05Handle || @@ -81,7 +89,12 @@ export function mergeCurrentProfileIntoLookup( currentProfile: | Pick< Profile, - "pubkey" | "displayName" | "verifiedName" | "avatarUrl" | "nip05Handle" + | "pubkey" + | "displayName" + | "verifiedName" + | "verifiedNameExpiresAt" + | "avatarUrl" + | "nip05Handle" > | null | undefined, @@ -95,6 +108,7 @@ export function mergeCurrentProfileIntoLookup( [normalizePubkey(currentProfile.pubkey)]: { displayName: currentProfile.displayName, verifiedName: currentProfile.verifiedName ?? null, + verifiedNameExpiresAt: currentProfile.verifiedNameExpiresAt ?? null, // `Profile` does not carry the kind-0 `name`; keep whatever the batch // lookup already resolved so mention aliases survive the merge. name: profiles?.[normalizePubkey(currentProfile.pubkey)]?.name ?? null, @@ -132,13 +146,13 @@ export function resolveUserLabel(input: { } const profile = getResolvedProfile(pubkey, profiles); - const verifiedName = profile?.verifiedName?.trim(); const displayName = profile?.displayName?.trim(); const nip05Handle = profile?.nip05Handle?.trim(); const safeFallback = fallbackName?.trim(); const label = formatVerifiedUserLabel( displayName || nip05Handle || safeFallback, - verifiedName, + profile?.verifiedName, + profile?.verifiedNameExpiresAt, ); if (label) { return label; @@ -151,9 +165,10 @@ export function resolveUserVerification(input: { pubkey: string; profiles?: UserProfileLookup; }): string | null { - return ( - getResolvedProfile(input.pubkey, input.profiles)?.verifiedName?.trim() || - null + const profile = getResolvedProfile(input.pubkey, input.profiles); + return getCurrentVerifiedName( + profile?.verifiedName, + profile?.verifiedNameExpiresAt, ); } diff --git a/desktop/src/features/profile/ui/ProfilePopover.tsx b/desktop/src/features/profile/ui/ProfilePopover.tsx index c6b68e0a19..456ea42a31 100644 --- a/desktop/src/features/profile/ui/ProfilePopover.tsx +++ b/desktop/src/features/profile/ui/ProfilePopover.tsx @@ -24,6 +24,7 @@ interface ProfilePopoverProps { onOpenChange: (open: boolean) => void; displayName: string; verifiedName?: string | null; + verifiedNameExpiresAt?: number | null; avatarUrl: string | null; avatarDataUrl?: string | null; currentStatus: PresenceStatus; @@ -55,6 +56,7 @@ export function ProfilePopover({ onOpenChange, displayName, verifiedName, + verifiedNameExpiresAt, avatarUrl, avatarDataUrl, currentStatus, @@ -147,7 +149,10 @@ export function ProfilePopover({ {displayName}

{verifiedName ? ( - + ) : null} {/* ── Presence chip (opens status chooser) ─────────── */} diff --git a/desktop/src/features/profile/ui/UserProfilePanelFields.tsx b/desktop/src/features/profile/ui/UserProfilePanelFields.tsx index 9c0aa81aab..799b039401 100644 --- a/desktop/src/features/profile/ui/UserProfilePanelFields.tsx +++ b/desktop/src/features/profile/ui/UserProfilePanelFields.tsx @@ -24,6 +24,7 @@ import type { RelayAgent, } from "@/shared/api/types"; import { VerifiedBadge } from "@/shared/ui/VerifiedBadge"; +import { getCurrentVerifiedName } from "@/shared/lib/verifiedIdentity"; const RUNTIME_LABELS: Record = { goose: "Goose", @@ -177,7 +178,10 @@ export function buildPublicFields({ }); } - const verifiedName = profile?.verifiedName?.trim(); + const verifiedName = getCurrentVerifiedName( + profile?.verifiedName, + profile?.verifiedNameExpiresAt, + ); if (verifiedName) { fields.push({ displayValue: verifiedName, @@ -186,7 +190,10 @@ export function buildPublicFields({ testId: "user-profile-relay-verified-identity", trailingNode: ( - + Binding active ), diff --git a/desktop/src/features/profile/ui/UserProfilePanelSections.tsx b/desktop/src/features/profile/ui/UserProfilePanelSections.tsx index 01071afcb4..d2b6a8c8e4 100644 --- a/desktop/src/features/profile/ui/UserProfilePanelSections.tsx +++ b/desktop/src/features/profile/ui/UserProfilePanelSections.tsx @@ -51,6 +51,7 @@ import { cn } from "@/shared/lib/cn"; import { Alert, AlertDescription, AlertTitle } from "@/shared/ui/alert"; import { Badge } from "@/shared/ui/badge"; import { VerifiedBadge } from "@/shared/ui/VerifiedBadge"; +import { getCurrentVerifiedName } from "@/shared/lib/verifiedIdentity"; export { AgentInstructionsFocusedView } from "@/features/profile/ui/UserProfilePanelAgentDetails"; @@ -478,6 +479,10 @@ function ProfileHero({ userStatus: ProfileSummaryViewProps["userStatus"]; }) { const presenceDotClassName = isBot ? "h-4.5 w-4.5" : "h-3.5 w-3.5"; + const verifiedName = getCurrentVerifiedName( + profile?.verifiedName, + profile?.verifiedNameExpiresAt, + ); return (
@@ -528,13 +533,16 @@ function ProfileHero({ ) : null}
- {profile?.verifiedName?.trim() ? ( + {verifiedName ? (
- {profile.verifiedName.trim()} - + {verifiedName} +
) : null} diff --git a/desktop/src/features/profile/ui/UserProfilePopover.tsx b/desktop/src/features/profile/ui/UserProfilePopover.tsx index cad007178b..aa7cdac13c 100644 --- a/desktop/src/features/profile/ui/UserProfilePopover.tsx +++ b/desktop/src/features/profile/ui/UserProfilePopover.tsx @@ -237,8 +237,11 @@ export function UserProfilePopover({ managedAgentsQuery.isPending || usersBatchQuery.isPending); const displayName = - formatVerifiedUserLabel(profile?.displayName, profile?.verifiedName) ?? - truncatePubkey(pubkey); + formatVerifiedUserLabel( + profile?.displayName, + profile?.verifiedName, + profile?.verifiedNameExpiresAt, + ) ?? truncatePubkey(pubkey); // Owner signal mirrors UserProfilePanel: a declared NIP-OA owner whose agent // runs elsewhere holds no local seckey, so key custody (`isOwner`) alone // wrongly hides the affordance from them — and gating on bot-ness alone shows @@ -533,7 +536,10 @@ export function UserProfilePopover({
{profile?.verifiedName ? ( - + ) : null} {isBotProfile && botIdenticonValue ? ( {profile?.verifiedName ? ( - + ) : null} diff --git a/desktop/src/shared/api/tauriProfiles.ts b/desktop/src/shared/api/tauriProfiles.ts index e3bc3bff24..abc6cbd8d7 100644 --- a/desktop/src/shared/api/tauriProfiles.ts +++ b/desktop/src/shared/api/tauriProfiles.ts @@ -12,6 +12,7 @@ type RawProfile = { pubkey: string; display_name: string | null; verified_name?: string | null; + verified_name_expires_at?: number | null; avatar_url: string | null; about: string | null; nip05_handle: string | null; @@ -41,6 +42,7 @@ function fromRawProfile(profile: RawProfile): Profile { pubkey: profile.pubkey, displayName: profile.display_name, verifiedName: profile.verified_name ?? null, + verifiedNameExpiresAt: profile.verified_name_expires_at ?? null, avatarUrl: profile.avatar_url, about: profile.about, nip05Handle: profile.nip05_handle, @@ -55,6 +57,7 @@ function fromRawUserProfileSummary( return { displayName: profile.display_name, verifiedName: profile.verified_name ?? null, + verifiedNameExpiresAt: profile.verified_name_expires_at ?? null, name: profile.name ?? null, avatarUrl: profile.avatar_url, nip05Handle: profile.nip05_handle, @@ -68,6 +71,7 @@ function fromRawUserSearchResult(user: RawUserSearchResult): UserSearchResult { pubkey: user.pubkey, displayName: user.display_name, verifiedName: user.verified_name ?? null, + verifiedNameExpiresAt: user.verified_name_expires_at ?? null, avatarUrl: user.avatar_url, nip05Handle: user.nip05_handle, ownerPubkey: user.owner_pubkey, diff --git a/desktop/src/shared/api/types.ts b/desktop/src/shared/api/types.ts index 20ffe32bcd..13d27f6a30 100644 --- a/desktop/src/shared/api/types.ts +++ b/desktop/src/shared/api/types.ts @@ -110,6 +110,8 @@ export type Profile = { displayName: string | null; /** Relay-authoritative display identity bound to this pubkey. */ verifiedName?: string | null; + /** Unix timestamp (seconds) after which `verifiedName` is no longer trusted. */ + verifiedNameExpiresAt?: number | null; avatarUrl: string | null; about: string | null; nip05Handle: string | null; @@ -125,6 +127,8 @@ export type UserProfileSummary = { displayName: string | null; /** Relay-authoritative display identity bound to this pubkey. */ verifiedName?: string | null; + /** Unix timestamp (seconds) after which `verifiedName` is no longer trusted. */ + verifiedNameExpiresAt?: number | null; /** Kind-0 `name` field, kept separate from `displayName` so @mention text * can be matched against either alias (agents/CLI resolve mentions against * `display_name` *or* `name` at send time). */ @@ -144,6 +148,7 @@ export type UserSearchResult = { pubkey: string; displayName: string | null; verifiedName?: string | null; + verifiedNameExpiresAt?: number | null; avatarUrl: string | null; nip05Handle: string | null; ownerPubkey: string | null; diff --git a/desktop/src/shared/hooks/useVerifiedIdentityExpiry.ts b/desktop/src/shared/hooks/useVerifiedIdentityExpiry.ts new file mode 100644 index 0000000000..4012f6fc5d --- /dev/null +++ b/desktop/src/shared/hooks/useVerifiedIdentityExpiry.ts @@ -0,0 +1,44 @@ +import * as React from "react"; + +import { millisecondsUntilVerifiedIdentityExpiry } from "@/shared/lib/verifiedIdentity"; + +const MAX_TIMEOUT_MS = 2_147_483_647; + +/** + * Force a render at the earliest assertion cutoff. Callers then re-run the + * local-clock sanitizer, even when React Query is serving an offline cache. + */ +export function useVerifiedIdentityExpiryRevision( + expirations: ReadonlyArray, +): number { + const nowMs = Date.now(); + let nextDelayMs: number | null = null; + for (const expiresAt of expirations) { + const delayMs = millisecondsUntilVerifiedIdentityExpiry(expiresAt, nowMs); + if ( + delayMs !== null && + delayMs > 0 && + (nextDelayMs === null || delayMs < nextDelayMs) + ) { + nextDelayMs = delayMs; + } + } + + const [revision, setRevision] = React.useState(0); + React.useEffect(() => { + // Re-arm after a timer tick even if a wall-clock adjustment happens to + // produce the same remaining delay as the previous render. + void revision; + if (nextDelayMs === null) { + return; + } + + const timeout = setTimeout( + () => setRevision((current) => current + 1), + Math.min(nextDelayMs + 1, MAX_TIMEOUT_MS), + ); + return () => clearTimeout(timeout); + }, [nextDelayMs, revision]); + + return revision; +} diff --git a/desktop/src/shared/lib/verifiedIdentity.test.mjs b/desktop/src/shared/lib/verifiedIdentity.test.mjs new file mode 100644 index 0000000000..db640aa8d9 --- /dev/null +++ b/desktop/src/shared/lib/verifiedIdentity.test.mjs @@ -0,0 +1,51 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + getCurrentVerifiedName, + millisecondsUntilVerifiedIdentityExpiry, + withCurrentVerifiedIdentity, +} from "./verifiedIdentity.ts"; + +const NOW_MS = 1_800_000_000_000; +const NOW_SECONDS = NOW_MS / 1_000; + +test("returns a verified name only before its local expiration", () => { + assert.equal( + getCurrentVerifiedName(" Example ", NOW_SECONDS + 60, NOW_MS), + "Example", + ); + assert.equal(getCurrentVerifiedName("Example", NOW_SECONDS, NOW_MS), null); +}); + +test("missing and malformed expirations fail closed", () => { + assert.equal(getCurrentVerifiedName("Example", null, NOW_MS), null); + assert.equal( + getCurrentVerifiedName("Example", NOW_SECONDS + 0.5, NOW_MS), + null, + ); + assert.equal(getCurrentVerifiedName("Example", Number.NaN, NOW_MS), null); +}); + +test("computes the exact cutoff delay used by expiry render timers", () => { + assert.equal( + millisecondsUntilVerifiedIdentityExpiry(NOW_SECONDS + 60, NOW_MS), + 60_000, + ); + assert.equal( + millisecondsUntilVerifiedIdentityExpiry(NOW_SECONDS - 1, NOW_MS), + 0, + ); +}); + +test("sanitizes cached identity objects without churning valid values", () => { + const valid = { + verifiedName: "Example", + verifiedNameExpiresAt: NOW_SECONDS + 60, + }; + assert.equal(withCurrentVerifiedIdentity(valid, NOW_MS), valid); + assert.deepEqual(withCurrentVerifiedIdentity(valid, NOW_MS + 60_000), { + verifiedName: null, + verifiedNameExpiresAt: NOW_SECONDS + 60, + }); +}); diff --git a/desktop/src/shared/lib/verifiedIdentity.ts b/desktop/src/shared/lib/verifiedIdentity.ts new file mode 100644 index 0000000000..2c0312d7a3 --- /dev/null +++ b/desktop/src/shared/lib/verifiedIdentity.ts @@ -0,0 +1,57 @@ +export type VerifiedIdentityFields = { + verifiedName?: string | null; + verifiedNameExpiresAt?: number | null; +}; + +function verifiedIdentityExpiryMs( + expiresAt: number | null | undefined, +): number | null { + if (!Number.isSafeInteger(expiresAt) || (expiresAt ?? 0) <= 0) { + return null; + } + + const expiresAtMs = (expiresAt as number) * 1_000; + return Number.isSafeInteger(expiresAtMs) ? expiresAtMs : null; +} + +/** + * Return a verified name only while its relay assertion is still valid. + * Missing or malformed expirations fail closed so old cached responses cannot + * keep a trust label alive while the relay is unreachable. + */ +export function getCurrentVerifiedName( + verifiedName: string | null | undefined, + expiresAt: number | null | undefined, + nowMs = Date.now(), +): string | null { + const name = verifiedName?.trim(); + const expiresAtMs = verifiedIdentityExpiryMs(expiresAt); + if (!name || expiresAtMs === null || expiresAtMs <= nowMs) { + return null; + } + + return name; +} + +export function millisecondsUntilVerifiedIdentityExpiry( + expiresAt: number | null | undefined, + nowMs = Date.now(), +): number | null { + const expiresAtMs = verifiedIdentityExpiryMs(expiresAt); + return expiresAtMs === null ? null : Math.max(0, expiresAtMs - nowMs); +} + +/** Preserve object identity until the verified-name view actually changes. */ +export function withCurrentVerifiedIdentity( + identity: T, + nowMs = Date.now(), +): T { + const verifiedName = getCurrentVerifiedName( + identity.verifiedName, + identity.verifiedNameExpiresAt, + nowMs, + ); + return identity.verifiedName === verifiedName + ? identity + : { ...identity, verifiedName }; +} diff --git a/desktop/src/shared/ui/VerifiedBadge.tsx b/desktop/src/shared/ui/VerifiedBadge.tsx index e4149bb7f1..359639ac0f 100644 --- a/desktop/src/shared/ui/VerifiedBadge.tsx +++ b/desktop/src/shared/ui/VerifiedBadge.tsx @@ -1,11 +1,28 @@ +import { useVerifiedIdentityExpiryRevision } from "@/shared/hooks/useVerifiedIdentityExpiry"; +import { getCurrentVerifiedName } from "@/shared/lib/verifiedIdentity"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/shared/ui/tooltip"; -export function VerifiedBadge({ verifiedName }: { verifiedName: string }) { +export function VerifiedBadge({ + verifiedName, + verifiedNameExpiresAt, +}: { + verifiedName: string; + verifiedNameExpiresAt: number | null | undefined; +}) { + useVerifiedIdentityExpiryRevision([verifiedNameExpiresAt]); + const currentVerifiedName = getCurrentVerifiedName( + verifiedName, + verifiedNameExpiresAt, + ); + if (!currentVerifiedName) { + return null; + } + return ( -

Verified as {verifiedName}

+

Verified as {currentVerifiedName}

); diff --git a/docs/CORPORATE_IDENTITY.md b/docs/CORPORATE_IDENTITY.md new file mode 100644 index 0000000000..00b47b42bd --- /dev/null +++ b/docs/CORPORATE_IDENTITY.md @@ -0,0 +1,78 @@ +# Corporate identity + +Corporate identity is an optional relay policy enabled with +`BUZZ_REQUIRE_CORPORATE_IDENTITY=true`. The relay verifies an asymmetric JWT +after the request proves control of a Nostr key, then admits the request only +when the existing community policy also succeeds. + +## Required JWT policy + +- `BUZZ_CORPORATE_IDENTITY_JWKS_URI` must be HTTPS and contain no credentials. +- JWTs must have a supported asymmetric algorithm, a `kid`, and valid `exp`, + `iss`, and `aud` claims. A present `nbf` claim is enforced. +- `BUZZ_CORPORATE_IDENTITY_NPUB_CLAIM`, when configured, is mandatory and must + equal the authenticated Nostr key. Leaving it unset enables first-use + uid-to-key enrollment in the private binding table. +- JWKS requests have connect and total timeouts, reject redirects, cap the + response at 1 MiB, cache keys for five minutes, and coalesce refreshes. + +`BUZZ_REQUIRE_CORPORATE_IDENTITY` and +`BUZZ_ALLOW_CORPORATE_IDENTITY_DELEGATION` are strict booleans. Misspellings and +non-UTF-8 values stop configuration loading instead of silently disabling a +gate. + +## Binding and revocation lifecycle + +JWT validation is read-only. The relay creates or refreshes a binding only +after admission, allowlist, role, and community membership checks succeed. +Invite claims commit the binding, membership, policy evidence, and invite use +in one PostgreSQL transaction. + +Revocation has three explicit meanings: + +- `principal` disables every key for an issuer-qualified uid. Normal + authentication cannot re-enroll the principal with another key. +- `key` revokes one key but does not silently authorize a replacement. +- `rotation` is the audit state written by an explicit atomic old-key to + new-key rotation. + +WebSocket and audio sessions revalidate the authoritative binding at least +every 30 seconds. Direct sessions also close at JWT expiry. Delegated sessions +check the owner's binding, so disabling an owner evicts the owner's agents as +well as the direct owner session. + +Corporate NIP-OA delegation is transport-wide and therefore accepts only an +empty conditions string. Conditional tags must be evaluated for a specific +operation and are not treated as blanket corporate identity authority. + +## Privacy and public assertions + +`BUZZ_CORPORATE_IDENTITY_DISPLAY_CLAIM` is private. Its default (`email`) is +stored only in the community-scoped binding table and audit data; it is not +published to Nostr. + +Public projection is separately opt-in with +`BUZZ_CORPORATE_IDENTITY_PUBLIC_DISPLAY_CLAIM`. When set, that claim is +published as a relay-signed NIP-85 label. Assertions carry both `active=true` +and an `expiration` no later than one hour or the JWT's expiry, whichever comes +first. Clients require the relay signature, active status, and a future +expiration. Removing the opt-in publishes an inactive replacement only when a +prior public assertion exists. + +NIP-85 events are replaceable relay events and may also remain in downstream +caches or archives after replacement. Operators must choose a non-sensitive, +user-approved public label and account for that retention when configuring the +public claim. + +## Route policy + +Corporate identity applies to authenticated WebSocket and audio connections, +the NIP-98 event/query/count bridge, moderation reads, invite mint and claim, +Git smart HTTP, media uploads, and protected media reads. + +Intentional exemptions are public media reads when media GET authentication is +disabled, health/readiness/metrics endpoints, NIP-11 and NIP-05 discovery, +operator and admin control planes with their own authentication, secret-backed +workflow hooks, public join-policy documents, invite policy-acceptance +callbacks, and static local web callbacks. These exemptions must remain in the +central route-policy test matrix when routes change. diff --git a/migrations/0028_identity_binding_lifecycle.sql b/migrations/0028_identity_binding_lifecycle.sql new file mode 100644 index 0000000000..a1bc42bf7d --- /dev/null +++ b/migrations/0028_identity_binding_lifecycle.sql @@ -0,0 +1,94 @@ +-- Explicit corporate identity revocation and rotation semantics. +-- +-- principal: disables every key for the issuer-qualified principal. +-- key: revokes only this key; a different key still requires an explicit +-- operator rotation because ordinary authentication never replaces an +-- active binding. +-- rotation: records the old key retired by an authorized atomic rotation. + +ALTER TABLE identity_bindings + ADD COLUMN revocation_scope TEXT NOT NULL DEFAULT 'principal' + CHECK (revocation_scope IN ('principal', 'key', 'rotation')), + ADD COLUMN rotation_completed_at TIMESTAMPTZ, + ADD COLUMN rotated_to_pubkey BYTEA, + ADD COLUMN rotation_by BYTEA, + ADD COLUMN rotation_reason TEXT, + ADD CONSTRAINT chk_identity_bindings_rotation_state CHECK ( + (rotation_completed_at IS NULL + AND rotated_to_pubkey IS NULL + AND rotation_by IS NULL + AND rotation_reason IS NULL) + OR + (rotation_completed_at IS NOT NULL + AND rotated_to_pubkey IS NOT NULL + AND length(rotated_to_pubkey) = 32 + AND (rotation_by IS NULL OR length(rotation_by) = 32) + AND rotation_reason IS NOT NULL + AND length(rotation_reason) > 0) + ); + +CREATE INDEX idx_identity_bindings_revoked_principal + ON identity_bindings (community_id, issuer, uid) + WHERE revoked_at IS NOT NULL AND revocation_scope = 'principal'; + +-- Principal status is separate from key history so operators can disable a +-- principal before first enrollment and after a single-key revocation. +CREATE TABLE identity_principals ( + community_id UUID NOT NULL REFERENCES communities(id), + issuer TEXT NOT NULL, + uid TEXT NOT NULL, + disabled_at TIMESTAMPTZ, + disabled_by BYTEA, + disabled_reason TEXT, + PRIMARY KEY (community_id, issuer, uid), + CHECK (length(issuer) > 0), + CHECK (length(uid) > 0), + CHECK (disabled_by IS NULL OR length(disabled_by) = 32), + CHECK ((disabled_at IS NULL) = (disabled_reason IS NULL)) +); + +-- Rows revoked before this lifecycle migration represented principal-level +-- disablement. Preserve that security state instead of allowing the same uid +-- to re-enroll with a fresh key after upgrade. +INSERT INTO identity_principals + (community_id, issuer, uid, disabled_at, disabled_by, disabled_reason) +SELECT DISTINCT ON (community_id, issuer, uid) + community_id, + issuer, + uid, + revoked_at, + revoked_by, + COALESCE(NULLIF(revoked_reason, ''), 'legacy principal revocation') +FROM identity_bindings +WHERE revoked_at IS NOT NULL +ORDER BY community_id, issuer, uid, revoked_at ASC; + +-- A revoked credential cannot be rebound to a different principal in the +-- same community. Explicit rotation may consume an old revoked key, but may +-- never select a revoked key as the replacement. +CREATE TABLE identity_revoked_keys ( + community_id UUID NOT NULL REFERENCES communities(id), + pubkey BYTEA NOT NULL, + revoked_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + revoked_by BYTEA, + reason TEXT NOT NULL, + PRIMARY KEY (community_id, pubkey), + CHECK (length(pubkey) = 32), + CHECK (revoked_by IS NULL OR length(revoked_by) = 32), + CHECK (length(reason) > 0) +); + +-- Preserve every pre-migration revoked credential as a community-wide key +-- tombstone. This prevents a legacy-revoked key from binding to a different +-- issuer-qualified principal after upgrade. +INSERT INTO identity_revoked_keys + (community_id, pubkey, revoked_at, revoked_by, reason) +SELECT DISTINCT ON (community_id, pubkey) + community_id, + pubkey, + revoked_at, + revoked_by, + COALESCE(NULLIF(revoked_reason, ''), 'legacy key revocation') +FROM identity_bindings +WHERE revoked_at IS NOT NULL +ORDER BY community_id, pubkey, revoked_at ASC; diff --git a/schema/schema.sql b/schema/schema.sql index 88c457805f..3ce067ee34 100644 --- a/schema/schema.sql +++ b/schema/schema.sql @@ -188,9 +188,8 @@ CREATE UNIQUE INDEX idx_users_okta ON users (community_id, okta_user_id) -- Conformance: verified identity is community-scoped. An issuer-qualified uid -- is the stable product/user-management identity; a Nostr pubkey is the -- protocol credential currently bound to it. This table is intentionally a --- binding foundation, not a full grant/session lifecycle model. Revocation --- columns are reserved for follow-up admin/rotation flows, while PR1 only --- creates or validates active bindings during existing auth paths. +-- binding and lifecycle authority. Revocation scope distinguishes principal +-- disablement, a single-key revocation, and an operator-authorized rotation. CREATE TABLE identity_bindings ( community_id UUID NOT NULL REFERENCES communities(id), @@ -205,10 +204,29 @@ CREATE TABLE identity_bindings ( revoked_at TIMESTAMPTZ, revoked_by BYTEA, revoked_reason TEXT, + revocation_scope TEXT NOT NULL DEFAULT 'principal' + CHECK (revocation_scope IN ('principal', 'key', 'rotation')), + rotation_completed_at TIMESTAMPTZ, + rotated_to_pubkey BYTEA, + rotation_by BYTEA, + rotation_reason TEXT, CONSTRAINT chk_identity_bindings_issuer_not_empty CHECK (length(issuer) > 0), CONSTRAINT chk_identity_bindings_uid_not_empty CHECK (length(uid) > 0), CONSTRAINT chk_identity_bindings_pubkey_len CHECK (length(pubkey) = 32), - CONSTRAINT chk_identity_bindings_revoked_by_len CHECK (revoked_by IS NULL OR length(revoked_by) = 32) + CONSTRAINT chk_identity_bindings_revoked_by_len CHECK (revoked_by IS NULL OR length(revoked_by) = 32), + CONSTRAINT chk_identity_bindings_rotation_state CHECK ( + (rotation_completed_at IS NULL + AND rotated_to_pubkey IS NULL + AND rotation_by IS NULL + AND rotation_reason IS NULL) + OR + (rotation_completed_at IS NOT NULL + AND rotated_to_pubkey IS NOT NULL + AND length(rotated_to_pubkey) = 32 + AND (rotation_by IS NULL OR length(rotation_by) = 32) + AND rotation_reason IS NOT NULL + AND length(rotation_reason) > 0) + ) ); CREATE UNIQUE INDEX idx_identity_bindings_active_principal @@ -219,6 +237,35 @@ CREATE UNIQUE INDEX idx_identity_bindings_active_pubkey WHERE revoked_at IS NULL; CREATE INDEX idx_identity_bindings_pubkey ON identity_bindings (community_id, pubkey); +CREATE INDEX idx_identity_bindings_revoked_principal + ON identity_bindings (community_id, issuer, uid) + WHERE revoked_at IS NOT NULL AND revocation_scope = 'principal'; + +CREATE TABLE identity_principals ( + community_id UUID NOT NULL REFERENCES communities(id), + issuer TEXT NOT NULL, + uid TEXT NOT NULL, + disabled_at TIMESTAMPTZ, + disabled_by BYTEA, + disabled_reason TEXT, + PRIMARY KEY (community_id, issuer, uid), + CHECK (length(issuer) > 0), + CHECK (length(uid) > 0), + CHECK (disabled_by IS NULL OR length(disabled_by) = 32), + CHECK ((disabled_at IS NULL) = (disabled_reason IS NULL)) +); + +CREATE TABLE identity_revoked_keys ( + community_id UUID NOT NULL REFERENCES communities(id), + pubkey BYTEA NOT NULL, + revoked_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + revoked_by BYTEA, + reason TEXT NOT NULL, + PRIMARY KEY (community_id, pubkey), + CHECK (length(pubkey) = 32), + CHECK (revoked_by IS NULL OR length(revoked_by) = 32), + CHECK (length(reason) > 0) +); -- ── Events (partitioned by month on created_at) ────────────────────────────── -- Conformance: "Channel-less global events and DMs". `community_id` leads the