Files
buzz/mobile/test/shared/hosted/organization_relay_auth_test.dart
Tom Brow db4478e8d2 feat(mobile): organization sign-in for NIP-FI relays (#8700)
Block is turning on NIP-FI enforcement on the Block relay. Desktop gets
organization sign-in in block/buzz-app#1424. Mobile can already attach
NIP-FI assertions, but only for Builderlab-hosted communities, through
the build's single Builderlab account. The dogfood build needs that
account for public hosted communities, so it can't simply be pointed at
the Block tenant.

This adds a separate **organization realm**, configured at build time:

- `BUZZ_ORGANIZATION_URL`: the tenant's HTTPS origin (for example
`https://block.builderlab.xyz`).
- `BUZZ_ORGANIZATION_RELAYS`: the exact relay hosts that trust that
tenant.

The two must be set together. The app refuses to start if they're
malformed, overlap a hosted community, or reuse the hosted origin.
Without them, nothing changes.

For a configured relay:

- The app keeps its own organization session and signs in through the
browser at the tenant's existing login (`/api/goose/v1/auth/login`).
Block SSO happens there.
- It requests assertions from the same `/v1/buzz/identity/assertions`
route that hosted communities use, and attaches them to the relay
socket, HTTP, media, huddle and remote-agent requests.
- Unlike the hosted path, it doesn't require an identity backup before
the first binding. As on desktop, the tenant binds the member's existing
key on first issuance. A key already bound to a different one is refused
before any request is sent.
- When signed out, it connects without an assertion and lets the relay
decide. A bottom banner offers **Sign in**. After sign-in, the relay
reconnects with a fresh assertion. Hosted communities keep their
existing banner and flow.

The tenant accepts only the registered
`xyz.block.buzz.mobile:/auth/callback` return URL, so both realms share
it. Each `BrowserAuth` owner leaves callbacks whose `state` belongs to
another owner's attempt to that owner.

### Before merge

- [ ] Kenny Lopez reviews the visible changes.

### Validation

Added tests (`organization_relay_auth_test.dart`):

- Configuration parsing and exact host matching.
- An assertion is issued for the exact relay and key, then cached.
- A different bound key is refused.
- Signed out connects without an assertion.
- Other relays never receive the assertion.
- The shared callback is routed between the hosted and organization
owners.

Full `mobile-check` and `mobile-test` pass. RunnerTests pass locally
except `testNativeNavigationTitleExpandsAgainAtTop`, which this PR
doesn't touch.

Added tests (`organization_sign_in_test.dart`,
`relay_auth_isolation_test.dart`, `builderlab_account_test.dart`), each
failing without its fix:

- Concurrent account restores at cold start share one adopted account.
- An exchange from a cancelled attempt never changes a newer sign-in.
- Storage failures while clearing the intent or cancelling leave the
busy state.
- An unreadable saved organization session is replaced by signing in
again.
- A stalled organization issuer never delays a hosted relay's assertion.
This test needs `BUZZ_AUTH_DOMAINS` and skips without it. CI's
configured-auth-domains step doesn't list it yet, because that workflow
change needs a token with `workflow` scope.

Added tests also cover a restore after an offline start (the banner
clears once a relay retry restores the session) and the iOS bridge
allowlist (`/auth/native` and tenant login on Builderlab subdomains;
other hosts, paths, ports, userinfo and fragments refused).

Simulator (iPhone 17, iOS 27) with the dogfood defines against the
production Block relay `buzz.block.builderlab.xyz`, on a WARP Mac:

- The app starts with the organization configuration and connects to the
relay while signed out, showing the organization **Sign in** banner.
- **Sign in** opens the system sign-in session for
`block.builderlab.xyz`, and the banner shows **Finishing organization
sign-in…**. Cancelling returns to **Sign in** with no error. Before the
bridge fix, no browser opened and the banner reported that sign-in did
not finish.
- The bottom banners (organization sign-in, hosted reconnect, and the
sign-in recovery row) now sit above Home's floating Search/New bar,
which used to cover **Sign in**. A journey test checks the banner clears
the bar, and fails without the fix.

