Files
buzz/mobile/test/shared/hosted/builderlab_account_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

333 lines
11 KiB
Dart

import 'dart:async';
import 'hosted_http_fixture.dart';
import 'dart:convert';
import 'package:buzz/shared/hosted/builderlab_account.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';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final expiry = DateTime.now()
.toUtc()
.add(const Duration(days: 1))
.toIso8601String();
final verifier = List.filled(43, 'a').join();
setUp(() => FlutterSecureStorage.setMockInitialValues({}));
test(
'real client exchanges PKCE code, verifies, persists and restores session',
() async {
final requests = <http.Request>[];
final transport = MockClient((request) async {
requests.add(request);
expect(request.url.origin, 'https://app.builderlab.xyz');
expect(request.followRedirects, isFalse);
expect(request.headers.containsKey('cookie'), isFalse);
if (request.url.path.endsWith('/exchange')) {
expect(jsonDecode(request.body), {
'code': 'one-use',
'code_verifier': verifier,
});
expect(
request.headers.containsKey('X-BB-Session-Credential'),
isFalse,
);
return http.Response(
jsonEncode({'session_credential': 'secret', 'expires_at': expiry}),
200,
);
}
expect(request.headers['X-BB-Session-Credential'], 'secret');
return http.Response(
jsonEncode({'subject': 'account-1', 'expires_at': expiry}),
200,
);
});
final client = BuilderlabAccountClient(httpClient: transport);
expect(
(await client.exchange(code: 'one-use', verifier: verifier)).subject,
'account-1',
);
final restored = BuilderlabAccountClient(httpClient: transport);
expect((await restored.restore())!.subject, 'account-1');
expect(requests.length, 3);
await restored.clearLocalSession();
expect(
await BuilderlabAccountClient(httpClient: transport).restore(),
isNull,
);
},
);
testWidgets('total deadline releases account queue despite trickling body', (
tester,
) async {
final transport = TrickleClient(
(request) => http.Response(
jsonEncode(
request.url.path.endsWith('/exchange')
? {'session_credential': 'secret', 'expires_at': expiry}
: {'subject': 'account-1', 'expires_at': expiry},
),
200,
),
);
final client = BuilderlabAccountClient(httpClient: transport);
addTearDown(client.dispose);
Object? failure;
var cleared = false;
unawaited(
client
.exchange(code: 'code', verifier: verifier)
.then<void>(
(_) => fail('trickling response must not complete'),
onError: (Object error) => failure = error,
),
);
unawaited(client.clearLocalSession().then((_) => cleared = true));
await tester.pump();
await tester.pump(const Duration(seconds: 20));
await tester.pump(const Duration(seconds: 5));
expect(failure, isNull);
expect(cleared, isFalse);
await tester.pump(const Duration(seconds: 5));
expect(failure, AccountFailure.unavailable);
expect(transport.aborted, isTrue);
expect(transport.cancelled, isTrue);
expect(cleared, isTrue);
transport.slow = false;
final retry = client.exchange(code: 'retry', verifier: verifier);
await tester.pump();
expect((await retry).subject, 'account-1');
});
test('invalid verification cannot persist an exchanged credential', () async {
final transport = MockClient(
(request) async => http.Response(
jsonEncode(
request.url.path.endsWith('/exchange')
? {'session_credential': 'secret', 'expires_at': expiry}
: {'expires_at': expiry},
),
200,
),
);
final client = BuilderlabAccountClient(httpClient: transport);
await expectLater(
client.exchange(code: 'code', verifier: verifier),
throwsA(AccountFailure.invalidResponse),
);
expect(await client.restore(), isNull);
});
test('redirect and denial are not accepted as login success', () async {
for (final status in [302, 403]) {
final client = BuilderlabAccountClient(
httpClient: MockClient(
(_) async => http.Response('sensitive response', status),
),
);
await expectLater(
client.exchange(code: 'code', verifier: verifier),
throwsA(
status == 403 ? AccountFailure.denied : AccountFailure.unavailable,
),
);
expect(await client.restore(), isNull);
}
});
const storageKey = 'buzz_hosted_session_app_builderlab_xyz_v1';
String record(String subject, String credential) => jsonEncode({
'origin': 'https://app.builderlab.xyz',
'credential': credential,
'subject': subject,
'expires_at': expiry,
});
Future<String?> stored() =>
const FlutterSecureStorage().read(key: storageKey);
test('session storage is device-only on iOS', () {
expect(
BuilderlabAccountClient.defaultStorage.iOptions.accessibility,
KeychainAccessibility.first_unlock_this_device,
);
});
test('callback exchange waits for an in-flight startup restore', () async {
FlutterSecureStorage.setMockInitialValues({
storageKey: record('account-1', 'old'),
});
final restoreVerified = Completer<void>();
final client = BuilderlabAccountClient(
httpClient: MockClient((request) async {
if (request.url.path.endsWith('/exchange')) {
return http.Response(
jsonEncode({'session_credential': 'new', 'expires_at': expiry}),
200,
);
}
if (request.headers['X-BB-Session-Credential'] == 'old') {
await restoreVerified.future;
}
return http.Response(
jsonEncode({'subject': 'account-1', 'expires_at': expiry}),
200,
);
}),
);
final restoring = client.restore();
final exchanging = client.exchange(code: 'code', verifier: verifier);
restoreVerified.complete();
expect((await restoring)!.subject, 'account-1');
expect((await exchanging).subject, 'account-1');
expect(jsonDecode((await stored())!)['credential'], 'new');
});
test('concurrent restores share one adopted account', () async {
FlutterSecureStorage.setMockInitialValues({
storageKey: record('account-1', 'old'),
});
var verifications = 0;
final client = BuilderlabAccountClient(
httpClient: MockClient((request) async {
verifications++;
return http.Response(
jsonEncode({'subject': 'account-1', 'expires_at': expiry}),
200,
);
}),
);
final first = client.restore();
final second = client.restore();
final adopted = await first;
expect(await second, same(adopted));
expect(client.account, same(adopted));
expect(verifications, 1);
// A later restore still re-verifies, so expiry is detected on retry.
await client.restore();
expect(verifications, 2);
});
test('login for another account keeps the existing session', () async {
FlutterSecureStorage.setMockInitialValues({
storageKey: record('account-1', 'old'),
});
final client = BuilderlabAccountClient(
httpClient: MockClient(
(request) async => http.Response(
jsonEncode(
request.url.path.endsWith('/exchange')
? {'session_credential': 'new', 'expires_at': expiry}
: {'subject': 'account-2', 'expires_at': expiry},
),
200,
),
),
);
await expectLater(
client.exchange(code: 'code', verifier: verifier),
throwsA(AccountFailure.differentAccount),
);
expect(client.account, isNull);
expect(await stored(), record('account-1', 'old'));
});
test('only a rejected credential clears a stored session', () async {
for (final (status, failure) in [
(401, null),
(500, AccountFailure.unavailable),
(403, AccountFailure.denied),
]) {
FlutterSecureStorage.setMockInitialValues({
storageKey: record('account-1', 'old'),
});
final client = BuilderlabAccountClient(
httpClient: MockClient((_) async => http.Response('{}', status)),
);
if (failure == null) {
expect(await client.restore(), isNull);
expect(await stored(), isNull);
} else {
await expectLater(client.restore(), throwsA(failure));
expect(await stored(), record('account-1', 'old'));
}
}
});
test(
'unreadable record is a storage failure, not an absent session',
() async {
FlutterSecureStorage.setMockInitialValues({storageKey: 'not json'});
final client = BuilderlabAccountClient(
httpClient: MockClient((_) async => fail('no request expected')),
);
await expectLater(client.restore(), throwsA(AccountFailure.storage));
await expectLater(
client.exchange(code: 'code', verifier: verifier),
throwsA(AccountFailure.storage),
);
await client.clearLocalSession();
expect(await client.restore(), isNull);
},
);
test('rejected identity read clears the session', () async {
var sessionRevoked = false;
final client = BuilderlabAccountClient(
httpClient: MockClient((request) async {
if (request.url.path.endsWith('/current')) {
return http.Response('{}', 401);
}
if (request.url.path.endsWith('/me') &&
request.headers['X-BB-Session-Credential'] == 'secret' &&
sessionRevoked) {
return http.Response('{}', 401);
}
return http.Response(
jsonEncode(
request.url.path.endsWith('/exchange')
? {'session_credential': 'secret', 'expires_at': expiry}
: {'subject': 'account-1', 'expires_at': expiry},
),
200,
);
}),
);
await client.exchange(code: 'code', verifier: verifier);
// A route-level 401 with a valid session is an authorization failure.
await expectLater(client.currentIdentity(), throwsA(AccountFailure.denied));
expect(client.account, isNotNull);
expect(await stored(), isNotNull);
sessionRevoked = true;
await expectLater(
client.currentIdentity(),
throwsA(AccountFailure.signedOut),
);
expect(client.account, isNull);
expect(await stored(), isNull);
});
test('authenticated post accepts only Buzz account routes', () async {
final client = BuilderlabAccountClient(
httpClient: MockClient((_) async => fail('no request expected')),
);
for (final path in [
'/v1/auth/me',
'/v1/buzz',
'/v1/buzz/../auth/me',
'/v1/buzz/nsec-backups?x=1',
'https://evil.example/v1/buzz/nsec-backups',
'//evil.example/v1/buzz/nsec-backups',
]) {
expect(() => client.post(path, {}), throwsArgumentError, reason: path);
}
await expectLater(
client.post('/v1/buzz/nsec-backups/enrollment', {}),
throwsA(AccountFailure.signedOut),
);
});
}