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>
162 lines
6.0 KiB
Dart
162 lines
6.0 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:buzz/shared/hosted/builderlab_account.dart';
|
|
import 'package:buzz/shared/hosted/hosted_relay_auth.dart';
|
|
import 'package:buzz/shared/relay/relay_provider.dart';
|
|
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
|
import 'package:flutter_test/flutter_test.dart';
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:http/testing.dart';
|
|
import 'package:nostr/nostr.dart' as nostr;
|
|
|
|
void main() {
|
|
TestWidgetsFlutterBinding.ensureInitialized();
|
|
|
|
test(
|
|
'an assertion with no lifetime left is reissued, then reported',
|
|
() async {
|
|
final keys = nostr.Keys('0' * 63 + '1');
|
|
final expiry = DateTime.now().toUtc().add(const Duration(days: 1));
|
|
FlutterSecureStorage.setMockInitialValues({});
|
|
await const FlutterSecureStorage().write(
|
|
key: 'buzz_hosted_session_block_example_com_v1',
|
|
value: jsonEncode({
|
|
'origin': 'https://block.example.com',
|
|
'credential': 'org-secret',
|
|
'subject': 'member',
|
|
'expires_at': expiry.toIso8601String(),
|
|
}),
|
|
);
|
|
// Each 10 s assertion spends 20 s in flight.
|
|
const iat = 1800000000;
|
|
var elapsed = Duration.zero;
|
|
var issued = 0;
|
|
String segment(Object v) =>
|
|
base64Url.encode(utf8.encode(jsonEncode(v))).replaceAll('=', '');
|
|
http.Response json(Object body) => http.Response(jsonEncode(body), 200);
|
|
final account = BuilderlabAccountClient(
|
|
accountOrigin: Uri.parse('https://block.example.com'),
|
|
httpClient: MockClient((request) async {
|
|
if (request.url.path.endsWith('/identity/assertions')) {
|
|
issued++;
|
|
elapsed += const Duration(seconds: 20);
|
|
final claims = {'iat': iat, 'exp': iat + 10};
|
|
return json({
|
|
'assertion': '${segment({})}.${segment(claims)}.c2ln',
|
|
'nostr_pubkey': keys.public,
|
|
'expires_at': iat + 10,
|
|
});
|
|
}
|
|
return request.url.path.endsWith('/nostr-identities/current')
|
|
? json({
|
|
'identity': {'pubkey_hex': keys.public},
|
|
})
|
|
: json({
|
|
'subject': 'member',
|
|
'expires_at': expiry.toIso8601String(),
|
|
});
|
|
}),
|
|
);
|
|
final auth = HostedRelayAuth(
|
|
BuilderlabAccountClient(httpClient: MockClient((_) async => fail(''))),
|
|
organization: account,
|
|
organizationRelay: (_) => true,
|
|
enabled: true,
|
|
now: () => DateTime.fromMillisecondsSinceEpoch((iat - 100) * 1000),
|
|
elapsed: () => elapsed,
|
|
);
|
|
final relay = RelayConfig(
|
|
baseUrl: 'https://buzz.block.example.com',
|
|
nsec: keys.nsec,
|
|
);
|
|
await expectLater(
|
|
auth.headers(relay),
|
|
throwsA(AccountFailure.unavailable),
|
|
);
|
|
expect(issued, 3);
|
|
expect(auth.cachedHeaders(relay), isNull);
|
|
},
|
|
);
|
|
|
|
test(
|
|
'an assertion that expired while the device slept is reissued',
|
|
() async {
|
|
final keys = nostr.Keys('0' * 63 + '1');
|
|
final expiry = DateTime.now().toUtc().add(const Duration(days: 1));
|
|
FlutterSecureStorage.setMockInitialValues({});
|
|
await const FlutterSecureStorage().write(
|
|
key: 'buzz_hosted_session_block_example_com_v1',
|
|
value: jsonEncode({
|
|
'origin': 'https://block.example.com',
|
|
'credential': 'org-secret',
|
|
'subject': 'member',
|
|
'expires_at': expiry.toIso8601String(),
|
|
}),
|
|
);
|
|
// Each assertion lives 300 s from the issuer's wall time; the phone
|
|
// reads that plus [correction].
|
|
var wall = 1800000000;
|
|
var elapsed = Duration.zero;
|
|
var correction = 0;
|
|
var issued = 0;
|
|
String segment(Object v) =>
|
|
base64Url.encode(utf8.encode(jsonEncode(v))).replaceAll('=', '');
|
|
http.Response json(Object body) => http.Response(jsonEncode(body), 200);
|
|
final account = BuilderlabAccountClient(
|
|
accountOrigin: Uri.parse('https://block.example.com'),
|
|
httpClient: MockClient((request) async {
|
|
if (request.url.path.endsWith('/identity/assertions')) {
|
|
issued++;
|
|
final claims = {'iat': wall, 'exp': wall + 300};
|
|
return json({
|
|
'assertion': '${segment({})}.${segment(claims)}.c2ln',
|
|
'nostr_pubkey': keys.public,
|
|
'expires_at': wall + 300,
|
|
});
|
|
}
|
|
return request.url.path.endsWith('/nostr-identities/current')
|
|
? json({
|
|
'identity': {'pubkey_hex': keys.public},
|
|
})
|
|
: json({
|
|
'subject': 'member',
|
|
'expires_at': expiry.toIso8601String(),
|
|
});
|
|
}),
|
|
);
|
|
final auth = HostedRelayAuth(
|
|
BuilderlabAccountClient(httpClient: MockClient((_) async => fail(''))),
|
|
organization: account,
|
|
organizationRelay: (_) => true,
|
|
enabled: true,
|
|
now: () =>
|
|
DateTime.fromMillisecondsSinceEpoch((wall + correction) * 1000),
|
|
elapsed: () => elapsed,
|
|
);
|
|
final relay = RelayConfig(
|
|
baseUrl: 'https://buzz.block.example.com',
|
|
nsec: keys.nsec,
|
|
);
|
|
final first = await auth.headers(relay);
|
|
expect(issued, 1);
|
|
expect(auth.cachedHeaders(relay), first);
|
|
// Sleep: the wall clock moves on while the monotonic clock does not.
|
|
wall += 600;
|
|
elapsed += const Duration(seconds: 1);
|
|
expect(auth.cachedHeaders(relay), isNull);
|
|
await auth.headers(relay);
|
|
expect(issued, 2);
|
|
// 200 s later, the phone's clock is corrected 120 s forward. The token
|
|
// has 100 s of server lifetime left, but the wall bound now retires it:
|
|
// one re-mint, never a refusal.
|
|
wall += 200;
|
|
elapsed += const Duration(seconds: 200);
|
|
correction = 120;
|
|
expect(auth.cachedHeaders(relay), isNull);
|
|
final reminted = await auth.headers(relay);
|
|
expect(issued, 3);
|
|
expect(auth.cachedHeaders(relay), reminted);
|
|
},
|
|
);
|
|
}
|