![Home with the organization sign-in banner above the floating
bar](https://github.com/user-attachments/assets/c6ab74f4-3d88-4fe0-ae16-042a548056fe)
- The simulator run stopped at the system consent prompt (SSO does not
work in the simulator). The app calls were driven through the VM service
(the same `signIn()`/`cancel()` the banner buttons call) because the
simulator could not be tapped.

Device (iPhone 12 mini) against bb-block staging in enforce mode, where
every probe without an assertion gets 401:

- Signed out, the organization banner shows and the app stays
responsive. Cancel at the consent prompt returns to **Sign in**, and
retry works.
- Block SSO through Okta completes, and the relay admits the reconnect
with the assertion.
- After relaunch the app connects, loads channel history, and shows no
banner for over 60 seconds.
- Before the restore fix, 2 of 4 cold starts showed "cannot use this
community with this key" although the session was valid. With it, 8 of 8
cold starts connected.

Known limitation: adding an enforcing organization relay by community
link is tracked in #8791.

The dogfood build enables this in squareup/buzz-releases
(`tomb/dogfood-organization-sign-in`). App Store builds stay unchanged.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 07:23:12 -08:00

512 lines
17 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'package:buzz/shared/hosted/browser_auth.dart';
import 'package:buzz/shared/hosted/builderlab_account.dart';
import 'package:buzz/shared/hosted/hosted_relay_auth.dart';
import 'package:buzz/shared/hosted/organization_environment.dart';
import 'package:buzz/shared/hosted/organization_sign_in.dart';
import 'package:buzz/shared/relay/relay_provider.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:nostr/nostr.dart' as nostr;
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final keys = nostr.Keys(
'0000000000000000000000000000000000000000000000000000000000000001',
);
final organization = Uri.parse('https://block.example.com');
const relayHost = 'buzz.block.example.com';
final relay = RelayConfig(baseUrl: 'https://$relayHost', nsec: keys.nsec);
final expiry = DateTime.now().toUtc().add(const Duration(days: 1));
setUp(() => FlutterSecureStorage.setMockInitialValues({}));
group('OrganizationEnvironment', () {
test('origin and relays are configured together as an HTTPS origin', () {
expect(OrganizationEnvironment.parseOrigin('', ''), isNull);
expect(
OrganizationEnvironment.parseOrigin(
'https://block.example.com/',
relayHost,
),
organization,
);
for (final (url, relays) in [
('https://block.example.com', ''),
('', relayHost),
('http://block.example.com', relayHost),
('https://block.example.com/api/goose', relayHost),
('https://block.example.com:8443', relayHost),
('https://block.example.com?x=1', relayHost),
('https://app.builderlab.xyz', relayHost),
]) {
expect(
() => OrganizationEnvironment.parseOrigin(url, relays),
throwsStateError,
reason: '$url $relays',
);
}
});
test('relays are exact DNS hosts outside hosted communities', () {
expect(
OrganizationEnvironment.parseRelayHosts(' Buzz.Block.Example.com ,a.b'),
[relayHost, 'a.b'],
);
for (final relays in [
'wss://$relayHost',
'*.block.example.com',
'localhost',
'team.communities.buzz.xyz',
]) {
expect(
() => OrganizationEnvironment.parseRelayHosts(relays),
throwsStateError,
reason: relays,
);
}
});
test('matches only the configured host on the default port', () {
bool matches(String url) =>
OrganizationEnvironment.matches(Uri.parse(url), [relayHost]);
expect(matches('wss://$relayHost'), isTrue);
expect(matches('https://$relayHost/'), isTrue);
expect(matches('wss://$relayHost:443'), isTrue);
expect(matches('wss://team.$relayHost'), isFalse);
expect(matches('wss://$relayHost:8443'), isFalse);
expect(matches('wss://$relayHost/path'), isFalse);
expect(matches('ws://$relayHost'), isFalse);
});
});
group('organization relay assertions', () {
late List<http.Request> requests;
late Object? boundIdentity;
BuilderlabAccountClient organizationClient() => BuilderlabAccountClient(
accountOrigin: organization,
httpClient: MockClient((request) async {
requests.add(request);
expect(request.url.origin, organization.origin);
expect(request.headers['X-BB-Session-Credential'], 'org-secret');
return switch (request.url.path) {
'/api/goose/v1/auth/me' => http.Response(
jsonEncode({
'subject': 'member',
'expires_at': expiry.toIso8601String(),
}),
200,
),
'/api/goose/v1/buzz/nostr-identities/current' => http.Response(
jsonEncode({'identity': boundIdentity}),
200,
),
'/api/goose/v1/buzz/identity/assertions' => http.Response(
jsonEncode({
'assertion': 'org-token',
'nostr_pubkey': keys.public,
'expires_at': DateTime.now().millisecondsSinceEpoch ~/ 1000 + 120,
}),
200,
),
_ => http.Response('{}', 404),
};
}),
);
Future<void> saveSession() => const FlutterSecureStorage().write(
key: 'buzz_hosted_session_block_example_com_v1',
value: jsonEncode({
'origin': organization.toString(),
'credential': 'org-secret',
'subject': 'member',
'expires_at': expiry.toIso8601String(),
}),
);
HostedRelayAuth relayAuth(BuilderlabAccountClient organizationAccount) =>
HostedRelayAuth(
BuilderlabAccountClient(
httpClient: MockClient(
(request) async => fail('Hosted account must not be used'),
),
),
organization: organizationAccount,
organizationRelay: (relay) =>
OrganizationEnvironment.matches(relay, [relayHost]),
enabled: true,
);
setUp(() {
requests = [];
boundIdentity = null;
});
test(
'signed-in member gets an assertion for the exact relay and its key',
() async {
await saveSession();
final auth = relayAuth(organizationClient());
expect(auth.protects(relay), isTrue);
expect(auth.organizationProtects(relay), isTrue);
expect(await auth.headers(relay), {
'Nostr-Federated-Identity': 'Bearer org-token',
});
final issue = requests.last;
expect(issue.url.path, '/api/goose/v1/buzz/identity/assertions');
expect(jsonDecode(issue.body), {
'relay_url': 'wss://$relayHost',
'nostr_pubkey': keys.public,
});
expect(issue.headers['Authorization'], startsWith('Nostr '));
// Cached until near expiry.
await auth.headers(relay);
expect(
requests.where((r) => r.url.path.endsWith('/assertions')),
hasLength(1),
);
},
);
test('a key bound to the same member is accepted', () async {
await saveSession();
boundIdentity = {'pubkey_hex': keys.public};
final auth = relayAuth(organizationClient());
expect(await auth.headers(relay), contains('Nostr-Federated-Identity'));
});
test('an issued assertion serves cached reads for the relay', () async {
await saveSession();
final auth = relayAuth(organizationClient());
expect(auth.cachedHeaders(relay), isNull);
await auth.headers(relay);
expect(auth.cachedHeaders(relay), {
'Nostr-Federated-Identity': 'Bearer org-token',
});
});
test('a different bound key is refused before issuance', () async {
await saveSession();
boundIdentity = {'pubkey_hex': 'f' * 64};
final auth = relayAuth(organizationClient());
await expectLater(auth.headers(relay), throwsA(AccountFailure.denied));
expect(auth.failure, AccountFailure.denied);
expect(
requests.where((r) => r.url.path.endsWith('/assertions')),
isEmpty,
);
});
test('signed out connects without an assertion and records it', () async {
final auth = relayAuth(organizationClient());
expect(await auth.headers(relay), isEmpty);
expect(auth.failure, AccountFailure.signedOut);
expect(requests, isEmpty);
});
test('other relays never receive the organization assertion', () async {
await saveSession();
final auth = relayAuth(organizationClient());
for (final other in [
'https://team.$relayHost',
'https://other.example.com',
]) {
final config = RelayConfig(baseUrl: other, nsec: keys.nsec);
expect(auth.protects(config), isFalse);
expect(await auth.headers(config), isEmpty);
}
expect(requests, isEmpty);
});
});
test('each origin owner consumes only its own shared callback', () async {
late Uri hostedLogin;
late Uri organizationLogin;
final hosted = BrowserAuth(
openBrowser: (uri) async {
hostedLogin = uri;
return null;
},
);
final org = BrowserAuth(
origin: organization,
openBrowser: (uri) async {
organizationLogin = uri;
return null;
},
);
final hostedCodes = <BrowserAuthCode>[];
final orgCodes = <BrowserAuthCode>[];
final hostedFailures = <BrowserAuthFailure>[];
final orgFailures = <BrowserAuthFailure>[];
hosted.codes.listen(hostedCodes.add);
hosted.failures.listen(hostedFailures.add);
org.codes.listen(orgCodes.add);
org.failures.listen(orgFailures.add);
await org.start({'purpose': 'organization'});
expect(organizationLogin.origin, organization.origin);
expect(organizationLogin.path, '/api/goose/v1/auth/login');
expect(organizationLogin.queryParameters['returnTo'], BrowserAuth.callback);
final callback = Uri.parse(BrowserAuth.callback).replace(
queryParameters: {
'state': organizationLogin.queryParameters['state']!,
'code': 'org-code',
},
);
// Both owners see every app link; the hosted owner has no attempt.
await Future.wait([hosted.receive(callback), org.receive(callback)]);
await Future<void>.delayed(Duration.zero);
expect(orgCodes.single.code, 'org-code');
expect(hostedCodes, isEmpty);
expect(hostedFailures, isEmpty);
expect(orgFailures, isEmpty);
// A pending hosted login is untouched by the organization callback.
await hosted.start({'relay': 'wss://example.communities.buzz.xyz'});
await org.start({'purpose': 'organization'});
final second = Uri.parse(BrowserAuth.callback).replace(
queryParameters: {
'state': organizationLogin.queryParameters['state']!,
'code': 'org-code-2',
},
);
await hosted.receive(second);
await org.receive(second);
await Future<void>.delayed(Duration.zero);
expect(hostedFailures, isEmpty);
expect(orgCodes.last.code, 'org-code-2');
await hosted.receive(
Uri.parse(BrowserAuth.callback).replace(
queryParameters: {
'state': hostedLogin.queryParameters['state']!,
'code': 'hosted-code',
},
),
);
await Future<void>.delayed(Duration.zero);
expect(hostedCodes.single.code, 'hosted-code');
await hosted.dispose();
await org.dispose();
});
test(
'an expired abandoned attempt ignores another owner\'s callback',
() async {
var now = DateTime.utc(2026, 10, 29);
final hosted = BrowserAuth(
openBrowser: (_) async => null,
now: () => now,
);
late Uri organizationLogin;
final org = BrowserAuth(
origin: organization,
now: () => now,
openBrowser: (uri) async {
organizationLogin = uri;
return null;
},
);
final hostedFailures = <BrowserAuthFailure>[];
final orgCodes = <BrowserAuthCode>[];
hosted.failures.listen(hostedFailures.add);
org.codes.listen(orgCodes.add);
await hosted.start({'relay': 'wss://example.communities.buzz.xyz'});
await hosted.dispose();
// After a restart the abandoned hosted attempt is still saved, and stale.
final restarted = BrowserAuth(now: () => now);
restarted.failures.listen(hostedFailures.add);
now = now.add(const Duration(minutes: 30));
await org.start({'purpose': 'organization'});
final callback = Uri.parse(BrowserAuth.callback).replace(
queryParameters: {
'state': organizationLogin.queryParameters['state']!,
'code': 'org-code',
},
);
await restarted.receive(callback);
await org.receive(callback);
await Future<void>.delayed(Duration.zero);
expect(hostedFailures, isEmpty);
expect(orgCodes.single.code, 'org-code');
await restarted.dispose();
await org.dispose();
},
);
test(
'a restored owner consuming its callback is never failed by a peer',
() async {
late Uri organizationLogin;
final first = BrowserAuth(
origin: organization,
openBrowser: (uri) async {
organizationLogin = uri;
return null;
},
);
await first.start({'purpose': 'organization'});
await first.dispose();
// After a restart neither owner has the attempt in memory.
final gated = _PausedReadStorage();
final org = BrowserAuth(origin: organization, storage: gated);
final hosted = BrowserAuth(openBrowser: (_) async => null);
final hostedFailures = <BrowserAuthFailure>[];
final orgCodes = <BrowserAuthCode>[];
hosted.failures.listen(hostedFailures.add);
org.codes.listen(orgCodes.add);
final callback = Uri.parse(BrowserAuth.callback).replace(
queryParameters: {
'state': organizationLogin.queryParameters['state']!,
'code': 'org-code',
},
);
// The hosted owner's ownership check reads the peer attempt, which
// the organization owner consumes before that read returns.
final hostedReceive = hosted.receive(callback);
await gated.paused.future;
await org.receive(callback);
gated.resume.complete();
await hostedReceive;
await pumpEventQueue();
expect(orgCodes.single.code, 'org-code');
expect(hostedFailures, isEmpty);
await hosted.dispose();
await org.dispose();
},
);
test('completed sign-in stores the session and reconnects once', () async {
late Uri login;
var reconnects = 0;
final account = BuilderlabAccountClient(
accountOrigin: organization,
httpClient: MockClient((request) async {
expect(request.url.origin, organization.origin);
if (request.url.path.endsWith('/v1/auth/login/exchange')) {
return http.Response(
jsonEncode({
'session_credential': 'org-secret',
'expires_at': expiry.toIso8601String(),
}),
200,
);
}
if (request.url.path.endsWith('/v1/auth/me')) {
return http.Response(
jsonEncode({
'subject': 'member',
'expires_at': expiry.toIso8601String(),
}),
200,
);
}
return http.Response('{}', 404);
}),
);
final signIn = OrganizationSignIn(
account: account,
browser: BrowserAuth(
origin: organization,
openBrowser: (uri) async {
login = uri;
return null;
},
),
reconnect: () async => reconnects++,
);
await signIn.initialize();
expect(signIn.status, OrganizationSessionStatus.signedOut);
await signIn.signIn();
expect(signIn.status, OrganizationSessionStatus.signingIn);
await signIn.browser.receive(
Uri.parse(BrowserAuth.callback).replace(
queryParameters: {
'state': login.queryParameters['state']!,
'code': 'org-code',
},
),
);
await pumpEventQueue();
expect(signIn.status, OrganizationSessionStatus.signedIn);
expect(signIn.failure, isNull);
expect(reconnects, 1);
expect(account.account?.subject, 'member');
signIn.dispose();
});
test(
'a restore after an offline start shows the session signed in',
() async {
await const FlutterSecureStorage().write(
key: 'buzz_hosted_session_block_example_com_v1',
value: jsonEncode({
'origin': organization.toString(),
'credential': 'org-secret',
'subject': 'member',
'expires_at': expiry.toIso8601String(),
}),
);
var online = false;
final account = BuilderlabAccountClient(
accountOrigin: organization,
httpClient: MockClient((request) async {
if (!online) return http.Response('{}', 503);
expect(request.url.path, '/api/goose/v1/auth/me');
return http.Response(
jsonEncode({
'subject': 'member',
'expires_at': expiry.toIso8601String(),
}),
200,
);
}),
);
final signIn = OrganizationSignIn(
account: account,
browser: BrowserAuth(
origin: organization,
openBrowser: (uri) async => null,
),
reconnect: () async {},
);
await signIn.initialize();
expect(signIn.status, OrganizationSessionStatus.signedOut);
// A relay connection retry restores the session once back online.
online = true;
await account.restore();
expect(signIn.status, OrganizationSessionStatus.signedIn);
signIn.dispose();
},
);
}
/// Pauses the first read, then serves reads after the peer's changes.
class _PausedReadStorage extends FlutterSecureStorage {
final paused = Completer<void>();
final resume = Completer<void>();
@override
Future<String?> read({
required String key,
AppleOptions? iOptions,
AndroidOptions? aOptions,
LinuxOptions? lOptions,
WebOptions? webOptions,
AppleOptions? mOptions,
WindowsOptions? wOptions,
}) async {
if (!paused.isCompleted) {
paused.complete();
await resume.future;
}
return super.read(key: key);
}
}