link-assistant-router 1.10.1

Link.Assistant.Router — Claude MAX OAuth proxy and token gateway for Anthropic APIs
Documentation
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
//! Unit tests for [`crate::subscription`].
//!
//! Split from `subscription.rs` to keep that file within the repository's
//! 1000-line limit.

use super::*;
use std::fs;

/// `auth status` prints a padded provider column. A `Display` built on
/// `write_str` silently discards the requested width, so the format string
/// looks correct and only the rendered output disagrees — invisible to the
/// compiler, which is why this needs a test (issue #212).
#[test]
fn provider_display_honours_the_requested_width() {
    assert_eq!(
        format!("[{:<8}]", SubscriptionProvider::Codex),
        "[codex   ]"
    );
    assert_eq!(
        format!("[{:>8}]", SubscriptionProvider::Claude),
        "[  claude]"
    );
    // Padding must never truncate or alter a value that already fills the
    // column.
    assert_eq!(format!("[{:<3}]", SubscriptionProvider::Gemini), "[gemini]");
    // The unpadded rendering is unchanged.
    assert_eq!(SubscriptionProvider::Qwen.to_string(), "qwen");
}

fn tempdir() -> PathBuf {
    let dir = std::env::temp_dir().join(format!("router-sub-{}", uuid::Uuid::new_v4()));
    fs::create_dir_all(&dir).unwrap();
    dir
}

#[test]
fn provider_roundtrip_strings() {
    for p in SubscriptionProvider::ALL {
        assert_eq!(SubscriptionProvider::from_str_opt(p.as_str()), Some(p));
    }
    assert_eq!(
        SubscriptionProvider::from_str_opt("ChatGPT"),
        Some(SubscriptionProvider::Codex)
    );
    assert_eq!(
        SubscriptionProvider::from_str_opt("dashscope"),
        Some(SubscriptionProvider::Qwen)
    );
    assert!(SubscriptionProvider::from_str_opt("unknown").is_none());
}

#[test]
fn reads_codex_auth_json() {
    let dir = tempdir();
    fs::write(
        dir.join("auth.json"),
        r#"{"tokens":{"id_token":"x","access_token":"codex-access","refresh_token":"codex-refresh","account_id":"acct_123"},"last_refresh":"2026-06-01T00:00:00Z"}"#,
    )
    .unwrap();
    let reader = SubscriptionReader::new(SubscriptionProvider::Codex, &dir);
    let token = reader.read_token().expect("codex token");
    assert_eq!(token.access_token, "codex-access");
    assert_eq!(token.refresh_token.as_deref(), Some("codex-refresh"));
    assert_eq!(token.account_id.as_deref(), Some("acct_123"));
    assert_eq!(
        token.base_url(SubscriptionProvider::Codex),
        "https://chatgpt.com/backend-api/codex"
    );
}

