Skip to content

Commit 1b9b307

Browse files
browsquare-tombstudioclaude
authored
fix(mobile): renew expired assertions for native media and drop retired-session avatars (#9134)
Follow-up to [#9069 media auth](#9069), which merged at its approved head. This PR carries the fixes for the last review round on that PR. ### Changes - **Native media reads renew an expired assertion** (Carl's [recommended blocker](#9069 (comment))). Voice notes and posterless video previews hand headers to native code. They now use `freshNativeMediaHeadersProvider`, which awaits `HostedRelayAuth.headersForUrl` and so asks for a new assertion once the cached one has expired. Before, while the socket stayed up they sent none and the relay refused the read. If the renewal fails, the read falls back to cached headers and the relay decides. The voice-note player's `headers` callback is now `FutureOr`. Both the iOS authenticated download and the Android native load await it, then recheck their generation, so a cancel during a slow renewal never starts the stale load. - **Notification avatars drop a retired organization session** ([review thread](#9069 (comment))). When an avatar download finishes after the organization session that issued its assertion was replaced, BuzzPushKit removes the cached response and refuses the avatar. - **Test:** cached reads never present a signed-out or replaced account's assertion ([optional note](#9069 (comment))). Not changed: native reaction-detail avatars still use the cached assertion. After it expires they fall back to initials. ### Validation - Each new test was checked to fail with the code it guards reverted: - `replacedOrganizationSessionRefusesAvatar` (BuzzPushKit): a session replaced mid-download must be refused. - `fresh native media headers renew an expired assertion`: covers renewal and the fallback when renewal fails. - `remote voice notes renew an expired relay assertion`: a journey through `VoiceNoteAttachment`; it fails when the attachment is switched back to the synchronous provider. - `Android defers remote auth until playback starts`: now cancels during a slow renewal and expects no native load. - `an issued assertion serves cached reads for the relay`: now signs out and restores a replacement account. It fails without the account check. - `swift test` (69 tests) passes. The full mobile suite (`just mobile-install mobile-check mobile-test`) passes with these commits on main as of [#9069 media auth](#9069). - The automated full-app simulator run from [#9069 media auth](#9069) covers the surrounding flows. This change is limited to the header source for voice notes and video previews, and none of the test communities enforce the hosted assertion, so a simulator run would not show the difference. No end-to-end run against a relay that enforces the assertion. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Tom Brow <[email protected]> Co-authored-by: Tom Brow <[email protected]> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 74abe2f commit 1b9b307

11 files changed

Lines changed: 296 additions & 21 deletions

File tree

‎mobile/ios/BuzzPushKit/Sources/BuzzPushKit/BuzzNotificationAvatarLoader.swift‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,19 +107,28 @@ public final class BuzzNotificationAvatarLoader {
107107
if let assertion {
108108
request.setValue(assertion.header, forHTTPHeaderField: "Nostr-Federated-Identity")
109109
}
110-
self.download(request, scope: scope, completion: completion)
110+
self.download(request, scope: scope, assertion: assertion, completion: completion)
111111
}
112112
}
113113

114+
/// Bytes fetched with `assertion` are accepted only while the organization session that
115+
/// issued it is still the shared one, so a retired session's avatar never reaches the cache.
114116
private func download(
115117
_ request: URLRequest, scope: BuzzNotificationCacheScope,
118+
assertion: BuzzRelayAssertion? = nil,
116119
completion: @escaping (Result<Data, Error>) -> Void
117120
) {
118121
let configuration = URLSessionConfiguration.default
119122
configuration.httpCookieStorage = nil
120123
configuration.urlCredentialStorage = nil
121-
configuration.urlCache = httpCache(scope)
124+
let cache = httpCache(scope)
125+
configuration.urlCache = cache
122126
startDownload(request, configuration, Self.maximumDownloadBytes) { result in
127+
if let assertion, self.assertionIssuer?.isCurrent(assertion) != true {
128+
cache.removeCachedResponse(for: request)
129+
completion(.failure(BuzzNotificationCacheError.revoked))
130+
return
131+
}
123132
guard self.isCurrent(scope) else {
124133
completion(.failure(BuzzNotificationCacheError.revoked))
125134
return

‎mobile/ios/BuzzPushKit/Tests/BuzzPushKitTests/BuzzNotificationAvatarLoaderTests.swift‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,50 @@ struct BuzzNotificationAvatarLoaderTests {
161161
== "Bearer header.payload.signature")
162162
#expect(request.value(forHTTPHeaderField: "Authorization") != nil)
163163
}
164+
165+
@Test("An avatar fetched with an assertion from a replaced organization session is refused")
166+
func replacedOrganizationSessionRefusesAvatar() async throws {
167+
let key = String(repeating: "0", count: 63) + "1"
168+
let account = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
169+
let scope = try #require(
170+
BuzzNotificationCacheScope(
171+
community: PushLeaseCommunity(
172+
id: "community", name: "Test", relayUrl: "wss://relay.org.example", pubkey: account,
173+
policies: [], notificationSessionID: "session")))
174+
let configuration = URLSessionConfiguration.ephemeral
175+
configuration.protocolClasses = [AssertionIssuanceStub.self]
176+
let sessions = OrganizationSessions()
177+
let issuer = BuzzRelayAssertionIssuer(
178+
session: URLSession(configuration: configuration), loadSession: { sessions.current })
179+
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(
180+
UUID().uuidString)
181+
defer { try? FileManager.default.removeItem(at: directory) }
182+
let loader = BuzzNotificationAvatarLoader(
183+
directory: directory, privateKey: { _ in key }, isCurrent: { _ in true },
184+
assertionIssuer: issuer)
185+
let png = try #require(
186+
Data(
187+
base64Encoded:
188+
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aX1sAAAAASUVORK5CYII="
189+
))
190+
loader.startDownload = { _, _, _, completion in
191+
// The member signs in again while the avatar is in flight; the community is unchanged.
192+
sessions.replace()
193+
completion(.success(png))
194+
}
195+
196+
let result = await withCheckedContinuation { continuation in
197+
loader.load(
198+
source: "https://relay.org.example/media/\(String(repeating: "a", count: 64)).png",
199+
scope: scope
200+
) { continuation.resume(returning: $0) }
201+
}
202+
203+
guard case .failure(BuzzNotificationCacheError.revoked) = result else {
204+
Issue.record("Expected a revoked failure, got \(result)")
205+
return
206+
}
207+
}
164208
}
165209

