Skip to content

Commit a590b2b

Browse files
rmichelenaclaude
authored andcommitted
test(relay): cover NIP-OA owner materialization through both real paths
The unit tests this replaces did not protect the regression: reverting both production call sites left them green, because they exercised the helper rather than its callers. Seven Postgres-backed tests now enter at the production call sites — HTTP at `submit_event_authed`, the authenticated core of `POST /events`, and WebSocket at `handle_auth` itself. Verified by reverting each fix in turn: reverting the HTTP one fails `nip_oa_owner_http_records_owner_for_direct_member` and `..._refuses_an_expired_attestation`; reverting the WebSocket one fails `nip_oa_owner_ws_records_owner_and_sets_auth_context`. That also proves the tests genuinely execute rather than skipping — a skipped test cannot fail. Only the positive-recording cases discriminate. With the old code nothing is ever materialized on a closed relay, so the refusal cases hold vacuously there; they guard the new trust boundary, not the original regression. Coverage: owner recorded for a direct member; non-member owner refused; expired attestation refused, with the same tag accepted one second inside its window so the refusal is attributable to the time bound and not to some unrelated rejection; no tag records nothing; and on the WebSocket path the owner reaching the live `AuthContext`, which is what observer-frame authorization and the agent rate class both read. **And a CI step that selects them.** Without it these would satisfy the acceptance criterion on paper and still never run: `just test-unit` does not list `buzz-relay`, `run-tests.sh integration` only picks up `tests/` targets and this crate has none, and `ci.yml` selected just two `buzz-relay` modules by name. Every unit test in this crate — including the four being replaced — has therefore never executed in CI. The new step selects by test name rather than module because the tests span `api::bridge` and `handlers::auth`, and sets `REDIS_URL` as well as `DATABASE_URL` since the submit path takes the NIP-98 replay guard. NIP-42 rejects a stale AUTH event, so the WebSocket tests stamp at the real clock and express the tag's bounds relative to it — which is also how a live deployment presents an expiring credential. Refs block#4223, block#4937, block#4260. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Roberto Michelena <[email protected]>
1 parent 0820dea commit a590b2b

3 files changed

Lines changed: 537 additions & 0 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -721,6 +721,22 @@ jobs:
721721
--run-ignored ignored-only
722722
env:
723723
DATABASE_URL: postgres://buzz:${{ env.BUZZ_TEST_POSTGRES_PASSWORD }}@localhost:5432/buzz
724+
- name: NIP-OA owner materialization gate tests
725+
# Call-site integration for agent→owner materialization: a direct
726+
# member's attestation is recorded on a closed relay, while a
727+
# non-member owner and an expired attestation are refused. Selected by
728+
# name because these span two modules (api::bridge, handlers::auth) and
729+
# nothing else runs this crate's default test set — a test added here
730+
# without this step would never execute. Needs Redis as well as
731+
# Postgres: the submit path takes the NIP-98 replay guard.
732+
run: |
733+
cargo nextest run \
734+
--archive-file target/ci/backend-integration-tests.tar.zst \
735+
-E 'package(buzz-relay) and test(/nip_oa_owner_/)' \
736+
--run-ignored ignored-only
737+
env:
738+
DATABASE_URL: postgres://buzz:${{ env.BUZZ_TEST_POSTGRES_PASSWORD }}@localhost:5432/buzz
739+
REDIS_URL: redis://localhost:6379
724740
- name: NIP-ER reminder e2e
725741
# Feature e2e for NIP-ER (Event Reminders, kind:30300): write-path
726742
# validation, author-only read filtering, and scheduler delivery against

‎crates/buzz-relay/src/api/bridge.rs‎

