mirror of
https://github.com/block/buzz.git
synced 2026-11-28 04:01:45 +00:00
Ticket 6 of the [Android push design](https://github.com/block/buzz/pull/9555), building on [#9558 resolve push wakes](https://github.com/block/buzz/pull/9558). Enrollment (FCM token registration, ticket 7) landed separately in [#9811 enroll Android push](https://github.com/block/buzz/pull/9811), which also carries the Firebase build config, `POST_NOTIFICATIONS` and the auto-init switch. ## What it does A data-only FCM message wakes the app with no content. This PR turns that wake into notifications natively, with no UI: - `PushWakeService` (a `FirebaseMessagingService`) treats both a message and the deleted-messages callback as "sync now". - If the app is in the foreground it does nothing. Otherwise it starts a headless Flutter engine on `androidPushWakeMain`, which runs ticket 5's `resolvePushWake` and hands the notifications back to native code to post. - If nothing has been posted after 2 s, a generic "New activity" notification appears in the "Other" channel. The real result replaces it silently, or removes it when there is nothing to show. An 8 s native watchdog ends a run whose Dart side hangs. - One run per process. A wake that arrives mid-run joins it and sets the rerun flag from ticket 5. - Channels: Direct messages, Mentions, Other. Each conversation is one `MessagingStyle` notification, grouped under the app. Existing messages in a conversation are recovered from the active notification so a new wake appends instead of replacing. - Tapping opens the conversation through the existing push deep-link path (`pendingPushNotificationLink`), for a cold start and for a running app. This also turns on the cold-start tap handoff for Android, which was iOS-only. - The headless path sends the NIP-FI header that org-protected relays need, using the same `HostedRelayAuth` as the foreground app (background mode: a fresh assertion per wake that never records foreground failures). `resolvePushWake` gets one optional `relayHeaders` hook for it. ## Decisions - **Firebase config is build-time and never committed.** `BUZZ_FIREBASE_APP_ID`, `BUZZ_FIREBASE_API_KEY`, `BUZZ_FIREBASE_PROJECT_ID` and `BUZZ_FIREBASE_SENDER_ID` become string resources (no google-services plugin or JSON file). All four or none: a partial set fails the build, and a build with none works but has no push wake. Documented in `mobile/README.md`. - **The wake only reads the saved account session.** Its account clients share the foreground app's record, so they never save, replace or delete it. A rejected credential is dropped from the wake's memory only, which keeps a sign-in that finished mid-wake. - **No FCM token before enrollment.** Firebase Messaging's auto-init is off, so a configured build does not register with Firebase at launch. Ticket 7 requests the token when the app enrolls. - **Notifications disabled means the wake is skipped entirely**, so nothing is claimed as shown and the next wake after the user re-enables them still delivers. - **Debug hook.** Debug builds include an exported receiver that runs the same code path as the FCM service, for testing without Firebase. ## Known gaps - The foreground app does not yet write the shown-message record, so a message already read in the app can notify again after the app is backgrounded. This needs its own ticket. - `PushWakeService` is now the app's only messaging service, so it should hand `onNewToken` to the registration plugin from [#9811 enroll Android push](https://github.com/block/buzz/pull/9811). It doesn't yet. - Follow-ups now that enrollment is on main: real FCM wakes run one at a time and never join a run; a blocked or silent "Other" channel mutes a slow DM; a stale generic can make one message alert twice; NIP-FI issuance can use the whole wake budget; a consumed tap replays after process death; cold engine start registers every plugin. - Follow-ups from review: - A confirmed age restriction isn't applied to Android wakes, and the Android purge doesn't cancel posted notifications. - One unreadable entry, or a throw from `notify`, sends the whole batch, already recorded as shown, to the generic notification. - The foreground check can lag about 700 ms behind the app becoming visible. - There is no group summary, so below Android 16 several conversations show as separate cards. - On API 24 and 25 the notifications have no priority or defaults, so they don't sound. - A stall delivering the result over the channel can still use up the 1 s reserve before the watchdog. - A shown-message claim writes its marker before its watermark and prune I/O, so a stall past the 250 ms claim grace loses the message (from [#9558 Dart wake-to-notifications](https://github.com/block/buzz/pull/9558)). - A live tap during cold start can be handled before the startup tap, and the tap's target is carried in extras any app can send. - The native side has no JVM tests yet, although `app/src/test/kotlin` exists and CI runs it. A payload-contract test for `WakeNotification.fromDart` and a test of the production `_headlessRelayHeaders` wiring are follow-ups. The device runs below cover the native side, and the Dart side (payload shape, joined runs, header hook, cold-start tap) has tests. ### Validation Run on a Pixel 9a (Android 17) against a local fake relay with test data only, using a profile (AOT) build with the debug hook, since debug (JIT) builds start the Dart engine in 4 to 5 s and say little about real latency. Timings come from the `BuzzPushWake` log tags, measured from the start of the wake. | Scenario | Result | | --- | --- | | Cold wake, process killed, one DM | Notification posted at 2.0 s (engine 0.9 s, Dart ready 1.8 s), three runs within 0.1 s of each other | | Wake while the process is warm | Posted at 0.4 s | | Two conversations in one wake | One grouped notification card, each conversation its own `MessagingStyle`, posted at 2.1 s | | Relay answers in 2.4 s | Generic "New activity" at 2.0 s, replaced by the real notification at 5.8 s, generic removed, replacement did not beep (the system's `notification_alert` event shows no sound for it, while the generic did beep) | | Relay answers in 3.5 s (over the 3 s request limit) | Generic stays at 5.0 s, nothing is claimed | | Next wake after that, relay healthy | Real notification at 0.4 s and the stale generic is gone (the case fixed in `c786957`) | | Relay accepts the connection and never answers | Dart's own 3 s request timeout ends the wake at 5.0 s as incomplete, generic stays | | App in the foreground | Wake ignored, no notification; after backgrounding, the next wake delivers | | Tap, app running in background | The existing deep-link provider receives the right community, channel and message; notification dismisses | | Tap, process killed | Same | | 10 wakes in a row, debug build, app process kept alive | Network threads stay at 3 and total threads flat (53 to 58). Before the switch to dart:io, each wake left about 2 Cronet threads behind (3 to 11 over 5 wakes) | An earlier run on an Android 36 emulator gave the same behavior. Not exercised: the FCM service itself (it is not exported and there is no Firebase config), so the deleted-messages callback was not triggered, though it calls the same entry as the debug hook. The 8 s native watchdog was not reached: a hung relay is always ended earlier by Dart's request timeout, and only a hung Dart isolate would trigger it. NIP-FI against an org-protected relay is covered only by unit tests. The tap was checked up to the deep-link provider, not to the chat screen, because the fake relay does not serve the channel list the app needs to open it. On a debug (JIT) build the main thread is busy for several seconds starting the engine, so the 2 s generic timer, which runs on that thread, fired at 5.3 s. Added tests: [`android_push_wake_test.dart`](https://github.com/block/buzz/blob/android-push-wake-handling/mobile/test/shared/push/android_push_wake_test.dart) covers the native payload, joined and sequential wakes, the relay header hook, and a community whose headers fail. [`push_bridge_test.dart`](https://github.com/block/buzz/blob/android-push-wake-handling/mobile/test/shared/push/push_bridge_test.dart) covers the Android cold-start tap. ### Screenshots Before: no notification (nothing handles wakes). After, with test data, on the Pixel 9a (two conversations grouped) and on the emulator (one conversation after a cold wake): <img src="https://github.com/user-attachments/assets/d3d98784-fecc-4757-a867-0a93d5a210a5" width="300" alt="Two conversations grouped on a Pixel"> <img src="https://github.com/user-attachments/assets/1e7fea3c-7f72-4f8d-90d1-8c289cf1b740" width="300" alt="One conversation after a cold wake on an emulator"> ## Regressions - Adds the `POST_NOTIFICATIONS` permission and the Firebase Messaging and `lifecycle-process` dependencies, so the Android build and APK grow. The runtime permission prompt is not part of this PR. - Debug builds ship an exported broadcast receiver that can trigger a wake. Release builds do not include it. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost:3000> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
805 lines
27 KiB
Dart
805 lines
27 KiB
Dart
import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart';
|
|
import 'package:buzz/shared/hosted/known_community_sync.dart';
|
|
import '../community/community_storage_test.dart' show FakeSecureStorage;
|
|
import 'dart:async';
|
|
|
|
import 'hosted_http_fixture.dart';
|
|
|
|
import 'dart:convert';
|
|
|
|
import 'package:buzz/shared/hosted/builderlab_account.dart';
|
|
import 'package:buzz/shared/storage/serial_queue.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(
|
|
'same-subject setup completion resumes a parked account removal',
|
|
() async {
|
|
var needsSetup = true;
|
|
var removals = 0;
|
|
final client = BuilderlabAccountClient(
|
|
storage: FakeSecureStorage(),
|
|
httpClient: MockClient((request) async {
|
|
if (request.url.path.endsWith('/exchange')) {
|
|
return http.Response(
|
|
jsonEncode({
|
|
'session_credential': 'same-credential',
|
|
'expires_at': expiry,
|
|
}),
|
|
200,
|
|
);
|
|
}
|
|
if (request.url.path.endsWith('/me')) {
|
|
return http.Response(
|
|
jsonEncode({
|
|
'subject': 'same-owner',
|
|
'expires_at': expiry,
|
|
'account_status': needsSetup
|
|
? 'ACCOUNT_STATUS_NEEDS_DETAILS'
|
|
: 'ACCOUNT_STATUS_ACTIVE',
|
|
}),
|
|
200,
|
|
);
|
|
}
|
|
removals++;
|
|
return http.Response('{}', needsSetup ? 403 : 200);
|
|
}),
|
|
);
|
|
await client.exchange(code: 'first', verifier: verifier);
|
|
final sync = KnownCommunitySync(
|
|
account: client,
|
|
storage: FakeSecureStorage(),
|
|
localCommunities: () async => [],
|
|
);
|
|
addTearDown(() {
|
|
sync.dispose();
|
|
client.dispose();
|
|
});
|
|
await sync.remove('wss://team.example');
|
|
await sync.synchronize();
|
|
expect(sync.failure, AccountFailure.accountSetupRequired);
|
|
expect(removals, 1);
|
|
await client.restore();
|
|
await sync.synchronize();
|
|
expect(
|
|
removals,
|
|
1,
|
|
reason: 'ordinary restore must not bypass the parked session',
|
|
);
|
|
needsSetup = false;
|
|
await client.exchange(code: 'setup-completed', verifier: verifier);
|
|
await sync.synchronize();
|
|
expect(client.account!.subject, 'same-owner');
|
|
expect(removals, 2);
|
|
expect(await sync.pendingRemovals('same-owner'), isEmpty);
|
|
expect(sync.failure, isNull);
|
|
},
|
|
);
|
|
|
|
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',
|
|
'email': 'owner@example.com',
|
|
'expires_at': expiry,
|
|
}),
|
|
200,
|
|
);
|
|
});
|
|
// The notification extension's copy follows every adopt and clear.
|
|
final shared = <String?>[];
|
|
var unshareFails = false;
|
|
var shareFails = true;
|
|
Future<void> share(String? credential) async {
|
|
if (credential == null && unshareFails) throw StateError('keychain');
|
|
if (credential != null && shareFails) throw StateError('keychain');
|
|
shared.add(credential);
|
|
}
|
|
|
|
final storage = _SessionStorage();
|
|
final client = BuilderlabAccountClient(
|
|
httpClient: transport,
|
|
storage: storage,
|
|
onSessionChanged: share,
|
|
);
|
|
expect(
|
|
(await client.exchange(code: 'one-use', verifier: verifier)).subject,
|
|
'account-1',
|
|
);
|
|
// A failed share never blocks sign-in, and the next request retries it.
|
|
await Future<void>.delayed(Duration.zero);
|
|
expect(shared, isEmpty);
|
|
shareFails = false;
|
|
await client.post('/v1/buzz/known-communities/list', {});
|
|
await Future<void>.delayed(Duration.zero);
|
|
expect(shared, ['secret']);
|
|
await client.post('/v1/buzz/known-communities/list', {});
|
|
await Future<void>.delayed(Duration.zero);
|
|
expect(shared, ['secret']);
|
|
final restored = BuilderlabAccountClient(
|
|
httpClient: transport,
|
|
storage: storage,
|
|
onSessionChanged: share,
|
|
);
|
|
final restoredAccount = (await restored.restore())!;
|
|
expect(restoredAccount.subject, 'account-1');
|
|
expect(restoredAccount.email, 'owner@example.com');
|
|
expect(requests.length, 5);
|
|
await Future<void>.delayed(Duration.zero);
|
|
expect(shared, ['secret', 'secret']);
|
|
// A failed local deletion fails the sign-out and keeps the account
|
|
// signed in, so the extension gets its copy back after the removal.
|
|
storage.failDelete = true;
|
|
await expectLater(
|
|
restored.clearLocalSession(),
|
|
throwsA(AccountFailure.storage),
|
|
);
|
|
await Future<void>.delayed(Duration.zero);
|
|
expect(restored.account?.subject, 'account-1');
|
|
expect(shared, ['secret', 'secret', null, 'secret']);
|
|
expect(await client.restore(), isNotNull);
|
|
storage.failDelete = false;
|
|
// A failed removal fails the sign-out instead of leaving it shared, and
|
|
// the next restore retries it.
|
|
unshareFails = true;
|
|
await expectLater(
|
|
restored.clearLocalSession(),
|
|
throwsA(AccountFailure.storage),
|
|
);
|
|
unshareFails = false;
|
|
expect(
|
|
await BuilderlabAccountClient(
|
|
httpClient: transport,
|
|
onSessionChanged: share,
|
|
).restore(),
|
|
isNull,
|
|
);
|
|
expect(shared.last, isNull);
|
|
await restored.clearLocalSession();
|
|
expect(shared.last, isNull);
|
|
expect(restored.account, isNull);
|
|
expect(
|
|
await BuilderlabAccountClient(httpClient: transport).restore(),
|
|
isNull,
|
|
);
|
|
// A credential adopted while an earlier share is in flight is shared
|
|
// once that write completes.
|
|
final gate = Completer<void>();
|
|
final delayed = <String?>[];
|
|
var issued = 0;
|
|
final rotating = BuilderlabAccountClient(
|
|
httpClient: MockClient(
|
|
(request) async => http.Response(
|
|
jsonEncode(
|
|
request.url.path.endsWith('/exchange')
|
|
? {
|
|
'session_credential': 'next-${++issued}',
|
|
'expires_at': expiry,
|
|
}
|
|
: {'subject': 'account-1', 'expires_at': expiry},
|
|
),
|
|
200,
|
|
),
|
|
),
|
|
onSessionChanged: (credential) async {
|
|
await gate.future;
|
|
delayed.add(credential);
|
|
},
|
|
);
|
|
await rotating.exchange(code: 'one-use', verifier: verifier);
|
|
await rotating.exchange(code: 'two-use', verifier: verifier);
|
|
gate.complete();
|
|
await pumpEventQueue();
|
|
expect(delayed, ['next-1', 'next-2']);
|
|
},
|
|
);
|
|
|
|
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,
|
|
),
|
|
);
|
|
// Any queued account request waits for the deadline.
|
|
unawaited(client.restore().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');
|
|
});
|
|
|
|
for (final (name, body) in [
|
|
('a body that is not JSON', '{"oops"'),
|
|
('a body that is not an object', '[]'),
|
|
]) {
|
|
test('$name is reported as an account response error', () async {
|
|
final reporter = _RecordingDiagnostics();
|
|
final client = BuilderlabAccountClient(
|
|
httpClient: MockClient((_) async => http.Response(body, 200)),
|
|
diagnostics: reporter,
|
|
);
|
|
await expectLater(
|
|
client.exchange(code: 'code', verifier: verifier),
|
|
throwsA(AccountFailure.invalidResponse),
|
|
);
|
|
expect(reporter.errors, [
|
|
(FormatException, DiagnosticOperation.accountResponse),
|
|
]);
|
|
});
|
|
}
|
|
|
|
// 200 responses that parse but lack what the client requires.
|
|
for (final (name, exchange, me) in <(String, Object, Object)>[
|
|
('an exchange with no credential', <String, Object>{}, <String, Object>{}),
|
|
(
|
|
'a session with no subject',
|
|
{'session_credential': 'secret', 'expires_at': expiry},
|
|
{'expires_at': expiry},
|
|
),
|
|
(
|
|
'a session with an unreadable expiry',
|
|
{'session_credential': 'secret', 'expires_at': expiry},
|
|
{'subject': 'account-1', 'expires_at': 'soon'},
|
|
),
|
|
]) {
|
|
test('$name is reported as an account response error', () async {
|
|
final reporter = _RecordingDiagnostics();
|
|
final client = BuilderlabAccountClient(
|
|
httpClient: MockClient(
|
|
(request) async => http.Response(
|
|
jsonEncode(request.url.path.endsWith('/exchange') ? exchange : me),
|
|
200,
|
|
),
|
|
),
|
|
diagnostics: reporter,
|
|
);
|
|
await expectLater(
|
|
client.exchange(code: 'code', verifier: verifier),
|
|
throwsA(AccountFailure.invalidResponse),
|
|
);
|
|
expect(reporter.errors, [
|
|
(FormatException, DiagnosticOperation.accountResponse),
|
|
]);
|
|
});
|
|
}
|
|
|
|
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('a sign-out is never undone by a pending session check', () async {
|
|
FlutterSecureStorage.setMockInitialValues({
|
|
storageKey: record('account-1', 'old'),
|
|
});
|
|
final storage = _SessionStorage();
|
|
var check = Completer<void>();
|
|
final client = BuilderlabAccountClient(
|
|
storage: storage,
|
|
httpClient: MockClient((request) async {
|
|
await check.future;
|
|
return http.Response(
|
|
jsonEncode({'subject': 'account-1', 'expires_at': expiry}),
|
|
200,
|
|
);
|
|
}),
|
|
);
|
|
// A check already pending when sign-out starts doesn't hold it up.
|
|
final early = client.restore();
|
|
await pumpEventQueue();
|
|
await client.clearLocalSession();
|
|
check.complete();
|
|
expect(await early, isNull);
|
|
expect(client.account, isNull);
|
|
|
|
// Nor does a check that starts while the session is being deleted.
|
|
FlutterSecureStorage.setMockInitialValues({
|
|
storageKey: record('account-1', 'old'),
|
|
});
|
|
check = Completer<void>();
|
|
final deleted = Completer<void>();
|
|
storage.holdDelete = deleted.future;
|
|
final clearing = client.clearLocalSession();
|
|
final late = client.restore();
|
|
await pumpEventQueue();
|
|
deleted.complete();
|
|
await clearing;
|
|
check.complete();
|
|
expect(await late, isNull);
|
|
expect(client.account, isNull);
|
|
expect(await stored(), isNull);
|
|
});
|
|
|
|
test('an exchange queued before a sign-out cannot sign back in', () async {
|
|
FlutterSecureStorage.setMockInitialValues({
|
|
storageKey: record('account-1', 'old'),
|
|
});
|
|
final entered = Completer<void>();
|
|
final release = 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') {
|
|
if (!entered.isCompleted) entered.complete();
|
|
await release.future;
|
|
}
|
|
return http.Response(
|
|
jsonEncode({'subject': 'account-1', 'expires_at': expiry}),
|
|
200,
|
|
);
|
|
}),
|
|
);
|
|
addTearDown(() {
|
|
if (!release.isCompleted) release.complete();
|
|
client.dispose();
|
|
});
|
|
final restoring = client.restore();
|
|
await entered.future;
|
|
final exchanging = client
|
|
.exchange(code: 'code', verifier: verifier)
|
|
.then<Object?>((value) => value, onError: (Object error) => error);
|
|
await client.clearLocalSession();
|
|
release.complete();
|
|
await restoring;
|
|
expect(await exchanging, AccountFailure.unavailable);
|
|
expect(client.account, isNull);
|
|
expect(await stored(), isNull);
|
|
});
|
|
|
|
test('signing out leaves the extension without the session', () async {
|
|
FlutterSecureStorage.setMockInitialValues({
|
|
storageKey: record('account-1', 'old'),
|
|
});
|
|
// Extension writes land in call order, as the iOS bridge does.
|
|
final writes = SerialQueue();
|
|
var shareFails = true;
|
|
String? shared = 'old';
|
|
final unshareStarted = Completer<void>();
|
|
final releaseUnshare = Completer<void>();
|
|
final client = BuilderlabAccountClient(
|
|
httpClient: MockClient(
|
|
(request) async => http.Response(
|
|
jsonEncode({'subject': 'account-1', 'expires_at': expiry}),
|
|
200,
|
|
),
|
|
),
|
|
onSessionChanged: (credential) => writes.run(() async {
|
|
if (credential == null) {
|
|
if (!unshareStarted.isCompleted) unshareStarted.complete();
|
|
await releaseUnshare.future;
|
|
} else if (shareFails) {
|
|
throw StateError('keychain unavailable');
|
|
}
|
|
shared = credential;
|
|
}),
|
|
);
|
|
addTearDown(() {
|
|
if (!releaseUnshare.isCompleted) releaseUnshare.complete();
|
|
client.dispose();
|
|
});
|
|
// The first share fails, so the credential waits to be shared again.
|
|
await client.restore();
|
|
await pumpEventQueue();
|
|
shareFails = false;
|
|
final clearing = client.clearLocalSession();
|
|
await unshareStarted.future;
|
|
// An account request arriving mid-removal must not share it again.
|
|
final request = client.currentIdentity().then<Object?>(
|
|
(value) => value,
|
|
onError: (Object error) => error,
|
|
);
|
|
await pumpEventQueue();
|
|
releaseUnshare.complete();
|
|
await clearing;
|
|
await request;
|
|
await writes.run(() async {});
|
|
expect(client.account, isNull);
|
|
expect(await stored(), isNull);
|
|
expect(shared, isNull);
|
|
});
|
|
|
|
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('a read-only client never removes the session it shares', () async {
|
|
FlutterSecureStorage.setMockInitialValues({
|
|
storageKey: record('account-1', 'old'),
|
|
});
|
|
final oldChecked = Completer<void>();
|
|
var revoked = false;
|
|
http.Response verified() => http.Response(
|
|
jsonEncode({'subject': 'account-1', 'expires_at': expiry}),
|
|
200,
|
|
);
|
|
final foreground = BuilderlabAccountClient(
|
|
httpClient: MockClient((request) async {
|
|
if (request.url.path.endsWith('/exchange')) {
|
|
return http.Response(
|
|
jsonEncode({'session_credential': 'new', 'expires_at': expiry}),
|
|
200,
|
|
);
|
|
}
|
|
return verified();
|
|
}),
|
|
);
|
|
final wake = BuilderlabAccountClient(
|
|
readOnlySession: true,
|
|
httpClient: MockClient((request) async {
|
|
final credential = request.headers['X-BB-Session-Credential'];
|
|
if (credential == 'old') {
|
|
await oldChecked.future;
|
|
return http.Response('{}', 401);
|
|
}
|
|
if (request.url.path.endsWith('/me')) {
|
|
return revoked ? http.Response('{}', 401) : verified();
|
|
}
|
|
return http.Response('{}', 401);
|
|
}),
|
|
);
|
|
|
|
// The user signs in again while the wake's check of the old session is
|
|
// pending; its rejection must not delete the new one.
|
|
final restoring = wake.restore();
|
|
await foreground.exchange(code: 'code', verifier: verifier);
|
|
oldChecked.complete();
|
|
expect(await restoring, isNull);
|
|
expect(jsonDecode((await stored())!)['credential'], 'new');
|
|
|
|
// Nor may a request whose session check is rejected.
|
|
expect((await wake.restore())!.subject, 'account-1');
|
|
revoked = true;
|
|
await expectLater(
|
|
wake.currentIdentity(),
|
|
throwsA(AccountFailure.signedOut),
|
|
);
|
|
expect(wake.account, isNull);
|
|
expect(jsonDecode((await stored())!)['credential'], 'new');
|
|
expect(foreground.account!.subject, 'account-1');
|
|
});
|
|
|
|
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('only agent listings may exceed the default response bound', () async {
|
|
// 100 KB: past the 64 KB default, as a few full-length instructions are.
|
|
final large = jsonEncode({'status': 1, 'padding': 'x' * 100000});
|
|
final client = BuilderlabAccountClient(
|
|
httpClient: MockClient((request) async {
|
|
if (request.url.path.endsWith('/exchange')) {
|
|
return http.Response(
|
|
jsonEncode({'session_credential': 'secret', 'expires_at': expiry}),
|
|
200,
|
|
);
|
|
}
|
|
if (request.url.path.contains('/beekeeper/')) {
|
|
return http.Response(large, 200);
|
|
}
|
|
return http.Response(
|
|
jsonEncode({'subject': 'account-1', 'expires_at': expiry}),
|
|
200,
|
|
);
|
|
}),
|
|
);
|
|
await client.exchange(code: 'one-use', verifier: verifier);
|
|
expect((await client.post('/v3/beekeeper/list-agents', {}))['status'], 1);
|
|
await expectLater(
|
|
client.post('/v3/beekeeper/get-model-catalog', {}),
|
|
throwsA(anything),
|
|
);
|
|
});
|
|
|
|
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),
|
|
);
|
|
});
|
|
}
|
|
|
|
class _SessionStorage extends FlutterSecureStorage {
|
|
bool failDelete = false;
|
|
Future<void>? holdDelete;
|
|
|
|
@override
|
|
Future<void> delete({
|
|
required String key,
|
|
AppleOptions? iOptions,
|
|
AndroidOptions? aOptions,
|
|
LinuxOptions? lOptions,
|
|
WebOptions? webOptions,
|
|
AppleOptions? mOptions,
|
|
WindowsOptions? wOptions,
|
|
}) async {
|
|
if (failDelete) throw StateError('storage unavailable');
|
|
await holdDelete;
|
|
await super.delete(key: key);
|
|
}
|
|
}
|
|
|
|
class _RecordingDiagnostics extends NoopDiagnosticReporter {
|
|
final errors = <(Type, DiagnosticOperation)>[];
|
|
|
|
@override
|
|
void reportError(
|
|
Object error,
|
|
StackTrace? stackTrace, {
|
|
required DiagnosticOperation operation,
|
|
}) => errors.add((error.runtimeType, operation));
|
|
}
|