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>
This commit is contained in:
Will Pfleger
2026-11-20 15:48:36 -05:00
committed by GitHub
parent 81b4054e5d
commit 792a9ce563
9 changed files with 1608 additions and 139 deletions

View File

@@ -1,9 +1,14 @@
//! Relay invite HTTP API — mint and claim stateless invite codes.
//!
//! Routes (both NIP-98 signed, outside the Nostr event data plane):
//! 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
@@ -39,7 +44,9 @@ 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);
@@ -264,7 +271,6 @@ pub async fn mint_invite(
mint_invite_checked(state, slot, headers, body).await
}
#[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers
async fn mint_invite_checked(
state: Arc<AppState>,
slot: AccessSlot,
@@ -273,70 +279,17 @@ async fn mint_invite_checked(
) -> axum::response::Response {
use axum::response::IntoResponse as _;
let Some(tenant) = crate::nip_fi_shadow::bind_tenant(&state, &headers).await else {
return 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, "/api/invites");
// 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 = match admit_nip_fi_http_on_state(
&state,
&headers,
&slot,
bridge::make_nip98_closure_for_admission(
slot.clone(),
headers.clone(),
"POST",
url,
Some(body.to_vec()),
true, // invites always require NIP-98; no X-Pubkey dev fallback
true, // POST bodies must be covered by a payload tag
),
)
.await
{
Ok(a) => a,
Err(resp) => return resp,
};
let mut caller = bridge::ProvenCaller::new(admission, &slot, &tenant);
let pubkey = caller.pubkey;
// Replay detection runs after NIP-98+assertion admission (both proofs verified).
if let Err(e) = caller.replay(&state, &tenant).await {
return 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;
// The shared gate records the verified owner; a different stored owner
// keeps this route's own refusal code.
if let Err(e) = caller.check(
membership,
super::relay_members::MembershipRefusal::auth_result,
) {
if let super::relay_members::MembershipRefusal::Api(AuthReason::OwnerMismatch, _) = e {
return api_error(StatusCode::FORBIDDEN, "invite_owner_mismatch").into_response();
}
return e.into_response();
}
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, &mut caller, body, tenant, pubkey).await {
match mint_invite_inner(&state, body, tenant, pubkey).await {
Ok((json, minted)) => {
slot.detail(minted);
json.into_response()
@@ -345,42 +298,129 @@ async fn mint_invite_checked(
}
}
/// 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,
caller: &mut bridge::ProvenCaller,
body: axum::body::Bytes,
tenant: buzz_core::TenantContext,
pubkey: nostr::PublicKey,
) -> Result<(Json<Value>, crate::access::Detail), (StatusCode, Json<Value>)> {
// Authz mirrors kind:9030 (add member): owner or admin only.
let sender_hex = pubkey.to_hex();
let member = caller
.check(
state
.db
.get_relay_member(tenant.community(), &sender_hex)
.await,
|_| AuthResult::Denied(AuthReason::AuthorizationUnavailable),
)
.map_err(|e| internal_error(&format!("invite mint role lookup: {e}")))?;
// 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,
"only relay owners and admins can create invites",
)
})?;
let request: MintInviteRequest = if body.is_empty() {
MintInviteRequest::default()
} else {
@@ -403,7 +443,7 @@ async fn mint_invite_inner(
let minted = crate::access::Detail {
invite_id: Some(invite.invite_id),
expires_at: Some(invite.expires_at.timestamp()),
expires_at: invite.expires_at.map(|at| at.timestamp()),
max_uses: invite.max_uses,
..Default::default()
};
@@ -414,8 +454,8 @@ async fn mint_invite_inner(
))
}
/// The mint response contract shared by every mint route: the code, its
/// expiry in Unix seconds, its use limits, and the landing-page URL on `host`.
/// 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,
@@ -429,8 +469,9 @@ pub(crate) fn minted_invite_json(
"http"
};
serde_json::json!({
"invite_id": invite.invite_id,
"code": invite.code,
"expires_at": invite.expires_at.timestamp() as u64,
"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),
@@ -692,6 +733,7 @@ fn claim_key_rate_limited(
#[cfg(test)]
mod postgres_tests {
mod manage_tests;
mod owner_admission_tests;
mod recovery_postgres_tests;
mod restriction_tests;

View File

@@ -0,0 +1,217 @@
//! `GET /api/invites` and `POST /api/invites/revoke`.
//!
//! Neither response nor access line carries an invite code or its hash, and
//! request errors are fixed strings that never echo input.
use std::sync::Arc;
use axum::{
extract::{RawQuery, State},
http::{HeaderMap, StatusCode},
response::{IntoResponse as _, Json, Response},
};
use buzz_core::invite::{hash_v2_code, validate_v2_code};
use buzz_db::relay_invite::{InviteSelector, InviteSummary};
use serde::Deserialize;
use serde_json::Value;
use uuid::Uuid;
use super::{admit_invite_caller, api_error, internal_error, InviteGate};
use crate::access::{AccessSlot, AuthReason, AuthResult};
use crate::state::AppState;
const DEFAULT_LIST_LIMIT: i64 = 50;
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ListQuery {
limit: Option<i64>,
before: Option<String>,
}
/// The list cursor: the last row's `created_at` in Unix microseconds (the
/// column's precision) and its id, so a page never depends on that row
/// still existing.
fn encode_cursor(invite: &InviteSummary) -> String {
format!("{}_{}", invite.created_at.timestamp_micros(), invite.id)
}
fn decode_cursor(cursor: &str) -> Option<(chrono::DateTime<chrono::Utc>, Uuid)> {
let (micros, id) = cursor.split_once('_')?;
Some((
chrono::DateTime::from_timestamp_micros(micros.parse().ok()?)?,
id.parse().ok()?,
))
}
/// Body for `POST /api/invites/revoke`: exactly one of `id` or `code`.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RevokeInviteRequest {
id: Option<Uuid>,
code: Option<String>,
}
/// List invites — `GET /api/invites?limit=&before=`, NIP-98 signed by an
/// owner/admin over the full URL, query included. Newest first; when a page
/// is full, `next_before` is the opaque cursor to pass as `before`.
pub async fn list_invites(
State(state): State<Arc<AppState>>,
slot: AccessSlot,
RawQuery(query): RawQuery,
headers: HeaderMap,
) -> Response {
let path = match &query {
Some(query) => format!("/api/invites?{query}"),
None => "/api/invites".to_owned(),
};
let gate = InviteGate::Admin("only relay owners and admins can list invites");
let body = axum::body::Bytes::new();
let (tenant, _) =
match admit_invite_caller(&state, &slot, &headers, "GET", &path, &body, gate).await {
Ok(admitted) => admitted,
Err(response) => return response,
};
let query: ListQuery = match serde_urlencoded::from_str(query.as_deref().unwrap_or("")) {
Ok(query) => query,
Err(_) => return api_error(StatusCode::BAD_REQUEST, "invalid query").into_response(),
};
let before = match query.before.as_deref().map(decode_cursor) {
None => None,
Some(Some(cursor)) => Some(cursor),
Some(None) => return api_error(StatusCode::BAD_REQUEST, "invalid before").into_response(),
};
let limit = query.limit.unwrap_or(DEFAULT_LIST_LIMIT);
if !(1..=buzz_db::relay_invite::MAX_INVITE_LIST_LIMIT).contains(&limit) {
return api_error(
StatusCode::BAD_REQUEST,
&format!(
"limit must be between 1 and {}",
buzz_db::relay_invite::MAX_INVITE_LIST_LIMIT
),
)
.into_response();
}
let invites = match state
.db
.list_relay_invites(tenant.community(), limit, before)
.await
{
Ok(invites) => invites,
Err(e) => return internal_error(&format!("invite list: {e}")).into_response(),
};
let next_before = (invites.len() as i64 == limit)
.then(|| invites.last().map(encode_cursor))
.flatten();
let now = chrono::Utc::now();
Json(serde_json::json!({
"invites": invites.iter().map(|invite| invite_json(invite, now)).collect::<Vec<_>>(),
"next_before": next_before,
}))
.into_response()
}
fn invite_json(invite: &InviteSummary, now: chrono::DateTime<chrono::Utc>) -> Value {
serde_json::json!({
"id": invite.id,
"created_by": invite.created_by,
"created_at": invite.created_at.timestamp(),
"expires_at": invite.expires_at.map(|at| at.timestamp()),
"max_uses": invite.max_uses,
"use_count": invite.use_count,
"revoked_at": invite.revoked_at.map(|at| at.timestamp()),
"status": invite.status(now).as_str(),
})
}
/// Revoke an invite — `POST /api/invites/revoke` with `{"id": ...}` or
/// `{"code": "v2...."}`, NIP-98 signed with a payload tag. Owners and admins
/// can revoke any invite in the community; any other member only one they
/// created. Repeating a revoke returns the first `revoked_at`.
pub async fn revoke_invite(
State(state): State<Arc<AppState>>,
slot: AccessSlot,
headers: HeaderMap,
body: axum::body::Bytes,
) -> Response {
let (tenant, pubkey) = match admit_invite_caller(
&state,
&slot,
&headers,
"POST",
"/api/invites/revoke",
&body,
InviteGate::Member,
)
.await
{
Ok(admitted) => admitted,
Err(response) => return response,
};
let request: RevokeInviteRequest = match serde_json::from_slice(&body) {
Ok(request) => request,
Err(_) => {
return api_error(StatusCode::BAD_REQUEST, "invalid revoke request").into_response()
}
};
let token_hash;
let selector = match (request.id, request.code.as_deref()) {
(Some(id), None) => InviteSelector::Id(id),
(None, Some(code)) => {
// v1 codes have no row to revoke.
if validate_v2_code(code).is_err() {
return api_error(StatusCode::BAD_REQUEST, "invite_not_revocable").into_response();
}
token_hash = hash_v2_code(code);
InviteSelector::TokenHash(&token_hash)
}
_ => {
return api_error(
StatusCode::BAD_REQUEST,
"exactly one of id or code is required",
)
.into_response()
}
};
let revoked = state
.db
.revoke_relay_invite(tenant.community(), &pubkey.to_hex(), selector)
.await;
match revoked {
Ok(Some(revoked)) => {
slot.detail(crate::access::Detail {
invite_id: Some(revoked.id),
..Default::default()
});
Json(serde_json::json!({
"id": revoked.id,
"revoked_at": revoked.revoked_at.timestamp(),
}))
.into_response()
}
Ok(None) => api_error(StatusCode::NOT_FOUND, "invite_not_found").into_response(),
// The database made the final role decision; log its refusal.
Err(buzz_db::DbError::InviteRevokeForbidden) => {
slot.finish(AuthResult::Denied(AuthReason::NotRelayAdmin));
api_error(
StatusCode::FORBIDDEN,
"only relay owners, admins or the invite's creator can revoke it",
)
.into_response()
}
Err(buzz_db::DbError::InviteRestricted) => {
slot.finish(AuthResult::Denied(AuthReason::Restricted));
api_error(StatusCode::FORBIDDEN, "invite_restricted").into_response()
}
Err(buzz_db::DbError::AccessDenied(_)) => api_error(
StatusCode::SERVICE_UNAVAILABLE,
"community writes are temporarily unavailable",
)
.into_response(),
Err(e) => internal_error(&format!("invite revoke: {e}")).into_response(),
}
}

View File

@@ -0,0 +1,409 @@
mod postgres_tests {
use super::super::restriction_tests::postgres_tests::fixture;
use super::super::*;
fn nip98_get_header(keys: &Keys, url: &str) -> String {
let event = EventBuilder::new(Kind::HttpAuth, "")
.tags([
Tag::parse(["u", url]).unwrap(),
Tag::parse(["method", "GET"]).unwrap(),
])
.sign_with_keys(keys)
.unwrap();
let encoded = base64::engine::general_purpose::STANDARD
.encode(serde_json::to_string(&event).unwrap().as_bytes());
format!("Nostr {encoded}")
}
/// GET `path` signed for `signed_path`, which a test may make differ.
async fn get_signed(
state: Arc<AppState>,
host: &str,
path: &str,
signed_path: &str,
keys: &Keys,
) -> axum::response::Response {
let auth = nip98_get_header(keys, &format!("https://{host}{signed_path}"));
build_router(state)
.oneshot(
Request::builder()
.method("GET")
.uri(path)
.header(header::HOST, host)
.header(header::AUTHORIZATION, auth)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap()
}
async fn add_member(
state: &AppState,
community: buzz_core::CommunityId,
keys: &Keys,
role: &str,
) {
state
.db
.add_relay_member(
community,
&keys.public_key().to_hex(),
role,
None,
&state.relay_keypair,
)
.await
.map(|write| write.outcome)
.unwrap();
}
async fn mint(state: &Arc<AppState>, host: &str, keys: &Keys) -> Value {
let response = post_json(state.clone(), host, "/api/invites", keys, "{}".into()).await;
assert_eq!(response.status(), StatusCode::OK);
read_json(response).await
}
async fn revoke(
state: &Arc<AppState>,
host: &str,
keys: &Keys,
body: Value,
) -> (StatusCode, Value) {
let response = post_json(
state.clone(),
host,
"/api/invites/revoke",
keys,
body.to_string(),
)
.await;
(response.status(), read_json(response).await)
}
fn assert_no_secret(json: &Value, code: &str) {
let text = json.to_string();
assert!(!text.contains(code), "{text}");
assert!(!text.contains("token_hash"), "{text}");
assert!(
!text.contains(&hex::encode(Sha256::digest(code.as_bytes()))),
"{text}"
);
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn owner_lists_and_revokes_by_id_or_code() {
let (state, host, _, owner) = fixture().await;
let first = mint(&state, &host, &owner).await;
let second = mint(&state, &host, &owner).await;
let first_code = first["code"].as_str().unwrap().to_owned();
let second_code = second["code"].as_str().unwrap().to_owned();
let second_id = second["invite_id"]
.as_str()
.expect("mint returns invite_id");
let response =
get_signed(state.clone(), &host, "/api/invites", "/api/invites", &owner).await;
assert_eq!(response.status(), StatusCode::OK);
let listed = read_json(response).await;
assert_eq!(listed["invites"].as_array().unwrap().len(), 2);
assert_eq!(listed["invites"][0]["id"], second_id);
assert_eq!(listed["invites"][0]["status"], "active");
assert!(listed["invites"][0]["expires_at"].is_i64());
assert_eq!(listed["next_before"], Value::Null);
assert_no_secret(&listed, &first_code);
assert_no_secret(&listed, &second_code);
let (status, by_code) = revoke(
&state,
&host,
&owner,
serde_json::json!({ "code": first_code }),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(by_code["id"], first["invite_id"]);
assert_no_secret(&by_code, &first_code);
let (status, again) = revoke(
&state,
&host,
&owner,
serde_json::json!({ "id": first["invite_id"] }),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(again["revoked_at"], by_code["revoked_at"]);
let claim = post_json(
state.clone(),
&host,
"/api/invites/claim",
&Keys::generate(),
serde_json::json!({ "code": first_code }).to_string(),
)
.await;
assert_ne!(
claim.status(),
StatusCode::OK,
"a revoked link cannot be claimed"
);
let claim = post_json(
state.clone(),
&host,
"/api/invites/claim",
&Keys::generate(),
serde_json::json!({ "code": second_code }).to_string(),
)
.await;
assert_eq!(claim.status(), StatusCode::OK, "the other link still works");
let page = get_signed(
state.clone(),
&host,
"/api/invites?limit=1",
"/api/invites?limit=1",
&owner,
)
.await;
let page = read_json(page).await;
assert_eq!(page["invites"][0]["id"], second_id);
let cursor = page["next_before"]
.as_str()
.expect("a full page has a cursor");
let path = format!("/api/invites?before={cursor}");
let older = read_json(get_signed(state, &host, &path, &path, &owner).await).await;
assert_eq!(older["invites"][0]["id"], first["invite_id"]);
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn members_list_nothing_and_revoke_only_their_own() {
let (state, host, community, owner) = fixture().await;
let creator = Keys::generate();
let member = Keys::generate();
add_member(&state, community, &creator, "admin").await;
add_member(&state, community, &member, "member").await;
let invite = mint(&state, &host, &creator).await;
let owners = mint(&state, &host, &owner).await;
state
.db
.update_relay_member_role(
community,
&creator.public_key().to_hex(),
"member",
&state.relay_keypair,
)
.await
.map(|write| write.outcome)
.unwrap();
for keys in [&creator, &member, &Keys::generate()] {
let response =
get_signed(state.clone(), &host, "/api/invites", "/api/invites", keys).await;
assert_eq!(response.status(), StatusCode::FORBIDDEN);
}
let (status, _) = revoke(
&state,
&host,
&member,
serde_json::json!({ "id": invite["invite_id"] }),
)
.await;
assert_eq!(status, StatusCode::FORBIDDEN, "not the creator");
let (status, _) = revoke(
&state,
&host,
&creator,
serde_json::json!({ "id": owners["invite_id"] }),
)
.await;
assert_eq!(status, StatusCode::FORBIDDEN, "no longer an admin");
let (status, _) = revoke(
&state,
&host,
&Keys::generate(),
serde_json::json!({ "id": invite["invite_id"] }),
)
.await;
assert_eq!(status, StatusCode::FORBIDDEN, "not a member");
let (status, _) = revoke(
&state,
&host,
&creator,
serde_json::json!({ "id": invite["invite_id"] }),
)
.await;
assert_eq!(
status,
StatusCode::OK,
"a demoted creator still revokes their own"
);
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn revoke_rejects_bad_selectors_and_other_communities() {
let (state, host, _, owner) = fixture().await;
let (other_state, other_host, _, other_owner) = fixture().await;
let invite = mint(&other_state, &other_host, &other_owner).await;
let code = invite["code"].as_str().unwrap();
for body in [
serde_json::json!({}),
serde_json::json!({ "id": invite["invite_id"], "code": code }),
serde_json::json!({ "code": "not-a-code" }),
serde_json::json!({ "code": "v1.legacy" }),
] {
let (status, _) = revoke(&state, &host, &owner, body).await;
assert_eq!(status, StatusCode::BAD_REQUEST);
}
for body in [
serde_json::json!({ "id": invite["invite_id"] }),
serde_json::json!({ "code": code }),
serde_json::json!({ "id": Uuid::new_v4() }),
] {
let (status, json) = revoke(&state, &host, &owner, body).await;
assert_eq!(status, StatusCode::NOT_FOUND);
assert_no_secret(&json, code);
}
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn list_signature_covers_the_query() {
let (state, host, _, owner) = fixture().await;
for (path, signed) in [
("/api/invites?limit=200", "/api/invites?limit=10"),
("/api/invites?limit=10", "/api/invites"),
] {
let response = get_signed(state.clone(), &host, path, signed, &owner).await;
assert!(
matches!(
response.status(),
StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN
),
"{path} signed as {signed}: {}",
response.status()
);
}
let response = get_signed(
state,
&host,
"/api/invites?limit=0",
"/api/invites?limit=0",
&owner,
)
.await;
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}
/// Malformed list and revoke requests get fixed errors: neither the
/// response nor the access line echoes a code they carried.
#[tokio::test(flavor = "current_thread")]
#[ignore = "requires Postgres"]
async fn malformed_requests_never_echo_a_code() {
let (state, host, _, owner) = fixture().await;
let code = mint(&state, &host, &owner).await["code"]
.as_str()
.unwrap()
.to_owned();
let (_guard, out) = crate::access::tests::capture_scoped();
for body in [
serde_json::json!({ "code": 7, "id": code }),
serde_json::json!({ code.clone(): true }),
serde_json::json!([code]),
] {
let (status, json) = revoke(&state, &host, &owner, body).await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_no_secret(&json, &code);
}
for path in [
format!("/api/invites?{code}=1"),
format!("/api/invites?limit={code}"),
format!("/api/invites?before={code}"),
] {
let response = get_signed(state.clone(), &host, &path, &path, &owner).await;
assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{path}");
assert_no_secret(&read_json(response).await, &code);
}
assert!(!out.raw().contains(&code), "code logged: {}", out.raw());
}
/// A revoke the database refuses logs a denial with its reason.
#[tokio::test(flavor = "current_thread")]
#[ignore = "requires Postgres"]
async fn refused_revoke_logs_denied() {
let (state, host, community, owner) = fixture().await;
let member = Keys::generate();
add_member(&state, community, &member, "member").await;
let invite = mint(&state, &host, &owner).await;
let (_guard, out) = crate::access::tests::capture_scoped();
let (status, _) = revoke(
&state,
&host,
&member,
serde_json::json!({ "id": invite["invite_id"] }),
)
.await;
assert_eq!(status, StatusCode::FORBIDDEN);
let lines = out.lines();
assert_eq!(lines.len(), 1, "{lines:?}");
assert_eq!(lines[0]["route"], "/api/invites/revoke", "{}", lines[0]);
assert_eq!(lines[0]["outcome"], "denied", "{}", lines[0]);
assert_eq!(lines[0]["reason"], "not_relay_admin", "{}", lines[0]);
}
/// Replaying a signed list or revoke request is refused.
#[tokio::test]
#[ignore = "requires Postgres"]
async fn replayed_list_and_revoke_are_refused() {
let (state, host, _, owner) = fixture().await;
let invite = mint(&state, &host, &owner).await;
let mut replaying = Arc::try_unwrap(state).unwrap_or_else(|_| panic!("sole state owner"));
replaying.nip98_replay = Arc::new(SeenOnceReplayGuard::new());
let state = Arc::new(replaying);
let auth = nip98_get_header(&owner, &format!("https://{host}/api/invites"));
let body = serde_json::json!({ "id": invite["invite_id"] }).to_string();
let revoke_auth = nip98_auth_header(
&owner,
&format!("https://{host}/api/invites/revoke"),
body.as_bytes(),
);
for attempt in 0..2 {
let list = build_router(state.clone())
.oneshot(
Request::builder()
.method("GET")
.uri("/api/invites")
.header(header::HOST, &host)
.header(header::AUTHORIZATION, &auth)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let revoke = build_router(state.clone())
.oneshot(
Request::builder()
.method("POST")
.uri("/api/invites/revoke")
.header(header::HOST, &host)
.header(header::AUTHORIZATION, &revoke_auth)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(body.clone()))
.unwrap(),
)
.await
.unwrap();
if attempt == 0 {
assert_eq!(list.status(), StatusCode::OK);
assert_eq!(revoke.status(), StatusCode::OK);
} else {
assert_ne!(list.status(), StatusCode::OK, "replayed list");
assert_ne!(revoke.status(), StatusCode::OK, "replayed revoke");
}
}
}
}

View File

@@ -122,7 +122,7 @@ pub async fn mint_community_invite(
})?;
slot.detail(crate::access::Detail {
invite_id: Some(invite.invite_id),
expires_at: Some(invite.expires_at.timestamp()),
expires_at: invite.expires_at.map(|at| at.timestamp()),
max_uses: invite.max_uses,
..Default::default()
});