Skip to content

Commit 3df6179

Browse files
npub17jjz49l9jjmhhk7cac63j8yt9z555n9cw8vk7v5jz4vzw4ppld5qgj57ccTyler Longwell
andcommitted
fence(auth): host-binding side door + access-checker community fence
Two adversarially-proven multi-tenant fences for the auth lane on the frozen Lane 0 SHA: 1. NIP-98 verifier: drop loopback aliasing unconditionally. normalize_url() collapsed localhost / ::1 -> 127.0.0.1 — a testing convenience that becomes a row-zero side door under multi-tenant. The u-tag host is the community binding (docs/multi-tenant-conformance.md, NIP-98 row); collapsing the three would let an event signed for localhost pass against a 127.0.0.1-resolved community (or vice versa). Inverted the localhost test to bite the new strict rule: signed-for-one vs expected-other now REJECTS, identity still passes. Adversarial: re-introduced the aliasing -> test goes red -> restored. 2. ChannelAccessChecker: thread &TenantContext through every method. Frozen 0001 has channels PK (community_id, id), so the same UUID legitimately co-exists across communities. A bare WHERE id = implementation would be a cross-community existence oracle. Mirror of buzz-db rule 4a.1 on the auth side. MockAccessChecker keyed on (community, pubkey, channel_id); new test access_does_not_cross_communities bites the bare-id direction. Adversarial: dropped the community filter from the mock -> test goes red -> restored. No external impl of ChannelAccessChecker in-tree (DB uses a separate free function under Mari's lane), so the trait signature change is contained. cargo test -p buzz-auth: 45 passed / 0 failed. Lane: auth (buzz-auth). Base: e349d76 (frozen Lane 0). Co-authored-by: Tyler Longwell <[email protected]> Signed-off-by: Tyler Longwell <[email protected]>
1 parent f54d728 commit 3df6179

2 files changed

Lines changed: 120 additions & 33 deletions

File tree

‎crates/buzz-auth/src/access.rs‎

Lines changed: 90 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use std::collections::HashSet;
77
use std::future::Future;
88

9+
use buzz_core::TenantContext;
910
use nostr::PublicKey;
1011
use uuid::Uuid;
1112

@@ -17,24 +18,39 @@ use crate::scope::Scope;
1718
/// Implemented by the database layer (`buzz-db`) in production. The `buzz-auth`
1819
/// crate defines the trait so it can enforce access rules without a direct dependency
1920
/// on `buzz-db`.
21+
///
22+
/// ## Tenant scoping
23+
///
24+
/// Every method takes `&TenantContext`. Channel UUIDs are not globally unique under
25+
/// multi-tenant — the frozen schema's `channels` PK is `(community_id, id)`, so the
26+
/// same UUID can legitimately exist in two communities. A bare `WHERE id = $1`
27+
/// implementation would be a cross-community existence oracle and could return
28+
/// `true` for a B-community membership when the request bound community is A.
29+
/// Implementations MUST scope every query by `ctx.community()` (S1 cross-community
30+
/// fence at the access layer).
2031
pub trait ChannelAccessChecker: Send + Sync {
21-
/// Return the set of channel UUIDs accessible to `pubkey`.
32+
/// Return the set of channel UUIDs in `ctx`'s community accessible to `pubkey`.
33+
///
34+
/// Channels in other communities, even with the same UUID, MUST NOT appear.
2235
fn accessible_channel_ids(
2336
&self,
37+
ctx: &TenantContext,
2438
pubkey: &PublicKey,
2539
) -> impl Future<Output = Result<HashSet<Uuid>, AuthError>> + Send;
2640

27-
/// Returns `true` if `pubkey` is a member of `channel_id`.
41+
/// Returns `true` if `pubkey` is a member of `(ctx.community, channel_id)`.
2842
///
29-
/// Default implementation calls [`Self::accessible_channel_ids`] and checks membership.
30-
/// Implementations may override this with a more efficient point-lookup query.
43+
/// Default implementation calls [`Self::accessible_channel_ids`] and checks
44+
/// membership. Implementations may override this with a more efficient
45+
/// scoped point-lookup query.
3146
fn can_access(
3247
&self,
48+
ctx: &TenantContext,
3349
pubkey: &PublicKey,
3450
channel_id: Uuid,
3551
) -> impl Future<Output = Result<bool, AuthError>> + Send {
3652
async move {
37-
let ids = self.accessible_channel_ids(pubkey).await?;
53+
let ids = self.accessible_channel_ids(ctx, pubkey).await?;
3854
Ok(ids.contains(&channel_id))
3955
}
4056
}
@@ -52,40 +68,45 @@ pub fn require_scope(scopes: &[Scope], required: Scope) -> Result<(), AuthError>
5268
}
5369
}
5470

