Files
buzz/crates/buzz-relay/src/api/invites.rs
Will Pfleger 792a9ce563 feat(relay): list and revoke invite links (#9680)
Stack: this PR → #9690

## What this does

Adds listing and revocation for v2 invite links, and makes every reader
of an invite's expiry accept a missing value.

- **`GET /api/invites?limit=&before=`** lists the community's v2
invites, newest first: id, creator, created/expiry/revoked times, uses
and a computed `status` (`active`, `revoked`, `expired`, `exhausted`).
Owner/admin only. The NIP-98 signature covers the full URL including the
query. `limit` defaults to 50 (max 200). `next_before` is an opaque
cursor holding the last row's `created_at` (microseconds) and id, so
paging doesn't depend on that row still existing.
- **`POST /api/invites/revoke`** takes exactly one of `{"id": "<uuid>"}`
or `{"code": "v2...."}`. The code is hashed and looked up only inside
the request's community. v1 and malformed codes get `400
invite_not_revocable`; an invite not in the community gets 404. Revoking
twice returns the first `revoked_at`. Members who already joined stay.
- **Authorization.** Mint, list and revoke share one HTTP admission
helper (tenant bind → NIP-98 via NIP-FI → replay → membership/ban →
NIP-OA owner link → role gate). Revoke's final decision is made in the
write transaction, in the same order as mint: admission lock → actor's
role row `FOR SHARE` → restriction check → invite row `FOR UPDATE`.
Owners and admins can revoke any invite; any other member only one they
created. A removed or restricted actor is refused. Mint now uses the
same role-lock helper.
- **Mint response** now includes `invite_id`.
- **Nullable expiry readers.** Claim, list, the mint response and
operator mint treat a missing `expires_at` as "never expires". The
column is still `NOT NULL` here.
- **Secrets.** No list/revoke response or access-log line contains a
code or its hash; request errors are fixed strings that never echo
input. Revoke logs only `invite_id`. A revoke the database refuses is
logged as denied with its reason.

## Deploy order

A follow-up PR adds links that never expire (`expires_at` nullable).
**It depends on this PR being deployed everywhere first**, so every
serving relay can read a missing expiry before one is written.

## Tests

- DB (`relay_invite/manage_postgres_tests.rs`): revoke by code targets
exactly one of two near-identical invites, idempotent revoke, community
scoping, creator demoted to member can revoke theirs, a member who
didn't create it is refused, a removed creator is refused, a restricted
admin is refused, a demotion holding the role row or a restriction
holding the admission lock makes revoke wait and then refuse with the
row unchanged, a paused claim and a revoke serialize with the member
kept, revoke is refused while the community is quiescing, paging
survives deleting the cursor row, and a row with no expiry is listed,
claimed, kept by the reaper and revocable (on a scratch database with
`NOT NULL` dropped).
- Relay (`invites/postgres_tests/manage_tests.rs`): list/revoke by id
and code end to end, no code or hash in responses, member/non-member
refusals, bad selectors, other-community lookups, query-string signature
binding, malformed requests not echoing a code in responses or access
logs, refused revokes logged as denied, and replayed list/revoke
requests refused.

---------

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
2026-11-20 15:48:36 -05:00

2939 lines
108 KiB
Rust

//! Relay invite HTTP API — mint and claim stateless invite codes.
//!
//! Routes (all NIP-98 signed, outside the Nostr event data plane):
//!
//! - `POST /api/invites` — mint an invite code. Caller must hold the `owner`
//! or `admin` role in the tenant community (mirrors the kind:9030 authz).
//! - `GET /api/invites` — list the community's v2 invites, newest first.
//! Owner/admin only. Never returns a code or its hash.
//! - `POST /api/invites/revoke` — revoke one v2 invite by `id` or by `code`.
//! Owners and admins can revoke any invite; a member can revoke one they
//! created. Idempotent; existing members stay. Never echoes the code.
//! - `POST /api/invites/claim` — claim an invite code. Deliberately **exempt
//! from the relay-membership gate**: the whole point is that the caller is
//! not a member yet. NIP-98 proves control of the joining pubkey; the HMAC
//! on the code proves an admin authorized the join.
//!
//! Token format, key derivation, and security trade-offs live in
//! [`crate::invite_token`].
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::Duration;
use axum::{
extract::State,
http::{HeaderMap, StatusCode},
response::{Html, Json},
};
use serde::Deserialize;
use serde_json::Value;
use crate::access::{AccessSlot, AuthReason, AuthResult};
use crate::handlers::side_effects::{
auto_join_default_channels, fan_out_nip43_membership_list, publish_nip43_member_added,
};
use crate::nip_fi_http::admit_nip_fi_http_on_state;
use buzz_core::invite::{
hash_v2_code, validate_v2_code, DEFAULT_INVITE_TTL_SECS, MAX_INVITE_TTL_SECS, MAX_INVITE_USES,
MIN_INVITE_TTL_SECS, V2_PREFIX,
};
use crate::invite_token;
use crate::state::AppState;
use super::{api_error, bridge, internal_error};
mod claim_auth;
mod manage;
use claim_auth::{authenticate, map_claim_error};
pub use manage::{list_invites, revoke_invite};
/// Fixed-window size for the per-pubkey claim rate limiter.
pub(crate) const CLAIM_RATE_WINDOW: Duration = Duration::from_secs(60);
/// Max claim attempts per pubkey per window. Claims are idempotent and a real
/// user performs exactly one, so this only bounds brute-force probing.
const CLAIM_RATE_LIMIT: u32 = 10;
/// Maximum distinct pubkeys retained by the process-local claim limiter.
/// NIP-98 proves key ownership, not that a key is costly to create, so this
/// bound is required in addition to expiry.
pub(crate) const CLAIM_RATE_CACHE_CAPACITY: u64 = 10_000;
/// Body for `POST /api/invites`.
#[derive(Debug, Default, Deserialize)]
pub struct MintInviteRequest {
/// Requested lifetime in seconds. Must be between
/// [`MIN_INVITE_TTL_SECS`] and
/// [`invite_token::MAX_INVITE_TTL_SECS`]; defaults to 72 h.
#[serde(default)]
pub ttl_secs: Option<u64>,
/// Maximum number of uses before the invite is exhausted. `None` (omitted
/// or `null`) means unlimited — preserves current behavior. When present,
/// must be an integer from 1 through [`MAX_INVITE_USES`].
#[serde(default)]
pub max_uses: Option<i32>,
}
pub(crate) fn validate_mint_request(
request: &MintInviteRequest,
) -> Result<(u64, Option<i32>), (StatusCode, Json<Value>)> {
let ttl = request.ttl_secs.unwrap_or(DEFAULT_INVITE_TTL_SECS);
if !(MIN_INVITE_TTL_SECS..=MAX_INVITE_TTL_SECS).contains(&ttl) {
return Err(api_error(
StatusCode::BAD_REQUEST,
&format!(
"ttl_secs must be between {} and {MAX_INVITE_TTL_SECS}",
MIN_INVITE_TTL_SECS
),
));
}
if let Some(max_uses) = request.max_uses {
if !(1..=MAX_INVITE_USES).contains(&max_uses) {
return Err(api_error(
StatusCode::BAD_REQUEST,
&format!("max_uses must be between 1 and {MAX_INVITE_USES}"),
));
}
}
Ok((ttl, request.max_uses))
}
/// Body for `POST /api/invites/claim`.
#[derive(Debug, Deserialize)]
pub struct ClaimInviteRequest {
/// The invite code to redeem.
pub code: String,
/// Relay-issued proof of accepting the configured terms, when required.
#[serde(default)]
pub policy_receipt: Option<String>,
}
/// Body for `POST /api/invites/accept-policy`.
#[derive(Debug, Deserialize)]
pub struct AcceptPolicyRequest {
/// Invite code the acceptance receipt will be bound to.
pub code: String,
/// Policy revision displayed by the client.
pub policy_version: String,
/// Minimum-age assertion, required only when configured by the operator.
#[serde(default)]
pub age_confirmed: bool,
}
/// Public join policy shared by every client-side join surface.
pub async fn join_policy(State(state): State<Arc<AppState>>) -> Json<Value> {
match &state.config.join_policy {
Some(policy) => Json(serde_json::json!({
"policy": {
"terms_markdown": policy.terms_markdown,
"privacy_markdown": policy.privacy_markdown,
"age_attestation_required": policy.age_attestation_required,
"version": policy.version
}
})),
None => Json(serde_json::json!({})),
}
}
/// `GET /api/join-policy/terms` — Terms of Service as a standalone HTML page.
///
/// Serves the operator-configured Markdown as a real browser page so desktop
/// clients can hand the link to the system browser instead of rendering the
/// document inside the webview (which requires app chrome the onboarding
/// surfaces don't have). 404 when no terms document is configured.
pub async fn join_policy_terms(
State(state): State<Arc<AppState>>,
) -> Result<Html<String>, (StatusCode, Json<Value>)> {
policy_document_page(&state, "Terms of Service", |policy| {
policy.terms_markdown.as_deref()
})
}
/// `GET /api/join-policy/privacy` — Privacy Policy as a standalone HTML page.
pub async fn join_policy_privacy(
State(state): State<Arc<AppState>>,
) -> Result<Html<String>, (StatusCode, Json<Value>)> {
policy_document_page(&state, "Privacy Policy", |policy| {
policy.privacy_markdown.as_deref()
})
}
fn policy_document_page(
state: &AppState,
title: &str,
select: impl Fn(&crate::config::JoinPolicyConfig) -> Option<&str>,
) -> Result<Html<String>, (StatusCode, Json<Value>)> {
let markdown = state
.config
.join_policy
.as_ref()
.and_then(select)
.ok_or_else(|| api_error(StatusCode::NOT_FOUND, "join_policy_not_configured"))?;
Ok(Html(render_policy_document(title, markdown)))
}
/// Render operator Markdown into a minimal self-contained HTML page.
///
/// Raw HTML embedded in the Markdown is escaped and rendered as text — the
/// operator authors a policy document, not a web page, and this keeps the
/// endpoint from serving arbitrary operator-controlled markup.
fn render_policy_document(title: &str, markdown: &str) -> String {
use pulldown_cmark::{html, Event, Parser};
let mut body = String::new();
html::push_html(
&mut body,
Parser::new(markdown).map(|event| match event {
Event::Html(raw) => Event::Text(raw.into_string().into()),
Event::InlineHtml(raw) => Event::Text(raw.into_string().into()),
other => other,
}),
);
// Titles are fixed literals today; escape anyway so a future caller
// can't accidentally inject markup through this seam.
let escaped_title = title
.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;");
format!(
"<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n\
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\
<title>{escaped_title}</title>\n\
<style>body{{max-width:42rem;margin:2rem auto;padding:0 1rem;\
font-family:system-ui,sans-serif;line-height:1.6}}</style>\n\
</head>\n<body>\n{body}</body>\n</html>\n"
)
}
/// Exchange explicit policy acceptance for a short-lived, invite-bound receipt.
pub async fn accept_policy(
State(state): State<Arc<AppState>>,
body: axum::body::Bytes,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
let Some(policy) = &state.config.join_policy else {
return Err(api_error(
StatusCode::NOT_FOUND,
"join_policy_not_configured",
));
};
let request: AcceptPolicyRequest = serde_json::from_slice(&body).map_err(|e| {
api_error(
StatusCode::BAD_REQUEST,
&format!("invalid policy acceptance JSON: {e}"),
)
})?;
if request.policy_version != policy.version
|| (policy.age_attestation_required && !request.age_confirmed)
{
return Err(api_error(
StatusCode::BAD_REQUEST,
"join_policy_not_accepted",
));
}
let key = invite_token::derive_invite_key(&state.relay_keypair);
let receipt = invite_token::mint_policy_acceptance(&key, &request.code, &policy.version);
Ok(Json(serde_json::json!({ "receipt": receipt })))
}
pub(crate) fn map_mint_error(error: buzz_db::DbError) -> (StatusCode, Json<Value>) {
match error {
buzz_db::DbError::InviteRestricted => api_error(StatusCode::FORBIDDEN, "invite_restricted"),
buzz_db::DbError::InviteIssuerNotAdmin => api_error(
StatusCode::FORBIDDEN,
"only relay owners and admins can create invites",
),
buzz_db::DbError::InvalidData(message) | buzz_db::DbError::DeletionSafety(message) => {
api_error(StatusCode::BAD_REQUEST, &message)
}
buzz_db::DbError::AccessDenied(_) => api_error(
StatusCode::SERVICE_UNAVAILABLE,
"community writes are temporarily unavailable",
),
error => internal_error(&format!("invite mint: {error}")),
}
}
/// Mint an invite code — `POST /api/invites`, NIP-98 signed by an owner/admin.
///
/// Returns the code, its expiry, and a shareable landing-page URL on the
/// tenant host.
pub async fn mint_invite(
State(state): State<Arc<AppState>>,
slot: AccessSlot,
headers: HeaderMap,
body: axum::body::Bytes,
) -> axum::response::Response {
// NIP-FI gate wraps the entire handler so the denial is emitted as exact
// text/plain bytes. [FI-TRACE-AUTHORITY-UNIFORM]
mint_invite_checked(state, slot, headers, body).await
}
async fn mint_invite_checked(
state: Arc<AppState>,
slot: AccessSlot,
headers: HeaderMap,
body: axum::body::Bytes,
) -> axum::response::Response {
use axum::response::IntoResponse as _;
let gate = InviteGate::Admin("only relay owners and admins can create invites");
let (tenant, pubkey) =
match admit_invite_caller(&state, &slot, &headers, "POST", "/api/invites", &body, gate)
.await
{
Ok(admitted) => admitted,
Err(response) => return response,
};
// The request's access line carries the minted invite.
match mint_invite_inner(&state, body, tenant, pubkey).await {
Ok((json, minted)) => {
slot.detail(minted);
json.into_response()
}
Err(e) => e.into_response(),
}
}
/// The last HTTP admission step of an invite-management route.
#[derive(Clone, Copy)]
pub(crate) enum InviteGate {
/// Owner or admin; the message is the route's refusal.
Admin(&'static str),
/// Any member. The database transaction makes the final role decision.
Member,
}
/// Admission shared by the invite-management routes, in order: tenant bind,
/// NIP-98 through NIP-FI admission for `method` and `path_and_query`, replay,
/// relay membership and ban, the NIP-OA owner link, then `gate`.
#[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers
pub(crate) async fn admit_invite_caller(
state: &Arc<AppState>,
slot: &AccessSlot,
headers: &HeaderMap,
method: &'static str,
path_and_query: &str,
body: &axum::body::Bytes,
gate: InviteGate,
) -> Result<(buzz_core::TenantContext, nostr::PublicKey), axum::response::Response> {
use axum::response::IntoResponse as _;
let Some(tenant) = crate::nip_fi_shadow::bind_tenant(state, headers).await else {
return Err(api_error(
StatusCode::NOT_FOUND,
"relay: no community is configured for this host",
)
.into_response());
};
let url = bridge::nip98_expected_url(&state.config.relay_url, &tenant, path_and_query);
let has_body = method != "GET";
// NIP-FI admission: NIP-98 extraction runs inside the closure, followed by
// assertion verify → pair → deny-map in fixed order. The proven pubkey is
// only available through the returned NipFiAdmission. [FI-TRACE-AUTHORITY-UNIFORM]
let admission = admit_nip_fi_http_on_state(
state,
headers,
slot,
bridge::make_nip98_closure_for_admission(
slot.clone(),
headers.clone(),
method,
url,
has_body.then(|| body.to_vec()),
true, // invites always require NIP-98; no X-Pubkey dev fallback
has_body, // POST bodies must be covered by a payload tag
),
)
.await?;
let mut caller = bridge::ProvenCaller::new(admission, slot, &tenant);
let pubkey = caller.pubkey;
// Replay detection runs after NIP-98+assertion admission (both proofs verified).
caller
.replay(state, &tenant)
.await
.map_err(|e| e.into_response())?;
// Membership and community ban, same step as the other NIP-98 routes.
let membership = super::relay_members::enforce_relay_membership(
state,
&tenant,
pubkey.as_bytes(),
super::relay_members::extract_auth_tag_header(headers),
caller.signed_at,
caller.token_owner,
)
.await;
let membership = match gate {
InviteGate::Admin(_) => caller.check(
membership,
super::relay_members::MembershipRefusal::auth_result,
),
InviteGate::Member => caller.admit_member(membership),
};
// The shared gate records the verified owner; a different stored owner
// keeps this route's own refusal code.
if let Err(e) = membership {
if let super::relay_members::MembershipRefusal::Api(AuthReason::OwnerMismatch, _) = e {
return Err(api_error(StatusCode::FORBIDDEN, "invite_owner_mismatch").into_response());
}
return Err(e.into_response());
}
if let InviteGate::Admin(refusal) = gate {
// Authz mirrors kind:9030 (add member): owner or admin only.
let member = caller
.check(
state
.db
.get_relay_member(tenant.community(), &pubkey.to_hex())
.await,
|_| AuthResult::Denied(AuthReason::AuthorizationUnavailable),
)
.map_err(|e| internal_error(&format!("invite role lookup: {e}")).into_response())?;
// The role gate is the route's last admission step.
let role = member.map(|m| m.role).unwrap_or_default();
caller
.admit(
if role == "owner" || role == "admin" {
Ok(())
} else {
Err(())
},
|()| AuthResult::Denied(AuthReason::NotRelayAdmin),
)
.map_err(|()| api_error(StatusCode::FORBIDDEN, refusal).into_response())?;
}
Ok((tenant, pubkey))
}
async fn mint_invite_inner(
state: &AppState,
body: axum::body::Bytes,
tenant: buzz_core::TenantContext,
pubkey: nostr::PublicKey,
) -> Result<(Json<Value>, crate::access::Detail), (StatusCode, Json<Value>)> {
let sender_hex = pubkey.to_hex();
let request: MintInviteRequest = if body.is_empty() {
MintInviteRequest::default()
} else {
serde_json::from_slice(&body).map_err(|e| {
api_error(
StatusCode::BAD_REQUEST,
&format!("invalid invite JSON: {e}"),
)
})?
};
let (ttl, max_uses) = validate_mint_request(&request)?;
// Mint a v2 opaque, database-backed invite.
let invite = state
.db
.mint_relay_invite_as_admin(tenant.community(), &sender_hex, ttl, max_uses)
.await
.map_err(map_mint_error)?;
let minted = crate::access::Detail {
invite_id: Some(invite.invite_id),
expires_at: invite.expires_at.map(|at| at.timestamp()),
max_uses: invite.max_uses,
..Default::default()
};
Ok((
Json(minted_invite_json(state, tenant.host(), &invite)),
minted,
))
}
/// The mint response contract shared by every mint route: the invite id, the
/// code, its expiry in Unix seconds (`null` for a link that never expires), its use limits, and the landing-page URL on `host`.
pub(crate) fn minted_invite_json(
state: &AppState,
host: &str,
invite: &buzz_db::relay_invite::MintedInvite,
) -> Value {
// Same TLS-posture logic as nip98_expected_url: wss deployments get an
// https landing page URL, ws dev/test deployments get http.
let scheme = if state.config.relay_url.trim_start().starts_with("wss://") {
"https"
} else {
"http"
};
serde_json::json!({
"invite_id": invite.invite_id,
"code": invite.code,
"expires_at": invite.expires_at.map(|at| at.timestamp()),
"max_uses": invite.max_uses,
"uses_remaining": invite.uses_remaining,
"url": format!("{scheme}://{host}/invite/{}", invite.code),
})
}
/// Claim an invite code — `POST /api/invites/claim`, NIP-98 signed by the
/// *joining* pubkey. Exempt from the relay-membership gate by design.
///
/// Routing is by exact prefix: `v2.` codes go to the database-backed
/// redemption path; every other code goes to the v1 HMAC verifier. A `v2.`
/// code is never fallen back to v1 verification.
pub async fn claim_invite(
State(state): State<Arc<AppState>>,
slot: AccessSlot,
headers: HeaderMap,
body: axum::body::Bytes,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
let (tenant, pubkey, verified_owner) =
authenticate(&state, &slot, &headers, "/api/invites/claim", &body).await?;
// The request's access line carries whether the claim joined.
let claimed = claim_invite_authed(&state, &slot, tenant, pubkey, verified_owner, &body).await;
if let Ok(Json(json)) = &claimed {
slot.detail(crate::access::Detail {
joined: Some(json["status"] == "joined"),
..Default::default()
});
}
claimed
}
async fn claim_invite_authed(
state: &Arc<AppState>,
slot: &AccessSlot,
tenant: buzz_core::TenantContext,
pubkey: nostr::PublicKey,
verified_owner: Option<nostr::PublicKey>,
body: &[u8],
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
if claim_rate_limited(state, tenant.community(), &pubkey) {
return Err(api_error(
StatusCode::TOO_MANY_REQUESTS,
"too many invite claim attempts, slow down",
));
}
let request: ClaimInviteRequest = serde_json::from_slice(body)
.map_err(|e| api_error(StatusCode::BAD_REQUEST, &format!("invalid claim JSON: {e}")))?;
let claimer_hex = pubkey.to_hex();
let owner_hex = verified_owner.map(|owner| owner.to_hex());
let key = invite_token::derive_invite_key(&state.relay_keypair);
// --- v2 database-backed path ---
//
// Route by exact prefix: v2. codes use the durable invite table. No
// fallback to v1 HMAC verification for malformed v2 input.
if request.code.starts_with(V2_PREFIX) {
validate_v2_code(&request.code)
.map_err(|_| api_error(StatusCode::FORBIDDEN, "invite_invalid"))?;
// Join-policy receipt verification, same mechanism as v1: the receipt
// is bound to the code string by SHA-256, so it works for v2 codes.
if let Some(policy) = &state.config.join_policy {
let receipt = request
.policy_receipt
.as_deref()
.ok_or_else(|| api_error(StatusCode::FORBIDDEN, "join_policy_required"))?;
invite_token::verify_policy_acceptance(&key, receipt, &request.code, &policy.version)
.map_err(|_| api_error(StatusCode::FORBIDDEN, "join_policy_required"))?;
}
let token_hash = hash_v2_code(&request.code);
let write = state
.db
.claim_relay_invite_with_owner(
tenant.community(),
&token_hash,
&claimer_hex,
state
.config
.join_policy
.as_ref()
.map(|policy| policy.version.as_str()),
owner_hex.as_deref(),
&state.relay_keypair,
)
.await
.map_err(|e| map_claim_error(slot, e))?;
metrics::counter!("buzz_users_created_total", "community" => tenant.host().to_owned())
.increment(write.outcome.users_created);
if write.outcome.owner_link_created {
state.disconnect_unowned_agent_clusterwide(&tenant, pubkey.as_bytes());
}
// Publish the member-added delta only on Joined; successful repeated
// claims may still have durable default-channel work to finish.
let joined = matches!(
write.outcome.outcome,
buzz_db::relay_invite::ClaimOutcome::Joined { .. }
);
if matches!(
write.outcome.outcome,
buzz_db::relay_invite::ClaimOutcome::Joined { .. }
| buzz_db::relay_invite::ClaimOutcome::AlreadyMember { .. }
) {
finish_committed_claim(&tenant, state, &claimer_hex, write.snapshot, joined).await;
}
return match write.outcome.outcome {
buzz_db::relay_invite::ClaimOutcome::Joined { .. } => Ok(Json(serde_json::json!({
"status": "joined",
"community_id": tenant.community().to_string(),
"host": tenant.host(),
"role": "member",
}))),
buzz_db::relay_invite::ClaimOutcome::AlreadyMember { .. } => {
Ok(Json(serde_json::json!({
"status": "already_member",
"community_id": tenant.community().to_string(),
"host": tenant.host(),
"role": "member",
})))
}
buzz_db::relay_invite::ClaimOutcome::Expired => {
Err(api_error(StatusCode::FORBIDDEN, "invite_expired"))
}
buzz_db::relay_invite::ClaimOutcome::Exhausted => {
Err(api_error(StatusCode::FORBIDDEN, "invite_exhausted"))
}
// Deliberately indistinguishable, even for an issuer timeout whose
// link works again later: a claim never reveals the issuer's
// moderation state.
buzz_db::relay_invite::ClaimOutcome::Revoked
| buzz_db::relay_invite::ClaimOutcome::IssuerRestricted => {
Err(api_error(StatusCode::FORBIDDEN, "invite_invalid"))
}
buzz_db::relay_invite::ClaimOutcome::Restricted => {
slot.finish(AuthResult::Denied(AuthReason::Restricted));
Err(api_error(StatusCode::FORBIDDEN, "invite_restricted"))
}
buzz_db::relay_invite::ClaimOutcome::Invalid => {
Err(api_error(StatusCode::FORBIDDEN, "invite_invalid"))
}
};
}
// --- v1 HMAC path (stateless tokens, drain window) ---
let payload = invite_token::verify_invite_with_cutoff(
&key,
tenant.community(),
&request.code,
state.config.invite_v1_invalid_after,
)
.map_err(|e| match e {
// Expired is post-MAC: revealing it helps the UX without helping a forger.
invite_token::InviteError::Expired => api_error(StatusCode::FORBIDDEN, "invite_expired"),
// Everything else stays coarse so the endpoint is a poor oracle.
_ => api_error(StatusCode::FORBIDDEN, "invite_invalid"),
})?;
if let Some(policy) = &state.config.join_policy {
let receipt = request
.policy_receipt
.as_deref()
.ok_or_else(|| api_error(StatusCode::FORBIDDEN, "join_policy_required"))?;
invite_token::verify_policy_acceptance(&key, receipt, &request.code, &policy.version)
.map_err(|_| api_error(StatusCode::FORBIDDEN, "join_policy_required"))?;
}
let write = state
.db
.claim_relay_membership_with_owner(
tenant.community(),
&claimer_hex,
&payload.r,
state
.config
.join_policy
.as_ref()
.map(|policy| policy.version.as_str()),
owner_hex.as_deref(),
&state.relay_keypair,
)
.await
.map_err(|e| map_claim_error(slot, e))?;
metrics::counter!("buzz_users_created_total", "community" => tenant.host().to_owned())
.increment(write.outcome.users_created);
if write.outcome.owner_link_created {
state.disconnect_unowned_agent_clusterwide(&tenant, pubkey.as_bytes());
}
let was_inserted = write.outcome.inserted;
finish_committed_claim(&tenant, state, &claimer_hex, write.snapshot, was_inserted).await;
Ok(Json(serde_json::json!({
"status": if was_inserted { "joined" } else { "already_member" },
"community_id": tenant.community().to_string(),
"host": tenant.host(),
"role": payload.r,
})))
}
/// The follow-up of a claim whose roster write committed: the NIP-43
/// membership-list fan-out, the member-added delta for new members, and
/// any unfinished default-channel joins (including on a repeated claim).
///
/// It runs on its own task, which the handler awaits, so the response still
/// waits for the joins. A client that disconnects first makes the server
/// drop the handler's future: that detaches the task rather than cancelling
/// it partway. The durable token also survives a relay restart.
async fn finish_committed_claim(
tenant: &buzz_core::TenantContext,
state: &Arc<AppState>,
claimer_hex: &str,
snapshot: Option<buzz_core::StoredEvent>,
joined: bool,
) {
let follow_up = tokio::spawn({
let (tenant, state, claimer_hex) =
(tenant.clone(), Arc::clone(state), claimer_hex.to_owned());
async move {
fan_out_nip43_membership_list(&tenant, &state, snapshot).await;
if joined {
if let Err(e) = publish_nip43_member_added(&tenant, &state, &claimer_hex).await {
tracing::warn!("failed to publish NIP-43 member-added delta after claim: {e}");
}
}
auto_join_default_channels(&tenant, &state, &claimer_hex, None).await;
}
});
if let Err(e) = follow_up.await {
tracing::error!(member = %claimer_hex, error = %e, "invite claim follow-up task failed");
}
}
/// Fixed-window rate limit on claim attempts, keyed by community and claimer
/// pubkey so traffic for one tenant cannot consume another tenant's allowance.
///
/// Entries expire after one window and the cache has a hard capacity. Both are
/// important because a pre-membership caller can cheaply create fresh Nostr
/// keypairs; retaining one immortal entry per key would make the limiter itself
/// an unbounded-memory denial-of-service vector.
fn claim_rate_limited(
state: &AppState,
community: buzz_core::tenant::CommunityId,
pubkey: &nostr::PublicKey,
) -> bool {
claim_key_rate_limited(
&state.invite_claim_rate_limiter,
(community, pubkey.to_bytes()),
)
}
fn claim_key_rate_limited(
cache: &moka::sync::Cache<crate::state::ScopedPubkeyKey, Arc<std::sync::atomic::AtomicU32>>,
key: crate::state::ScopedPubkeyKey,
) -> bool {
let counter = cache.get_with(key, || Arc::new(std::sync::atomic::AtomicU32::new(0)));
counter.fetch_add(1, Ordering::Relaxed) >= CLAIM_RATE_LIMIT
}
#[cfg(test)]
mod postgres_tests {
mod manage_tests;
mod owner_admission_tests;
mod recovery_postgres_tests;
mod restriction_tests;
use std::sync::Arc;
use std::time::Duration;
use super::{claim_key_rate_limited, CLAIM_RATE_LIMIT, MAX_INVITE_USES, MIN_INVITE_TTL_SECS};
use axum::{
body::{to_bytes, Body},
http::{header, Request, StatusCode},
};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use hmac::{Hmac, KeyInit, Mac};
use nostr::{EventBuilder, EventId, Keys, Kind, Tag};
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::sync::Mutex;
use tower::ServiceExt;
use uuid::Uuid;
use crate::invite_token::{derive_invite_key, InvitePayload, MAX_INVITE_TTL_SECS};
use crate::router::build_router;
use crate::state::AppState;
struct AlwaysFreshReplayGuard;
impl buzz_auth::Nip98ReplayGuard for AlwaysFreshReplayGuard {
fn try_mark_in_scope<'a>(
&'a self,
_scope: &'a str,
_event_id: &'a nostr::EventId,
_ttl_secs: u64,
) -> std::pin::Pin<
Box<dyn std::future::Future<Output = Result<bool, buzz_auth::AuthError>> + Send + 'a>,
> {
Box::pin(async { Ok(true) })
}
}
const TEST_DB_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; // sadscan:disable np.postgres.1
fn claim_cache(
capacity: u64,
ttl: Duration,
) -> moka::sync::Cache<crate::state::ScopedPubkeyKey, Arc<std::sync::atomic::AtomicU32>> {
moka::sync::Cache::builder()
.max_capacity(capacity)
.time_to_live(ttl)
.build()
}
#[test]
fn claim_limiter_rejects_after_limit() {
let cache = claim_cache(100, Duration::from_secs(60));
let key = (buzz_core::CommunityId::from_uuid(Uuid::nil()), [7; 32]);
for _ in 0..CLAIM_RATE_LIMIT {
assert!(!claim_key_rate_limited(&cache, key));
}
assert!(claim_key_rate_limited(&cache, key));
}
#[test]
fn claim_limiter_expires_entries() {
let cache = claim_cache(100, Duration::from_millis(10));
let key = (buzz_core::CommunityId::from_uuid(Uuid::nil()), [8; 32]);
assert!(!claim_key_rate_limited(&cache, key));
assert!(cache.get(&key).is_some());
std::thread::sleep(Duration::from_millis(25));
cache.run_pending_tasks();
assert!(cache.get(&key).is_none());
assert!(!claim_key_rate_limited(&cache, key));
}
#[test]
fn claim_limiter_isolates_communities_for_same_pubkey() {
let cache = claim_cache(100, Duration::from_secs(60));
let pubkey = [9; 32];
let community_a = buzz_core::CommunityId::from_uuid(Uuid::from_u128(0xAAAA));
let community_b = buzz_core::CommunityId::from_uuid(Uuid::from_u128(0xBBBB));
for _ in 0..CLAIM_RATE_LIMIT {
assert!(!claim_key_rate_limited(&cache, (community_a, pubkey)));
}
assert!(claim_key_rate_limited(&cache, (community_a, pubkey)));
assert!(!claim_key_rate_limited(&cache, (community_b, pubkey)));
}
#[test]
fn claim_limiter_bounds_distinct_pubkeys() {
let capacity = 10;
let cache = claim_cache(capacity, Duration::from_secs(60));
for id in 0..100_u64 {
let mut pubkey = [0; 32];
pubkey[..8].copy_from_slice(&id.to_le_bytes());
let key = (buzz_core::CommunityId::from_uuid(Uuid::nil()), pubkey);
assert!(!claim_key_rate_limited(&cache, key));
}
cache.run_pending_tasks();
assert!(cache.entry_count() <= capacity);
}
fn nip98_auth_header(keys: &Keys, url: &str, body: &[u8]) -> String {
let hash: [u8; 32] = Sha256::digest(body).into();
let tags = vec![
Tag::parse(["u", url]).expect("u tag"),
Tag::parse(["method", "POST"]).expect("method tag"),
Tag::parse(["payload", hex::encode(hash).as_str()]).expect("payload tag"),
];
let event = EventBuilder::new(Kind::HttpAuth, "")
.tags(tags)
.sign_with_keys(keys)
.expect("sign NIP-98 event");
let event_json = serde_json::to_string(&event).expect("serialize NIP-98 event");
let encoded = base64::engine::general_purpose::STANDARD.encode(event_json.as_bytes());
format!("Nostr {encoded}")
}
/// Build a closed-relay (`require_relay_membership = true`) test state with
/// a fresh community on `host`; returns `None` when Postgres is unavailable.
async fn invite_test_state(host: &str) -> Option<Arc<AppState>> {
let mut config = crate::config::Config::for_test(); // [FI-TRACE-ENV-RACE]
let database_url = std::env::var("BUZZ_TEST_DATABASE_URL")
.or_else(|_| std::env::var("DATABASE_URL"))
.unwrap_or_else(|_| TEST_DB_URL.to_string());
config.database_url = database_url.clone();
config.redis_url = "redis://127.0.0.1:1".to_string();
config.relay_url = format!("wss://{host}");
// The claim route must work on relays where membership is enforced —
// that is the entire point of an invite.
config.require_relay_membership = true;
let pool = sqlx::PgPool::connect(&database_url).await.ok()?;
let db = buzz_db::Db::from_pool(pool.clone());
db.ensure_configured_community(host).await.ok()?;
let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).ok()?;
let pubsub = Arc::new(
buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone())
.await
.ok()?,
);
let audit = buzz_audit::AuditService::new(pool.clone());
let auth = buzz_auth::AuthService::new(config.auth.clone());
let search = buzz_search::SearchService::new(pool.clone());
let workflow_engine = Arc::new(buzz_workflow::WorkflowEngine::new(
db.clone(),
buzz_workflow::WorkflowConfig::default(),
));
let media_storage = buzz_media::MediaStorage::new(&config.media).ok()?;
let (mut state, _audit_shutdown) = AppState::new(
config,
db,
redis_pool,
audit,
pubsub,
auth,
search,
workflow_engine,
Keys::generate(),
media_storage,
);
state.nip98_replay = Arc::new(AlwaysFreshReplayGuard);
Some(Arc::new(state))
}
async fn post_json(
state: Arc<AppState>,
host: &str,
path: &str,
keys: &Keys,
body: String,
) -> axum::response::Response {
let url = format!("https://{host}{path}");
let auth = nip98_auth_header(keys, &url, body.as_bytes());
build_router(state)
.oneshot(
Request::builder()
.method("POST")
.uri(path)
.header(header::HOST, host)
.header(header::AUTHORIZATION, auth)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(body))
.expect("request"),
)
.await
.expect("response")
}
async fn read_json(response: axum::response::Response) -> Value {
let bytes = to_bytes(response.into_body(), 1024 * 1024)
.await
.expect("read response body");
serde_json::from_slice(&bytes).expect("response JSON")
}
async fn mint_code(state: Arc<AppState>, host: &str, owner: &Keys, request: Value) -> String {
let response = post_json(state, host, "/api/invites", owner, request.to_string()).await;
assert_eq!(response.status(), StatusCode::OK);
read_json(response)
.await
.get("code")
.and_then(Value::as_str)
.expect("minted code")
.to_string()
}
async fn event_count(state: &AppState, community: buzz_core::CommunityId, kind: i32) -> i64 {
state
.db
.count_events(&buzz_db::EventQuery {
kinds: Some(vec![kind]),
global_only: true,
..buzz_db::EventQuery::for_community(community)
})
.await
.expect("count side-effect events")
}
#[test]
fn mint_request_deserialization_is_strict() {
for valid in [
serde_json::json!({}),
serde_json::json!({ "max_uses": null }),
serde_json::json!({ "max_uses": 1 }),
serde_json::json!({ "max_uses": MAX_INVITE_USES }),
] {
serde_json::from_value::<super::MintInviteRequest>(valid).expect("valid request");
}
for invalid in [
serde_json::json!({ "max_uses": 1.5 }),
serde_json::json!({ "max_uses": "10" }),
serde_json::json!({ "ttl_secs": -1 }),
serde_json::json!({ "ttl_secs": 1.5 }),
serde_json::json!({ "ttl_secs": "3600" }),
] {
assert!(
serde_json::from_value::<super::MintInviteRequest>(invalid.clone()).is_err(),
"accepted wrong JSON type: {invalid}"
);
}
}
#[test]
fn mint_request_validation_enforces_bounds_without_a_database() {
use super::validate_mint_request;
for (request, expected) in [
(
super::MintInviteRequest::default(),
(crate::invite_token::DEFAULT_INVITE_TTL_SECS, None),
),
(
super::MintInviteRequest {
ttl_secs: Some(MIN_INVITE_TTL_SECS),
max_uses: Some(1),
},
(MIN_INVITE_TTL_SECS, Some(1)),
),
(
super::MintInviteRequest {
ttl_secs: Some(MAX_INVITE_TTL_SECS),
max_uses: Some(MAX_INVITE_USES),
},
(MAX_INVITE_TTL_SECS, Some(MAX_INVITE_USES)),
),
] {
assert_eq!(
validate_mint_request(&request).expect("valid request"),
expected
);
}
for request in [
super::MintInviteRequest {
ttl_secs: None,
max_uses: Some(0),
},
super::MintInviteRequest {
ttl_secs: None,
max_uses: Some(-1),
},
super::MintInviteRequest {
ttl_secs: None,
max_uses: Some(MAX_INVITE_USES + 1),
},
super::MintInviteRequest {
ttl_secs: Some(MIN_INVITE_TTL_SECS - 1),
max_uses: None,
},
super::MintInviteRequest {
ttl_secs: Some(MAX_INVITE_TTL_SECS + 1),
max_uses: None,
},
] {
assert_eq!(
validate_mint_request(&request)
.expect_err("invalid request")
.0,
StatusCode::BAD_REQUEST
);
}
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn mint_validates_max_uses_and_ttl_bounds() {
let host = format!("invites-validation-{}.example", Uuid::new_v4().simple());
let owner = Keys::generate();
let state = invite_test_state(&host)
.await
.expect("requires reachable Postgres and relay test state");
let community = state
.db
.lookup_community_by_host(&host)
.await
.expect("lookup")
.expect("community exists");
let _ = state
.db
.add_relay_member(
community.id,
&owner.public_key().to_hex(),
"owner",
None,
&nostr::Keys::generate(),
)
.await
.map(|write| write.outcome)
.expect("seed owner");
for body in [
serde_json::json!({ "max_uses": 0 }),
serde_json::json!({ "max_uses": -1 }),
serde_json::json!({ "max_uses": MAX_INVITE_USES + 1 }),
serde_json::json!({ "ttl_secs": MIN_INVITE_TTL_SECS - 1 }),
serde_json::json!({ "ttl_secs": MAX_INVITE_TTL_SECS + 1 }),
] {
let response = post_json(
state.clone(),
&host,
"/api/invites",
&owner,
body.to_string(),
)
.await;
assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{body}");
}
for body in [
serde_json::json!({}),
serde_json::json!({ "max_uses": null }),
serde_json::json!({ "max_uses": 1 }),
serde_json::json!({ "max_uses": MAX_INVITE_USES }),
serde_json::json!({ "ttl_secs": MIN_INVITE_TTL_SECS }),
serde_json::json!({ "ttl_secs": MAX_INVITE_TTL_SECS }),
] {
let response = post_json(
state.clone(),
&host,
"/api/invites",
&owner,
body.to_string(),
)
.await;
assert_eq!(response.status(), StatusCode::OK, "{body}");
}
}
#[test]
fn mint_fence_errors_map_to_temporary_unavailability() {
let (status, body) = super::map_mint_error(buzz_db::DbError::AccessDenied(
"community is write-fenced".to_string(),
));
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(
body.0.get("error").and_then(Value::as_str),
Some("community writes are temporarily unavailable")
);
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn malformed_and_unknown_v2_codes_are_forbidden_without_v1_fallback() {
let host = format!("invites-v2-invalid-{}.example", Uuid::new_v4().simple());
let joiner = Keys::generate();
let state = invite_test_state(&host)
.await
.expect("requires reachable Postgres and relay test state");
let unknown = format!("v2.{}", URL_SAFE_NO_PAD.encode([9_u8; 32]));
for code in [
"v2.".to_string(),
"v2.not-base64!".to_string(),
format!("v2.{}", URL_SAFE_NO_PAD.encode([9_u8; 31])),
unknown,
] {
let response = post_json(
state.clone(),
&host,
"/api/invites/claim",
&joiner,
serde_json::json!({ "code": code }).to_string(),
)
.await;
assert_eq!(response.status(), StatusCode::FORBIDDEN, "{code}");
assert_eq!(
read_json(response)
.await
.get("error")
.and_then(Value::as_str),
Some("invite_invalid")
);
}
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn bounded_v2_claims_publish_side_effects_only_for_joined() {
let host = format!(
"invites-v2-side-effects-{}.example",
Uuid::new_v4().simple()
);
let owner = Keys::generate();
let first = Keys::generate();
let second = Keys::generate();
let state = invite_test_state(&host)
.await
.expect("requires reachable Postgres and relay test state");
let community = state
.db
.lookup_community_by_host(&host)
.await
.expect("lookup")
.expect("community exists");
state
.db
.add_relay_member(
community.id,
&owner.public_key().to_hex(),
"owner",
None,
&nostr::Keys::generate(),
)
.await
.map(|write| write.outcome)
.expect("seed owner");
let before_delta_count = event_count(
&state,
community.id,
buzz_core::kind::KIND_NIP43_MEMBER_ADDED as i32,
)
.await;
let before_list_count = event_count(
&state,
community.id,
buzz_core::kind::KIND_NIP43_MEMBERSHIP_LIST as i32,
)
.await;
let code = mint_code(
state.clone(),
&host,
&owner,
serde_json::json!({ "max_uses": 1 }),
)
.await;
let claim_body = serde_json::json!({ "code": code }).to_string();
let response = post_json(
state.clone(),
&host,
"/api/invites/claim",
&first,
claim_body.clone(),
)
.await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
read_json(response)
.await
.get("status")
.and_then(Value::as_str),
Some("joined")
);
let delta_count = event_count(
&state,
community.id,
buzz_core::kind::KIND_NIP43_MEMBER_ADDED as i32,
)
.await;
let list_count = event_count(
&state,
community.id,
buzz_core::kind::KIND_NIP43_MEMBERSHIP_LIST as i32,
)
.await;
assert_eq!(delta_count, before_delta_count + 1);
assert_eq!(list_count, before_list_count + 1);
let response = post_json(
state.clone(),
&host,
"/api/invites/claim",
&first,
claim_body.clone(),
)
.await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
read_json(response)
.await
.get("status")
.and_then(Value::as_str),
Some("already_member")
);
assert_eq!(
event_count(
&state,
community.id,
buzz_core::kind::KIND_NIP43_MEMBER_ADDED as i32,
)
.await,
delta_count
);
assert_eq!(
event_count(
&state,
community.id,
buzz_core::kind::KIND_NIP43_MEMBERSHIP_LIST as i32,
)
.await,
list_count
);
let response = post_json(
state.clone(),
&host,
"/api/invites/claim",
&second,
claim_body,
)
.await;
assert_eq!(response.status(), StatusCode::FORBIDDEN);
assert_eq!(
read_json(response)
.await
.get("error")
.and_then(Value::as_str),
Some("invite_exhausted")
);
assert_eq!(
event_count(
&state,
community.id,
buzz_core::kind::KIND_NIP43_MEMBER_ADDED as i32,
)
.await,
delta_count
);
assert_eq!(
event_count(
&state,
community.id,
buzz_core::kind::KIND_NIP43_MEMBERSHIP_LIST as i32,
)
.await,
list_count
);
}
/// How many kind:44100 notifications name `member_hex` across the
/// community, one per channel the relay joined them to.
async fn added_notification_count(
state: &AppState,
community: buzz_core::CommunityId,
member_hex: &str,
) -> i64 {
state
.db
.count_events(&buzz_db::EventQuery {
kinds: Some(vec![buzz_core::kind::KIND_MEMBER_ADDED_NOTIFICATION as i32]),
p_tag_hex: Some(member_hex.to_string()),
global_only: true,
..buzz_db::EventQuery::for_community(community)
})
.await
.expect("count 44100")
}
/// How many `member_joined` kind:40099 notices in `channel_id` target
/// `member_hex`.
async fn member_joined_notice_count(
state: &AppState,
community: buzz_core::CommunityId,
channel_id: Uuid,
member_hex: &str,
) -> usize {
state
.db
.query_events(&buzz_db::EventQuery {
kinds: Some(vec![40099]),
channel_id: Some(channel_id),
..buzz_db::EventQuery::for_community(community)
})
.await
.expect("query 40099")
.iter()
.filter_map(|stored| serde_json::from_str::<Value>(&stored.event.content).ok())
.filter(|content| content["type"] == "member_joined" && content["target"] == member_hex)
.count()
}
/// The channel roles the relay holds for `keys` in `channels`, in order.
async fn channel_roles(
state: &AppState,
community: buzz_core::CommunityId,
channels: &[Uuid],
keys: &Keys,
) -> Vec<Option<String>> {
let mut roles = Vec::new();
for channel_id in channels {
roles.push(
state
.db
.get_member_role(community, *channel_id, &keys.public_key().to_bytes())
.await
.expect("member role"),
);
}
roles
}
/// Wait until a session blocked by `blocker_pid` waits for the channel
/// row lock `put_member` takes, failing if `task` finishes first.
async fn wait_for_put_member_behind<T>(
pool: &sqlx::PgPool,
blocker_pid: i32,
task: &tokio::task::JoinHandle<T>,
) {
let deadline = std::time::Instant::now() + Duration::from_secs(10);
loop {
let waiting: bool = sqlx::query_scalar(
"SELECT EXISTS (SELECT 1 FROM pg_stat_activity \
WHERE wait_event_type = 'Lock' \
AND $1 = ANY(pg_blocking_pids(pid)) \
AND query LIKE 'SELECT archived_at, deleted_at IS NOT NULL FROM channels %FOR NO KEY UPDATE')",
)
.bind(blocker_pid)
.fetch_one(pool)
.await
.expect("read lock waiters");
if waiting {
return;
}
assert!(
!task.is_finished(),
"the join finished without waiting for the held channel row"
);
assert!(
std::time::Instant::now() < deadline,
"the join never waited for the held channel row"
);
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
/// Claiming an invite joins the new member to the community's effective
/// default channels, once. Four channels flagged by the relay owner:
/// one open, one archived after flagging, one made private after
/// flagging, plus an unflagged control. A v2 claim joins the open one
/// only, with its kind:39002 roster, one kind:44100 and one
/// `member_joined` notice; a kind:9022 leave followed by a re-claim is
/// `already_member` and does not re-add. The v1 token path joins the same
/// way. The archived guard the shared join body owns is bound directly.
/// Mutation: delete `auto_join_default_channels` at either claim site →
/// RED.
#[tokio::test]
#[ignore = "requires Postgres"]
async fn claim_auto_joins_default_channels_once() {
use crate::handlers::group_state_postgres_tests::{
create_channel, edit_channel, group_state_tags, http_auth,
};
use crate::handlers::ingest::ingest_event;
use crate::handlers::side_effects::join_channel_as_self;
let host = format!("invites-auto-join-{}.example", Uuid::new_v4().simple());
let owner = Keys::generate();
let state = invite_test_state(&host)
.await
.expect("requires reachable Postgres and relay test state");
let community = state
.db
.lookup_community_by_host(&host)
.await
.expect("lookup")
.expect("community exists")
.id;
let tenant = buzz_core::TenantContext::resolved(community, &host);
state
.db
.add_relay_member(
community,
&owner.public_key().to_hex(),
"owner",
None,
&Keys::generate(),
)
.await
.map(|write| write.outcome)
.expect("seed owner");
let flagged = create_channel(&state, &tenant, &owner, &[]).await;
let archived = create_channel(&state, &tenant, &owner, &[]).await;
let private = create_channel(&state, &tenant, &owner, &[]).await;
let control = create_channel(&state, &tenant, &owner, &[]).await;
for channel_id in [flagged, archived, private] {
edit_channel(
&state,
&tenant,
&owner,
channel_id,
&[&["auto_join", "true"]],
)
.await
.expect("relay owner flags channel");
}
edit_channel(&state, &tenant, &owner, archived, &[&["archived", "true"]])
.await
.expect("archive after flagging");
edit_channel(
&state,
&tenant,
&owner,
private,
&[&["visibility", "private"]],
)
.await
.expect("make private after flagging");
let channels = [flagged, archived, private, control];
let joiner = Keys::generate();
let joiner_hex = joiner.public_key().to_hex();
let archived_refusal =
join_channel_as_self(&tenant, &state, archived, &joiner.public_key().to_bytes())
.await
.expect_err("self-join of an archived channel");
assert!(
archived_refusal.to_string().contains("archived"),
"{archived_refusal}"
);
assert_eq!(
added_notification_count(&state, community, &joiner_hex).await,
0
);
let code = mint_code(
state.clone(),
&host,
&owner,
serde_json::json!({ "max_uses": 1 }),
)
.await;
let claim_body = serde_json::json!({ "code": code }).to_string();
let response = post_json(
state.clone(),
&host,
"/api/invites/claim",
&joiner,
claim_body.clone(),
)
.await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(read_json(response).await["status"], "joined");
assert_eq!(
channel_roles(&state, community, &channels, &joiner).await,
[Some("member".to_string()), None, None, None],
"joined to the effective default channel only"
);
assert!(
group_state_tags(&state, &tenant, flagged, 39002)
.await
.iter()
.any(|tag| tag[0] == "p" && tag[1] == joiner_hex),
"kind:39002 of the default channel lists the new member"
);
assert_eq!(
added_notification_count(&state, community, &joiner_hex).await,
1
);
assert_eq!(
member_joined_notice_count(&state, community, flagged, &joiner_hex).await,
1
);
// Leaving is respected: a re-claim is a no-op, not a re-add.
let leave = EventBuilder::new(Kind::Custom(9022), "")
.tags([Tag::parse(["h", &flagged.to_string()]).unwrap()])
.sign_with_keys(&joiner)
.expect("sign 9022");
let left = ingest_event(&state, &tenant, leave, http_auth(&joiner))
.await
.expect("ingest 9022");
assert!(left.accepted, "{:?}", left.message);
assert_eq!(
channel_roles(&state, community, &[flagged], &joiner).await,
[None]
);
let response = post_json(
state.clone(),
&host,
"/api/invites/claim",
&joiner,
claim_body,
)
.await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(read_json(response).await["status"], "already_member");
assert_eq!(
channel_roles(&state, community, &channels, &joiner).await,
[None, None, None, None],
"a re-claim must not resurrect a kind:9022 leave"
);
assert_eq!(
added_notification_count(&state, community, &joiner_hex).await,
1
);
assert_eq!(
member_joined_notice_count(&state, community, flagged, &joiner_hex).await,
1
);
// The v1 HMAC token path joins the same way.
let v1_joiner = Keys::generate();
let v1_joiner_hex = v1_joiner.public_key().to_hex();
let v1_code = forge_v1_invite_code(&state, community, unix_now() + 3600);
let response = post_json(
state.clone(),
&host,
"/api/invites/claim",
&v1_joiner,
serde_json::json!({ "code": v1_code }).to_string(),
)
.await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(read_json(response).await["status"], "joined");
assert_eq!(
channel_roles(&state, community, &channels, &v1_joiner).await,
[Some("member".to_string()), None, None, None]
);
assert_eq!(
added_notification_count(&state, community, &v1_joiner_hex).await,
1
);
}
/// A default channel archived after the auto-join listed it is skipped:
/// no membership row, no kind:39002 roster entry, no kind:44100 and no
/// `member_joined` notice. The test holds an uncommitted archive of the
/// listed channel, so the auto-join reads the committed channel state and
/// then waits for the membership write's channel row lock. The archive
/// commits and the join resumes on an archived channel. Mutation: drop the channel row lock or the archived refusal
/// from `put_members` → RED.
#[tokio::test]
#[ignore = "requires Postgres"]
async fn auto_join_skips_a_default_channel_archived_while_it_joins() {
use crate::handlers::group_state_postgres_tests::{
create_channel, edit_channel, group_state_tags,
};
use crate::handlers::side_effects::auto_join_default_channels;
let host = format!(
"invites-auto-join-archive-{}.example",
Uuid::new_v4().simple()
);
let owner = Keys::generate();
let state = invite_test_state(&host)
.await
.expect("requires reachable Postgres and relay test state");
let community = state
.db
.lookup_community_by_host(&host)
.await
.expect("lookup")
.expect("community exists")
.id;
let tenant = buzz_core::TenantContext::resolved(community, &host);
let joiner = Keys::generate();
let joiner_hex = joiner.public_key().to_hex();
let _ = state
.db
.add_relay_member(
community,
&owner.public_key().to_hex(),
"owner",
None,
&Keys::generate(),
)
.await
.expect("seed relay owner");
let _ = state
.db
.add_relay_member_with_default_channels(
community,
&joiner_hex,
"member",
&joiner_hex,
&Keys::generate(),
)
.await
.expect("seed pending default-channel admission");
let starter = create_channel(&state, &tenant, &owner, &[]).await;
edit_channel(&state, &tenant, &owner, starter, &[&["auto_join", "true"]])
.await
.expect("relay owner flags channel");
let pool = state.db.pool().clone();
let mut archive = pool.begin().await.expect("begin archive");
let archive_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
.fetch_one(&mut *archive)
.await
.expect("archive backend pid");
sqlx::query("UPDATE channels SET archived_at = NOW() WHERE community_id = $1 AND id = $2")
.bind(community.as_uuid())
.bind(starter)
.execute(&mut *archive)
.await
.expect("archive the default channel");
let auto_join = tokio::spawn({
let state = Arc::clone(&state);
let tenant = tenant.clone();
let joiner_hex = joiner_hex.clone();
async move { auto_join_default_channels(&tenant, &state, &joiner_hex, None).await }
});
// Wait until the join is blocked on the channel row lock in
// the membership write, behind the archive, so it has already listed
// the channel.
wait_for_put_member_behind(&pool, archive_pid, &auto_join).await;
archive.commit().await.expect("commit archive");
tokio::time::timeout(Duration::from_secs(10), auto_join)
.await
.expect("the auto-join returns after the archive commits")
.expect("auto-join task must not panic");
assert_eq!(
channel_roles(&state, community, &[starter], &joiner).await,
[None],
"an archived default channel must not admit the new member"
);
assert!(
!group_state_tags(&state, &tenant, starter, 39002)
.await
.iter()
.any(|tag| tag[0] == "p" && tag[1] == joiner_hex),
"kind:39002 must not list the new member"
);
assert_eq!(
added_notification_count(&state, community, &joiner_hex).await,
0
);
assert_eq!(
member_joined_notice_count(&state, community, starter, &joiner_hex).await,
0
);
}
/// A client that disconnects mid-claim does not cut the auto-join short.
/// The server drops the handler's future on a disconnect; the test does
/// the same by aborting the request while the auto-join waits in
/// `put_member` behind a held lock on the first default channel's row.
/// Once the lock is released, the claimer still joins both default
/// channels, for a v2 and a v1 claim. Mutation: run the follow-up inline
/// in the handler again → RED (the claimer joins no channel).
#[tokio::test]
#[ignore = "requires Postgres"]
async fn claim_follow_up_survives_a_client_disconnect() {
use crate::handlers::group_state_postgres_tests::{create_channel, edit_channel};
let host = format!(
"invites-auto-join-disconnect-{}.example",
Uuid::new_v4().simple()
);
let owner = Keys::generate();
let state = invite_test_state(&host)
.await
.expect("requires reachable Postgres and relay test state");
let community = state
.db
.lookup_community_by_host(&host)
.await
.expect("lookup")
.expect("community exists")
.id;
let tenant = buzz_core::TenantContext::resolved(community, &host);
state
.db
.add_relay_member(
community,
&owner.public_key().to_hex(),
"owner",
None,
&Keys::generate(),
)
.await
.map(|write| write.outcome)
.expect("seed owner");
let first = create_channel(&state, &tenant, &owner, &[]).await;
let second = create_channel(&state, &tenant, &owner, &[]).await;
for channel_id in [first, second] {
edit_channel(
&state,
&tenant,
&owner,
channel_id,
&[&["auto_join", "true"]],
)
.await
.expect("relay owner flags channel");
}
let v2_code = mint_code(
state.clone(),
&host,
&owner,
serde_json::json!({ "max_uses": 1 }),
)
.await;
let v1_code = forge_v1_invite_code(&state, community, unix_now() + 3600);
let pool = state.db.pool().clone();
for code in [v2_code, v1_code] {
let joiner = Keys::generate();
let joiner_hex = joiner.public_key().to_hex();
let mut hold = pool.begin().await.expect("begin hold");
let hold_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
.fetch_one(&mut *hold)
.await
.expect("hold backend pid");
sqlx::query("SELECT 1 FROM channels WHERE community_id = $1 AND id = $2 FOR UPDATE")
.bind(community.as_uuid())
.bind(first)
.execute(&mut *hold)
.await
.expect("hold the first default channel's row");
let claim = tokio::spawn({
let (state, host, joiner) = (state.clone(), host.clone(), joiner.clone());
let body = serde_json::json!({ "code": code }).to_string();
async move { post_json(state, &host, "/api/invites/claim", &joiner, body).await }
});
wait_for_put_member_behind(&pool, hold_pid, &claim).await;
claim.abort();
assert!(
claim
.await
.expect_err("the claim was still waiting")
.is_cancelled(),
"the claim request was dropped"
);
hold.rollback().await.expect("release the held row");
let deadline = std::time::Instant::now() + Duration::from_secs(10);
while added_notification_count(&state, community, &joiner_hex).await < 2 {
assert!(
std::time::Instant::now() < deadline,
"the auto-join stopped with the dropped claim: {:?}",
channel_roles(&state, community, &[first, second], &joiner).await
);
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(
channel_roles(&state, community, &[first, second], &joiner).await,
[Some("member".to_string()), Some("member".to_string())]
);
}
}
/// A mint and a claim each write one access line carrying what they
/// did, and the invite code reaches no log.
#[tokio::test(flavor = "current_thread")]
#[ignore = "requires Postgres"]
async fn mint_and_claim_write_one_line_each_without_the_code() {
let host = format!("invites-{}.example", Uuid::new_v4().simple());
let (owner, joiner) = (Keys::generate(), Keys::generate());
let state = invite_test_state(&host).await.expect("local Postgres");
let community = state
.db
.lookup_community_by_host(&host)
.await
.expect("lookup")
.expect("community exists");
let _ = state
.db
.add_relay_member(
community.id,
&owner.public_key().to_hex(),
"owner",
None,
&nostr::Keys::generate(),
)
.await
.expect("seed owner");
let (_guard, out) = crate::access::tests::capture_scoped();
let code = mint_code(
state.clone(),
&host,
&owner,
serde_json::json!({ "max_uses": 3 }),
)
.await;
let mint = out.lines();
assert_eq!(mint.len(), 1, "{mint:?}");
assert_eq!(mint[0]["route"], "/api/invites", "{}", mint[0]);
assert_eq!(mint[0]["status"], 200, "{}", mint[0]);
assert_eq!(mint[0]["max_uses"], 3, "{}", mint[0]);
assert!(mint[0]["invite_id"].is_string(), "{}", mint[0]);
assert!(mint[0]["expires_at"].is_i64(), "{}", mint[0]);
let response = post_json(
state,
&host,
"/api/invites/claim",
&joiner,
serde_json::json!({ "code": code }).to_string(),
)
.await;
assert_eq!(response.status(), StatusCode::OK);
let lines = out.lines();
assert_eq!(lines.len(), 2, "one line per request: {lines:?}");
assert_eq!(lines[1]["route"], "/api/invites/claim", "{}", lines[1]);
assert_eq!(lines[1]["joined"], true, "{}", lines[1]);
assert_eq!(
lines[1]["pubkey"],
joiner.public_key().to_hex(),
"{}",
lines[1]
);
assert!(
!out.raw().contains(&code),
"invite code logged: {}",
out.raw()
);
}
/// A member who is not an owner or admin is refused a mint, and a banned
/// claimer is refused a claim: each logs `denied` with its reason, never
/// the membership admission's `success`.
#[tokio::test(flavor = "current_thread")]
#[ignore = "requires Postgres"]
async fn invite_refusals_after_membership_log_denied() {
let host = format!("invites-{}.example", Uuid::new_v4().simple());
let (owner, member, banned) = (Keys::generate(), Keys::generate(), Keys::generate());
let state = invite_test_state(&host).await.expect("local Postgres");
let community = state
.db
.lookup_community_by_host(&host)
.await
.expect("lookup")
.expect("community exists")
.id;
for (key, role) in [(&owner, "owner"), (&member, "member")] {
let _ = state
.db
.add_relay_member(
community,
&key.public_key().to_hex(),
role,
None,
&Keys::generate(),
)
.await
.expect("seed member");
}
let code = mint_code(state.clone(), &host, &owner, serde_json::json!({})).await;
state
.db
.ban_community_member(
community,
banned.public_key().as_bytes(),
owner.public_key().as_bytes(),
None,
None,
)
.await
.expect("seed ban");
let (_guard, out) = crate::access::tests::capture_scoped();
let mint = post_json(state.clone(), &host, "/api/invites", &member, "{}".into()).await;
assert_eq!(mint.status(), StatusCode::FORBIDDEN);
let claim = post_json(
state,
&host,
"/api/invites/claim",
&banned,
serde_json::json!({ "code": code }).to_string(),
)
.await;
assert_eq!(claim.status(), StatusCode::FORBIDDEN);
assert_eq!(read_json(claim).await["error"], "invite_restricted");
let lines = out.lines();
assert_eq!(lines.len(), 2, "one line per request: {lines:?}");
for (line, reason) in lines.iter().zip(["not_relay_admin", "restricted"]) {
assert_eq!(line["outcome"], "denied", "{line}");
assert_eq!(line["reason"], reason, "{line}");
}
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn owner_mints_and_new_pubkey_claims() {
let host = format!("invites-{}.example", Uuid::new_v4().simple());
let owner = Keys::generate();
let joiner = Keys::generate();
let Some(state) = invite_test_state(&host).await else {
return;
};
let community = state
.db
.lookup_community_by_host(&host)
.await
.expect("lookup")
.expect("community exists");
let community_id = community.id;
state
.db
.add_relay_member(
community_id,
&owner.public_key().to_hex(),
"owner",
None,
&nostr::Keys::generate(),
)
.await
.map(|write| write.outcome)
.expect("seed owner");
// Mint.
let response = post_json(
state.clone(),
&host,
"/api/invites",
&owner,
"{}".to_string(),
)
.await;
assert_eq!(response.status(), StatusCode::OK);
let json = read_json(response).await;
let code = json.get("code").and_then(Value::as_str).expect("code");
let url = json.get("url").and_then(Value::as_str).expect("url");
assert!(url.contains("/invite/"), "unexpected url: {url}");
// Claim on a closed relay by a pubkey that is not yet a member.
let claim_body = serde_json::json!({ "code": code }).to_string();
let response = post_json(
state.clone(),
&host,
"/api/invites/claim",
&joiner,
claim_body.clone(),
)
.await;
assert_eq!(response.status(), StatusCode::OK);
let json = read_json(response).await;
assert_eq!(json.get("status").and_then(Value::as_str), Some("joined"));
assert_eq!(json.get("role").and_then(Value::as_str), Some("member"));
let member = state
.db
.get_relay_member(community_id, &joiner.public_key().to_hex())
.await
.expect("member lookup")
.expect("joiner is now a member");
assert_eq!(member.role, "member");
// Second claim is idempotent.
let response = post_json(state, &host, "/api/invites/claim", &joiner, claim_body).await;
assert_eq!(response.status(), StatusCode::OK);
let json = read_json(response).await;
assert_eq!(
json.get("status").and_then(Value::as_str),
Some("already_member")
);
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn join_policy_gate_end_to_end() {
let host = format!("invites-policy-{}.example", Uuid::new_v4().simple());
let owner = Keys::generate();
let joiner = Keys::generate();
let Some(state) = invite_test_state(&host).await else {
return;
};
// Force the join policy on regardless of env.
let mut state_inner = (*state).clone();
let mut config = state_inner.config.as_ref().clone();
config.join_policy = Some(crate::config::JoinPolicyConfig {
terms_markdown: Some("# Terms".to_string()),
privacy_markdown: Some("# Privacy".to_string()),
age_attestation_required: true,
version: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string(),
});
state_inner.config = Arc::new(config);
let state = Arc::new(state_inner);
let community = state
.db
.lookup_community_by_host(&host)
.await
.expect("lookup")
.expect("community exists");
state
.db
.add_relay_member(
community.id,
&owner.public_key().to_hex(),
"owner",
None,
&nostr::Keys::generate(),
)
.await
.map(|write| write.outcome)
.expect("seed owner");
// Mint an invite.
let response = post_json(
state.clone(),
&host,
"/api/invites",
&owner,
"{}".to_string(),
)
.await;
assert_eq!(response.status(), StatusCode::OK);
let json = read_json(response).await;
let code = json
.get("code")
.and_then(Value::as_str)
.expect("code")
.to_string();
// 1. Claim WITHOUT receipt -> 403 (checkbox bypass).
let response = post_json(
state.clone(),
&host,
"/api/invites/claim",
&joiner,
serde_json::json!({ "code": code }).to_string(),
)
.await;
assert_eq!(
response.status(),
StatusCode::FORBIDDEN,
"no-receipt claim must fail"
);
// 2. Forged receipt (wrong key) -> 403.
let forged = crate::invite_token::mint_policy_acceptance(
&[9u8; 32],
&code,
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
);
let response = post_json(
state.clone(),
&host,
"/api/invites/claim",
&joiner,
serde_json::json!({ "code": code, "policy_receipt": forged }).to_string(),
)
.await;
assert_eq!(
response.status(),
StatusCode::FORBIDDEN,
"forged receipt must fail"
);
// 3. Receipt bound to a DIFFERENT invite code -> 403.
let key = crate::invite_token::derive_invite_key(&state.relay_keypair);
let other = crate::invite_token::mint_policy_acceptance(
&key,
"some-other-code",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
);
let response = post_json(
state.clone(),
&host,
"/api/invites/claim",
&joiner,
serde_json::json!({ "code": code, "policy_receipt": other }).to_string(),
)
.await;
assert_eq!(
response.status(),
StatusCode::FORBIDDEN,
"cross-invite receipt must fail"
);
// 4. Receipt for a STALE policy version -> 403.
let stale = crate::invite_token::mint_policy_acceptance(
&key,
&code,
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
);
let response = post_json(
state.clone(),
&host,
"/api/invites/claim",
&joiner,
serde_json::json!({ "code": code, "policy_receipt": stale }).to_string(),
)
.await;
assert_eq!(
response.status(),
StatusCode::FORBIDDEN,
"stale-version receipt must fail"
);
// 5. accept-policy without age confirmation -> 400.
let response = post_json(
state.clone(),
&host,
"/api/invites/accept-policy",
&joiner,
serde_json::json!({ "code": code, "policy_version": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "age_confirmed": false })
.to_string(),
)
.await;
assert_eq!(
response.status(),
StatusCode::BAD_REQUEST,
"age not confirmed must be rejected when required"
);
// 5b. accept-policy with stale version -> 400.
let response = post_json(
state.clone(),
&host,
"/api/invites/accept-policy",
&joiner,
serde_json::json!({ "code": code, "policy_version": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "age_confirmed": true })
.to_string(),
)
.await;
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
// 6. Legit flow: accept-policy -> receipt -> claim OK.
let response = post_json(
state.clone(),
&host,
"/api/invites/accept-policy",
&joiner,
serde_json::json!({ "code": code, "policy_version": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "age_confirmed": true })
.to_string(),
)
.await;
assert_eq!(response.status(), StatusCode::OK);
let receipt = read_json(response)
.await
.get("receipt")
.and_then(Value::as_str)
.expect("receipt")
.to_string();
let response = post_json(
state.clone(),
&host,
"/api/invites/claim",
&joiner,
serde_json::json!({ "code": code, "policy_receipt": receipt }).to_string(),
)
.await;
assert_eq!(
response.status(),
StatusCode::OK,
"legit receipt claim must succeed"
);
let json = read_json(response).await;
assert_eq!(json.get("status").and_then(Value::as_str), Some("joined"));
let member = state
.db
.get_relay_member(community.id, &joiner.public_key().to_hex())
.await
.expect("member lookup")
.expect("joiner is now a member");
assert_eq!(member.role, "member");
assert!(
state
.db
.has_join_policy_acceptance(
community.id,
&joiner.public_key().to_hex(),
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
)
.await
.expect("policy acceptance lookup"),
"accepted policy version must be persisted",
);
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn non_admin_cannot_mint() {
let host = format!("invites-{}.example", Uuid::new_v4().simple());
let member = Keys::generate();
let outsider = Keys::generate();
let Some(state) = invite_test_state(&host).await else {
return;
};
let community = state
.db
.lookup_community_by_host(&host)
.await
.expect("lookup")
.expect("community exists");
let community_id = community.id;
state
.db
.add_relay_member(
community_id,
&member.public_key().to_hex(),
"member",
None,
&nostr::Keys::generate(),
)
.await
.map(|write| write.outcome)
.expect("seed member");
for keys in [&member, &outsider] {
let response =
post_json(state.clone(), &host, "/api/invites", keys, "{}".to_string()).await;
assert_eq!(response.status(), StatusCode::FORBIDDEN);
}
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn claim_rejects_invalid_code() {
let host = format!("invites-{}.example", Uuid::new_v4().simple());
let joiner = Keys::generate();
let Some(state) = invite_test_state(&host).await else {
return;
};
let body = serde_json::json!({ "code": "garbage.code" }).to_string();
let response = post_json(state.clone(), &host, "/api/invites/claim", &joiner, body).await;
assert_eq!(response.status(), StatusCode::FORBIDDEN);
let json = read_json(response).await;
assert_eq!(
json.get("error").and_then(Value::as_str),
Some("invite_invalid")
);
let community = state
.db
.lookup_community_by_host(&host)
.await
.expect("lookup")
.expect("community exists");
let is_member = state
.db
.is_relay_member(community.id, &joiner.public_key().to_hex())
.await
.expect("member check");
assert!(!is_member, "invalid code must not admit anyone");
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn code_minted_for_one_community_fails_on_another() {
let host_a = format!("invites-a-{}.example", Uuid::new_v4().simple());
let host_b = format!("invites-b-{}.example", Uuid::new_v4().simple());
let owner = Keys::generate();
let joiner = Keys::generate();
let Some(state) = invite_test_state(&host_a).await else {
return;
};
state
.db
.ensure_configured_community(&host_b)
.await
.expect("second community");
let community_a = state
.db
.lookup_community_by_host(&host_a)
.await
.expect("lookup")
.expect("community a");
state
.db
.add_relay_member(
community_a.id,
&owner.public_key().to_hex(),
"owner",
None,
&nostr::Keys::generate(),
)
.await
.map(|write| write.outcome)
.expect("seed owner");
let response = post_json(
state.clone(),
&host_a,
"/api/invites",
&owner,
"{}".to_string(),
)
.await;
assert_eq!(response.status(), StatusCode::OK);
let json = read_json(response).await;
let code = json.get("code").and_then(Value::as_str).expect("code");
// Present community A's code on community B's host.
let body = serde_json::json!({ "code": code }).to_string();
let response = post_json(state, &host_b, "/api/invites/claim", &joiner, body).await;
assert_eq!(response.status(), StatusCode::FORBIDDEN);
}
fn unix_now() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("time")
.as_secs()
}
/// Forge a v1 HMAC invite payload expiring at `expires_at`, signed with
/// the relay's derived invite key. `mint_invite` only mints v2 codes now
/// and clamps ttl to 60s minimum, so v1 and expired codes are built by
/// hand at the token layer.
fn forge_v1_invite_code(
state: &AppState,
community: buzz_core::CommunityId,
expires_at: u64,
) -> String {
let key = derive_invite_key(&state.relay_keypair);
let payload = InvitePayload {
c: community.as_uuid().to_string(),
r: "member".to_string(),
e: expires_at,
n: "test-nonce".to_string(),
};
let payload_bytes = serde_json::to_vec(&payload).expect("payload serializes");
let mut mac =
<Hmac<Sha256> as KeyInit>::new_from_slice(&key).expect("HMAC accepts any key size");
mac.update(&payload_bytes);
let mac_bytes = mac.finalize().into_bytes();
format!(
"{}.{}",
URL_SAFE_NO_PAD.encode(&payload_bytes),
URL_SAFE_NO_PAD.encode(mac_bytes),
)
}
/// Endpoint-level proof that expired codes (with a valid MAC) are
/// rejected by `/api/invites/claim` with the distinguishable
/// `invite_expired` body, and do not admit the caller.
#[tokio::test]
#[ignore = "requires Postgres"]
async fn claim_rejects_expired_code() {
let host = format!("invites-{}.example", Uuid::new_v4().simple());
let joiner = Keys::generate();
let state = invite_test_state(&host)
.await
.expect("requires reachable Postgres and relay test state");
let community = state
.db
.lookup_community_by_host(&host)
.await
.expect("lookup")
.expect("community exists");
let code = forge_v1_invite_code(&state, community.id, unix_now() - 10);
let body = serde_json::json!({ "code": code }).to_string();
let response = post_json(state.clone(), &host, "/api/invites/claim", &joiner, body).await;
assert_eq!(response.status(), StatusCode::FORBIDDEN);
let json = read_json(response).await;
// The expired branch is deliberately distinguishable from the generic
// `invite_invalid` so the UX can prompt the user for a fresh link
// without becoming a MAC oracle.
assert_eq!(
json.get("error").and_then(Value::as_str),
Some("invite_expired"),
"expired branch must be distinguishable from generic invalid",
);
let is_member = state
.db
.is_relay_member(community.id, &joiner.public_key().to_hex())
.await
.expect("member check");
assert!(!is_member, "expired code must not admit anyone");
}
/// NIP-98 replay guard that returns `Ok(true)` the first time a given
/// event id is seen and `Ok(false)` on every subsequent call — mirrors
/// what the Redis guard does after a `SET NX` succeeds and then fails.
struct SeenOnceReplayGuard {
seen: Mutex<std::collections::HashSet<[u8; 32]>>,
}
impl SeenOnceReplayGuard {
fn new() -> Self {
Self {
seen: Mutex::new(std::collections::HashSet::new()),
}
}
}
impl buzz_auth::Nip98ReplayGuard for SeenOnceReplayGuard {
fn try_mark_in_scope<'a>(
&'a self,
_scope: &'a str,
event_id: &'a EventId,
_ttl_secs: u64,
) -> std::pin::Pin<
Box<dyn std::future::Future<Output = Result<bool, buzz_auth::AuthError>> + Send + 'a>,
> {
let bytes = *event_id.as_bytes();
let inserted = self.seen.lock().expect("replay set").insert(bytes);
Box::pin(async move { Ok(inserted) })
}
}
/// Endpoint-level proof that a replayed NIP-98 auth event on a claim POST
/// is rejected — the first claim succeeds, but reusing the exact same
/// Authorization header (same signed NIP-98 event id) is rejected as
/// replay before the invite verification ever runs.
#[tokio::test]
#[ignore = "requires Postgres"]
async fn claim_rejects_replayed_nip98_auth() {
let host = format!("invites-{}.example", Uuid::new_v4().simple());
let owner = Keys::generate();
let joiner = Keys::generate();
let state_arc = invite_test_state(&host)
.await
.expect("requires reachable Postgres and relay test state");
// Swap the always-fresh guard for one that fires the second time the
// same event id is presented — the code path we're pinning.
let mut state_owned =
Arc::try_unwrap(state_arc).unwrap_or_else(|_| panic!("sole owner of AppState"));
state_owned.nip98_replay = Arc::new(SeenOnceReplayGuard::new());
let state = Arc::new(state_owned);
let community = state
.db
.lookup_community_by_host(&host)
.await
.expect("lookup")
.expect("community exists");
state
.db
.add_relay_member(
community.id,
&owner.public_key().to_hex(),
"owner",
None,
&nostr::Keys::generate(),
)
.await
.map(|write| write.outcome)
.expect("seed owner");
// Mint a valid code so the replay under test is on the claim path.
let response = post_json(
state.clone(),
&host,
"/api/invites",
&owner,
"{}".to_string(),
)
.await;
assert_eq!(response.status(), StatusCode::OK);
let json = read_json(response).await;
let code = json.get("code").and_then(Value::as_str).expect("code");
// Build one NIP-98 header and reuse it verbatim on two claim POSTs.
let claim_body = serde_json::json!({ "code": code }).to_string();
let claim_url = format!("https://{host}/api/invites/claim");
let claim_auth = nip98_auth_header(&joiner, &claim_url, claim_body.as_bytes());
let send_claim = |auth: String, body: String| {
let state = state.clone();
let host = host.clone();
async move {
build_router(state)
.oneshot(
Request::builder()
.method("POST")
.uri("/api/invites/claim")
.header(header::HOST, host.as_str())
.header(header::AUTHORIZATION, auth)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(body))
.expect("request"),
)
.await
.expect("response")
}
};
let first = send_claim(claim_auth.clone(), claim_body.clone()).await;
assert_eq!(first.status(), StatusCode::OK);
// Same signed auth event, sent again → replay guard fires.
let second = send_claim(claim_auth, claim_body).await;
assert_eq!(second.status(), StatusCode::UNAUTHORIZED);
let json = read_json(second).await;
assert_eq!(
json.get("error").and_then(Value::as_str),
Some("NIP-98: replay detected"),
);
}
/// Endpoint-level proof that `/api/invites/claim` enforces the per-pubkey
/// fixed-window rate limit — the same joiner probing the endpoint hits
/// 429 on the `CLAIM_RATE_LIMIT + 1`th attempt inside the window.
///
/// We use invalid codes throughout so no membership state can change; the
/// limiter runs before code verification, so the transition from
/// `invite_invalid` (403) to `too many invite claim attempts` (429) proves
/// the limiter guard is on the request path and fires on repeat pubkey.
#[tokio::test]
#[ignore = "requires Postgres"]
async fn claim_rate_limit_fires_on_repeat_pubkey() {
let host = format!("invites-{}.example", Uuid::new_v4().simple());
let joiner = Keys::generate();
let state_arc = invite_test_state(&host)
.await
.expect("requires reachable Postgres and relay test state");
// Fresh limiter with the production limit so the assertion pins the
// in-endpoint threshold, not a test-only budget.
let mut state_owned =
Arc::try_unwrap(state_arc).unwrap_or_else(|_| panic!("sole owner of AppState"));
state_owned.invite_claim_rate_limiter = Arc::new(claim_cache(
super::CLAIM_RATE_CACHE_CAPACITY,
super::CLAIM_RATE_WINDOW,
));
let state = Arc::new(state_owned);
let body = serde_json::json!({ "code": "garbage.code" }).to_string();
for _ in 0..CLAIM_RATE_LIMIT {
let response = post_json(
state.clone(),
&host,
"/api/invites/claim",
&joiner,
body.clone(),
)
.await;
assert_eq!(
response.status(),
StatusCode::FORBIDDEN,
"attempts up to the limit should reach code verification and be rejected as invalid",
);
let json = read_json(response).await;
assert_eq!(
json.get("error").and_then(Value::as_str),
Some("invite_invalid"),
);
}
let over_limit = post_json(state, &host, "/api/invites/claim", &joiner, body).await;
assert_eq!(over_limit.status(), StatusCode::TOO_MANY_REQUESTS);
let json = read_json(over_limit).await;
assert_eq!(
json.get("error").and_then(Value::as_str),
Some("too many invite claim attempts, slow down"),
);
}
#[test]
fn policy_document_renders_markdown_and_escapes_raw_html() {
let page = super::render_policy_document(
"Terms of Service",
"# Terms\n\nBe kind & honest.\n\n<script>alert(1)</script>",
);
assert!(page.contains("<title>Terms of Service</title>"), "{page}");
assert!(page.contains("<h1>Terms</h1>"), "{page}");
// `&` inside prose must be entity-encoded by the HTML writer.
assert!(page.contains("Be kind &amp; honest."), "{page}");
// Raw HTML in operator Markdown renders as escaped text, never markup.
assert!(!page.contains("<script>"), "{page}");
assert!(
page.contains("&lt;script&gt;alert(1)&lt;/script&gt;"),
"{page}"
);
}
/// The document routes are public (no NIP-98) and 404 until configured,
/// exactly like the JSON policy endpoint they sit beside.
#[tokio::test]
#[ignore = "requires Postgres"]
async fn join_policy_document_pages_serve_configured_markdown() {
let host = format!("invites-docs-{}.example", Uuid::new_v4().simple());
let Some(state) = invite_test_state(&host).await else {
return;
};
let get_page = |state: Arc<crate::state::AppState>, path: &'static str| {
let host = host.clone();
async move {
build_router(state)
.oneshot(
Request::builder()
.method("GET")
.uri(path)
.header(header::HOST, host)
.body(Body::empty())
.expect("request"),
)
.await
.expect("response")
}
};
// Unconfigured relay: both documents 404.
let response = get_page(state.clone(), "/api/join-policy/terms").await;
assert_eq!(response.status(), StatusCode::NOT_FOUND);
let response = get_page(state.clone(), "/api/join-policy/privacy").await;
assert_eq!(response.status(), StatusCode::NOT_FOUND);
// Configure terms only — terms serves HTML, privacy still 404s.
let mut state_inner = (*state).clone();
let mut config = state_inner.config.as_ref().clone();
config.join_policy = Some(crate::config::JoinPolicyConfig {
terms_markdown: Some("# Terms\n\nNo funny business.".to_string()),
privacy_markdown: None,
age_attestation_required: false,
version: "v".repeat(64),
});
state_inner.config = Arc::new(config);
let state = Arc::new(state_inner);
let response = get_page(state.clone(), "/api/join-policy/terms").await;
assert_eq!(response.status(), StatusCode::OK);
let content_type = response
.headers()
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or_default()
.to_string();
assert!(content_type.starts_with("text/html"), "{content_type}");
let bytes = to_bytes(response.into_body(), 1024 * 1024)
.await
.expect("read body");
let page = String::from_utf8(bytes.to_vec()).expect("utf8");
assert!(page.contains("<h1>Terms</h1>"), "{page}");
assert!(page.contains("No funny business."), "{page}");
let response = get_page(state, "/api/join-policy/privacy").await;
assert_eq!(response.status(), StatusCode::NOT_FOUND);
}
// ── NIP-FI seam tests: POST /api/invites ──────────────────────────────────
//
// Gate under test: `admit_nip_fi_http_on_state` in `mint_invite_checked`.
// The router's assertion guard runs first and only verifies the assertion,
// so the handler's own admission is what enforces key pairing.
//
// Infrastructure: `#[ignore = "requires Postgres"]` + tokio::test on the
// invites harness; NIP-FI Enforce is enabled by patching the config after
// state construction.
// Static P-256 test key, shared with the bridge/media/settings NIP-FI tests.
const NIP_FI_TEST_ISSUER: &str = "https://issuer.example";
const NIP_FI_TEST_AUDIENCE: &str = "https://relay.example";
const NIP_FI_TEST_KID: &str = "test-key-1";
const NIP_FI_TEST_EC_PKCS8_PEM: &str = "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgcnxDM4EiirH9dHUE\nWZc759TX4s5PAn8kO5ovXSnGxCWhRANCAARFb6ZnsfkqOOXyEhj3KBQphGKF4vTa\nzhebbavbZ1ZoklqkF1cGg+jTO7rONAVEzXvXUWtV6CdDV+rybiVmFP2w\n-----END PRIVATE KEY-----\n"; // sadscan:disable np.pem.1 kingfisher.privkey.2 -- public ES256 test fixture
/// Clone `base` into an Enforce-mode state. With `with_verifier`, a real
/// ES256 verifier over the static test key is injected so a signed
/// assertion passes the router guard and reaches the handler.
fn nip_fi_enforce_state(base: &AppState, with_verifier: bool) -> Arc<AppState> {
use buzz_auth::{
AssertionKeySet, FederatedAssertionVerifier, FreshnessClass, IssuerPolicy,
IssuerRegistry, StaticIssuerKeySource, TokenClass, VerifyAssertion,
};
use jsonwebtoken::{jwk::JwkSet, Algorithm};
let mut state = base.clone();
let mut config = (*state.config).clone();
config.require_auth_token = true;
config.nip_fi.mode = buzz_auth::NipFiMode::Enforce;
config.nip_fi.communities =
crate::nip_fi_core::test_support::any_host("https://relay.example");
state.config = Arc::new(config);
if !with_verifier {
return Arc::new(state);
}
let jwks: JwkSet = serde_json::from_value(serde_json::json!({
"keys": [{
"kty": "EC", "crv": "P-256", "use": "sig", "alg": "ES256",
"kid": NIP_FI_TEST_KID,
"x": "RW-mZ7H5Kjjl8hIY9ygUKYRiheL02s4Xm22r22dWaJI",
"y": "WqQXVwaD6NM7us40BUTNe9dRa1XoJ0NX6vJuJWYU_bA"
}]
}))
.expect("valid test JWKS");
let hard_deadline = chrono::Utc::now() + chrono::Duration::seconds(3600);
let key_set =
AssertionKeySet::new_for_test(NIP_FI_TEST_ISSUER.to_owned(), 1, jwks, hard_deadline)
.expect("valid test key set");
let jwks_contract = buzz_auth::JwksSourceContract::new(
format!("{NIP_FI_TEST_ISSUER}/.well-known/jwks.json"),
300,
3600,
)
.expect("valid jwks contract");
let policy = IssuerPolicy::new(
NIP_FI_TEST_ISSUER.to_owned(),
vec![NIP_FI_TEST_AUDIENCE.to_owned()],
TokenClass::DedicatedNipFi,
FreshnessClass::OfflineJwt,
vec![Algorithm::ES256],
60,
3600,
None,
jwks_contract,
)
.expect("valid issuer policy");
let mut registry = IssuerRegistry::new();
registry.insert(policy);
let verifier: Arc<dyn VerifyAssertion> = Arc::new(FederatedAssertionVerifier::new(
registry,
StaticIssuerKeySource::new([key_set]),
));
state.nip_fi_verifier = Some(verifier);
Arc::new(state)
}
/// Mint a signed NIP-FI assertion binding `keys`' pubkey.
fn nip_fi_signed_assertion(keys: &Keys) -> String {
use jsonwebtoken::{Algorithm, EncodingKey, Header};
let now = chrono::Utc::now().timestamp();
let claims = serde_json::json!({
"iss": NIP_FI_TEST_ISSUER,
"aud": NIP_FI_TEST_AUDIENCE,
"iat": now,
"exp": now + 600,
"sub": "test-subject",
"nostr_pubkey": keys.public_key().to_hex(),
});
let mut header = Header::new(Algorithm::ES256);
header.kid = Some(NIP_FI_TEST_KID.to_owned());
header.typ = Some("nip-fi+jwt".to_owned());
let key = EncodingKey::from_ec_pem(NIP_FI_TEST_EC_PKCS8_PEM.as_bytes())
.expect("valid test EC PEM");
jsonwebtoken::encode(&header, &claims, &key).expect("sign assertion")
}
/// POST `/api/invites` with a NIP-98 proof from `nip98_keys` and, when
/// given, a NIP-FI assertion; returns `(status, body)`.
async fn nip_fi_post_mint(
state: Arc<AppState>,
host: &str,
nip98_keys: &Keys,
assertion: Option<String>,
) -> (StatusCode, Vec<u8>) {
let url = format!("https://{host}/api/invites");
let mut request = Request::builder()
.method("POST")
.uri("/api/invites")
.header(header::HOST, host)
.header(
header::AUTHORIZATION,
nip98_auth_header(nip98_keys, &url, b"{}"),
)
.header(header::CONTENT_TYPE, "application/json");
if let Some(token) = assertion {
request = request.header("Nostr-Federated-Identity", format!("Bearer {token}"));
}
let response = build_router(state)
.oneshot(request.body(Body::from("{}")).expect("request"))
.await
.expect("response");
let status = response.status();
let body = to_bytes(response.into_body(), 1024 * 1024)
.await
.expect("read body")
.to_vec();
(status, body)
}
/// Valid NIP-98 + no assertion → the router's outer assertion guard denies
/// 401 before the handler runs. This witnesses the guard only; handler
/// pairing is covered by `nip_fi_enforce_mint_invite_key_mismatch_is_403`.
///
#[tokio::test]
#[ignore = "requires Postgres"]
async fn nip_fi_enforce_mint_invite_no_assertion_is_401() {
let host = format!("nip-fi-invites-seam-{}.local", Uuid::new_v4().simple());
let Some(state_base) = invite_test_state(&host).await else {
return;
};
// No verifier: the guard's missing-assertion check fires before any
// verifier lookup.
let state = nip_fi_enforce_state(&state_base, false);
let (status, _) = nip_fi_post_mint(state, &host, &Keys::generate(), None).await;
assert_eq!(
status,
StatusCode::UNAUTHORIZED,
"NIP-FI enforce mode: POST /api/invites with valid NIP-98 + no assertion MUST be \
denied 401 by the router's outer assertion guard [FI-TRACE-HTTP-INGRESS]"
);
}
/// Valid assertion for key A + NIP-98 proof for key B → the request passes
/// the router guard (which only verifies the assertion) and the handler's
/// `admit_nip_fi_http_on_state` denies on key pairing with exactly 403
/// `authorization denied\n`. Key B is a seeded owner, so without the
/// handler's admission the mint would succeed.
///
/// Falsifying mutation: replace the handler's `admit_nip_fi_http_on_state`
/// with NIP-98-only admission (`admit_nip_fi_http` in Off mode) — the
/// owner's mint succeeds with 200.
///
/// [FI-INV-05] [FI-TRACE-ASSERTION-KEY-MISMATCH]
#[tokio::test]
#[ignore = "requires Postgres"]
async fn nip_fi_enforce_mint_invite_key_mismatch_is_403() {
let host = format!("nip-fi-invites-pair-{}.local", Uuid::new_v4().simple());
let state_base = invite_test_state(&host)
.await
.expect("requires reachable Postgres and relay test state");
let asserted = Keys::generate();
let owner = Keys::generate();
seed_nip_fi_owner(&state_base, &host, &owner).await;
let state = nip_fi_enforce_state(&state_base, true);
let (status, body) = nip_fi_post_mint(
state,
&host,
&owner,
Some(nip_fi_signed_assertion(&asserted)),
)
.await;
assert_eq!(
(status, body.as_slice()),
(StatusCode::FORBIDDEN, b"authorization denied\n".as_slice()),
"assertion for key A + NIP-98 for key B MUST reach mint_invite_checked and be \
denied by its NIP-FI key pairing"
);
}
/// Same-key control for the mismatch test: assertion and NIP-98 both for
/// the seeded owner → admission succeeds and the handler mints normally.
/// Proves the handler does not deny every assertion-bearing request.
#[tokio::test]
#[ignore = "requires Postgres"]
async fn nip_fi_enforce_mint_invite_same_key_mints() {
let host = format!("nip-fi-invites-ctrl-{}.local", Uuid::new_v4().simple());
let state_base = invite_test_state(&host)
.await
.expect("requires reachable Postgres and relay test state");
let owner = Keys::generate();
seed_nip_fi_owner(&state_base, &host, &owner).await;
let state = nip_fi_enforce_state(&state_base, true);
let (status, body) =
nip_fi_post_mint(state, &host, &owner, Some(nip_fi_signed_assertion(&owner))).await;
assert_eq!(
status,
StatusCode::OK,
"matching assertion and NIP-98 keys must be admitted and mint: {}",
String::from_utf8_lossy(&body)
);
let json: Value = serde_json::from_slice(&body).expect("mint response JSON");
assert!(json.get("code").and_then(Value::as_str).is_some(), "{json}");
}
async fn seed_nip_fi_owner(state: &AppState, host: &str, owner: &Keys) {
let community = state
.db
.lookup_community_by_host(host)
.await
.expect("lookup")
.expect("community exists");
state
.db
.add_relay_member(
community.id,
&owner.public_key().to_hex(),
"owner",
None,
&nostr::Keys::generate(),
)
.await
.map(|write| write.outcome)
.expect("seed owner");
}
}