Lines changed: 254 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3895,4 +3895,258 @@ mod tests {
38953895
"attribution line must carry the pubkey;\nlog:\n{log}"
38963896
);
38973897
}
3898+
// ── NIP-OA owner materialization over the real HTTP path ────────────────
3899+
//
3900+
// These enter at `submit_event_authed`, the authenticated core of
3901+
// `POST /events`: everything outside it is NIP-98 verification and the
3902+
// attribution log, and everything the owner path touches — the membership
3903+
// gate, `resolve_nip_oa_owner`, `materialize_nip_oa_owner` — is inside.
3904+
// Reverting the production call site makes the first test below fail,
3905+
// which the previous pure unit tests did not.
3906+
//
3907+
// `#[ignore]`d because they need Postgres and Redis; CI selects them by
3908+
// name (`test(/nip_oa_owner_/)`), since no job runs this crate's default
3909+
// test set.
3910+
3911+
async fn nip_oa_test_state() -> Option<(Arc<AppState>, sqlx::PgPool)> {
3912+
let mut config = crate::config::Config::from_env().ok()?;
3913+
// The regression is closed-relay-only: on an open relay the owner was
3914+
// always recorded.
3915+
config.require_relay_membership = true;
3916+
let pool = sqlx::PgPool::connect(&config.database_url).await.ok()?;
3917+
let db = buzz_db::Db::from_pool(pool.clone());
3918+
let redis_pool = deadpool_redis::Config::from_url(&config.redis_url)
3919+
.create_pool(Some(deadpool_redis::Runtime::Tokio1))
3920+
.ok()?;
3921+
let pubsub = Arc::new(
3922+
buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone())
3923+
.await
3924+
.ok()?,
3925+
);
3926+
let audit = buzz_audit::AuditService::new(pool.clone());
3927+
let auth = buzz_auth::AuthService::new(config.auth.clone());
3928+
let search = buzz_search::SearchService::new(pool.clone());
3929+
let workflow_engine = Arc::new(buzz_workflow::WorkflowEngine::new(
3930+
db.clone(),
3931+
buzz_workflow::WorkflowConfig::default(),
3932+
));
3933+
let media_storage = buzz_media::MediaStorage::new(&config.media).ok()?;
3934+
let (state, _audit_shutdown) = AppState::new(
3935+
config,
3936+
db,
3937+
redis_pool,
3938+
audit,
3939+
pubsub,
3940+
auth,
3941+
search,
3942+
workflow_engine,
3943+
Keys::generate(),
3944+
media_storage,
3945+
);
3946+
Some((Arc::new(state), pool))
3947+
}
3948+
3949+
async fn seed_community(pool: &sqlx::PgPool) -> TenantContext {
3950+
let id = uuid::Uuid::new_v4();
3951+
let host = format!("nip-oa-{}.example", id.simple());
3952+
sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)")
3953+
.bind(id)
3954+
.bind(&host)
3955+
.execute(pool)
3956+
.await
3957+
.expect("insert test community");
3958+
TenantContext::resolved(buzz_core::CommunityId::from_uuid(id), host)
3959+
}
3960+
3961+
/// A signed event for the request body. Its ingest outcome is irrelevant:
3962+
/// owner materialization happens before ingest, so the assertion holds
3963+
/// whether or not the event itself is accepted.
3964+
fn body_event(keys: &Keys) -> Vec<u8> {
3965+
let event = EventBuilder::new(Kind::TextNote, "nip-oa owner materialization probe")
3966+
.sign_with_keys(keys)
3967+
.expect("sign body event");
3968+
serde_json::to_vec(&event).expect("serialize body event")
3969+
}
3970+
3971+
fn auth_tag_headers(tag_json: &str) -> HeaderMap {
3972+
let mut headers = HeaderMap::new();
3973+
headers.insert("x-auth-tag", tag_json.parse().expect("header value"));
3974+
headers
3975+
}
3976+
3977+
async fn stored_owner(
3978+
state: &AppState,
3979+
tenant: &TenantContext,
3980+
agent: &nostr::PublicKey,
3981+
) -> Option<Vec<u8>> {
3982+
state
3983+
.db
3984+
.get_agent_channel_policy(tenant.community(), agent.as_bytes())
3985+
.await
3986+
.expect("read agent policy")
3987+
.and_then(|(_, owner)| owner)
3988+
}
3989+
3990+
/// Run one `POST /events` submission as `agent`, presenting `tag_json`.
3991+
async fn submit_with_tag(
3992+
state: &Arc<AppState>,
3993+
tenant: &TenantContext,
3994+
agent: &Keys,
3995+
tag_json: Option<&str>,
3996+
auth_event_created_at: u64,
3997+
) {
3998+
let headers = match tag_json {
3999+
Some(tag) => auth_tag_headers(tag),
4000+
None => HeaderMap::new(),
4001+
};
4002+
submit_event_authed(
4003+
state,
4004+
tenant,
4005+
&headers,
4006+
&body_event(agent),
4007+
agent.public_key(),
4008+
fresh_nip98_event_id_bytes(),
4009+
Some(auth_event_created_at),
4010+
)
4011+
.await;
4012+
}
4013+
4014+
/// The regression itself: a direct relay member on a closed relay presents
4015+
/// a valid attestation, and the owner is recorded. Before the fix this
4016+
/// silently resolved to no owner, so `owner_only` policies had nothing to
4017+
/// match and observer frames were refused.
4018+
#[tokio::test]
4019+
#[ignore = "requires Postgres and Redis"]
4020+
async fn nip_oa_owner_http_records_owner_for_direct_member() {
4021+
let Some((state, pool)) = nip_oa_test_state().await else {
4022+
return;
4023+
};
4024+
let tenant = seed_community(&pool).await;
4025+
let agent = Keys::generate();
4026+
let owner = Keys::generate();
4027+
4028+
for pubkey in [agent.public_key(), owner.public_key()] {
4029+
state
4030+
.db
4031+
.add_relay_member(tenant.community(), &pubkey.to_hex(), "member", None)
4032+
.await
4033+
.expect("add relay member");
4034+
}
4035+
4036+
let tag = buzz_sdk::nip_oa::compute_auth_tag(&owner, &agent.public_key(), "")
4037+
.expect("compute auth tag");
4038+
submit_with_tag(&state, &tenant, &agent, Some(&tag), 1_000).await;
4039+
4040+
assert_eq!(
4041+
stored_owner(&state, &tenant, &agent.public_key()).await,
4042+
Some(owner.public_key().to_bytes().to_vec()),
4043+
"a direct member's verified owner must be recorded on a closed relay",
4044+
);
4045+
}
4046+
4047+
/// A member cannot mint a throwaway keypair, attest itself, and have that
4048+
/// key trusted: the resolved owner selects the agent rate class and is
4049+
/// first-write-wins, so an untrusted key must never reach the record.
4050+
#[tokio::test]
4051+
#[ignore = "requires Postgres and Redis"]
4052+
async fn nip_oa_owner_http_refuses_an_owner_that_is_not_a_relay_member() {
4053+
let Some((state, pool)) = nip_oa_test_state().await else {
4054+
return;
4055+
};
4056+
let tenant = seed_community(&pool).await;
4057+
let agent = Keys::generate();
4058+
let stranger = Keys::generate();
4059+
4060+
state
4061+
.db
4062+
.add_relay_member(
4063+
tenant.community(),
4064+
&agent.public_key().to_hex(),
4065+
"member",
4066+
None,
4067+
)
4068+
.await
4069+
.expect("add relay member");
4070+
4071+
let tag = buzz_sdk::nip_oa::compute_auth_tag(&stranger, &agent.public_key(), "")
4072+
.expect("compute auth tag");
4073+
submit_with_tag(&state, &tenant, &agent, Some(&tag), 1_000).await;
4074+
4075+
assert_eq!(
4076+
stored_owner(&state, &tenant, &agent.public_key()).await,
4077+
None,
4078+
"a non-member owner must not be recorded on a closed relay",
4079+
);
4080+
}
4081+
4082+
/// A signature that verifies is not a credential that is valid: an expired
4083+
/// attestation must not materialize, or expiry means nothing.
4084+
#[tokio::test]
4085+
#[ignore = "requires Postgres and Redis"]
4086+
async fn nip_oa_owner_http_refuses_an_expired_attestation() {
4087+
let Some((state, pool)) = nip_oa_test_state().await else {
4088+
return;
4089+
};
4090+
let tenant = seed_community(&pool).await;
4091+
let agent = Keys::generate();
4092+
let owner = Keys::generate();
4093+
4094+
for pubkey in [agent.public_key(), owner.public_key()] {
4095+
state
4096+
.db
4097+
.add_relay_member(tenant.community(), &pubkey.to_hex(), "member", None)
4098+
.await
4099+
.expect("add relay member");
4100+
}
4101+
4102+
let expired =
4103+
buzz_sdk::nip_oa::compute_auth_tag(&owner, &agent.public_key(), "created_at<1000")
4104+
.expect("compute auth tag");
4105+
// Auth event is at the bound, which is outside it — bounds are strict.
4106+
submit_with_tag(&state, &tenant, &agent, Some(&expired), 1_000).await;
4107+
4108+
assert_eq!(
4109+
stored_owner(&state, &tenant, &agent.public_key()).await,
4110+
None,
4111+
"an expired attestation must not be materialized",
4112+
);
4113+
4114+
// Same tag, inside its window: proves the refusal above is the time
4115+
// bound and not some unrelated rejection.
4116+
submit_with_tag(&state, &tenant, &agent, Some(&expired), 999).await;
4117+
assert_eq!(
4118+
stored_owner(&state, &tenant, &agent.public_key()).await,
4119+
Some(owner.public_key().to_bytes().to_vec()),
4120+
"the same attestation inside its window must be recorded",
4121+
);
4122+
}
4123+
4124+
/// Membership alone never invents an owner.
4125+
#[tokio::test]
4126+
#[ignore = "requires Postgres and Redis"]
4127+
async fn nip_oa_owner_http_without_a_tag_records_nothing() {
4128+
let Some((state, pool)) = nip_oa_test_state().await else {
4129+
return;
4130+
};
4131+
let tenant = seed_community(&pool).await;
4132+
let agent = Keys::generate();
4133+
4134+
state
4135+
.db
4136+
.add_relay_member(
4137+
tenant.community(),
4138+
&agent.public_key().to_hex(),
4139+
"member",
4140+
None,
4141+
)
4142+
.await
4143+
.expect("add relay member");
4144+
4145+
submit_with_tag(&state, &tenant, &agent, None, 1_000).await;
4146+
4147+
assert_eq!(
4148+
stored_owner(&state, &tenant, &agent.public_key()).await,
4149+
None,
4150+
);
4151+
}
38984152
}

0 commit comments

Comments
 (0)