55-
/// Verify read access: scope + membership.
71+
/// Verify read access: scope + membership in `ctx`'s community.
5672
pub async fn check_read_access(
5773
checker: &impl ChannelAccessChecker,
74+
ctx: &TenantContext,
5875
pubkey: &PublicKey,
5976
channel_id: Uuid,
6077
scopes: &[Scope],
6178
) -> Result<(), AuthError> {
6279
require_scope(scopes, Scope::MessagesRead)?;
63-
if checker.can_access(pubkey, channel_id).await? {
80+
if checker.can_access(ctx, pubkey, channel_id).await? {
6481
Ok(())
6582
} else {
6683
Err(AuthError::ChannelAccessDenied)
6784
}
6885
}
6986

70-
/// Verify write access: scope + membership.
87+
/// Verify write access: scope + membership in `ctx`'s community.
7188
pub async fn check_write_access(
7289
checker: &impl ChannelAccessChecker,
90+
ctx: &TenantContext,
7391
pubkey: &PublicKey,
7492
channel_id: Uuid,
7593
scopes: &[Scope],
7694
) -> Result<(), AuthError> {
7795
require_scope(scopes, Scope::MessagesWrite)?;
78-
if checker.can_access(pubkey, channel_id).await? {
96+
if checker.can_access(ctx, pubkey, channel_id).await? {
7997
Ok(())
8098
} else {
8199
Err(AuthError::ChannelAccessDenied)
82100
}
83101
}
84102

85103
/// In-memory [`ChannelAccessChecker`] for unit tests.
104+
///
105+
/// Membership is keyed on the full `(community_id, pubkey, channel_id)` tuple
106+
/// so the mock can't accidentally model a non-tenant-scoped checker.
86107
#[cfg(any(test, feature = "test-utils"))]
87108
pub struct MockAccessChecker {
88-
allowed: HashSet<(String, Uuid)>,
109+
allowed: HashSet<(uuid::Uuid, String, Uuid)>,
89110
}
90111

91112
#[cfg(any(test, feature = "test-utils"))]
@@ -97,9 +118,10 @@ impl MockAccessChecker {
97118
}
98119
}
99120

100-
/// Grant `pubkey` access to `channel_id`.
101-
pub fn allow(&mut self, pubkey: &PublicKey, channel_id: Uuid) {
102-
self.allowed.insert((pubkey.to_hex(), channel_id));
121+
/// Grant `pubkey` access to `channel_id` inside `ctx`'s community.
122+
pub fn allow(&mut self, ctx: &TenantContext, pubkey: &PublicKey, channel_id: Uuid) {
123+
self.allowed
124+
.insert((*ctx.community().as_uuid(), pubkey.to_hex(), channel_id));
103125
}
104126
}
105127

@@ -112,75 +134,118 @@ impl Default for MockAccessChecker {
112134

113135
#[cfg(any(test, feature = "test-utils"))]
114136
impl ChannelAccessChecker for MockAccessChecker {
115-
async fn accessible_channel_ids(&self, pubkey: &PublicKey) -> Result<HashSet<Uuid>, AuthError> {
137+
async fn accessible_channel_ids(
138+
&self,
139+
ctx: &TenantContext,
140+
pubkey: &PublicKey,
141+
) -> Result<HashSet<Uuid>, AuthError> {
142+
let community = *ctx.community().as_uuid();
116143
let hex = pubkey.to_hex();
117144
Ok(self
118145
.allowed
119146
.iter()
120-
.filter(|(pk, _)| pk == &hex)
121-
.map(|(_, id)| *id)
147+
.filter(|(c, pk, _)| *c == community && pk == &hex)
148+
.map(|(_, _, id)| *id)
122149
.collect())
123150
}
124151
}
125152

126153
#[cfg(test)]
127154
mod tests {
128155
use super::*;
156+
use buzz_core::CommunityId;
129157
use nostr::Keys;
130158

159+
fn fixture_ctx() -> TenantContext {
160+
TenantContext::resolved(CommunityId::from_uuid(Uuid::new_v4()), "test.example")
161+
}
162+
131163
#[tokio::test]
132164
async fn mock_checker_allow_and_deny() {
165+
let ctx = fixture_ctx();
133166
let keys = Keys::generate();
134167
let pk = keys.public_key();
135168
let allowed_ch = Uuid::new_v4();
136169
let denied_ch = Uuid::new_v4();
137170

138171
let mut checker = MockAccessChecker::new();
139-
checker.allow(&pk, allowed_ch);
172+
checker.allow(&ctx, &pk, allowed_ch);
140173

141-
assert!(checker.can_access(&pk, allowed_ch).await.unwrap());
142-
assert!(!checker.can_access(&pk, denied_ch).await.unwrap());
174+
assert!(checker.can_access(&ctx, &pk, allowed_ch).await.unwrap());
175+
assert!(!checker.can_access(&ctx, &pk, denied_ch).await.unwrap());
143176
}
144177

145178
#[tokio::test]
146179
async fn read_access_denied_by_scope() {
180+
let ctx = fixture_ctx();
147181
let keys = Keys::generate();
148182
let pk = keys.public_key();
149183
let ch = Uuid::new_v4();
150184

151185
let mut checker = MockAccessChecker::new();
152-
checker.allow(&pk, ch);
186+
checker.allow(&ctx, &pk, ch);
153187

154188
assert!(matches!(
155-
check_read_access(&checker, &pk, ch, &[]).await,
189+
check_read_access(&checker, &ctx, &pk, ch, &[]).await,
156190
Err(AuthError::InsufficientScope { .. })
157191
));
158192
}
159193

160194
#[tokio::test]
161195
async fn read_access_denied_by_membership() {
196+
let ctx = fixture_ctx();
162197
let keys = Keys::generate();
163198
let pk = keys.public_key();
164199
let ch = Uuid::new_v4();
165200
let checker = MockAccessChecker::new();
166201

167202
assert!(matches!(
168-
check_read_access(&checker, &pk, ch, &[Scope::MessagesRead]).await,
203+
check_read_access(&checker, &ctx, &pk, ch, &[Scope::MessagesRead]).await,
169204
Err(AuthError::ChannelAccessDenied)
170205
));
171206
}
172207

173208
#[tokio::test]
174209
async fn read_access_granted() {
210+
let ctx = fixture_ctx();
175211
let keys = Keys::generate();
176212
let pk = keys.public_key();
177213
let ch = Uuid::new_v4();
178214

179215
let mut checker = MockAccessChecker::new();
180-
checker.allow(&pk, ch);
216+
checker.allow(&ctx, &pk, ch);
181217

182-
assert!(check_read_access(&checker, &pk, ch, &[Scope::MessagesRead])
218+
assert!(
219+
check_read_access(&checker, &ctx, &pk, ch, &[Scope::MessagesRead])
220+
.await
221+
.is_ok()
222+
);
223+
}
224+
225+
#[tokio::test]
226+
async fn access_does_not_cross_communities() {
227+
// S1 fence at the access layer: same pubkey, same channel UUID, two
228+
// communities. A grant in A MUST NOT show up under B's TenantContext.
229+
// This bites the existence-oracle direction a bare `WHERE id=$1`
230+
// checker would have left open.
231+
let ctx_a = fixture_ctx();
232+
let ctx_b = fixture_ctx();
233+
let keys = Keys::generate();
234+
let pk = keys.public_key();
235+
let ch = Uuid::new_v4();
236+
237+
let mut checker = MockAccessChecker::new();
238+
checker.allow(&ctx_a, &pk, ch);
239+
240+
assert!(checker.can_access(&ctx_a, &pk, ch).await.unwrap());
241+
assert!(
242+
!checker.can_access(&ctx_b, &pk, ch).await.unwrap(),
243+
"access in community A must NOT leak into community B for same (pubkey, channel_id)"
244+
);
245+
assert!(checker
246+
.accessible_channel_ids(&ctx_b, &pk)
183247
.await
184-
.is_ok());
248+
.unwrap()
249+
.is_empty());
185250
}
186251
}

‎crates/buzz-auth/src/nip98.rs‎

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -134,17 +134,19 @@ pub fn verify_nip98_event(
134134
///
135135
/// - Lowercases scheme and host (already done by the `url` crate).
136136
/// - Strips trailing slash from path.
137-
/// - Treats `localhost` and `::1` as equivalent to `127.0.0.1`.
137+
///
138+
/// **No loopback aliasing.** `localhost`, `::1`, and `127.0.0.1` are three
139+
/// distinct hosts here. Under multi-tenant the `u`-tag host is the row-zero
140+
/// community binding (`docs/multi-tenant-conformance.md`, NIP-98 row): if
141+
/// `verify_nip98_event` collapses them, an event signed for `localhost`
142+
/// would pass against a `127.0.0.1`-resolved community (or vice versa) —
143+
/// a host-binding side door. Tests reconstruct `expected_url` from their
144+
/// own bound host, the same shape production does.
138145
fn normalize_url(raw: &str) -> String {
139146
let mut parsed = match Url::parse(raw) {
140147
Ok(u) => u,
141148
Err(_) => return raw.to_lowercase(),
142149
};
143-
if let Some(host) = parsed.host_str() {
144-
if host == "localhost" || host == "::1" {
145-
let _ = parsed.set_host(Some("127.0.0.1"));
146-
}
147-
}
148150
let path = parsed.path().trim_end_matches('/').to_string();
149151
parsed.set_path(&path);
150152
parsed.to_string()
@@ -284,12 +286,32 @@ mod tests {
284286
}
285287

286288
#[test]
287-
fn localhost_normalized() {
289+
fn loopback_aliases_are_distinct_hosts() {
290+
// Under multi-tenant, the `u`-tag host is the row-zero community
291+
// binding. An event signed for `localhost` MUST NOT pass against an
292+
// expected URL on `127.0.0.1` (or `::1`) — collapsing the three would
293+
// be a host-check side door. Production reconstructs `expected_url`
294+
// from the community-bound host; tests do the same.
288295
let keys = Keys::generate();
289296
let localhost_url = "http://localhost:3000/api/tokens";
290297
let loopback_url = "http://127.0.0.1:3000/api/tokens";
291298
let json = make_nip98_event(&keys, localhost_url, TEST_METHOD, None, None);
292299
let result = verify_nip98_event(&json, loopback_url, TEST_METHOD, None);
293-
assert!(result.is_ok());
300+
assert!(
301+
matches!(result, Err(AuthError::Nip98Invalid(_))),
302+
"localhost u-tag must NOT match a 127.0.0.1 expected_url; got {result:?}"
303+
);
304+
305+
// Symmetric: signed-for-127.0.0.1 against expected localhost — same answer.
306+
let json2 = make_nip98_event(&keys, loopback_url, TEST_METHOD, None, None);
307+
let result2 = verify_nip98_event(&json2, localhost_url, TEST_METHOD, None);
308+
assert!(
309+
matches!(result2, Err(AuthError::Nip98Invalid(_))),
310+
"127.0.0.1 u-tag must NOT match a localhost expected_url; got {result2:?}"
311+
);
312+
313+
// And identity still holds — same host on both sides verifies.
314+
let json3 = make_nip98_event(&keys, loopback_url, TEST_METHOD, None, None);
315+
assert!(verify_nip98_event(&json3, loopback_url, TEST_METHOD, None).is_ok());
294316
}
295317
}

0 commit comments

Comments
 (0)