Skip to content

Commit 0bf52ba

Browse files
rmichelenaclaude
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 3a3806e commit 0bf52ba

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
@@ -722,6 +722,22 @@ jobs:
722722
--run-ignored ignored-only
723723
env:
724724
DATABASE_URL: postgres://buzz:${{ env.BUZZ_TEST_POSTGRES_PASSWORD }}@localhost:5432/buzz
725+
- name: NIP-OA owner materialization gate tests
726+
# Call-site integration for agent→owner materialization: a direct
727+
# member's attestation is recorded on a closed relay, while a
728+
# non-member owner and an expired attestation are refused. Selected by
729+
# name because these span two modules (api::bridge, handlers::auth) and
730+
# nothing else runs this crate's default test set — a test added here
731+
# without this step would never execute. Needs Redis as well as
732+
# Postgres: the submit path takes the NIP-98 replay guard.
733+
run: |
734+
cargo nextest run \
735+
--archive-file target/ci/backend-integration-tests.tar.zst \
736+
-E 'package(buzz-relay) and test(/nip_oa_owner_/)' \
737+
--run-ignored ignored-only
738+
env:
739+
DATABASE_URL: postgres://buzz:${{ env.BUZZ_TEST_POSTGRES_PASSWORD }}@localhost:5432/buzz
740+
REDIS_URL: redis://localhost:6379
725741
- name: NIP-ER reminder e2e
726742
# Feature e2e for NIP-ER (Event Reminders, kind:30300): write-path
727743
# 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
@@ -3819,4 +3819,258 @@ mod tests {
38193819
"attribution line must carry the pubkey;\nlog:\n{log}"
38203820
);
38213821
}
3822+
// ── NIP-OA owner materialization over the real HTTP path ────────────────
3823+
//
3824+
// These enter at `submit_event_authed`, the authenticated core of
3825+
// `POST /events`: everything outside it is NIP-98 verification and the
3826+
// attribution log, and everything the owner path touches — the membership
3827+
// gate, `resolve_nip_oa_owner`, `materialize_nip_oa_owner` — is inside.
3828+
// Reverting the production call site makes the first test below fail,
3829+
// which the previous pure unit tests did not.
3830+
//
3831+
// `#[ignore]`d because they need Postgres and Redis; CI selects them by
3832+
// name (`test(/nip_oa_owner_/)`), since no job runs this crate's default
3833+
// test set.
3834+
3835+
async fn nip_oa_test_state() -> Option<(Arc<AppState>, sqlx::PgPool)> {
3836+
let mut config = crate::config::Config::from_env().ok()?;
3837+
// The regression is closed-relay-only: on an open relay the owner was
3838+
// always recorded.
3839+
config.require_relay_membership = true;
3840+
let pool = sqlx::PgPool::connect(&config.database_url).await.ok()?;
3841+
let db = buzz_db::Db::from_pool(pool.clone());
3842+
let redis_pool = deadpool_redis::Config::from_url(&config.redis_url)
3843+
.create_pool(Some(deadpool_redis::Runtime::Tokio1))
3844+
.ok()?;
3845+
let pubsub = Arc::new(
3846+
buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone())
3847+
.await
3848+
.ok()?,
3849+
);
3850+
let audit = buzz_audit::AuditService::new(pool.clone());
3851+
let auth = buzz_auth::AuthService::new(config.auth.clone());
3852+
let search = buzz_search::SearchService::new(pool.clone());
3853+
let workflow_engine = Arc::new(buzz_workflow::WorkflowEngine::new(
3854+
db.clone(),
3855+
buzz_workflow::WorkflowConfig::default(),
3856+
));
3857+
let media_storage = buzz_media::MediaStorage::new(&config.media).ok()?;
3858+
let (state, _audit_shutdown) = AppState::new(
3859+
config,
3860+
db,
3861+
redis_pool,
3862+
audit,
3863+
pubsub,
3864+
auth,
3865+
search,
3866+
workflow_engine,
3867+
Keys::generate(),
3868+
media_storage,
3869+
);
3870+
Some((Arc::new(state), pool))
3871+
}
3872+
3873+
async fn seed_community(pool: &sqlx::PgPool) -> TenantContext {
3874+
let id = uuid::Uuid::new_v4();
3875+
let host = format!("nip-oa-{}.example", id.simple());
3876+
sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)")
3877+
.bind(id)
3878+
.bind(&host)
3879+
.execute(pool)
3880+
.await
3881+
.expect("insert test community");
3882+
TenantContext::resolved(buzz_core::CommunityId::from_uuid(id), host)
3883+
}
3884+
3885+
/// A signed event for the request body. Its ingest outcome is irrelevant:
3886+
/// owner materialization happens before ingest, so the assertion holds
3887+
/// whether or not the event itself is accepted.
3888+
fn body_event(keys: &Keys) -> Vec<u8> {
3889+
let event = EventBuilder::new(Kind::TextNote, "nip-oa owner materialization probe")
3890+
.sign_with_keys(keys)
3891+
.expect("sign body event");
3892+
serde_json::to_vec(&event).expect("serialize body event")
3893+
}
3894+
3895+
fn auth_tag_headers(tag_json: &str) -> HeaderMap {
3896+
let mut headers = HeaderMap::new();
3897+
headers.insert("x-auth-tag", tag_json.parse().expect("header value"));
3898+
headers
3899+
}
3900+
3901+
async fn stored_owner(
3902+
state: &AppState,
3903+
tenant: &TenantContext,
3904+
agent: &nostr::PublicKey,
3905+
) -> Option<Vec<u8>> {
3906+
state
3907+
.db
3908+
.get_agent_channel_policy(tenant.community(), agent.as_bytes())
3909+
.await
3910+
.expect("read agent policy")
3911+
.and_then(|(_, owner)| owner)
3912+
}
3913+
3914+
/// Run one `POST /events` submission as `agent`, presenting `tag_json`.
3915+
async fn submit_with_tag(
3916+
state: &Arc<AppState>,
3917+
tenant: &TenantContext,
3918+
agent: &Keys,
3919+
tag_json: Option<&str>,
3920+
auth_event_created_at: u64,
3921+
) {
3922+
let headers = match tag_json {
3923+
Some(tag) => auth_tag_headers(tag),
3924+
None => HeaderMap::new(),
3925+
};
3926+
submit_event_authed(
3927+
state,
3928+
tenant,
3929+
&headers,
3930+
&body_event(agent),
3931+
agent.public_key(),
3932+
fresh_nip98_event_id_bytes(),
3933+
Some(auth_event_created_at),
3934+
)
3935+
.await;
3936+
}
3937+
3938+
/// The regression itself: a direct relay member on a closed relay presents
3939+
/// a valid attestation, and the owner is recorded. Before the fix this
3940+
/// silently resolved to no owner, so `owner_only` policies had nothing to
3941+
/// match and observer frames were refused.
3942+
#[tokio::test]
3943+
#[ignore = "requires Postgres and Redis"]
3944+
async fn nip_oa_owner_http_records_owner_for_direct_member() {
3945+
let Some((state, pool)) = nip_oa_test_state().await else {
3946+
return;
3947+
};
3948+
let tenant = seed_community(&pool).await;
3949+
let agent = Keys::generate();
3950+
let owner = Keys::generate();
3951+
3952+
for pubkey in [agent.public_key(), owner.public_key()] {
3953+
state
3954+
.db
3955+
.add_relay_member(tenant.community(), &pubkey.to_hex(), "member", None)
3956+
.await
3957+
.expect("add relay member");
3958+
}
3959+
3960+
let tag = buzz_sdk::nip_oa::compute_auth_tag(&owner, &agent.public_key(), "")
3961+
.expect("compute auth tag");
3962+
submit_with_tag(&state, &tenant, &agent, Some(&tag), 1_000).await;
3963+
3964+
assert_eq!(
3965+
stored_owner(&state, &tenant, &agent.public_key()).await,
3966+
Some(owner.public_key().to_bytes().to_vec()),
3967+
"a direct member's verified owner must be recorded on a closed relay",
3968+
);
3969+
}
3970+
3971+
/// A member cannot mint a throwaway keypair, attest itself, and have that
3972+
/// key trusted: the resolved owner selects the agent rate class and is
3973+
/// first-write-wins, so an untrusted key must never reach the record.
3974+
#[tokio::test]
3975+
#[ignore = "requires Postgres and Redis"]
3976+
async fn nip_oa_owner_http_refuses_an_owner_that_is_not_a_relay_member() {
3977+
let Some((state, pool)) = nip_oa_test_state().await else {
3978+
return;
3979+
};
3980+
let tenant = seed_community(&pool).await;
3981+
let agent = Keys::generate();
3982+
let stranger = Keys::generate();
3983+
3984+
state
3985+
.db
3986+
.add_relay_member(
3987+
tenant.community(),
3988+
&agent.public_key().to_hex(),
3989+
"member",
3990+
None,
3991+
)
3992+
.await
3993+
.expect("add relay member");
3994+
3995+
let tag = buzz_sdk::nip_oa::compute_auth_tag(&stranger, &agent.public_key(), "")
3996+
.expect("compute auth tag");
3997+
submit_with_tag(&state, &tenant, &agent, Some(&tag), 1_000).await;
3998+
3999+
assert_eq!(
4000+
stored_owner(&state, &tenant, &agent.public_key()).await,
4001+
None,
4002+
"a non-member owner must not be recorded on a closed relay",
4003+
);
4004+
}
4005+
4006+
/// A signature that verifies is not a credential that is valid: an expired
4007+
/// attestation must not materialize, or expiry means nothing.
4008+
#[tokio::test]
4009+
#[ignore = "requires Postgres and Redis"]
4010+
async fn nip_oa_owner_http_refuses_an_expired_attestation() {
4011+
let Some((state, pool)) = nip_oa_test_state().await else {
4012+
return;
4013+
};
4014+
let tenant = seed_community(&pool).await;
4015+
let agent = Keys::generate();
4016+
let owner = Keys::generate();
4017+
4018+
for pubkey in [agent.public_key(), owner.public_key()] {
4019+
state
4020+
.db
4021+
.add_relay_member(tenant.community(), &pubkey.to_hex(), "member", None)
4022+
.await
4023+
.expect("add relay member");
4024+
}
4025+
4026+
let expired =
4027+
buzz_sdk::nip_oa::compute_auth_tag(&owner, &agent.public_key(), "created_at<1000")
4028+
.expect("compute auth tag");
4029+
// Auth event is at the bound, which is outside it — bounds are strict.
4030+
submit_with_tag(&state, &tenant, &agent, Some(&expired), 1_000).await;
4031+
4032+
assert_eq!(
4033+
stored_owner(&state, &tenant, &agent.public_key()).await,
4034+
None,
4035+
"an expired attestation must not be materialized",
4036+
);
4037+
4038+
// Same tag, inside its window: proves the refusal above is the time
4039+
// bound and not some unrelated rejection.
4040+
submit_with_tag(&state, &tenant, &agent, Some(&expired), 999).await;
4041+
assert_eq!(
4042+
stored_owner(&state, &tenant, &agent.public_key()).await,
4043+
Some(owner.public_key().to_bytes().to_vec()),
4044+
"the same attestation inside its window must be recorded",
4045+
);
4046+
}
4047+
4048+
/// Membership alone never invents an owner.
4049+
#[tokio::test]
4050+
#[ignore = "requires Postgres and Redis"]
4051+
async fn nip_oa_owner_http_without_a_tag_records_nothing() {
4052+
let Some((state, pool)) = nip_oa_test_state().await else {
4053+
return;
4054+
};
4055+
let tenant = seed_community(&pool).await;
4056+
let agent = Keys::generate();
4057+
4058+
state
4059+
.db
4060+
.add_relay_member(
4061+
tenant.community(),
4062+
&agent.public_key().to_hex(),
4063+
"member",
4064+
None,
4065+
)
4066+
.await
4067+
.expect("add relay member");
4068+
4069+
submit_with_tag(&state, &tenant, &agent, None, 1_000).await;
4070+
4071+
assert_eq!(
4072+
stored_owner(&state, &tenant, &agent.public_key()).await,
4073+
None,
4074+
);
4075+
}
38224076
}

0 commit comments

Comments
 (0)