jacquard 0.12.1

Simple and powerful AT Protocol client library for Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
#![cfg(all(test, feature = "scope-check"))]

use std::collections::VecDeque;
use std::sync::Arc;

use bytes::Bytes;
use http::{Response as HttpResponse, StatusCode};
use jacquard::client::Agent;
use jacquard::deps::fluent_uri::Uri;
use jacquard::types::did::Did;
use jacquard::types::string::{DidService, Nsid};
use jacquard::xrpc::XrpcClient;
use jacquard::{BosStr, IntoStatic};
use jacquard_common::http_client::HttpClient;
use jacquard_oauth::atproto::AtprotoClientMetadata;
use jacquard_oauth::client::OAuthSession;
use jacquard_oauth::resolver::OAuthResolver;
use jacquard_oauth::scopes::{
    RepoAction, RepoCollection, RepoScope, RpcAudience, RpcLexicon, RpcScope, Scope, Scopes,
};
use jacquard_oauth::session::SessionRegistry;
use jacquard_oauth::session::{ClientData, ClientSessionData, DpopClientData};
use jacquard_oauth::types::{OAuthAuthorizationServerMetadata, OAuthTokenType, TokenSet};
use smol_str::{SmolStr, format_smolstr};
use std::collections::BTreeSet;
use tokio::sync::Mutex;

#[derive(Clone, Default)]
struct MockClient {
    queue: Arc<Mutex<VecDeque<http::Response<Vec<u8>>>>>,
    log: Arc<Mutex<Vec<http::Request<Vec<u8>>>>>,
}

impl MockClient {
    async fn push(&self, resp: http::Response<Vec<u8>>) {
        self.queue.lock().await.push_back(resp);
    }
}

impl HttpClient for MockClient {
    type Error = std::convert::Infallible;
    fn send_http(
        &self,
        request: http::Request<Vec<u8>>,
    ) -> impl core::future::Future<
        Output = core::result::Result<http::Response<Vec<u8>>, Self::Error>,
    > + Send {
        let log = self.log.clone();
        let queue = self.queue.clone();
        async move {
            log.lock().await.push(request);
            Ok(queue.lock().await.pop_front().expect("no queued response"))
        }
    }
}

impl jacquard::identity::resolver::IdentityResolver for MockClient {
    fn options(&self) -> &jacquard::identity::resolver::ResolverOptions {
        use std::sync::LazyLock;
        static OPTS: LazyLock<jacquard::identity::resolver::ResolverOptions> =
            LazyLock::new(jacquard::identity::resolver::ResolverOptions::default);
        &OPTS
    }
    async fn resolve_handle<S: BosStr>(
        &self,
        _handle: &jacquard::types::string::Handle<S>,
    ) -> std::result::Result<Did, jacquard::identity::resolver::IdentityError> {
        Ok(Did::new_static("did:plc:alice").unwrap())
    }
    async fn resolve_did_doc<S: BosStr>(
        &self,
        _did: &Did<S>,
    ) -> std::result::Result<
        jacquard::identity::resolver::DidDocResponse,
        jacquard::identity::resolver::IdentityError,
    > {
        let doc = serde_json::json!({
            "@context": ["https://www.w3.org/ns/did/v1"],
            "id": "did:plc:alice",
            "alsoKnownAs": ["at://alice.bsky.social"],
            "service": [{
                "id": "#atproto_pds",
                "type": "AtprotoPersonalDataServer",
                "serviceEndpoint": "https://pds.example.com"
            }]
        });
        Ok(jacquard::identity::resolver::DidDocResponse {
            buffer: Bytes::from(serde_json::to_vec(&doc).unwrap()),
            status: StatusCode::OK,
            requested: None,
        })
    }
}