166210
private final class AvatarRequests: @unchecked Sendable {
@@ -171,6 +215,20 @@ private final class AvatarRequests: @unchecked Sendable {
171215
func record(_ request: URLRequest) { lock.withLock { requests.append(request) } }
172216
}
173217

218+
private final class OrganizationSessions: @unchecked Sendable {
219+
private let lock = NSLock()
220+
private var credential = "session-credential"
221+
222+
var current: BuzzOrganizationSession {
223+
lock.withLock {
224+
BuzzOrganizationSession(
225+
origin: "https://identity.org.example", credential: credential,
226+
relayHosts: ["relay.org.example"])
227+
}
228+
}
229+
func replace() { lock.withLock { credential = "replacement-credential" } }
230+
}
231+
174232
private final class AvatarScopeState: @unchecked Sendable {
175233
private let lock = NSLock()
176234
private var current = true

‎mobile/lib/features/channels/message_content/video_preview.dart‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,9 @@ final videoPreviewFrameLoaderProvider = Provider<VideoPreviewFrameLoader>((
3030
ref,
3131
) {
3232
// The native player fetches the URL itself, outside the hosted HTTP client.
33-
final headersFor = ref.watch(nativeMediaHeadersProvider);
34-
return (url) => _loadVideoPreviewFrame(url, headers: headersFor(url));
33+
final headersFor = ref.watch(freshNativeMediaHeadersProvider);
34+
return (url) async =>
35+
_loadVideoPreviewFrame(url, headers: await headersFor(url));
3536
});
3637

3738
class _MessageVideoPreview extends HookConsumerWidget {

‎mobile/lib/features/channels/voice_note_attachment.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ class VoiceNoteAttachment extends HookConsumerWidget {
5454
unawaited(
5555
player.loadRemote(
5656
source,
57-
headers: () => ref.read(nativeMediaHeadersProvider)(source),
57+
headers: () => ref.read(freshNativeMediaHeadersProvider)(source),
5858
fallbackDuration: duration,
5959
),
6060
);

‎mobile/lib/features/channels/voice_note_recording.dart‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,7 @@ abstract class VoiceNotePlayerController extends ChangeNotifier {
333333

334334
Future<void> loadRemote(
335335
String url, {
336-
required Map<String, String> Function() headers,
336+
required FutureOr<Map<String, String>> Function() headers,
337337
required Duration fallbackDuration,
338338
});
339339

@@ -525,7 +525,7 @@ class DeviceVoiceNotePlayerController extends VoiceNotePlayerController {
525525
VoiceNotePlaybackState _state = const VoiceNotePlaybackState();
526526
({
527527
String url,
528-
Map<String, String> Function() headers,
528+
FutureOr<Map<String, String>> Function() headers,
529529
Duration fallbackDuration,
530530
})?
531531
_pendingRemote;
@@ -561,7 +561,7 @@ class DeviceVoiceNotePlayerController extends VoiceNotePlayerController {
561561
@override
562562
Future<void> loadRemote(
563563
String url, {
564-
required Map<String, String> Function() headers,
564+
required FutureOr<Map<String, String>> Function() headers,
565565
required Duration fallbackDuration,
566566
}) {
567567
_replaceSource();
@@ -601,6 +601,9 @@ class DeviceVoiceNotePlayerController extends VoiceNotePlayerController {
601601
_downloadAbort = requestAbort;
602602
File? file;
603603
try {
604+
// Awaited first: a hosted relay may need a fresh assertion, and a newer
605+
// operation started meanwhile must win.
606+
final headers = await remote.headers();
604607
if (playbackOperationGeneration != _playbackOperationGeneration) {
605608
if (!requestAbort.isCompleted) requestAbort.complete();
606609
return null;
@@ -609,7 +612,7 @@ class DeviceVoiceNotePlayerController extends VoiceNotePlayerController {
609612
'GET',
610613
uri,
611614
abortTrigger: requestAbort.future,
612-
)..headers.addAll(remote.headers());
615+
)..headers.addAll(headers);
613616
final response = await _client
614617
.send(request)
615618
.timeout(
@@ -839,7 +842,17 @@ class DeviceVoiceNotePlayerController extends VoiceNotePlayerController {
839842
}
840843
} else {
841844
await _load(
842-
() => _player.setUrl(remote.url, headers: remote.headers()),
845+
() async {
846+
final headers = await remote.headers();
847+
// A cancel or new source while a slow assertion renews must
848+
// not start the stale native load.
849+
if (_disposed ||
850+
sourceGeneration != _sourceGeneration ||
851+
playbackOperationGeneration != _playbackOperationGeneration) {
852+
return null;
853+
}
854+
return _player.setUrl(remote.url, headers: headers);
855+
},
843856
fallbackDuration: remote.fallbackDuration,
844857
sourceGeneration: sourceGeneration,
845858
playbackOperationGeneration: playbackOperationGeneration,

‎mobile/lib/shared/hosted/native_media_headers.dart‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import 'package:flutter/foundation.dart';
12
import 'package:hooks_riverpod/hooks_riverpod.dart';
23

34
import '../relay/relay.dart';
@@ -24,3 +25,29 @@ final nativeMediaHeadersProvider =
2425
};
2526
};
2627
});
28+
29+
/// [nativeMediaHeadersProvider] for a caller that can wait, such as a player
30+
/// about to fetch. It asks for a fresh assertion when the cached one has
31+
/// expired, which the synchronous form cannot do while the socket stays up.
32+
/// If the assertion fails, the read goes out with whatever is cached and the
33+
/// relay decides.
34+
final freshNativeMediaHeadersProvider =
35+
Provider<Future<Map<String, String>> Function(String)>((ref) {
36+
final media = ref.watch(mediaGetAuthServiceProvider);
37+
final hosted = ref.watch(hostedRelayAuthProvider);
38+
final config = ref.watch(relayConfigProvider);
39+
return (url) async {
40+
final uri = Uri.tryParse(url);
41+
var assertion = const <String, String>{};
42+
if (uri != null) {
43+
try {
44+
assertion = await hosted.headersForUrl(config, uri);
45+
} on Object catch (error) {
46+
debugPrint('Native media assertion failed: $error');
47+
assertion = hosted.cachedHeadersForUrl(config, uri);
48+
}
49+
}
50+
// Minted after the wait, so a slow refresh cannot age the media proof.
51+
return {...media.headersFor(url), ...assertion};
52+
};
53+
});

‎mobile/test/features/channels/compose_bar_test.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -551,7 +551,7 @@ class _FakeVoiceNotePlayer extends VoiceNotePlayerController {
551551
@override
552552
Future<void> loadRemote(
553553
String url, {
554-
required Map<String, String> Function() headers,
554+
required FutureOr<Map<String, String>> Function() headers,
555555
required Duration fallbackDuration,
556556
}) => loadLocal(url, fallbackDuration: fallbackDuration);
557557

‎mobile/test/features/channels/message_content_test.dart‎

Lines changed: 86 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ import 'package:buzz/features/channels/voice_note_recording.dart';
3232
import 'package:buzz/shared/deeplink/deep_link.dart';
3333
import 'package:buzz/shared/deeplink/pending_deep_link_provider.dart';
3434
import 'package:buzz/shared/emoji/emoji_only.dart';
35+
import 'package:buzz/shared/hosted/builderlab_account.dart';
36+
import 'package:buzz/shared/hosted/hosted_relay_auth.dart';
3537
import 'package:buzz/shared/relay/relay.dart';
3638
import 'package:buzz/shared/theme/theme.dart';
3739
import 'package:buzz/shared/widgets/buzz_loading_indicator.dart';
@@ -97,7 +99,7 @@ class _FakeVoiceNotePlayer extends VoiceNotePlayerController {
9799
@override
98100
Future<void> loadRemote(
99101
String url, {
100-
required Map<String, String> Function() headers,
102+
required FutureOr<Map<String, String>> Function() headers,
101103
required Duration fallbackDuration,
102104
}) => loadLocal(url, fallbackDuration: fallbackDuration);
103105

@@ -123,6 +125,48 @@ class _FakeVoiceNotePlayer extends VoiceNotePlayerController {
123125
}
124126
}
125127

128+
class _HeadersVoiceNotePlayer extends _FakeVoiceNotePlayer {
129+
FutureOr<Map<String, String>> Function()? headers;
130+
131+
@override
132+
Future<void> loadRemote(
133+
String url, {
134+
required FutureOr<Map<String, String>> Function() headers,
135+
required Duration fallbackDuration,
136+
}) {
137+
this.headers = headers;
138+
return super.loadRemote(
139+
url,
140+
headers: headers,
141+
fallbackDuration: fallbackDuration,
142+
);
143+
}
144+
}
145+
146+
class _FixedRelayConfig extends RelayConfigNotifier {
147+
_FixedRelayConfig(this.config);
148+
149+
final RelayConfig config;
150+
151+
@override
152+
RelayConfig build() => config;
153+
}
154+
155+
/// A hosted relay whose cached assertion has expired, so only a fresh
156+
/// request carries one.
157+
class _ExpiredHostedRelayAuth extends HostedRelayAuth {
158+
_ExpiredHostedRelayAuth() : super(BuilderlabAccountClient(), enabled: false);
159+
160+
@override
161+
Map<String, String>? cachedHeaders(RelayConfig config) => null;
162+
163+
@override
164+
Future<Map<String, String>> headersForUrl(
165+
RelayConfig config,
166+
Uri url,
167+
) async => {'Nostr-Federated-Identity': 'Bearer fresh-token'};
168+
}
169+
126170
class _LoadingVoiceNotePlayer extends _FakeVoiceNotePlayer {
127171
@override
128172
VoiceNotePlaybackState get state =>
@@ -131,7 +175,7 @@ class _LoadingVoiceNotePlayer extends _FakeVoiceNotePlayer {
131175
@override
132176
Future<void> loadRemote(
133177
String url, {
134-
required Map<String, String> Function() headers,
178+
required FutureOr<Map<String, String>> Function() headers,
135179
required Duration fallbackDuration,
136180
}) async {}
137181
}
@@ -173,7 +217,7 @@ class _BufferingVoiceNotePlayer extends _FakeVoiceNotePlayer {
173217
@override
174218
Future<void> loadRemote(
175219
String url, {
176-
required Map<String, String> Function() headers,
220+
required FutureOr<Map<String, String>> Function() headers,
177221
required Duration fallbackDuration,
178222
}) async {}
179223

@@ -244,7 +288,7 @@ class _RetryableVoiceNotePlayer extends _FakeVoiceNotePlayer {
244288
@override
245289
Future<void> loadRemote(
246290
String url, {
247-
required Map<String, String> Function() headers,
291+
required FutureOr<Map<String, String>> Function() headers,
248292
required Duration fallbackDuration,
249293
}) async {}
250294

@@ -1399,6 +1443,44 @@ void main() {
13991443
},
14001444
);
14011445

1446+
testWidgets('remote voice notes renew an expired relay assertion', (
1447+
tester,
1448+
) async {
1449+
final player = _HeadersVoiceNotePlayer();
1450+
final hosted = _ExpiredHostedRelayAuth();
1451+
addTearDown(hosted.dispose);
1452+
final nsec = nostr.Keys.generate().nsec;
1453+
await tester.pumpWidget(
1454+
_testable(
1455+
const VoiceNoteAttachment.remote(
1456+
url: 'https://relay.example/media/voice.m4a',
1457+
duration: Duration(seconds: 3),
1458+
waveform: [],
1459+
),
1460+
overrides: [
1461+
voiceNotePlayerFactoryProvider.overrideWithValue(() => player),
1462+
relayConfigProvider.overrideWith(
1463+
() => _FixedRelayConfig(
1464+
RelayConfig(baseUrl: 'https://relay.example', nsec: nsec),
1465+
),
1466+
),
1467+
mediaGetAuthServiceProvider.overrideWithValue(
1468+
MediaGetAuthService(
1469+
baseUrl: 'https://relay.example',
1470+
nsec: nsec,
1471+
),
1472+
),
1473+
hostedRelayAuthProvider.overrideWithValue(hosted),
1474+
],
1475+
),
1476+
);
1477+
await tester.pump();
1478+
1479+
final headers = await player.headers!();
1480+
expect(headers['Authorization'], startsWith('Nostr '));
1481+
expect(headers['Nostr-Federated-Identity'], 'Bearer fresh-token');
1482+
});
1483+
14021484
testWidgets('routes repeated loading-control taps through toggle', (
14031485
tester,
14041486
) async {

0 commit comments

Comments
 (0)