#[test]
fn reads_codex_account_id_from_id_token() {
    use base64::Engine as _;
    // header.payload.signature with payload carrying the nested account id.
    let payload = serde_json::json!({
        "https://api.openai.com/auth": { "chatgpt_account_id": "acct_from_jwt" }
    });
    let payload_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .encode(serde_json::to_vec(&payload).unwrap());
    let id_token = format!("aGVhZGVy.{payload_b64}.sig");
    let dir = tempdir();
    fs::write(
        dir.join("auth.json"),
        format!(r#"{{"tokens":{{"id_token":"{id_token}","access_token":"a"}}}}"#),
    )
    .unwrap();
    let reader = SubscriptionReader::new(SubscriptionProvider::Codex, &dir);
    let token = reader.read_token().expect("codex token");
    assert_eq!(token.account_id.as_deref(), Some("acct_from_jwt"));
}

#[test]
fn reads_codex_expiry_from_access_token() {
    use base64::Engine as _;
    let dir = tempdir();
    let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(br#"{"exp":1770000000}"#);
    let access = format!("header.{payload}.signature");
    fs::write(
        dir.join("auth.json"),
        format!(r#"{{"tokens":{{"access_token":"{access}"}}}}"#),
    )
    .unwrap();
    let token = SubscriptionReader::new(SubscriptionProvider::Codex, &dir)
        .read_token()
        .unwrap();
    assert_eq!(token.expires_at_ms, Some(1_770_000_000_000));
}

#[test]
fn reads_gemini_oauth_creds() {
    let dir = tempdir();
    fs::write(
        dir.join("oauth_creds.json"),
        r#"{"access_token":"gem-access","refresh_token":"gem-refresh","expiry_date":9999999999999,"token_type":"Bearer","scope":"https://www.googleapis.com/auth/cloud-platform"}"#,
    )
    .unwrap();
    let reader = SubscriptionReader::new(SubscriptionProvider::Gemini, &dir);
    let token = reader.read_token().expect("gemini token");
    assert_eq!(token.access_token, "gem-access");
    assert_eq!(token.refresh_token.as_deref(), Some("gem-refresh"));
    assert_eq!(token.expires_at_ms, Some(9_999_999_999_999));
    assert_eq!(
        token.base_url(SubscriptionProvider::Gemini),
        "https://cloudcode-pa.googleapis.com"
    );
}

#[test]
fn external_owner_marker_survives_read_and_blocks_rotation() {
    let dir = tempfile::tempdir().unwrap();
    let reader = SubscriptionReader::new(SubscriptionProvider::Claude, dir.path());
    let document = mark_external_refresh_owner(
        r#"{"claudeAiOauth":{"accessToken":"external-access","refreshToken":"external-refresh","expiresAt":9999999999999}}"#,
    )
    .unwrap();
    reader.install_document(&document).unwrap();

    let (token, origin) = reader.read_token_from().unwrap();
    assert_eq!(origin, crate::platform_keychain::Origin::ExternalFile);
    assert_eq!(token.refresh_token.as_deref(), Some("external-refresh"));
    let error =
        crate::credential_store::CredentialStore::prepare_refresh(&reader, &token).unwrap_err();
    assert!(error.contains("externally owned"), "{error}");
    let mut successor = token;
    successor.access_token = "router-successor".into();
    successor.refresh_token = Some("router-spent-external-link".into());
    let error = reader.write_token(&successor).unwrap_err().to_string();
    assert!(error.contains("externally owned"), "{error}");
    let unchanged = reader.read_token().unwrap();
    assert_eq!(unchanged.access_token, "external-access");
    assert_eq!(unchanged.refresh_token.as_deref(), Some("external-refresh"));
}

#[test]
fn direct_reader_waits_for_the_file_transaction_commit_boundary() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join(".credentials.json");
    let old = br#"{"claudeAiOauth":{"accessToken":"old"}}"#;
    let new = br#"{"claudeAiOauth":{"accessToken":"new"}}"#;
    std::fs::write(&path, old).unwrap();
    let lock_path = credential_file_lock_path(&path);
    let lock = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&lock_path)
        .unwrap();
    lock.lock().unwrap();
    let rollback_path = dir.path().join("..credentials.json.router-rollback");
    let commit_path = dir.path().join("..credentials.json.router-commit");
    let mut rollback = vec![1];
    rollback.extend_from_slice(old);
    crate::durable_file::atomic_write_owner_only(&rollback_path, &rollback).unwrap();
    crate::durable_file::atomic_write_owner_only(&path, new).unwrap();

    let reader = SubscriptionReader::new(SubscriptionProvider::Claude, dir.path());
    let (sender, receiver) = std::sync::mpsc::channel();
    let handle = std::thread::spawn(move || sender.send(reader.read_token()).unwrap());
    std::thread::sleep(std::time::Duration::from_millis(50));
    assert!(matches!(
        receiver.try_recv(),
        Err(std::sync::mpsc::TryRecvError::Empty)
    ));

    crate::durable_file::atomic_write_owner_only(&commit_path, b"committed\n").unwrap();
    lock.unlock().unwrap();
    let token = receiver
        .recv_timeout(std::time::Duration::from_secs(2))
        .unwrap()
        .unwrap();
    handle.join().unwrap();
    assert_eq!(token.access_token, "new");
    assert!(!rollback_path.exists());
    assert!(!commit_path.exists());
}

#[test]
fn reads_qwen_oauth_creds_with_resource_url() {
    let dir = tempdir();
    fs::write(
        dir.join("oauth_creds.json"),
        r#"{"access_token":"qwen-access","refresh_token":"qwen-refresh","token_type":"Bearer","resource_url":"portal.qwen.ai","expiry_date":9999999999999}"#,
    )
    .unwrap();
    let reader = SubscriptionReader::new(SubscriptionProvider::Qwen, &dir);
    let token = reader.read_token().expect("qwen token");
    assert_eq!(token.access_token, "qwen-access");
    assert_eq!(token.resource_url.as_deref(), Some("portal.qwen.ai"));
    // resource_url overrides the default DashScope base and gets the exact
    // `/v1` suffix Qwen Code itself adds, plus a scheme when absent.
    assert_eq!(
        token.base_url(SubscriptionProvider::Qwen),
        "https://portal.qwen.ai/v1"
    );
}

#[test]
fn qwen_without_resource_url_uses_default_base() {
    let dir = tempdir();
    fs::write(
        dir.join("oauth_creds.json"),
        r#"{"access_token":"qwen-access"}"#,
    )
    .unwrap();
    let reader = SubscriptionReader::new(SubscriptionProvider::Qwen, &dir);
    let token = reader.read_token().expect("qwen token");
    assert_eq!(
        token.base_url(SubscriptionProvider::Qwen),
        "https://dashscope.aliyuncs.com/compatible-mode/v1"
    );
}

#[test]
fn reads_claude_nested_credentials() {
    let dir = tempdir();
    fs::write(
        dir.join(".credentials.json"),
        r#"{"claudeAiOauth":{"accessToken":"sk-ant-oat-nested","refreshToken":"sk-ant-ort-x","expiresAt":9999999999999}}"#,
    )
    .unwrap();
    let reader = SubscriptionReader::new(SubscriptionProvider::Claude, &dir);
    let token = reader.read_token().expect("claude token");
    assert_eq!(token.access_token, "sk-ant-oat-nested");
    assert_eq!(token.refresh_token.as_deref(), Some("sk-ant-ort-x"));
    assert_eq!(token.expires_at_ms, Some(9_999_999_999_999));
}

#[test]
fn claude_pool_reader_preserves_legacy_credential_candidates() {
    let dir = tempdir();
    fs::write(dir.join("oauth.json"), r#"{"accessToken":"legacy"}"#).unwrap();
    let token = SubscriptionReader::new(SubscriptionProvider::Claude, &dir)
        .read_token()
        .unwrap();

    assert_eq!(token.access_token, "legacy");
}

#[test]
fn missing_credentials_errors() {
    let reader = SubscriptionReader::new(
        SubscriptionProvider::Gemini,
        "/tmp/router-nonexistent-sub-dir",
    );
    let err = reader.read_token().unwrap_err();
    assert!(matches!(err, SubscriptionError::NoCredentials(_)));
}

#[test]
fn expiry_detection() {
    let token = SubscriptionToken {
        access_token: "a".into(),
        refresh_token: None,
        expires_at_ms: Some(1000),
        account_id: None,
        resource_url: None,
    };
    assert!(token.is_expired(2000));
    assert!(!token.is_expired(500));
}

#[test]
fn discover_credential_path_finds_existing() {
    let dir = tempdir();
    fs::write(dir.join("oauth_creds.json"), r#"{"access_token":"x"}"#).unwrap();
    let reader = SubscriptionReader::new(SubscriptionProvider::Qwen, &dir);
    assert_eq!(
        reader.discover_credential_path(),
        Some(dir.join("oauth_creds.json"))
    );
}

#[test]
fn resolve_home_uses_subdir() {
    // Without the override env var set, falls back to <home>/<subdir>.
    let home = SubscriptionProvider::Codex.resolve_home("/home/alice");
    assert!(home.ends_with(".codex"));
}

/// A rotated refresh token must reach disk, or the next process start
/// replays a token the vendor has already spent (issue #205).
#[test]
fn write_token_persists_a_rotated_refresh_token_for_codex() {
    let dir = tempdir();
    // The real Codex layout, including fields this crate does not model.
    fs::write(
        dir.join("auth.json"),
        r#"{"auth_mode":"chatgpt","tokens":{"id_token":"id-1","access_token":"old-access","refresh_token":"old-refresh","account_id":"acct_1"},"last_refresh":"2026-08-11T11:31:03Z"}"#,
    )
    .unwrap();
    let reader = SubscriptionReader::new(SubscriptionProvider::Codex, &dir);

    reader
        .write_token(&SubscriptionToken {
            access_token: "new-access".into(),
            refresh_token: Some("new-refresh".into()),
            expires_at_ms: Some(9_000),
            account_id: Some("acct_1".into()),
            resource_url: None,
        })
        .expect("the rotated token should be written");

    let written: serde_json::Value =
        serde_json::from_str(&fs::read_to_string(dir.join("auth.json")).unwrap()).unwrap();
    assert_eq!(written["tokens"]["access_token"], "new-access");
    assert_eq!(written["tokens"]["refresh_token"], "new-refresh");
    // Fields the vendor CLI relies on must survive the merge.
    assert_eq!(written["tokens"]["id_token"], "id-1");
    assert_eq!(written["auth_mode"], "chatgpt");
    assert_eq!(written["tokens"]["account_id"], "acct_1");
    // The refresh is stamped so the vendor CLI sees it happened.
    assert_ne!(written["last_refresh"], "2026-08-11T11:31:03Z");

    // And the round trip reads back what was written.
    let reread = reader.read_token().expect("re-read");
    assert_eq!(reread.access_token, "new-access");
    assert_eq!(reread.refresh_token.as_deref(), Some("new-refresh"));
}

#[test]
fn write_token_preserves_the_claude_nested_layout() {
    let dir = tempdir();
    fs::write(
        dir.join(".credentials.json"),
        r#"{"claudeAiOauth":{"accessToken":"old","refreshToken":"old-r","expiresAt":1,"scopes":["user:inference"],"subscriptionType":"max"}}"#,
    )
    .unwrap();
    let reader = SubscriptionReader::new(SubscriptionProvider::Claude, &dir);

    reader
        .write_token(&SubscriptionToken {
            access_token: "fresh".into(),
            refresh_token: Some("fresh-r".into()),
            expires_at_ms: Some(4_242),
            account_id: None,
            resource_url: None,
        })
        .expect("write");

    let written: serde_json::Value =
        serde_json::from_str(&fs::read_to_string(dir.join(".credentials.json")).unwrap()).unwrap();
    let block = &written["claudeAiOauth"];
    assert_eq!(block["accessToken"], "fresh");
    assert_eq!(block["refreshToken"], "fresh-r");
    assert_eq!(block["expiresAt"], 4_242);
    // Vendor-only fields are untouched.
    assert_eq!(block["subscriptionType"], "max");
    assert_eq!(block["scopes"][0], "user:inference");
}

#[test]
fn write_token_updates_the_flat_gemini_and_qwen_layout() {
    for (provider, extra) in [
        (SubscriptionProvider::Gemini, "\"scope\":\"cloud-platform\""),
        (
            SubscriptionProvider::Qwen,
            "\"resource_url\":\"portal.qwen.ai\"",
        ),
    ] {
        let dir = tempdir();
        fs::write(
            dir.join("oauth_creds.json"),
            format!(
                r#"{{"access_token":"old","refresh_token":"old-r","expiry_date":1,"token_type":"Bearer",{extra}}}"#
            ),
        )
        .unwrap();
        let reader = SubscriptionReader::new(provider, &dir);

        reader
            .write_token(&SubscriptionToken {
                access_token: "fresh".into(),
                refresh_token: Some("fresh-r".into()),
                expires_at_ms: Some(7_000),
                account_id: None,
                resource_url: None,
            })
            .expect("write");

        let written: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(dir.join("oauth_creds.json")).unwrap())
                .unwrap();
        assert_eq!(written["access_token"], "fresh", "{provider}");
        assert_eq!(written["refresh_token"], "fresh-r", "{provider}");
        assert_eq!(written["expiry_date"], 7_000, "{provider}");
        assert_eq!(written["token_type"], "Bearer", "{provider}");
    }
}

/// Writing to a credential directory with no file is refused rather than
/// creating one the vendor CLI did not write.
#[test]
fn write_token_requires_an_existing_credential_file() {
    let dir = tempdir();
    let reader = SubscriptionReader::new(SubscriptionProvider::Codex, &dir);
    assert!(matches!(
        reader.write_token(&SubscriptionToken {
            access_token: "x".into(),
            refresh_token: None,
            expires_at_ms: None,
            account_id: None,
            resource_url: None,
        }),
        Err(SubscriptionError::NoCredentials(_))
    ));
}

/// Write a Claude credential file holding `expires_at_ms`, and return a reader
/// rooted at its home.
fn claude_home_expiring_at(dir: &std::path::Path, expires_at_ms: i64) -> SubscriptionReader {
    fs::write(
        dir.join(".credentials.json"),
        serde_json::json!({
            "claudeAiOauth": {
                "accessToken": "file-access",
                "refreshToken": "file-refresh",
                "expiresAt": expires_at_ms,
            }
        })
        .to_string(),
    )
    .unwrap();
    SubscriptionReader::new(SubscriptionProvider::Claude, dir)
}

fn keychain_token(access: &str, expires_at_ms: Option<i64>) -> SubscriptionToken {
    SubscriptionToken {
        access_token: access.to_string(),
        refresh_token: Some("keychain-refresh".into()),
        expires_at_ms,
        account_id: None,
        resource_url: None,
    }
}

/// The bug in #249: the file had expired hours ago while the Keychain held a
/// live credential, and the router read only the file. The live one must win.
#[test]
fn a_live_keychain_credential_beats_an_expired_file() {
    let dir = tempfile::tempdir().unwrap();
    let reader = claude_home_expiring_at(dir.path(), 1_000);

    let (token, origin) = reader
        .select_store(Some(keychain_token("keychain-access", Some(9_999_999))))
        .expect("a credential is available");

    assert_eq!(origin, crate::platform_keychain::Origin::Keychain);
    assert_eq!(token.access_token, "keychain-access");
    assert!(
        crate::credential_store::ensure_refreshable_origin(reader.provider(), origin).is_err(),
        "an injected Keychain winner must be read-only to Router refresh"
    );
}

/// The file must keep winning when it is the newer credential, so a stale
/// keychain entry left by an older client cannot drag a working router back.
#[test]
fn a_newer_file_is_not_displaced_by_a_stale_keychain_entry() {
    let dir = tempfile::tempdir().unwrap();
    let reader = claude_home_expiring_at(dir.path(), 9_999_999);

    let (token, origin) = reader
        .select_store(Some(keychain_token("keychain-access", Some(1_000))))
        .expect("a credential is available");

    assert_eq!(origin, crate::platform_keychain::Origin::File);
    assert_eq!(token.access_token, "file-access");
}

/// A store that merely mirrors the file must change nothing: equal expiries
/// mean there is no evidence the store is ahead.
#[test]
fn an_equal_keychain_entry_leaves_the_file_in_place() {
    let dir = tempfile::tempdir().unwrap();
    let reader = claude_home_expiring_at(dir.path(), 5_000);

    let (_, origin) = reader
        .select_store(Some(keychain_token("keychain-access", Some(5_000))))
        .expect("a credential is available");

    assert_eq!(origin, crate::platform_keychain::Origin::File);
}

/// With no store entry the reader must behave exactly as it did before #249 —
/// this is what every non-macOS platform, and every other provider, sees.
#[test]
fn without_a_store_the_file_is_used_unchanged() {
    let dir = tempfile::tempdir().unwrap();
    let reader = claude_home_expiring_at(dir.path(), 5_000);

    let (token, origin) = reader
        .select_store(None)
        .expect("a credential is available");

    assert_eq!(origin, crate::platform_keychain::Origin::File);
    assert_eq!(token.access_token, "file-access");
}

/// A keychain credential must be usable even with no credential file at all:
/// a machine that only ever logged in through a recent client has no file.
#[test]
fn a_keychain_credential_is_used_when_no_file_exists() {
    let dir = tempfile::tempdir().unwrap();
    let reader = SubscriptionReader::new(SubscriptionProvider::Claude, dir.path());

    let (token, origin) = reader
        .select_store(Some(keychain_token("keychain-access", Some(9_999_999))))
        .expect("the store credential is available");

    assert_eq!(origin, crate::platform_keychain::Origin::Keychain);
    assert_eq!(token.access_token, "keychain-access");
}

/// A file promotion cannot replace a platform-store credential with a later
/// expiry. Import must detect that the candidate would remain shadowed and
/// refuse before reporting success.
#[test]
fn a_newer_platform_credential_would_shadow_an_import_candidate() {
    let candidate = keychain_token("candidate", Some(6_000));

    assert!(SubscriptionReader::candidate_is_shadowed_by_store(
        &candidate,
        Some(keychain_token("keychain", Some(7_000)))
    ));
    assert!(!SubscriptionReader::candidate_is_shadowed_by_store(
        &candidate,
        Some(keychain_token("keychain", Some(6_000)))
    ));
    assert!(!SubscriptionReader::candidate_is_shadowed_by_store(
        &candidate, None
    ));
}

/// Neither store holding a credential must still report the file's error, so a
/// machine with nothing configured says what it always said.
#[test]
fn with_neither_store_the_file_error_is_reported() {
    let dir = tempfile::tempdir().unwrap();
    let reader = SubscriptionReader::new(SubscriptionProvider::Claude, dir.path());

    assert!(reader.select_store(None).is_err());
}

/// An expiry-less store credential must not displace a file that has a usable
/// expiry: an unknown expiry cannot be shown to be newer.
#[test]
fn a_store_credential_without_an_expiry_does_not_displace_the_file() {
    let dir = tempfile::tempdir().unwrap();
    let reader = claude_home_expiring_at(dir.path(), 5_000);

    let (_, origin) = reader
        .select_store(Some(keychain_token("keychain-access", None)))
        .expect("a credential is available");

    assert_eq!(origin, crate::platform_keychain::Origin::File);
}

/// A reader rooted somewhere other than the vendor's default home must never
/// consult the machine-wide store.
///
/// The store holds one entry for the whole machine. Letting it answer for a
/// pooled account would make every account in a pool report the same
/// subscription — turning a fix for one stale credential into silent
/// cross-account leakage.
#[test]
fn a_pooled_home_never_consults_the_machine_store() {
    let dir = tempfile::tempdir().unwrap();
    let reader = SubscriptionReader::new(SubscriptionProvider::Claude, dir.path());

    assert!(
        !reader.is_vendor_default_home(),
        "a temp directory is not the vendor default home"
    );
    assert!(
        reader.read_token_from_keychain().is_none(),
        "a pooled reader must not read the machine-wide store"
    );
}

/// The store holds the same JSON shape the file does, so the vendor's own
/// entry must parse without a second parser.
#[test]
fn a_store_entry_parses_like_the_file() {
    let reader = SubscriptionReader::new(SubscriptionProvider::Claude, "/nonexistent");

    let token = reader
        .parse_store_credential(
            r#"{"claudeAiOauth":{"accessToken":"kc-access","refreshToken":"kc-refresh","expiresAt":123}}"#,
        )
        .expect("the vendor entry must parse");

    assert_eq!(token.access_token, "kc-access");
    assert_eq!(token.refresh_token.as_deref(), Some("kc-refresh"));
    assert_eq!(token.expires_at_ms, Some(123));
}

/// An entry this crate cannot read must leave the file as the source rather
/// than failing the command — the pre-#249 behaviour on every platform.
#[test]
fn an_unreadable_store_entry_yields_no_credential() {
    let reader = SubscriptionReader::new(SubscriptionProvider::Claude, "/nonexistent");

    assert!(reader.parse_store_credential("not json at all").is_none());
    assert!(reader.parse_store_credential("{}").is_none());
    assert!(
        reader
            .parse_store_credential(r#"{"claudeAiOauth":{}}"#)
            .is_none(),
        "an entry with no token must not be adopted"
    );
}

/// Every provider names an upstream, so a missing default cannot silently
/// route a subscription at the wrong vendor.
#[test]
fn every_provider_has_a_default_upstream() {
    for provider in SubscriptionProvider::ALL {
        let base = provider.default_base_url();
        assert!(
            base.starts_with("https://"),
            "{provider} must default to an HTTPS upstream, got {base}"
        );
    }
}

/// Each error variant renders its own message, so an operator sees what went
/// wrong rather than the variant's name.
#[test]
fn every_error_renders_its_message() {
    let errors = [
        SubscriptionError::NoCredentials("no credentials".into()),
        SubscriptionError::ReadError("read failed".into()),
        SubscriptionError::ParseError("parse failed".into()),
        SubscriptionError::NoToken("no token".into()),
    ];

    for error in errors {
        let rendered = error.to_string();
        assert!(!rendered.is_empty());
        assert!(
            !rendered.contains("SubscriptionError"),
            "the variant name leaked into the message: {rendered}"
        );
    }
}

/// Qwen returns a bare host, so the scheme and `/v1` suffix are added; a base
/// that already ends in `/v1` is left alone.
#[test]
fn a_qwen_resource_url_is_completed_only_where_it_is_incomplete() {
    let bare = SubscriptionToken {
        access_token: "a".into(),
        refresh_token: None,
        expires_at_ms: None,
        account_id: None,
        resource_url: Some("dashscope.example".into()),
    };
    let completed = bare.base_url(SubscriptionProvider::Qwen);
    assert!(completed.starts_with("https://"), "{completed}");
    assert!(completed.ends_with("/v1"), "{completed}");

    let already_complete = SubscriptionToken {
        resource_url: Some("https://dashscope.example/compatible-mode/v1".into()),
        ..bare
    };
    assert_eq!(
        already_complete.base_url(SubscriptionProvider::Qwen),
        "https://dashscope.example/compatible-mode/v1",
        "a complete resource URL must not be rewritten"
    );
}

/// An adopted credential lands where the provider's own client writes, which
/// is not the same as the first name it is searched under.
///
/// Claude Code reads and writes `.credentials.json`; legacy names are only
/// fallbacks and cannot shadow the canonical login.
#[test]
fn an_installed_document_lands_where_the_vendor_client_writes() {
    let dir = tempfile::tempdir().expect("home");
    let reader = SubscriptionReader::new(SubscriptionProvider::Claude, dir.path());
    let document = r#"{"claudeAiOauth":{"accessToken":"a","refreshToken":"r","expiresAt":1}}"#;

    let installed = reader.install_document(document).expect("install");

    assert_eq!(installed, dir.path().join(".credentials.json"));
    assert_eq!(
        std::fs::read_to_string(&installed).expect("read back"),
        document
    );
    assert_eq!(
        SubscriptionProvider::Claude.canonical_credential_filename(),
        ".credentials.json"
    );
    assert_eq!(
        SubscriptionProvider::Codex.canonical_credential_filename(),
        "auth.json"
    );
}

#[test]
fn malformed_or_stale_legacy_claude_files_never_shadow_the_canonical_login() {
    for legacy in [
        "not-json".to_string(),
        serde_json::json!({
            "claudeAiOauth": {
                "accessToken": "expired-legacy",
                "expiresAt": 1,
            }
        })
        .to_string(),
        serde_json::json!({
            "claudeAiOauth": {
                "accessToken": "newer-legacy",
                "expiresAt": 9_999_999_999_999_i64,
            }
        })
        .to_string(),
    ] {
        let dir = tempfile::tempdir().expect("Claude home");
        fs::write(dir.path().join("credentials.json"), legacy).unwrap();
        fs::write(
            dir.path().join(".credentials.json"),
            r#"{"claudeAiOauth":{"accessToken":"canonical","expiresAt":1000}}"#,
        )
        .unwrap();

        let token = SubscriptionReader::new(SubscriptionProvider::Claude, dir.path())
            .read_token()
            .expect("canonical credential");
        assert_eq!(token.access_token, "canonical");
    }
}

/// The document is handed back verbatim, so fields the router does not model
/// survive an import.
///
/// `SubscriptionToken` carries no `id_token`, and Codex derives its account id
/// from that field on every read — re-serializing a parsed token would drop
/// exactly what the next read depends on.
#[test]
fn the_import_source_keeps_fields_the_token_does_not_model() {
    let dir = tempfile::tempdir().expect("home");
    let document = r#"{"auth_mode":"chatgpt","tokens":{"id_token":"i","access_token":"a","refresh_token":"r"}}"#;
    std::fs::write(dir.path().join("auth.json"), document).expect("plant");
    let reader = SubscriptionReader::new(SubscriptionProvider::Codex, dir.path());

    let source = reader.read_document_for_import().expect("read for import");

    assert_eq!(
        source.document, document,
        "the document must survive verbatim"
    );
    assert_eq!(source.origin, crate::platform_keychain::Origin::File);
    assert!(source.document.contains("id_token"));
    assert!(source.document.contains("auth_mode"));
}

/// The reported credential is the selected one (issue #280).
///
/// Import read the source twice through two methods that select the platform
/// store by different rules: the document consulted the store for any home,
/// while the token describing it consulted the store only for the vendor's
/// default home. An import always names a source that differs from the
/// destination — otherwise there is nothing to adopt — so on macOS the two
/// disagreed on every run, and a live Keychain credential was selected under
/// the stale file's verdict: `EXPIRED 3 days ago ... REJECTED by the vendor`
/// for a credential that served traffic seconds later.
///
/// The direction that matters: the verdict must follow the bytes, whichever
/// store won.
#[test]
fn the_described_credential_is_the_installed_one() {
    let dir = tempfile::tempdir().unwrap();
    // The #280 shape: a file that expired long ago beside a live store entry.
    let reader = claude_home_expiring_at(dir.path(), 1_000);
    let store = serde_json::json!({
        "claudeAiOauth": {
            "accessToken": "keychain-access",
            "refreshToken": "keychain-refresh",
            "expiresAt": 9_999_999_i64,
        }
    })
    .to_string();

    let source = reader
        .import_from_store(Some(&store))
        .expect("a credential is available");

    assert_eq!(
        source.origin,
        crate::platform_keychain::Origin::Keychain,
        "the live store credential is the one to adopt"
    );
    assert_eq!(
        source.document, store,
        "the store credential is the selected document"
    );
    assert_eq!(
        source.token.access_token, "keychain-access",
        "the described token must be the installed document's, not the file's"
    );
    assert_eq!(
        source.token.expires_at_ms,
        Some(9_999_999),
        "reporting the file's expiry is what declared a working credential dead"
    );
}

/// The same invariant with the file winning: the verdict follows the bytes.
///
/// Guards the inverse failure the issue names — a stale credential installed
/// under a fresh verdict — so the fix cannot be read as "always prefer the
/// store".
#[test]
fn a_file_newer_than_the_store_is_described_as_installed_too() {
    let dir = tempfile::tempdir().unwrap();
    let reader = claude_home_expiring_at(dir.path(), 9_999_999);
    let store = serde_json::json!({
        "claudeAiOauth": {
            "accessToken": "keychain-access",
            "refreshToken": "keychain-refresh",
            "expiresAt": 1_000_i64,
        }
    })
    .to_string();

    let source = reader
        .import_from_store(Some(&store))
        .expect("a credential is available");

    assert_eq!(source.origin, crate::platform_keychain::Origin::File);
    assert_eq!(source.token.access_token, "file-access");
    assert!(source.document.contains("file-access"));
}

/// An explicitly named source is read as given, whatever the store holds
/// (issue #285).
///
/// The platform store is a single machine-wide entry, so consulting it for any
/// home let it answer for a directory it does not describe. On macOS it usually
/// holds the newest credential, so it beat every named source and no spelling
/// of `auth import <provider> <dir>` could reach the file the operator pointed
/// at — a pool of per-account directories collapsed onto the one interactive
/// login.
///
/// Asserted through `import_source_keychain`, which is the function the guard
/// lives in: `import_from_store` takes the store entry as a parameter, so a
/// test that called it directly would bypass the guard and pass either way.
/// This also keeps the test honest on every platform — the real Keychain is
/// never read, which no test may do.
#[test]
fn a_named_source_does_not_consult_the_platform_store() {
    let dir = tempfile::tempdir().unwrap();
    let reader = claude_home_expiring_at(dir.path(), 1_000);

    assert!(
        !reader.is_vendor_default_home(),
        "a temp directory is not the vendor's home, which is what makes this the #285 case"
    );
    assert!(
        !reader.consults_platform_store_for_import(),
        "an explicitly named source must not reach for the machine-wide store"
    );
    // And the lookup itself yields nothing, which is what the caller sees.
    assert!(reader.import_source_keychain().is_none());
}

/// The unqualified case still consults the store, so issue #249 keeps working.
///
/// `auth import claude` with no directory resolves to the vendor's own home,
/// where a live Keychain credential sits beside a file nothing rotates. Gating
/// the store on the *default* home is what separates "adopt the login this
/// machine has" from "adopt this credential, from there" — the distinction
/// issue #285 asked for. Without this the fix would silently undo #249.
///
/// `HOME` is read rather than set: this process never mutates the environment
/// (the crate denies `unsafe_code`, and a shared variable is not a test's to
/// change), so the reader is built against whatever home this run really has.
#[test]
fn the_vendor_default_home_still_consults_the_platform_store() {
    let Ok(home) = std::env::var("HOME") else {
        // Nothing to assert about a default home that cannot be resolved.
        return;
    };
    let reader = SubscriptionReader::new(
        SubscriptionProvider::Claude,
        SubscriptionProvider::Claude.resolve_home(&home),
    );

    assert!(
        reader.consults_platform_store_for_import(),
        "the vendor's own home must still consult the store, or the #249 recovery is lost"
    );
}

/// A home with no credential is an error naming the home, not an empty import.
#[test]
fn importing_from_an_empty_home_is_an_error() {
    let dir = tempfile::tempdir().expect("home");
    let reader = SubscriptionReader::new(SubscriptionProvider::Codex, dir.path());

    let error = reader
        .read_document_for_import()
        .expect_err("an absent credential must not import as empty");

    assert!(format!("{error}").contains("codex"), "{error}");
}

/// A syntactically valid vendor document with no access token is distinct from
/// an absent file and must report the provider and path it rejected.
#[test]
fn a_credential_document_without_an_access_token_is_rejected() {
    let dir = tempfile::tempdir().expect("credential home");
    let path = dir.path().join("oauth_creds.json");
    std::fs::write(&path, r#"{"refresh_token":"orphaned"}"#).expect("credential file");
    let reader = SubscriptionReader::new(SubscriptionProvider::Qwen, dir.path());

    let error = reader.read_token().expect_err("access token is mandatory");

    assert!(matches!(error, SubscriptionError::NoToken(_)));
    assert!(error.to_string().contains("qwen"), "{error}");
    assert!(
        error.to_string().contains(&path.display().to_string()),
        "{error}"
    );
}

/// A malformed credential cannot be rewritten because doing so would discard
/// vendor-owned fields that the router cannot reconstruct.
#[test]
fn write_token_refuses_to_replace_a_malformed_vendor_document() {
    let dir = tempfile::tempdir().expect("credential home");
    std::fs::write(dir.path().join("oauth_creds.json"), "not json").expect("credential file");
    let reader = SubscriptionReader::new(SubscriptionProvider::Gemini, dir.path());
    let fresh = SubscriptionToken {
        access_token: "fresh".into(),
        refresh_token: Some("fresh-refresh".into()),
        expires_at_ms: Some(1_000),
        account_id: None,
        resource_url: None,
    };

    assert!(matches!(
        reader.write_token(&fresh),
        Err(SubscriptionError::ParseError(_))
    ));
    assert_eq!(
        std::fs::read_to_string(dir.path().join("oauth_creds.json")).unwrap(),
        "not json"
    );
}

#[path = "subscription_write_error_tests.rs"]
mod write_error_tests;