mirror of
https://github.com/block/buzz.git
synced 2026-11-24 18:21:59 +00:00
## Summary Switch Community currently shows only device-saved communities, leaving account destinations behind a separate Find step. It now merges saved communities with supported account destinations directly, keeps Add Community, and removes the redundant Find action from that Add route. Initial onboarding and identity recovery keep their discovery entry. Find lists supported account addresses before hosted identity setup; hosted selection still performs binding, backup, and admission, while external selection opens the existing identity flow. Mobile also saves QR/address additions and explicit removals through Builder Lab's existing known-communities account APIs. A per-account local journal retries transient failures, survives restarts, pauses in the background, and fences requests against account changes. External secure addresses use the existing self-hosted entry flow; account destinations never imply membership or bypass admission. Remote list omissions do not delete local identities. Explicit additions store an account owner and revision atomically with local credentials. Legacy/unclaimed destinations remain local-only until explicitly added while signed in; signing into another account never claims retained destinations. Restart reconciliation lets a committed re-add supersede an older removal even if the retry-journal write failed. Local deletion and its credential-free account-removal intent commit in one storage write, independent of the account-only retry journal. Removing one of several local identities owned by the same account at an address retains its account destination until that account’s last identity is removed. Another account’s saved identity does not block removal or lose its credentials during recovery. Offline edits retain the stored account subject without treating it as network authorization. Discovery-only intent survives browser callbacks, app restart, and retry. Onboarding recovery controls have a Material ancestor in the actual route. Pending status is fenced to the current subject; interrupted older removals offer explicit local completion, and denied requests offer browser reauthentication. Same-host ports have distinct labels and confirmations, and unsupported hosted ports are excluded. This changes the mobile client and its public-build CI test list only: no relay endpoints, events, migrations, or backend deployment. ### Related issue No duplicate found among open known-communities/switcher issues and PRs. Related picker editing work: #6632 (renaming communities). ### Testing Validated after merging main (`02535e1b53`) at `c4ee037f7e710962f176540abf88d26e98c2823c`. Wes’s follow-up fixes cover push-revocation commit ordering, same-account removal confirmation, and recovery after completed hosted admission. The merge also preserves main’s toolbar and session protections; a test override now accepts the updated relay subscription parameter. - Formatting, static analysis, and differential file-size checks pass. - Prior full CI and security review passed on `3adb117aae`; security checks also passed on `cf3836ecb`. Fresh CI and security review are required for this head. - Mutation checks fail when either the initiating-account removal guard or the rendered-status subject fence is removed; both guards were restored before final validation. - CI explicitly runs the public-only account discovery and synchronization journeys. - Added journeys cover paused removal across A→B, offline restart, journal read/write failures, duplicate local identities in either removal order, delayed status reads across accounts, real browser handoff after denial, unbound external discovery, and local same-host port removal. - Earlier journeys cover pairing acknowledgement and restart after journal-write failure, same-subject setup completion, offline/rejected removal with reopen/retry, and fresh external-only/mixed account entry. - Regression coverage includes discovery deduplication and retry, hosted and external selection, Add without Find, account-only removal, shared authentication/removal persistence, restart recovery, latest-intent ordering, account changes, and retry pause/resume. - `just mobile-check`, `just file-size-check`, and `just mobile-test`: 4,954 default-build tests passed (71 skipped), plus 27 crypto-package tests. - Full public-account suite: 5,012 passed, 12 skipped, one pre-existing failure in `fullscreen_onboarding_test.dart` ("Home stays hidden until community choice and admission"). The same assertion was reproduced on clean base `8cce12f591`: expected both communities imported, actual only the selected community. - Follow-up regression journeys cover both A/B same-address removal orderings, recovery preserving B’s saved key, the production onboarding widget composition, and retained discovery intent with callback/retry plus normal-sign-in controls. - Native/live-account and human testing remain outstanding. The tests use fake network/storage boundaries; live account API behavior, cross-device synchronization, native accessibility, and timeout/late-server-commit ordering still require integration verification. - The three expanded recovery/removal journeys pass and each fails when the corresponding fix is removed. A durably journaled revocation now finishes the confirmed removal even if the account changes during journaling; pre-journal account mismatches still abort. Confirmation copy counts only same-account identities. Explicit account recovery retires a completed join target while preserving in-progress targets. ### Preview Sample-data Flutter widget renders: saved-only and combined lists. These illustrate the picker layout, not a device session or live account sync. | Saved-only | Combined | | --- | --- | |  |  | ### Manual verification 1. Sign into a public account with a community saved on another device. Open Switch Community; verify it appears alongside local choices and Add. 2. Select a hosted and an external community; verify the existing identity/admission flow opens. Add should not offer Find again. 3. Add a community by QR/address, then check the account list on desktop. Remove it on mobile and verify the account entry disappears while other devices retain their local credentials. 4. Repeat removal offline, restart, then reconnect/resume. Verify the queued removal reaches the account service without switching identities. 5. On a fresh device, verify external-only and mixed account lists offer external entry. Check two ports on the same host remain distinguishable. 6. Sign out of account A and into B; retained A destinations must not upload to B. Explicitly add a B destination and verify it syncs. 7. Reject or interrupt account removal; verify visible pending/failure status. A denied session must open browser sign-in through “Sign in again” and retry after exchange; setup-required accounts retain their setup action. 8. Keep two local identities owned by the same account at one address; removing the first must keep the account entry, and removing the last must queue account removal. Repeat with A and B at that address; removing A must preserve B’s saved credentials and still sync A’s removal. 9. Restart offline with a stored account, add/remove an external community, then reconnect as the same account and verify convergence. Explicit sign-out must not claim new local-only entries. 10. Start Find my communities, restart during browser authentication, then return or retry. External destinations must appear before hosted identity setup; normal sign-in must retain its identity checks. --------- Signed-off-by: kenny lopez <klopez4212@gmail.com> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
682 lines
23 KiB
Dart
682 lines
23 KiB
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');
|
|
});
|
|
|
|
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(
|
|
'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);
|
|
}
|
|
}
|