Skip to content

Commit da6051f

Browse files
npub17jjz49l9jjmhhk7cac63j8yt9z555n9cw8vk7v5jz4vzw4ppld5qgj57ccTyler Longwell
andcommitted
test(conformance): fill api_tokens_nip98_replay row — doc-only api_token half + wire-driven NIP-98 replay half
Fills both `pending_lane` stubs in `mod api_tokens_nip98_replay`: # `token_minted_in_a_does_not_authorize_in_b` — doc-only The api_token mint surface does not exist on the wire in `buzz-relay`: no `/tokens` route in `router.rs:52-79` (verified by hand on PR head), no `tokens` module in `crates/buzz-relay/src/api/`. The 792-line self-service minting endpoint that existed pre-rewrite (sprout-relay PR block#37, commit `f84da74d3`) was deliberately not ported. Api_tokens are *consumed* (not minted) by the Blossom upload path at `media.rs:638`. This means "mint in A, present to B" has no wire precondition — a wire-driven row would test a contract with no entry point. The honest shape is doc-only, mirroring `audit_log`: where audit proves the *output* surface does not exist on the wire, api_tokens proves the *input* surface does not. Both are strictly stronger isolation claims than a wire-denied assertion. The `(community_id, token_hash)` fence itself is directly proven at the storage layer (where direct Postgres access is in-convention): * `crates/buzz-db/src/api_token.rs:425 lookup_by_hash_is_scoped_to_community` — same hash in A and B, A-scoped lookup returns A only. * `crates/buzz-db/src/api_token.rs:488 active_lookup_by_hash_is_scoped_to_community` — mirror for the revoked-filter variant. Plus the consumer fence: `media.rs:638` calls the scoped DB lookup with `tenant.community()` derived from request host *before* token resolution (`media.rs:97` comment names the row-44 fence explicitly). # `nip98_replay_seenset_is_shared_and_community_scoped` — wire-driven Load-bearing wire claim: within-community replay rejection. Sign a NIP-98 event E for A's `u=`, POST to A → 200. POST again → 401 with a body that names replay detection. The proof that the shared (cross-pod) seen-set is in the request path at all — without it, any pod would re-honor a spent NIP-98 event. Mutate-bite: `check_nip98_replay → noop` in `bridge.rs:79` (return `Ok(())` without consulting the guard). Under mutation, second POST goes 200 instead of 401. Test asserts the failure with named assertion message pointing at the mutate-bite handle, so a future reader sees what would have been caught. Cross-community independence is a *tripwire*, not a bite: sign an independent NIP-98 event E' for B's `u=` (different event_id by u-tag canonicalization divergence), POST to B → 200 even though E was spent in A. Catches future namespace-globalization regressions (key truncation, u-normalization collapse) that would break the spend-spread, on top of the unit-layer proof at `crates/buzz-auth/src/nip98_replay.rs:163 key_isolates_communities_for_same_event_id` (which the substrate's own doc-comment names as "belt-and-suspenders"). The prefix-drop mutation considered earlier turned out to be vacuous against natural wire traffic: u-tag divergence across communities makes event_ids already community-distinct, so dropping the community prefix from `nip98_replay_key` does not collapse natural traffic into a shared slot. A same-event_id-different-community wire collision can't be constructed because u-host (`verify_bridge_auth`) rejects with 401 before the replay check runs. That artificial property is proven at the unit layer; the wire layer asserts the load-bearing per-call replay rejection. # Bar * `cargo check -p buzz-test-client --tests`: clean. * `cargo clippy -p buzz-test-client --tests -- -D warnings`: clean. * `cargo fmt -p buzz-test-client -- --check`: clean. * Default test run (no `--ignored`): 1 passed (doc-only `#[test]`), 16 ignored (live rows). * `--ignored api_tokens` against fresh `:3300` harness (`BUZZ_GIT_CONFORMANCE_PROBE=false`): GREEN. * Mutate-bite `check_nip98_replay → noop` on `bridge.rs:79`, rebuild, restart: RED on the within-A second-POST assertion ("second POST to A with the same NIP-98 event MUST be rejected as replay (got 200 OK)"), `left: 200, right: 401`. Restored byte-identical, GREEN again. Base: PR block#1321 head `ae703c5c8`. Test-only diff: zero lines in `buzz-db`, `buzz-relay`, or `buzz-auth` production code. Matrix 8/14. Co-authored-by: Tyler Longwell <[email protected]> Signed-off-by: Tyler Longwell <[email protected]>
1 parent ae703c5 commit da6051f