impl OAuthResolver for MockClient {
    async fn get_authorization_server_metadata(
        &self,
        issuer: &str,
    ) -> Result<OAuthAuthorizationServerMetadata, jacquard_oauth::resolver::ResolverError> {
        let mut md = OAuthAuthorizationServerMetadata::default();
        md.issuer = SmolStr::from(issuer);
        md.token_endpoint = format_smolstr!("{}/token", issuer);
        md.authorization_endpoint = format_smolstr!("{}/authorize", issuer);
        md.require_pushed_authorization_requests = Some(true);
        md.pushed_authorization_request_endpoint = Some(format_smolstr!("{}/par", issuer));
        md.token_endpoint_auth_methods_supported = Some(vec![SmolStr::from("none")]);
        md.dpop_signing_alg_values_supported = Some(vec![SmolStr::from("ES256")]);
        Ok(md)
    }

    async fn get_resource_server_metadata(
        &self,
        _pds: &str,
    ) -> Result<OAuthAuthorizationServerMetadata, jacquard_oauth::resolver::ResolverError> {
        let mut md = OAuthAuthorizationServerMetadata::default();
        md.issuer = SmolStr::from("https://issuer");
        md.token_endpoint = SmolStr::from("https://issuer/token");
        md.authorization_endpoint = SmolStr::from("https://issuer/authorize");
        md.require_pushed_authorization_requests = Some(true);
        md.pushed_authorization_request_endpoint = Some(SmolStr::from("https://issuer/par"));
        md.token_endpoint_auth_methods_supported = Some(vec![SmolStr::from("none")]);
        md.dpop_signing_alg_values_supported = Some(vec![SmolStr::from("ES256")]);
        Ok(md)
    }

    async fn verify_issuer<S: BosStr + Sync>(
        &self,
        _server_metadata: &OAuthAuthorizationServerMetadata,
        _sub: &Did<S>,
    ) -> Result<jacquard::deps::fluent_uri::Uri<String>, jacquard_oauth::resolver::ResolverError>
    {
        Ok(
            jacquard::deps::fluent_uri::Uri::parse("https://pds.example.com")
                .unwrap()
                .to_owned(),
        )
    }
}

impl jacquard_oauth::dpop::DpopExt for MockClient {}

fn get_session_ok() -> http::Response<Vec<u8>> {
    HttpResponse::builder()
        .status(StatusCode::OK)
        .header(http::header::CONTENT_TYPE, "application/json")
        .body(
            serde_json::to_vec(&serde_json::json!({
                "did":"did:plc:alice",
                "handle":"alice.bsky.social",
                "active":true
            }))
            .unwrap(),
        )
        .unwrap()
}

