Skip to content

Commit b7be627

Browse files
tlongwell-blocknpub1jh9wn95s0472h86ahapupaf7m6kx4v9sx2n0atj2hltcfer8k06s5n3pyfnpub1jmc9dt2lyvzu3h0kxlwxt5zg4fxp9476awyxw6gwxn72g6cw7exqs64whmnpub12gtutshhh76rx0jx697f32f9tffd4hhp3hx58fp4x6u4uemkm7sqf8f757
authored
feat: add invite QR and mobile direct join (#1957)
Signed-off-by: npub1jh9wn95s0472h86ahapupaf7m6kx4v9sx2n0atj2hltcfer8k06s5n3pyf <95cae996907d7cab9f5dbf43c0f53edeac6ab0b032a6feae4abfd784e467b3f5@sprout-oss.stage.blox.sqprod.co> Signed-off-by: npub1jmc9dt2lyvzu3h0kxlwxt5zg4fxp9476awyxw6gwxn72g6cw7exqs64whm <96f056ad5f2305c8ddf637dc65d048aa4c12d7daeb8867690e34fca46b0ef64c@sprout-oss.stage.blox.sqprod.co> Signed-off-by: npub12gtutshhh76rx0jx697f32f9tffd4hhp3hx58fp4x6u4uemkm7sqf8f757 <5217c5c2f7bfb4333e46d17c98a9255a52dadee18dcd43a43536b95e6776dfa0@sprout-oss.stage.blox.sqprod.co> Co-authored-by: npub1jh9wn95s0472h86ahapupaf7m6kx4v9sx2n0atj2hltcfer8k06s5n3pyf <95cae996907d7cab9f5dbf43c0f53edeac6ab0b032a6feae4abfd784e467b3f5@sprout-oss.stage.blox.sqprod.co> Co-authored-by: npub1jmc9dt2lyvzu3h0kxlwxt5zg4fxp9476awyxw6gwxn72g6cw7exqs64whm <96f056ad5f2305c8ddf637dc65d048aa4c12d7daeb8867690e34fca46b0ef64c@sprout-oss.stage.blox.sqprod.co> Co-authored-by: npub12gtutshhh76rx0jx697f32f9tffd4hhp3hx58fp4x6u4uemkm7sqf8f757 <5217c5c2f7bfb4333e46d17c98a9255a52dadee18dcd43a43536b95e6776dfa0@sprout-oss.stage.blox.sqprod.co>
1 parent b43b883 commit b7be627

16 files changed

Lines changed: 1722 additions & 24 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -631,6 +631,11 @@ jobs:
631631
done
632632
cat /tmp/buzz-relay.log
633633
exit 1
634+
- name: Invite claim security tests
635+
run: |
636+
cargo test --profile ci -p buzz-relay claim_ -- --ignored --nocapture
637+
env:
638+
DATABASE_URL: postgres://buzz:buzz_dev@localhost:5432/buzz
634639
- name: NIP-ER reminder e2e
635640
# Feature e2e for NIP-ER (Event Reminders, kind:30300): write-path
636641
# validation, author-only read filtering, and scheduler delivery against
@@ -673,7 +678,9 @@ jobs:
673678
chmod +x ./target/ci/buzz-relay ./target/ci/git-credential-nostr
674679
./scripts/start-relay-for-tests.sh --no-build
675680
- name: Relay E2E tests
676-
run: cargo test -p buzz-test-client --test e2e_persona --test e2e_nostr_interop -- --ignored --nocapture
681+
run: |
682+
cargo test -p buzz-test-client --test e2e_persona --test e2e_nostr_interop -- --ignored --nocapture
683+
cargo test -p buzz-test-client --test e2e_relay invite -- --ignored --nocapture
677684
env:
678685
RELAY_URL: ws://localhost:3000
679686
GIT_CREDENTIAL_NOSTR_BIN: ${{ github.workspace }}/target/ci/git-credential-nostr

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

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

Lines changed: 248 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -400,13 +400,17 @@ mod tests {
400400
body::{to_bytes, Body},
401401
http::{header, Request, StatusCode},
402402
};
403-
use base64::Engine;
404-
use nostr::{EventBuilder, Keys, Kind, Tag};
403+
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
404+
use hmac::{Hmac, KeyInit, Mac};
405+
use nostr::{EventBuilder, EventId, Keys, Kind, Tag};
405406
use serde_json::Value;
406407
use sha2::{Digest, Sha256};
408+
use std::sync::Mutex;
407409
use tower::ServiceExt;
408410
use uuid::Uuid;
409411

412+
use crate::invite_token::{derive_invite_key, InvitePayload};
413+
410414
use crate::router::build_router;
411415
use crate::state::AppState;
412416

@@ -973,6 +977,248 @@ mod tests {
973977
assert_eq!(response.status(), StatusCode::FORBIDDEN);
974978
}
975979

980+
/// Forge an already-expired invite payload signed with the relay's derived
981+
/// invite key. `mint_invite` clamps ttl to 60s minimum, so the only way to
982+
/// produce an expired code is to build the payload by hand at the token
983+
/// layer.
984+
fn forge_expired_invite_code(
985+
state: &AppState,
986+
community: buzz_core::CommunityId,
987+
seconds_ago: u64,
988+
) -> String {
989+
let key = derive_invite_key(&state.relay_keypair);
990+
let now = std::time::SystemTime::now()
991+
.duration_since(std::time::UNIX_EPOCH)
992+
.expect("time")
993+
.as_secs();
994+
let payload = InvitePayload {
995+
c: community.as_uuid().to_string(),
996+
r: "member".to_string(),
997+
e: now.saturating_sub(seconds_ago),
998+
n: "test-nonce".to_string(),
999+
};
1000+
let payload_bytes = serde_json::to_vec(&payload).expect("payload serializes");
1001+
let mut mac =
1002+
<Hmac<Sha256> as KeyInit>::new_from_slice(&key).expect("HMAC accepts any key size");
1003+
mac.update(&payload_bytes);
1004+
let mac_bytes = mac.finalize().into_bytes();
1005+
format!(
1006+
"{}.{}",
1007+
URL_SAFE_NO_PAD.encode(&payload_bytes),
1008+
URL_SAFE_NO_PAD.encode(mac_bytes),
1009+
)
1010+
}
1011+
1012+
/// Endpoint-level proof that expired codes (with a valid MAC) are
1013+
/// rejected by `/api/invites/claim` with the distinguishable
1014+
/// `invite_expired` body, and do not admit the caller.
1015+
#[tokio::test]
1016+
#[ignore = "requires Postgres"]
1017+
async fn claim_rejects_expired_code() {
1018+
let host = format!("invites-{}.example", Uuid::new_v4().simple());
1019+
let joiner = Keys::generate();
1020+
let state = invite_test_state(&host)
1021+
.await
1022+
.expect("requires reachable Postgres and relay test state");
1023+
let community = state
1024+
.db
1025+
.lookup_community_by_host(&host)
1026+
.await
1027+
.expect("lookup")
1028+
.expect("community exists");
1029+
let code = forge_expired_invite_code(&state, community.id, 10);
1030+
1031+
let body = serde_json::json!({ "code": code }).to_string();
1032+
let response = post_json(state.clone(), &host, "/api/invites/claim", &joiner, body).await;
1033+
assert_eq!(response.status(), StatusCode::FORBIDDEN);
1034+
let json = read_json(response).await;
1035+
// The expired branch is deliberately distinguishable from the generic
1036+
// `invite_invalid` so the UX can prompt the user for a fresh link
1037+
// without becoming a MAC oracle.
1038+
assert_eq!(
1039+
json.get("error").and_then(Value::as_str),
1040+
Some("invite_expired"),
1041+
"expired branch must be distinguishable from generic invalid",
1042+
);
1043+
1044+
let is_member = state
1045+
.db
1046+
.is_relay_member(community.id, &joiner.public_key().to_hex())
1047+
.await
1048+
.expect("member check");
1049+
assert!(!is_member, "expired code must not admit anyone");
1050+
}
1051+
1052+
/// NIP-98 replay guard that returns `Ok(true)` the first time a given
1053+
/// event id is seen and `Ok(false)` on every subsequent call — mirrors
1054+
/// what the Redis guard does after a `SET NX` succeeds and then fails.
1055+
struct SeenOnceReplayGuard {
1056+
seen: Mutex<std::collections::HashSet<[u8; 32]>>,
1057+
}
1058+
1059+
impl SeenOnceReplayGuard {
1060+
fn new() -> Self {
1061+
Self {
1062+
seen: Mutex::new(std::collections::HashSet::new()),
1063+
}
1064+
}
1065+
}
1066+
1067+
impl buzz_auth::Nip98ReplayGuard for SeenOnceReplayGuard {
1068+
fn try_mark_in_scope<'a>(
1069+
&'a self,
1070+
_scope: &'a str,
1071+
event_id: &'a EventId,
1072+
_ttl_secs: u64,
1073+
) -> std::pin::Pin<
1074+
Box<dyn std::future::Future<Output = Result<bool, buzz_auth::AuthError>> + Send + 'a>,
1075+
> {
1076+
let bytes = *event_id.as_bytes();
1077+
let inserted = self.seen.lock().expect("replay set").insert(bytes);
1078+
Box::pin(async move { Ok(inserted) })
1079+
}
1080+
}
1081+
1082+
/// Endpoint-level proof that a replayed NIP-98 auth event on a claim POST
1083+
/// is rejected — the first claim succeeds, but reusing the exact same
1084+
/// Authorization header (same signed NIP-98 event id) is rejected as
1085+
/// replay before the invite verification ever runs.
1086+
#[tokio::test]
1087+
#[ignore = "requires Postgres"]
1088+
async fn claim_rejects_replayed_nip98_auth() {
1089+
let host = format!("invites-{}.example", Uuid::new_v4().simple());
1090+
let owner = Keys::generate();
1091+
let joiner = Keys::generate();
1092+
let state_arc = invite_test_state(&host)
1093+
.await
1094+
.expect("requires reachable Postgres and relay test state");
1095+
// Swap the always-fresh guard for one that fires the second time the
1096+
// same event id is presented — the code path we're pinning.
1097+
let mut state_owned =
1098+
Arc::try_unwrap(state_arc).unwrap_or_else(|_| panic!("sole owner of AppState"));
1099+
state_owned.nip98_replay = Arc::new(SeenOnceReplayGuard::new());
1100+
let state = Arc::new(state_owned);
1101+
1102+
let community = state
1103+
.db
1104+
.lookup_community_by_host(&host)
1105+
.await
1106+
.expect("lookup")
1107+
.expect("community exists");
1108+
state
1109+
.db
1110+
.add_relay_member(community.id, &owner.public_key().to_hex(), "owner", None)
1111+
.await
1112+
.expect("seed owner");
1113+
1114+
// Mint a valid code so the replay under test is on the claim path.
1115+
let response = post_json(
1116+
state.clone(),
1117+
&host,
1118+
"/api/invites",
1119+
&owner,
1120+
"{}".to_string(),
1121+
)
1122+
.await;
1123+
assert_eq!(response.status(), StatusCode::OK);
1124+
let json = read_json(response).await;
1125+
let code = json.get("code").and_then(Value::as_str).expect("code");
1126+
1127+
// Build one NIP-98 header and reuse it verbatim on two claim POSTs.
1128+
let claim_body = serde_json::json!({ "code": code }).to_string();
1129+
let claim_url = format!("https://{host}/api/invites/claim");
1130+
let claim_auth = nip98_auth_header(&joiner, &claim_url, claim_body.as_bytes());
1131+
1132+
let send_claim = |auth: String, body: String| {
1133+
let state = state.clone();
1134+
let host = host.clone();
1135+
async move {
1136+
build_router(state)
1137+
.oneshot(
1138+
Request::builder()
1139+
.method("POST")
1140+
.uri("/api/invites/claim")
1141+
.header(header::HOST, host.as_str())
1142+
.header(header::AUTHORIZATION, auth)
1143+
.header(header::CONTENT_TYPE, "application/json")
1144+
.body(Body::from(body))
1145+
.expect("request"),
1146+
)
1147+
.await
1148+
.expect("response")
1149+
}
1150+
};
1151+
1152+
let first = send_claim(claim_auth.clone(), claim_body.clone()).await;
1153+
assert_eq!(first.status(), StatusCode::OK);
1154+
1155+
// Same signed auth event, sent again → replay guard fires.
1156+
let second = send_claim(claim_auth, claim_body).await;
1157+
assert_eq!(second.status(), StatusCode::UNAUTHORIZED);
1158+
let json = read_json(second).await;
1159+
assert_eq!(
1160+
json.get("error").and_then(Value::as_str),
1161+
Some("NIP-98: replay detected"),
1162+
);
1163+
}
1164+
1165+
/// Endpoint-level proof that `/api/invites/claim` enforces the per-pubkey
1166+
/// fixed-window rate limit — the same joiner probing the endpoint hits
1167+
/// 429 on the `CLAIM_RATE_LIMIT + 1`th attempt inside the window.
1168+
///
1169+
/// We use invalid codes throughout so no membership state can change; the
1170+
/// limiter runs before code verification, so the transition from
1171+
/// `invite_invalid` (403) to `too many invite claim attempts` (429) proves
1172+
/// the limiter guard is on the request path and fires on repeat pubkey.
1173+
#[tokio::test]
1174+
#[ignore = "requires Postgres"]
1175+
async fn claim_rate_limit_fires_on_repeat_pubkey() {
1176+
let host = format!("invites-{}.example", Uuid::new_v4().simple());
1177+
let joiner = Keys::generate();
1178+
let state_arc = invite_test_state(&host)
1179+
.await
1180+
.expect("requires reachable Postgres and relay test state");
1181+
// Fresh limiter with the production limit so the assertion pins the
1182+
// in-endpoint threshold, not a test-only budget.
1183+
let mut state_owned =
1184+
Arc::try_unwrap(state_arc).unwrap_or_else(|_| panic!("sole owner of AppState"));
1185+
state_owned.invite_claim_rate_limiter = Arc::new(claim_cache(
1186+
super::CLAIM_RATE_CACHE_CAPACITY,
1187+
super::CLAIM_RATE_WINDOW,
1188+
));
1189+
let state = Arc::new(state_owned);
1190+
1191+
let body = serde_json::json!({ "code": "garbage.code" }).to_string();
1192+
for _ in 0..CLAIM_RATE_LIMIT {
1193+
let response = post_json(
1194+
state.clone(),
1195+
&host,
1196+
"/api/invites/claim",
1197+
&joiner,
1198+
body.clone(),
1199+
)
1200+
.await;
1201+
assert_eq!(
1202+
response.status(),
1203+
StatusCode::FORBIDDEN,
1204+
"attempts up to the limit should reach code verification and be rejected as invalid",
1205+
);
1206+
let json = read_json(response).await;
1207+
assert_eq!(
1208+
json.get("error").and_then(Value::as_str),
1209+
Some("invite_invalid"),
1210+
);
1211+
}
1212+
1213+
let over_limit = post_json(state, &host, "/api/invites/claim", &joiner, body).await;
1214+
assert_eq!(over_limit.status(), StatusCode::TOO_MANY_REQUESTS);
1215+
let json = read_json(over_limit).await;
1216+
assert_eq!(
1217+
json.get("error").and_then(Value::as_str),
1218+
Some("too many invite claim attempts, slow down"),
1219+
);
1220+
}
1221+
9761222
#[test]
9771223
fn policy_document_renders_markdown_and_escapes_raw_html() {
9781224
let page = super::render_policy_document(

‎crates/buzz-test-client/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ base64 = "0.22"
3333
hex = { workspace = true }
3434
rand = { workspace = true }
3535
sha2 = { workspace = true }
36+
sqlx = { workspace = true }
3637
chrono = { workspace = true }
3738
s3 = { version = "0.37", package = "rust-s3", default-features = false, features = ["tokio-rustls-tls", "fail-on-err", "tags"] }
3839
buzz-sdk = { workspace = true }

0 commit comments

Comments
 (0)