mirror of
https://github.com/block/buzz.git
synced 2026-11-24 18:21:59 +00:00
Lets clients whose clocks are up to 120 s off sign in to NIP-FI communities and stay connected. **Relay** - NIP-42 AUTH and NIP-98 HTTP Auth accept `created_at` within ±120 s, using a shared `buzz_auth::TIMESTAMP_TOLERANCE_SECS`. This covers relay login, audio admission, bridge, admin, invites, NIP-FI policy and Git. - `DEFAULT_REPLAY_TTL_SECS` goes from 120 to 250 s: a 2 × 120 s window, plus 1 s for the inclusive whole-second bounds, plus a 9 s budget for the clock difference between relay pods. A compile-time assert checks the arithmetic. The 9 s is an operational assumption about NTP-synced pods, and the doc comment says so. No `deploy/` override exists. - Media (kind 24242): - Both modes accept `created_at` up to 120 s in the future and an `expiration` greater than `now − 120`. - Strict: the 120 s age limit and the 60 s lifetime cap. - Permissive: keeps its 3600 s age allowance and has no lifetime cap. - `buzz-auth` and `buzz-media` read the time through a `wall_now()` that tests can pin (a `#[cfg(test)]` thread-local), so boundary tests are exact. - Git transport: comments only. It still reuses one proof per session, so the reuse window now matches ±120 s. **CLI** - The desktop-provider lane asks the desktop app for the assertion every time and keeps no copy, so the desktop's cache owns each token's deadline. It looks the token up again after signing and sends that one, so a provider may hand out a new token on every call. - The direct-mint cache sets its deadline to `min(request_start + (exp − iat), receipt + (exp − local_now))`, on a monotonic clock. `request_start` is when the attempt that got the reply was sent, not the start of the retry loop. - An assertion with no local lifetime left is never returned or sent. The cache asks again, up to 3 times, then fails with an auth error that points at the computer's clock. An assertion without a readable `iat` is refused. `iat` may be fractional (a NumericDate); the lifetime is `max(0, floor(exp − iat))` whole seconds. **Cache reuse (CLI, Flutter, iOS):** each cached token records when it arrived on both the monotonic and the wall clock. It is reused only while `max(monotonic elapsed, wall elapsed)` since arrival is under its budget (`refresh point − receipt`, on the monotonic clock). A negative wall elapsed counts as 0. The monotonic clocks used here stop while the device sleeps, so the wall clock ends reuse after a sleep; setting the wall clock back can't stretch a token, because the monotonic bound still applies. **Mobile** - Flutter `HostedRelayAuth`: the same lifetime rule, on a monotonic clock, for async acquisition and for the synchronous `cachedHeaders` media path. A token with no local lifetime left is never sent: issuance is retried up to 3 times, then fails as `unavailable`. A token without a readable `iat` fails as `invalidResponse`. - Flutter refusal hint: the account client reads `Date` when a 403's headers arrive, before the body (`boundedHttpResponse` gains an `onHeaders` callback). The 403 stays `AccountFailure.denied` even if its body is then lost, late or too large. The hint is stored with the refusal it explains (`HostedRelayAuth.failureClockHint`), cleared when that community next gets a token or the account session changes, and left alone by other communities' issuance. The account client records a 403's hint only for the acquisition whose own request was refused (`BuilderlabAccountClient.observingRefusals`), so an unrelated account call, such as the organization key backup, never supplies a sign-in's hint. When the offset is over 115 s, the reconnect and organization banners add "Your device's clock looks about N minutes off, which can cause this. Check your date and time settings." - iOS `BuzzRelayAssertionIssuer`: the same lifetime rule, on `systemUptime`. An assertion without a readable `iat` is refused. - iOS push enrollment: a new grant's window starts 120 s in the past, so `not_before = now − 120` and `expires_at = now − 120 + lifetime`. A fast phone then neither signs a `not_before` the gateway hasn't reached nor goes over its 30-day maximum. A resumed journal resubmits the installation expiry it already attested, byte for byte. The delegation, which is signed fresh each time, expires at the earlier of that expiry and `not_before + lifetime`, so a journal written by an older client on a fast phone still gets a grant the gateway accepts. The saved grant records the delegation's expiry. - Flutter and iOS already sign a fresh proof with a `nonce` on every issuer attempt, so their retries needed no change. **Specs:** NIP-FA proof bounds (120 s old / 120 s future), plus NIP-FI Git (`±120s`), media freshness, the media read residual and the media trace row. `desktop/` is untouched. Not exercised live: Git clone/push, audio join and push delivery with a skewed client clock. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: Tom Brow <tomb@squareup.com>
300 lines
10 KiB
Dart
300 lines
10 KiB
Dart
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
import 'package:buzz/shared/hosted/builderlab_account.dart';
|
|
import 'package:buzz/shared/hosted/hosted_backup_service.dart';
|
|
import 'package:buzz/shared/hosted/hosted_relay_auth.dart';
|
|
import 'package:buzz/shared/hosted/hpke_backup.dart';
|
|
import 'package:buzz/shared/hosted/builderlab_build.dart';
|
|
import 'package:buzz/shared/hosted/organization_key_backup.dart';
|
|
import 'package:buzz/shared/relay/relay_provider.dart';
|
|
import 'package:flutter/services.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;
|
|
import '../../helpers/test_assertion.dart';
|
|
|
|
class _FakeHpke extends HpkeBackup {
|
|
_FakeHpke(this.envelope);
|
|
final Map<String, dynamic> envelope;
|
|
int seals = 0;
|
|
@override
|
|
Future<Map<String, dynamic>> seal({
|
|
required Map<String, dynamic> enrollment,
|
|
required String secretHex,
|
|
}) async {
|
|
seals++;
|
|
return envelope;
|
|
}
|
|
}
|
|
|
|
void main() {
|
|
TestWidgetsFlutterBinding.ensureInitialized();
|
|
final fixture =
|
|
jsonDecode(
|
|
File(
|
|
'../desktop/src-tauri/src/testdata/hpke_nsec_backup_v1.json',
|
|
).readAsStringSync(),
|
|
)
|
|
as Map<String, dynamic>;
|
|
final envelope = Map<String, dynamic>.from(fixture['envelope'] as Map);
|
|
final keys = nostr.Keys(fixture['nostr_secret_key_hex'] as String);
|
|
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));
|
|
final pending = HostedBackupService.pendingKey(
|
|
organization.origin,
|
|
'member',
|
|
keys.public,
|
|
);
|
|
|
|
late List<String> paths;
|
|
late List<String> uploads;
|
|
late int statusCode;
|
|
late List<String> listed;
|
|
late String current;
|
|
late int uploadCode;
|
|
late DateTime now;
|
|
late _FakeHpke hpke;
|
|
|
|
BuilderlabAccountClient organizationClient() => BuilderlabAccountClient(
|
|
accountOrigin: organization,
|
|
httpClient: MockClient((request) async {
|
|
expect(request.url.origin, organization.origin);
|
|
expect(request.headers['X-BB-Session-Credential'], 'org-secret');
|
|
final path = request.url.path.replaceFirst('/api/goose', '');
|
|
paths.add(path);
|
|
return switch (path) {
|
|
'/v1/auth/me' => http.Response(
|
|
jsonEncode({
|
|
'subject': 'member',
|
|
'expires_at': expiry.toIso8601String(),
|
|
}),
|
|
200,
|
|
),
|
|
'/v1/buzz/nostr-identities/current' => http.Response(
|
|
jsonEncode({'identity': null}),
|
|
200,
|
|
),
|
|
'/v1/buzz/identity/assertions' => http.Response(
|
|
jsonEncode({
|
|
'assertion': testAssertion('org-token'),
|
|
'nostr_pubkey': keys.public,
|
|
'expires_at': DateTime.now().millisecondsSinceEpoch ~/ 1000 + 300,
|
|
}),
|
|
200,
|
|
),
|
|
'/v1/buzz/nsec-backups/status' => http.Response(
|
|
statusCode == 200
|
|
? jsonEncode({
|
|
'current_nostr_pubkey': current,
|
|
'backup_nostr_pubkeys': listed,
|
|
})
|
|
: 'Not Found',
|
|
statusCode,
|
|
),
|
|
'/v1/buzz/nsec-backups/enrollment' => http.Response(
|
|
jsonEncode(envelope),
|
|
200,
|
|
),
|
|
'/v1/buzz/nsec-backups' => () {
|
|
uploads.add(request.body);
|
|
return http.Response(
|
|
uploadCode == 200
|
|
? jsonEncode({
|
|
'stored': true,
|
|
'backup_id': envelope['backup_id'],
|
|
})
|
|
: 'Unavailable',
|
|
uploadCode,
|
|
);
|
|
}(),
|
|
_ => http.Response('{}', 404),
|
|
};
|
|
}),
|
|
);
|
|
|
|
/// Issues an organization assertion on a fresh relay connection, as a
|
|
/// reconnect does, without waiting for the backup it starts.
|
|
Future<void> assert_(OrganizationKeyBackup backup) async {
|
|
final auth = HostedRelayAuth(
|
|
BuilderlabAccountClient(
|
|
httpClient: MockClient(
|
|
(request) async => fail('Hosted account must not be used'),
|
|
),
|
|
),
|
|
organization: backup.account,
|
|
organizationBackup: backup,
|
|
organizationRelay: (relay) =>
|
|
BuilderlabBuild.matchesRelay(relay, [relayHost]),
|
|
enabled: true,
|
|
);
|
|
expect(await auth.headers(relay), {
|
|
'Nostr-Federated-Identity': 'Bearer ${testAssertion('org-token')}',
|
|
});
|
|
}
|
|
|
|
/// One assertion, then the backup it started runs to completion.
|
|
Future<void> connect(OrganizationKeyBackup backup) async {
|
|
await assert_(backup);
|
|
await pumpEventQueue(times: 200);
|
|
}
|
|
|
|
OrganizationKeyBackup backupFor(BuilderlabAccountClient account) =>
|
|
OrganizationKeyBackup(
|
|
account,
|
|
hpke: hpke,
|
|
supportsSealing: () async => true,
|
|
now: () => now,
|
|
);
|
|
|
|
setUp(() async {
|
|
FlutterSecureStorage.setMockInitialValues({});
|
|
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(),
|
|
}),
|
|
);
|
|
now = DateTime.utc(2026, 11, 3);
|
|
paths = [];
|
|
uploads = [];
|
|
statusCode = 200;
|
|
listed = [];
|
|
current = keys.public;
|
|
uploadCode = 200;
|
|
hpke = _FakeHpke(envelope);
|
|
});
|
|
|
|
List<String> backupPaths() =>
|
|
paths.where((path) => path.contains('nsec-backups')).toList();
|
|
|
|
test(
|
|
'a bound key is backed up once, replaying an uncertain upload exactly',
|
|
() async {
|
|
final backup = backupFor(organizationClient());
|
|
|
|
// The tenant is reachable but the upload's outcome is unknown. Two
|
|
// connections asserting at once share one attempt.
|
|
uploadCode = 503;
|
|
await Future.wait([assert_(backup), assert_(backup)]);
|
|
await pumpEventQueue(times: 200);
|
|
expect(backupPaths(), [
|
|
'/v1/buzz/nsec-backups/status',
|
|
'/v1/buzz/nsec-backups/enrollment',
|
|
'/v1/buzz/nsec-backups',
|
|
]);
|
|
expect(backup.lastFailure, AccountFailure.unavailable);
|
|
expect(await const FlutterSecureStorage().read(key: pending), isNotNull);
|
|
|
|
// The next assertion after the retry delay replays the saved envelope,
|
|
// not a new one.
|
|
uploadCode = 200;
|
|
paths.clear();
|
|
now = now.add(OrganizationKeyBackup.firstRetryDelay);
|
|
await connect(backup);
|
|
expect(backupPaths(), [
|
|
'/v1/buzz/nsec-backups/status',
|
|
'/v1/buzz/nsec-backups',
|
|
]);
|
|
expect(hpke.seals, 1);
|
|
expect(uploads, hasLength(2));
|
|
expect(uploads.last, uploads.first);
|
|
expect(jsonDecode(uploads.last), envelope);
|
|
expect(backup.lastFailure, isNull);
|
|
expect(await const FlutterSecureStorage().read(key: pending), isNull);
|
|
|
|
// Later assertions in this launch send no backup requests.
|
|
paths.clear();
|
|
await connect(backup);
|
|
expect(backupPaths(), isEmpty);
|
|
},
|
|
);
|
|
|
|
test('a listed key needs no upload and drops a leftover envelope', () async {
|
|
await const FlutterSecureStorage().write(key: pending, value: '{}');
|
|
listed = [keys.public];
|
|
final backup = backupFor(organizationClient());
|
|
await connect(backup);
|
|
expect(backupPaths(), ['/v1/buzz/nsec-backups/status']);
|
|
expect(hpke.seals, 0);
|
|
expect(await const FlutterSecureStorage().read(key: pending), isNull);
|
|
});
|
|
|
|
test('a tenant without backups is asked once per launch', () async {
|
|
statusCode = 404;
|
|
final backup = backupFor(organizationClient());
|
|
await connect(backup);
|
|
await connect(backup);
|
|
expect(backupPaths(), ['/v1/buzz/nsec-backups/status']);
|
|
expect(backup.lastFailure, AccountFailure.rejected);
|
|
});
|
|
|
|
test('a device that cannot seal sends no backup requests', () async {
|
|
final backup = OrganizationKeyBackup(
|
|
organizationClient(),
|
|
hpke: hpke,
|
|
supportsSealing: () async => false,
|
|
);
|
|
await connect(backup);
|
|
await connect(backup);
|
|
expect(backupPaths(), isEmpty);
|
|
});
|
|
|
|
test('failures retry after a growing delay and never stop', () async {
|
|
final backup = backupFor(organizationClient());
|
|
|
|
statusCode = 503;
|
|
await connect(backup);
|
|
expect(backup.lastFailure, AccountFailure.unavailable);
|
|
statusCode = 200;
|
|
// A relay refusal re-issues at once; that assertion waits.
|
|
await connect(backup);
|
|
expect(backupPaths(), ['/v1/buzz/nsec-backups/status']);
|
|
now = now.add(OrganizationKeyBackup.firstRetryDelay);
|
|
await connect(backup);
|
|
expect(uploads, hasLength(1));
|
|
expect(backup.lastFailure, isNull);
|
|
|
|
// A key bound to someone else's account is never uploaded. Its retries
|
|
// slow down to the longest delay but continue in a long-running app.
|
|
final other = backupFor(organizationClient());
|
|
current = 'f' * 64;
|
|
paths.clear();
|
|
// Each retry waits exactly its delay: none a second early, one on time.
|
|
await connect(other);
|
|
var delay = OrganizationKeyBackup.firstRetryDelay;
|
|
for (var i = 0; i < 9; i++) {
|
|
now = now.add(delay - const Duration(seconds: 1));
|
|
await connect(other);
|
|
expect(backupPaths(), hasLength(i + 1));
|
|
now = now.add(const Duration(seconds: 1));
|
|
await connect(other);
|
|
expect(backupPaths(), hasLength(i + 2));
|
|
delay = delay * 2 > OrganizationKeyBackup.maxRetryDelay
|
|
? OrganizationKeyBackup.maxRetryDelay
|
|
: delay * 2;
|
|
}
|
|
expect(other.lastFailure, HostedBackupFailure.identityMismatch);
|
|
expect(backupPaths(), List.filled(10, '/v1/buzz/nsec-backups/status'));
|
|
expect(uploads, hasLength(1));
|
|
});
|
|
|
|
test('a native sealing check that fails sends nothing', () async {
|
|
final backup = OrganizationKeyBackup(
|
|
organizationClient(),
|
|
hpke: hpke,
|
|
supportsSealing: () async => throw PlatformException(code: 'failed'),
|
|
);
|
|
await connect(backup);
|
|
expect(backup.lastFailure, HpkeBackupFailure.unavailable);
|
|
expect(backupPaths(), isEmpty);
|
|
});
|
|
}
|