From 61b04f647efdb5ee6dbbfe06a565c948b11d31d6 Mon Sep 17 00:00:00 2001 From: Tom Brow Date: Fri, 20 Nov 2026 10:59:27 -0800 Subject: [PATCH] Keep the install ID when its file fails to read A read error no longer counts as a damaged file, so a passing OS error can't replace a good install ID. Clock-window refusals are matched from the start of the relay's reason, and the attribution tests wait for the relay to receive the event and require the refusal itself. Co-authored-by: studio Signed-off-by: Tom Brow --- .../diagnostics/diagnostic_startup.dart | 12 ++-- .../lib/shared/relay/relay_closed_policy.dart | 27 ++++---- .../diagnostic_install_id_test.dart | 67 +++++++++++++++++++ .../relay/relay_rejection_reporting_test.dart | 4 +- ...relay_session_member_attribution_test.dart | 10 +-- 5 files changed, 96 insertions(+), 24 deletions(-) diff --git a/mobile/lib/shared/diagnostics/diagnostic_startup.dart b/mobile/lib/shared/diagnostics/diagnostic_startup.dart index a91c652b09..b2dacb2456 100644 --- a/mobile/lib/shared/diagnostics/diagnostic_startup.dart +++ b/mobile/lib/shared/diagnostics/diagnostic_startup.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:convert'; import 'dart:io'; import 'package:flutter/foundation.dart'; @@ -60,12 +61,15 @@ Future diagnosticInstallId({ final dir = await (directory ?? _installIdDirectory)(); final file = File('${dir.path}/$_installIdFile'); if (await file.exists()) { + // A failed read goes to the catch below and keeps the file: replacing it + // after a passing error would split this device's reports. + final bytes = await file.readAsBytes(); try { - final saved = (await file.readAsString()).trim(); + final saved = utf8.decode(bytes).trim(); if (saved.isNotEmpty) return saved; - } on FileSystemException { - // Unreadable, for instance not text: a damaged file is replaced below, - // not a reason to send reports without an install ID. + } on FormatException { + // Not text: a damaged file is replaced below, not a reason to send + // reports without an install ID. } } final created = const Uuid().v4(); diff --git a/mobile/lib/shared/relay/relay_closed_policy.dart b/mobile/lib/shared/relay/relay_closed_policy.dart index 7cc500bb63..d4e14bfc48 100644 --- a/mobile/lib/shared/relay/relay_closed_policy.dart +++ b/mobile/lib/shared/relay/relay_closed_policy.dart @@ -55,21 +55,18 @@ class RelayInvalidRequest implements Exception { String toString() => 'RelayInvalidRequest'; } -/// How the relay words a refusal for a timestamp outside its clock window, -/// after `invalid:`. It has one wording per kind of event: ordinary events -/// ("event timestamp too far from server time"), canvas events ("canvas event -/// timestamp too far in the future"), relay-admin, moderation and identity -/// archive commands ("event timestamp out of range: ..."), leave requests -/// ("leave request timestamp out of range (...)") and observer frames -/// ("observer frame timestamp outside ±5 minute freshness window"). Matched on -/// "timestamp" and the phrase after it, so a reason about something else that -/// merely mentions a timestamp ("feedback timestamp is out of range") is still -/// reported. +/// How the relay begins a refusal for a timestamp outside its clock window. +/// It has one wording per kind of event: ordinary events, canvas events, +/// relay-admin, moderation and identity archive commands (followed by the +/// timing details), leave requests (likewise) and observer frames. Matched from +/// the start of the reason, so a reason about something else that mentions a +/// timestamp, or echoes a value that does, is still reported. const _clockWindowRefusals = [ - 'timestamp too far from server time', - 'timestamp too far in the future', - 'timestamp out of range', - 'timestamp outside', + 'invalid: event timestamp too far from server time', + 'invalid: canvas event timestamp too far in the future', + 'invalid: event timestamp out of range', + 'invalid: leave request timestamp out of range', + 'invalid: observer frame timestamp outside', ]; /// Whether [message], a relay `OK` or `CLOSED` reason, says the app sent @@ -92,7 +89,7 @@ bool isInvalidRequestRejection(String message) { 'invalid: only members can add people in this channel', ) && !normalized.startsWith('invalid: cannot remove the last owner') && - !_clockWindowRefusals.any(normalized.contains); + !_clockWindowRefusals.any(normalized.startsWith); } /// Explicit access refusal; cached private history must not mask this error. diff --git a/mobile/test/shared/diagnostics/diagnostic_install_id_test.dart b/mobile/test/shared/diagnostics/diagnostic_install_id_test.dart index b4d7f8811a..6b2798e87e 100644 --- a/mobile/test/shared/diagnostics/diagnostic_install_id_test.dart +++ b/mobile/test/shared/diagnostics/diagnostic_install_id_test.dart @@ -1,4 +1,6 @@ +import 'dart:convert'; import 'dart:io'; +import 'dart:typed_data'; import 'package:buzz/shared/diagnostics/diagnostic_startup.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -25,4 +27,69 @@ void main() { expect(await diagnosticInstallId(directory: () async => directory), id); }); } + + // A read that fails, for instance with no file descriptor free, leaves the + // saved ID for the next launch rather than replacing it. + test('a file that fails to read keeps its install ID', () async { + final directory = await Directory.systemTemp.createTemp('install'); + addTearDown(() => directory.delete(recursive: true)); + const saved = '6c0fb3a6-5b7e-4d58-9a40-1c2e2f0b7d11'; + final file = File('${directory.path}/diagnostics_install_id'); + await file.writeAsString(saved); + + final id = await IOOverrides.runZoned( + () => diagnosticInstallId(directory: () async => directory), + createFile: (_) => _UnreadableFile(file), + ); + + expect(id, isNull); + expect(await file.readAsString(), saved); + }); +} + +/// [file], except that every read fails as the operating system refused it, +/// while writes still succeed. +class _UnreadableFile implements File { + _UnreadableFile(this.file); + + final File file; + + FileSystemException get _failure => + FileSystemException('Cannot open file', path, const OSError('', 24)); + + @override + String get path => file.path; + + @override + Future exists() => file.exists(); + + @override + Future readAsBytes() async => throw _failure; + + @override + Future readAsString({Encoding encoding = utf8}) async => + throw _failure; + + @override + Future writeAsString( + String contents, { + FileMode mode = FileMode.write, + Encoding encoding = utf8, + bool flush = false, + }) => file.writeAsString( + contents, + mode: mode, + encoding: encoding, + flush: flush, + ); + + @override + Future writeAsBytes( + List bytes, { + FileMode mode = FileMode.write, + bool flush = false, + }) => file.writeAsBytes(bytes, mode: mode, flush: flush); + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } diff --git a/mobile/test/shared/relay/relay_rejection_reporting_test.dart b/mobile/test/shared/relay/relay_rejection_reporting_test.dart index a6ccab85f2..dd4420093b 100644 --- a/mobile/test/shared/relay/relay_rejection_reporting_test.dart +++ b/mobile/test/shared/relay/relay_rejection_reporting_test.dart @@ -13,7 +13,7 @@ import '../diagnostics/recording_diagnostics.dart'; // What the relay's refusals do to the error list: only a reason that marks the // request as invalid is reported, apart from the outcomes the app handles -// itself. Every other reason is counted, not reported. Reasons are the relay's +// itself. No other reason is reported. Reasons are the relay's // own wording. void main() { // The relay's reasons for a request it refuses as invalid. @@ -21,6 +21,8 @@ void main() { 'invalid: bad signature', // Mentions a timestamp, but is not about the relay's clock window. 'invalid: feedback timestamp is out of range', + // Echoes a value that mentions the clock window. + 'invalid: unsupported report type: timestamp outside', // Limits. 'invalid: a DM may hold at most 9 people; agents do not count', 'invalid: content exceeds maximum size of 262144 bytes (got 262145)', diff --git a/mobile/test/shared/relay/relay_session_member_attribution_test.dart b/mobile/test/shared/relay/relay_session_member_attribution_test.dart index ca20f82e74..7e7f118ec0 100644 --- a/mobile/test/shared/relay/relay_session_member_attribution_test.dart +++ b/mobile/test/shared/relay/relay_session_member_attribution_test.dart @@ -46,7 +46,7 @@ void main() { final refused = session.publish(_event('event-1')); session.debugHandleMessage(['OK', 'event-1', false, 'invalid: bad']); - await expectLater(refused, throwsA(isA())); + await expectLater(refused, throwsA(isA())); expect(reporter.operations, [ if (reported) DiagnosticOperation.relayRejection, @@ -60,11 +60,13 @@ void main() { test('a refusal that arrives over the socket is ' '${member.reported ? '' : 'not '}reported while reports name ' '${member.label}', () async { + final received = Completer(); final answer = Completer(); final server = await loopbackRelay( onFrame: (socket, frame) async { if (frame.first != 'EVENT') return; final id = (frame[1] as Map)['id']; + received.complete(); await answer.future; socket.add(jsonEncode(['OK', id, false, 'invalid: bad signature'])); }, @@ -109,10 +111,10 @@ void main() { await connected.future; final refused = session.publish(_event('event-1')); - await Future.delayed(const Duration(milliseconds: 50)); + await received.future; reporter.setMember(member.pubkey(keys.public)); answer.complete(); - await expectLater(refused, throwsA(isA())); + await expectLater(refused, throwsA(isA())); expect(reporter.operations, [ if (member.reported) DiagnosticOperation.relayRejection, @@ -142,7 +144,7 @@ void main() { session.debugAttachSocketForTest(_Socket()); final refused = session.publish(_event(id)); session.debugHandleMessage(['OK', id, false, 'invalid: bad']); - await expectLater(refused, throwsA(isA())); + await expectLater(refused, throwsA(isA())); } final config = container.read(relayConfigProvider.notifier);