1 file changed

Lines changed: 308 additions & 12 deletions

File tree

‎crates/buzz-test-client/tests/conformance_multitenant.rs‎

Lines changed: 308 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -538,27 +538,323 @@ mod nip11_relay_info {
538538
mod api_tokens_nip98_replay {
539539
use super::*;
540540

541+
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
542+
use nostr::{EventBuilder, Keys, Kind, Tag};
543+
use sha2::{Digest, Sha256};
544+
541545
/// Obligation: token hash uniqueness/lookup is `(community_id, token_hash)`;
542546
/// a token minted in A does not authorize the same hash in B.
543-
#[tokio::test]
544-
#[ignore]
545-
async fn token_minted_in_a_does_not_authorize_in_b() {
546-
pending_lane(
547-
"buzz-auth",
548-
"identical token_hash in A and B → A's token rejected against B",
549-
);
547+
///
548+
/// **This row is doc-only — and that is the honest answer.**
549+
///
550+
/// Every other wire-driven row in this file proves a black-box property: a
551+
/// client addresses the relay over HTTP/WS and observes that the response
552+
/// denies a cross-community oracle. This row's obligation cannot be tested
553+
/// that way because **the api_token mint surface does not exist on the wire
554+
/// in `buzz-relay`** — there is no route by which a client can bind a token
555+
/// to a community over HTTP, so the "mint in A, present to B" precondition
556+
/// has no entry point.
557+
///
558+
/// Verified on PR head:
559+
/// * `crates/buzz-relay/src/router.rs:52-79` — full route list is `/`,
560+
/// `/info`, `/.well-known/nostr.json`, `/health`, `/_liveness`,
561+
/// `/_readiness`, `/events`, `/query`, `/count`, `/hooks/{id}`, plus
562+
/// the media, git, and git-policy sub-routers. **No `/tokens` route.**
563+
/// * `crates/buzz-relay/src/api/` directory is `{bridge, events, media,
564+
/// nip05, git/, mod}` — no `tokens` module. The 792-line
565+
/// `crates/sprout-relay/src/api/tokens.rs` self-service-minting
566+
/// endpoint that existed pre-rewrite (PR #37, commit `f84da74d3`) was
567+
/// deliberately not ported. Porting it to enable this row would be a
568+
/// product + security-surface decision, not a test-enablement task.
569+
/// * Api_tokens are consumed (not minted) by the Blossom upload path at
570+
/// `crates/buzz-relay/src/api/media.rs:638`, which extracts the
571+
/// `X-Auth-Token: buzz_*` header and looks up
572+
/// `state.db.get_api_token_by_hash_including_revoked(tenant.community(),
573+
/// &hash)`. The comment immediately above that call names the row-44
574+
/// fence explicitly: *"A token minted in community A presented to a
575+
/// host that resolves to community B must not authorize."*
576+
///
577+
/// So where other rows prove *the oracle is denied*, api_tokens proves
578+
/// *the oracle's input surface does not exist* — a sibling of the
579+
/// `audit_log` row (whose proof is that the *output* surface does not
580+
/// exist). Both are strictly stronger than a wire-denied assertion, and
581+
/// the honest way to state it is to cite the facts, not to invent an
582+
/// out-of-band mint path that would break the conformance file's black-box
583+
/// contract (its deps are `buzz-ws-client`/`reqwest`/`tokio-tungstenite`/
584+
/// `s3` — no `sqlx`, no `buzz-db`).
585+
///
586+
/// The `(community_id, token_hash)` fence itself is proven directly at the
587+
/// storage layer, where direct Postgres access is in-convention:
588+
///
589+
/// 1. `crates/buzz-db/src/api_token.rs:425
590+
/// lookup_by_hash_is_scoped_to_community` — inserts two rows with
591+
/// **identical 32-byte hash** in communities A and B (legal under
592+
/// `UNIQUE(community_id, token_hash)`), then asserts A-scoped lookup
593+
/// returns A's row only, B-scoped lookup returns B's row only, and a
594+
/// third (unrelated) community returns None. The mutate-bite handle
595+
/// is named in the test's doc-comment: strip `AND community_id = $1`
596+
/// from `get_api_token_by_hash_including_revoked` and the lookup
597+
/// becomes hash-only, returning whichever row Postgres picks
598+
/// first — the cross-tenancy assertion fails. Sharp row-44 shape.
599+
/// 2. `crates/buzz-db/src/api_token.rs:488
600+
/// active_lookup_by_hash_is_scoped_to_community` — mirror for the
601+
/// `revoked_at IS NULL` variant `Db::get_api_token_by_hash`. Same
602+
/// shape: same hash, distinct communities, scoped lookup returns the
603+
/// caller's row only.
604+
///
605+
/// And the consumer fence — `media.rs:638` — calls the scoped DB lookup
606+
/// with `tenant.community()` derived from the request host *before* token
607+
/// resolution (`media.rs:97` comment: *"This MUST run before scope
608+
/// resolution so the API-token lookup is keyed on (community_id,
609+
/// token_hash). Resolving scopes without a tenant in hand would query
610+
/// api_tokens by hash alone, defeating the cross-community fence."*).
611+
///
612+
/// Substrate on PR head: `api_tokens` table has UNIQUE index
613+
/// `(community_id, token_hash)`; `CommunityId` is a server-resolved type
614+
/// (never client input); `tenant.community()` is bound from the request
615+
/// host by `bind_community` before any tenant-scoped DB read or write.
616+
#[test]
617+
fn token_minted_in_a_does_not_authorize_in_b() {
618+
// Compile-time anchor: this row is doc-only by design. The proof lives
619+
// in the cited storage-layer unit tests; the wire surface for minting
620+
// does not exist (see module doc-comment for the verified route list).
621+
// If anyone adds a `/tokens` route to `buzz-relay`, this row's shape
622+
// should be revisited and a wire-driven body added.
550623
}
551624

552625
/// Obligation: NIP-98 replay seen-set is shared (any-pod) AND community
553-
/// scoped: a nonce spent in A is still spendable in B, but a replay within A
554-
/// is rejected from any pod.
626+
/// scoped: a nonce spent in A is still spendable in B, but a replay within
627+
/// A is rejected from any pod.
628+
///
629+
/// # Wire-observable claim and what bites it
630+
///
631+
/// The load-bearing wire-observable property is **within-community replay
632+
/// rejection**: a NIP-98 event posted twice to the same community must be
633+
/// rejected on the second attempt. This is the proof that the shared
634+
/// (cross-pod) seen-set is in the request path at all — without it, any
635+
/// pod would happily re-honor a spent NIP-98 event.
636+
///
637+
/// Mutate-bite for this assertion: turn `check_nip98_replay` into a no-op
638+
/// in `crates/buzz-relay/src/api/bridge.rs:79` (return `Ok(())` before
639+
/// consulting the guard). Under the mutation, the second POST goes 200
640+
/// instead of 401 → the within-community replay assertion fails RED. The
641+
/// bite fires on the replay check itself, not on a sibling fence.
642+
///
643+
/// # Why the cross-community independence arm is a tripwire, not a bite
644+
///
645+
/// The obligation's cross-community arm — "a nonce spent in A is still
646+
/// spendable in B" — IS asserted by this test, but as a **positive
647+
/// control** rather than a mutate-bite. Reasoning:
648+
///
649+
/// The replay key shape is `buzz:{community}:nip98:{event_id_hex}` (see
650+
/// `crates/buzz-auth/src/nip98_replay.rs:103 nip98_replay_key`). The
651+
/// community prefix is what makes the key per-community; the
652+
/// `event_id_hex` is what makes it per-event. **On natural wire traffic
653+
/// the event_id is already community-distinct**, because the NIP-98 `u`
654+
/// tag is part of the signed canonical bytes and the per-tenant host
655+
/// binding (see `verify_bridge_auth` + `nip98_expected_url` after the
656+
/// row-44 sibling fix `bf8a1a4fa`) forces the `u` to differ per community.
657+
/// So two events posted to A and B respectively are signed against
658+
/// different `u` values → they have different event_ids → their seen-set
659+
/// keys have different suffixes → they do not collide *regardless of
660+
/// whether the community prefix is present*.
661+
///
662+
/// This means the community prefix is **structurally redundant for
663+
/// natural wire traffic**. It is load-bearing only against an artificial
664+
/// "same event_id surfaces in two communities" scenario, which content-
665+
/// addressing makes implausible. The substrate's own doc-comment for the
666+
/// unit test that proves the prefix isolates such artificial collisions
667+
/// names the property as exactly that: "**Belt-and-suspenders**: even if a
668+
/// same-id event surfaces in two communities (which content-addressing
669+
/// makes implausible), the seen-set MUST consult two distinct rows."
670+
/// (`crates/buzz-auth/src/nip98_replay.rs:163
671+
/// key_isolates_communities_for_same_event_id`.)
672+
///
673+
/// Why u-host can't be bypassed to manufacture a wire collision: the
674+
/// bridge processes requests in this order (`bridge.rs:242-259`):
675+
/// 1. `bind_community` from request `Host` header (row-zero fence)
676+
/// 2. `nip98_expected_url(state.config.relay_url, &tenant, "/events")`
677+
/// builds the per-tenant expected `u`
678+
/// 3. `verify_bridge_auth` rejects with 401 unless the signed event's
679+
/// `u` tag matches the per-tenant expected URL
680+
/// 4. **Only then** is `check_nip98_replay` called
681+
///
682+
/// A same-physical-event posted to both A and B would be rejected at step
683+
/// 3 (u-host mismatch) for one of the two hosts, so it never reaches the
684+
/// replay check from a wire test. The replay-prefix-drop mutation
685+
/// proposed in earlier design rounds turned out to be vacuous against
686+
/// natural wire traffic; a wire-driven bite on the prefix's load-
687+
/// bearingness against the artificial-collision case is not constructible
688+
/// from this file's black-box vantage point. The unit test cited above
689+
/// proves it at the layer where the artificial construction is possible.
690+
///
691+
/// What the tripwire DOES catch: a future regression that globalizes the
692+
/// seen-set namespace by truncating or normalizing the key (e.g.,
693+
/// "simplifying" the key to just `buzz:nip98:{event_id}`, or
694+
/// canonicalizing `u` in a way that collapses cross-tenant `u` values
695+
/// into the same event_id) would break the "spend in A doesn't burn the
696+
/// slot in B" arm even though u-tags differ. The tripwire assertion gives
697+
/// such a regression somewhere to land at the wire layer, on top of the
698+
/// unit-layer same-id-collision proof.
699+
///
700+
/// # Test layout
701+
///
702+
/// Two distinct keypairs per community (Eva's setup-equivalence vacuity
703+
/// scar: distinct values make any leak surface as wrong-pubkey-spent /
704+
/// wrong-content-stored, not silent-absent). The wire surface is `POST
705+
/// /events` with `Authorization: Nostr <base64-NIP-98-event>`. Bodies are
706+
/// minimal valid kind:1 nostr events authored by the same NIP-98 signer
707+
/// (relay-membership is open under `BUZZ_REQUIRE_AUTH_TOKEN=false`).
555708
#[tokio::test]
556709
#[ignore]
557710
async fn nip98_replay_seenset_is_shared_and_community_scoped() {
558-
pending_lane(
559-
"buzz-auth",
560-
"replay key (community_id, event_id) in shared store; u-host must match req.community",
711+
let http_a = to_http(&url_a());
712+
let http_b = to_http(&url_b());
713+
714+
// Distinct keypairs per community — if the seen-set ever leaked into
715+
// a globalized namespace via a regression in u-canonicalization, the
716+
// tripwire assertion below catches it because B's post would 401 as
717+
// "already spent" using A's key's slot.
718+
let keys_a = Keys::generate();
719+
let keys_b = Keys::generate();
720+
assert_ne!(
721+
keys_a.public_key().to_hex(),
722+
keys_b.public_key().to_hex(),
723+
"test design requires distinct keys per community"
561724
);
725+
726+
// (1) Within-community replay rejection — the load-bearing wire bite.
727+
//
728+
// Sign a NIP-98 event E with u = A's /events URL, post it to A → must
729+
// 200. Post the exact same NIP-98 event again to A → must 401 with a
730+
// body that names replay detection. The mutate-bite is `check_nip98_
731+
// replay → noop` in `bridge.rs:79`; under that mutation the second
732+
// post goes 200 because the seen-set is not consulted, and this
733+
// assertion fails RED on the within-community arm.
734+
let events_url_a = format!("{http_a}/events");
735+
let body_a = build_kind1_event_json(&keys_a, "A within-community replay test");
736+
let auth_a_first = build_nip98_header(&keys_a, &events_url_a, "POST", body_a.as_bytes());
737+
738+
let client = reqwest::Client::new();
739+
let first_a = client
740+
.post(&events_url_a)
741+
.header("Authorization", &auth_a_first)
742+
.header("Content-Type", "application/json")
743+
.body(body_a.clone())
744+
.send()
745+
.await
746+
.unwrap_or_else(|e| panic!("first POST to A failed: {e}"));
747+
assert!(
748+
first_a.status().is_success(),
749+
"first NIP-98 post to A must succeed, got {} (body: {})",
750+
first_a.status(),
751+
first_a.text().await.unwrap_or_default(),
752+
);
753+
754+
// Repost the SAME NIP-98 event (byte-identical Authorization header,
755+
// byte-identical body — same canonical event id).
756+
let second_a = client
757+
.post(&events_url_a)
758+
.header("Authorization", &auth_a_first)
759+
.header("Content-Type", "application/json")
760+
.body(body_a)
761+
.send()
762+
.await
763+
.unwrap_or_else(|e| panic!("second POST to A failed: {e}"));
764+
assert_eq!(
765+
second_a.status(),
766+
reqwest::StatusCode::UNAUTHORIZED,
767+
"second POST to A with the same NIP-98 event MUST be rejected as \
768+
replay (got {}) — if this returns 200, the shared seen-set is \
769+
not in the request path. Mutate-bite handle: \
770+
`check_nip98_replay` in bridge.rs:79.",
771+
second_a.status(),
772+
);
773+
let second_a_body = second_a.text().await.unwrap_or_default();
774+
assert!(
775+
second_a_body.contains("replay"),
776+
"second POST to A's 401 body should name replay detection, got: \
777+
{second_a_body:?}",
778+
);
779+
780+
// (2) Cross-community spend-spread — tripwire, no mutate-bite.
781+
//
782+
// Sign an independent NIP-98 event E' for B's /events URL (different
783+
// u → different event_id by signed-canonical divergence). Post E' to
784+
// B → must 200 even though E was already spent in A. This catches a
785+
// future namespace-globalization regression in the seen-set (e.g.,
786+
// key truncation, u-normalization collapse) by giving such a
787+
// regression somewhere to land at the wire layer. The cross-
788+
// community-prefix isolation property against an artificial same-id
789+
// collision is proven at the unit layer by
790+
// `nip98_replay.rs:163 key_isolates_communities_for_same_event_id`.
791+
let events_url_b = format!("{http_b}/events");
792+
let body_b = build_kind1_event_json(&keys_b, "B cross-community spread test");
793+
let auth_b = build_nip98_header(&keys_b, &events_url_b, "POST", body_b.as_bytes());
794+
795+
let first_b = client
796+
.post(&events_url_b)
797+
.header("Authorization", &auth_b)
798+
.header("Content-Type", "application/json")
799+
.body(body_b)
800+
.send()
801+
.await
802+
.unwrap_or_else(|e| panic!("POST to B failed: {e}"));
803+
assert!(
804+
first_b.status().is_success(),
805+
"POST of an independent NIP-98 event to B must succeed (200) — \
806+
A's spent nonce must not burn B's seen-set slot. Got {} (body: \
807+
{}). Tripwire: if this fails, the seen-set namespace has been \
808+
globalized and the per-community scope is broken. The artificial \
809+
same-event_id-different-community case is proven separately at \
810+
`crates/buzz-auth/src/nip98_replay.rs:163 \
811+
key_isolates_communities_for_same_event_id`.",
812+
first_b.status(),
813+
first_b.text().await.unwrap_or_default(),
814+
);
815+
}
816+
817+
/// Build a `Authorization: Nostr <base64>` header value for NIP-98 HTTP
818+
/// auth (kind 27235 `HttpAuth` with `u`/`method`/`payload` tags). Mirrors
819+
/// the pattern in `crates/buzz-auth/src/nip98.rs` and the helper in
820+
/// `crates/buzz-test-client/tests/e2e_tokens.rs:52` — kept local to this
821+
/// row so the conformance file's rows stay self-contained.
822+
fn build_nip98_header(keys: &Keys, url: &str, method: &str, body: &[u8]) -> String {
823+
let payload_hash = hex::encode(Sha256::digest(body));
824+
let tags = vec![
825+
Tag::parse(["u", url]).expect("u tag"),
826+
Tag::parse(["method", method]).expect("method tag"),
827+
Tag::parse(["payload", &payload_hash]).expect("payload tag"),
828+
];
829+
let event = EventBuilder::new(Kind::HttpAuth, "")
830+
.tags(tags)
831+
.sign_with_keys(keys)
832+
.expect("sign NIP-98 event");
833+
let json = nostr::JsonUtil::as_json(&event);
834+
let encoded = BASE64.encode(json.as_bytes());
835+
format!("Nostr {encoded}")
836+
}
837+
838+
/// Build a minimal kind:1 nostr event JSON for the bridge ingest path.
839+
/// The body is just a valid signed event — the test does not care about
840+
/// the content beyond it surviving relay-side parsing.
841+
fn build_kind1_event_json(keys: &Keys, content: &str) -> String {
842+
let event = EventBuilder::new(Kind::TextNote, content)
843+
.sign_with_keys(keys)
844+
.expect("sign kind:1");
845+
nostr::JsonUtil::as_json(&event)
846+
}
847+
848+
/// Convert any base form to `http(s)://` for REST.
849+
fn to_http(base: &str) -> String {
850+
if base.starts_with("http://") || base.starts_with("https://") {
851+
base.trim_end_matches('/').to_string()
852+
} else {
853+
base.replace("wss://", "https://")
854+
.replace("ws://", "http://")
855+
.trim_end_matches('/')
856+
.to_string()
857+
}
562858
}
563859
}
564860

0 commit comments

Comments
 (0)