fn create_session_data(resolved_scopes: Option<Vec<Scope<SmolStr>>>) -> ClientSessionData {
    ClientSessionData {
        account_did: Did::new_static("did:plc:alice").unwrap(),
        session_id: SmolStr::from("state"),
        host_url: Uri::parse("https://pds.example.com")
            .expect("valid uri")
            .to_owned(),
        authserver_url: SmolStr::new_static("https://issuer"),
        authserver_token_endpoint: SmolStr::from("https://issuer/token"),
        authserver_revocation_endpoint: None,
        scopes: Scopes::new(SmolStr::new_static("atproto")).unwrap(),
        dpop_data: DpopClientData {
            dpop_key: jacquard_oauth::utils::generate_key(&[SmolStr::from("ES256")]).unwrap(),
            dpop_authserver_nonce: SmolStr::from(""),
            dpop_host_nonce: SmolStr::from(""),
        },
        token_set: TokenSet {
            iss: SmolStr::from("https://issuer"),
            sub: Did::new_static("did:plc:alice").unwrap(),
            aud: SmolStr::from("https://pds.example.com"),
            scope: None,
            refresh_token: Some(SmolStr::from("rt1")),
            access_token: SmolStr::from("atk1"),
            token_type: OAuthTokenType::DPoP,
            expires_at: None,
        },
        resolved_scopes,
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn test_scope_check_permits_matching_rpc() {
    let client = Arc::new(MockClient::default());

    // Queue a successful response for getSession
    client.push(get_session_ok()).await;

    let mut path = std::env::temp_dir();
    path.push(format!(
        "jacquard-scope-test-matching-{}.json",
        std::process::id()
    ));
    std::fs::write(&path, "{}").unwrap();
    let store = jacquard::client::FileAuthStore::new(&path);

    let client_data = ClientData {
        keyset: None,
        config: AtprotoClientMetadata::new_localhost(
            None,
            Some(Scopes::new(SmolStr::new_static("atproto")).unwrap()),
        ),
    };

    // Create resolved_scopes with rpc:com.atproto.server.getSession
    let mut rpc_lexicon = BTreeSet::new();
    rpc_lexicon.insert(RpcLexicon::Nsid(
        Nsid::<SmolStr>::new_static("com.atproto.server.getSession").unwrap(),
    ));
    let mut aud = BTreeSet::new();
    aud.insert(RpcAudience::All);
    let resolved_scopes = Some(vec![Scope::Rpc(RpcScope {
        lxm: rpc_lexicon,
        aud,
    })]);

    let session_data = create_session_data(resolved_scopes).into_static();
    let client_arc = client.clone();
    let registry = Arc::new(SessionRegistry::new(store, client_arc.clone(), client_data));
    registry.set(session_data.clone()).await.unwrap();
    let session = OAuthSession::new(registry, client_arc, session_data);

    let agent: Agent<_> = Agent::from(session);
    let resp = agent
        .send(jacquard::api::com_atproto::server::get_session::GetSession)
        .await
        .expect("xrpc send should succeed with matching scope");
    assert_eq!(resp.status(), StatusCode::OK);

    // Verify HTTP request was made
    let log = client.log.lock().await;
    assert_eq!(log.len(), 1, "expected 1 HTTP call");

    let _ = std::fs::remove_file(&path);
}

#[tokio::test(flavor = "multi_thread")]
async fn test_scope_check_denies_ungranted() {
    let client = Arc::new(MockClient::default());

    let mut path = std::env::temp_dir();
    path.push(format!(
        "jacquard-scope-test-deny-{}.json",
        std::process::id()
    ));
    std::fs::write(&path, "{}").unwrap();
    let store = jacquard::client::FileAuthStore::new(&path);

    let client_data = ClientData {
        keyset: None,
        config: AtprotoClientMetadata::new_localhost(
            None,
            Some(Scopes::new(SmolStr::new_static("atproto")).unwrap()),
        ),
    };

    // Create resolved_scopes with a different rpc scope
    let mut rpc_lexicon = BTreeSet::new();
    rpc_lexicon.insert(RpcLexicon::Nsid(
        Nsid::<SmolStr>::new_static("com.example.other").unwrap(),
    ));
    let mut aud = BTreeSet::new();
    aud.insert(RpcAudience::All);
    let resolved_scopes = Some(vec![Scope::Rpc(RpcScope {
        lxm: rpc_lexicon,
        aud,
    })]);

    let session_data = create_session_data(resolved_scopes).into_static();
    let client_arc = client.clone();
    let registry = Arc::new(SessionRegistry::new(store, client_arc.clone(), client_data));
    registry.set(session_data.clone()).await.unwrap();
    let session = OAuthSession::new(registry, client_arc, session_data);

    let agent: Agent<_> = Agent::from(session);
    let resp = agent
        .send(jacquard::api::com_atproto::server::get_session::GetSession)
        .await;

    // Should error because scope doesn't grant access.
    let err = match resp {
        Err(e) => e,
        Ok(_) => panic!("xrpc send should fail without matching scope"),
    };
    let err_msg = format!("{}", err);

    // Verify the error contains the denied NSID so the developer knows what failed.
    assert!(
        err_msg.contains("com.atproto.server.getSession"),
        "error should mention the denied NSID, got: {err_msg}"
    );

    // Verify the error contains the granted scopes so the developer can diagnose.
    assert!(
        err_msg.contains("com.example.other"),
        "error should mention the granted scopes for diagnostics, got: {err_msg}"
    );

    // Verify NO HTTP request was made (proof that AC7.3 works — scope check
    // short-circuits before the HTTP layer).
    let log = client.log.lock().await;
    assert_eq!(
        log.len(),
        0,
        "no HTTP request should be made when scope check fails"
    );

    let _ = std::fs::remove_file(&path);
}

#[tokio::test(flavor = "multi_thread")]
async fn test_scope_check_no_resolved_scopes_permits() {
    let client = Arc::new(MockClient::default());

    // Queue a successful response for getSession
    client.push(get_session_ok()).await;

    let mut path = std::env::temp_dir();
    path.push(format!(
        "jacquard-scope-test-none-{}.json",
        std::process::id()
    ));
    std::fs::write(&path, "{}").unwrap();
    let store = jacquard::client::FileAuthStore::new(&path);

    let client_data = ClientData {
        keyset: None,
        config: AtprotoClientMetadata::new_localhost(
            None,
            Some(Scopes::new(SmolStr::new_static("atproto")).unwrap()),
        ),
    };

    // Create session with None resolved_scopes (no resolution was done)
    let session_data = create_session_data(None).into_static();
    let client_arc = client.clone();
    let registry = Arc::new(SessionRegistry::new(store, client_arc.clone(), client_data));
    registry.set(session_data.clone()).await.unwrap();
    let session = OAuthSession::new(registry, client_arc, session_data);

    let agent: Agent<_> = Agent::from(session);
    let resp = agent
        .send(jacquard::api::com_atproto::server::get_session::GetSession)
        .await
        .expect("xrpc send should succeed when resolved_scopes is None");
    assert_eq!(resp.status(), StatusCode::OK);

    // Verify HTTP request was made
    let log = client.log.lock().await;
    assert_eq!(log.len(), 1, "expected 1 HTTP call");

    let _ = std::fs::remove_file(&path);
}

#[tokio::test(flavor = "multi_thread")]
async fn test_scope_check_wildcard_rpc_permits() {
    let client = Arc::new(MockClient::default());

    // Queue a successful response for getSession
    client.push(get_session_ok()).await;

    let mut path = std::env::temp_dir();
    path.push(format!(
        "jacquard-scope-test-wildcard-{}.json",
        std::process::id()
    ));
    std::fs::write(&path, "{}").unwrap();
    let store = jacquard::client::FileAuthStore::new(&path);

    let client_data = ClientData {
        keyset: None,
        config: AtprotoClientMetadata::new_localhost(
            None,
            Some(Scopes::new(SmolStr::new_static("atproto")).unwrap()),
        ),
    };

    // Create resolved_scopes with wildcard rpc scope
    let mut rpc_lexicon = BTreeSet::new();
    rpc_lexicon.insert(RpcLexicon::All);
    let mut aud = BTreeSet::new();
    aud.insert(RpcAudience::All);
    let resolved_scopes = Some(vec![Scope::Rpc(RpcScope {
        lxm: rpc_lexicon,
        aud,
    })]);

    let session_data = create_session_data(resolved_scopes).into_static();
    let client_arc = client.clone();
    let registry = Arc::new(SessionRegistry::new(store, client_arc.clone(), client_data));
    registry.set(session_data.clone()).await.unwrap();
    let session = OAuthSession::new(registry, client_arc, session_data);

    let agent: Agent<_> = Agent::from(session);
    let resp = agent
        .send(jacquard::api::com_atproto::server::get_session::GetSession)
        .await
        .expect("xrpc send should succeed with wildcard scope");
    assert_eq!(resp.status(), StatusCode::OK);

    // Verify HTTP request was made
    let log = client.log.lock().await;
    assert_eq!(log.len(), 1, "expected 1 HTTP call");

    let _ = std::fs::remove_file(&path);
}

/// Build the resolved scope set that would result from expanding
/// `include:app.bsky.authCreatePosts` — real permission set from
/// the AT Protocol spec.
///
/// Grants:
/// - rpc: app.bsky.video.{uploadVideo,getJobStatus,getUploadLimits}
/// - repo: app.bsky.feed.{post,postgate,threadgate} (create only)
fn resolved_scopes_auth_create_posts() -> Vec<Scope<SmolStr>> {
    let video_rpcs = [
        "app.bsky.video.uploadVideo",
        "app.bsky.video.getJobStatus",
        "app.bsky.video.getUploadLimits",
    ];
    let collections = [
        "app.bsky.feed.post",
        "app.bsky.feed.postgate",
        "app.bsky.feed.threadgate",
    ];

    let mut scopes = Vec::new();

    // RPC scopes for video endpoints.
    let mut lxm = BTreeSet::new();
    for nsid in &video_rpcs {
        lxm.insert(RpcLexicon::Nsid(Nsid::<SmolStr>::new_static(nsid).unwrap()));
    }
    let mut aud = BTreeSet::new();
    aud.insert(RpcAudience::All);
    scopes.push(Scope::Rpc(RpcScope { lxm, aud }));

    // Repo scopes for post creation (create-only).
    for col in &collections {
        let mut actions = BTreeSet::new();
        actions.insert(RepoAction::Create);
        scopes.push(Scope::Repo(RepoScope {
            collection: RepoCollection::Nsid(Nsid::<SmolStr>::new_static(col).unwrap()),
            actions,
        }));
    }

    scopes
}

#[tokio::test(flavor = "multi_thread")]
async fn test_realistic_scopes_video_rpc_permitted() {
    // Scenario: session has resolved app.bsky.authCreatePosts permissions.
    // Calling app.bsky.video.getUploadLimits should succeed.
    let client = Arc::new(MockClient::default());
    client
        .push(
            HttpResponse::builder()
                .status(StatusCode::OK)
                .header(http::header::CONTENT_TYPE, "application/json")
                .body(serde_json::to_vec(&serde_json::json!({"key": "value"})).unwrap())
                .unwrap(),
        )
        .await;

    let mut path = std::env::temp_dir();
    path.push(format!(
        "jacquard-scope-realistic-rpc-{}.json",
        std::process::id(),
    ));
    std::fs::write(&path, "{}").unwrap();
    let store = jacquard::client::FileAuthStore::new(&path);

    let client_data = ClientData {
        keyset: None,
        config: AtprotoClientMetadata::new_localhost(
            None,
            Some(Scopes::new(SmolStr::new_static("atproto")).unwrap()),
        ),
    };

    let session_data = create_session_data(Some(resolved_scopes_auth_create_posts())).into_static();
    let client_arc = client.clone();
    let registry = Arc::new(SessionRegistry::new(store, client_arc.clone(), client_data));
    registry.set(session_data.clone()).await.unwrap();
    let session = OAuthSession::new(registry, client_arc, session_data);

    let agent: Agent<_> = Agent::from(session);
    let resp = agent
        .send(jacquard::api::app_bsky::video::get_upload_limits::GetUploadLimits)
        .await
        .expect("video RPC should be permitted by authCreatePosts scope");
    assert_eq!(resp.status(), StatusCode::OK);

    let log = client.log.lock().await;
    assert_eq!(log.len(), 1, "expected 1 HTTP call");
    let _ = std::fs::remove_file(&path);
}

#[tokio::test(flavor = "multi_thread")]
async fn test_realistic_scopes_ungated_rpc_denied() {
    // Scenario: session has only authCreatePosts permissions.
    // Calling getSession (not in the permission set) should be DENIED.
    let client = Arc::new(MockClient::default());

    let mut path = std::env::temp_dir();
    path.push(format!(
        "jacquard-scope-realistic-deny-{}.json",
        std::process::id(),
    ));
    std::fs::write(&path, "{}").unwrap();
    let store = jacquard::client::FileAuthStore::new(&path);

    let client_data = ClientData {
        keyset: None,
        config: AtprotoClientMetadata::new_localhost(
            None,
            Some(Scopes::new(SmolStr::new_static("atproto")).unwrap()),
        ),
    };

    let session_data = create_session_data(Some(resolved_scopes_auth_create_posts())).into_static();
    let client_arc = client.clone();
    let registry = Arc::new(SessionRegistry::new(store, client_arc.clone(), client_data));
    registry.set(session_data.clone()).await.unwrap();
    let session = OAuthSession::new(registry, client_arc, session_data);

    let agent: Agent<_> = Agent::from(session);
    let err = match agent
        .send(jacquard::api::com_atproto::server::get_session::GetSession)
        .await
    {
        Err(e) => e,
        Ok(_) => panic!("getSession should be denied — not in authCreatePosts permission set"),
    };

    let err_msg = format!("{}", err);
    assert!(
        err_msg.contains("com.atproto.server.getSession"),
        "error should identify the denied NSID, got: {err_msg}"
    );

    // No HTTP call made — scope check short-circuited.
    let log = client.log.lock().await;
    assert_eq!(log.len(), 0, "no HTTP request when scope check fails");
    let _ = std::fs::remove_file(&path);
}

#[tokio::test(flavor = "multi_thread")]
async fn test_realistic_scopes_audience_specific_rpc_permitted() {
    // Critical regression test: granted scopes with a SPECIFIC audience
    // (e.g., did:web:api.bsky.app) must still permit the request.
    // The client doesn't know the target audience at pre-flight time —
    // audience enforcement is the server's responsibility.
    let client = Arc::new(MockClient::default());
    client
        .push(
            HttpResponse::builder()
                .status(StatusCode::OK)
                .header(http::header::CONTENT_TYPE, "application/json")
                .body(serde_json::to_vec(&serde_json::json!({"key": "value"})).unwrap())
                .unwrap(),
        )
        .await;

    let mut path = std::env::temp_dir();
    path.push(format!(
        "jacquard-scope-aud-specific-{}.json",
        std::process::id(),
    ));
    std::fs::write(&path, "{}").unwrap();
    let store = jacquard::client::FileAuthStore::new(&path);

    let client_data = ClientData {
        keyset: None,
        config: AtprotoClientMetadata::new_localhost(
            None,
            Some(Scopes::new(SmolStr::new_static("atproto")).unwrap()),
        ),
    };

    // Granted scope has a SPECIFIC audience — this is the normal case
    // for inter-service auth in permission sets (e.g., "aud": "did:web:api.bsky.app").
    let mut lxm = BTreeSet::new();
    lxm.insert(RpcLexicon::Nsid(
        Nsid::<SmolStr>::new_static("app.bsky.video.getUploadLimits").unwrap(),
    ));
    let mut aud = BTreeSet::new();
    aud.insert(RpcAudience::Did(
        DidService::<SmolStr>::new_static("did:web:api.bsky.app").unwrap(),
    ));
    let resolved_scopes = Some(vec![Scope::Rpc(RpcScope { lxm, aud })]);

    let session_data = create_session_data(resolved_scopes).into_static();
    let client_arc = client.clone();
    let registry = Arc::new(SessionRegistry::new(store, client_arc.clone(), client_data));
    registry.set(session_data.clone()).await.unwrap();
    let session = OAuthSession::new(registry, client_arc, session_data);

    let agent: Agent<_> = Agent::from(session);
    let resp = agent
        .send(jacquard::api::app_bsky::video::get_upload_limits::GetUploadLimits)
        .await
        .expect("RPC with audience-specific scope should still be permitted at pre-flight");
    assert_eq!(resp.status(), StatusCode::OK);

    let log = client.log.lock().await;
    assert_eq!(log.len(), 1, "expected 1 HTTP call");
    let _ = std::fs::remove_file(&path);
}