cpa-exec 0.4.4

Part of cliproxy: upstream provider executors
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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
//! Meta parity tests. Expected values come from the Go fixtures
//! (tests/device_fixtures/meta, generated by go/zz_rsfix_meta_test.go) or from Go's own
//! tests and source, never from this implementation.

use std::time::Duration;

use serde_json::{Value, json};

use super::*;
use crate::kimi_fixture::{Captured, Mock, assert_same_request, fixture, request};
use crate::meta_auth::{
    self, GoMap, MetaAuth, TokenStorage, credential_file_name, encode_token_file, go_map_from_json, login_with,
};
use cpa_common::json as gj;

/// A private directory under the system temp dir, removed on drop.
struct TempDir(std::path::PathBuf);

impl TempDir {
    fn new() -> Self {
        let path = std::env::temp_dir().join(format!("cpa-meta-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&path).unwrap();
        Self(path)
    }

    fn path(&self) -> &std::path::Path {
        &self.0
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

fn cfg() -> Config {
    Config::parse("").unwrap()
}

/// The Go capture server's origin, `http://127.0.0.1:<port>`, found anywhere in a fixture.
fn go_origin(fx: &Value) -> Option<String> {
    let text = fx.to_string();
    let start = text.find("http://127.0.0.1:")?;
    let rest = &text[start + "http://127.0.0.1:".len()..];
    let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
    Some(format!("http://127.0.0.1:{digits}"))
}

fn replace_origin(value: &Value, origin: &str, url: &str) -> Value {
    match value {
        Value::String(s) => Value::String(s.replace(origin, url)),
        Value::Array(items) => Value::Array(items.iter().map(|v| replace_origin(v, origin, url)).collect()),
        Value::Object(map) => Value::Object(
            map.iter()
                .map(|(k, v)| (k.clone(), replace_origin(v, origin, url)))
                .collect(),
        ),
        other => other.clone(),
    }
}

/// The credential Go executed with: metadata and attributes exactly as recorded, the
/// capture server's URL swapped for the Rust mock's.
fn meta_credential(fx: &Value, origin: &str, url: &str) -> Credential {
    let metadata = replace_origin(&fx["credential"], origin, url)
        .as_object()
        .cloned()
        .unwrap_or_default();
    let mut c = Credential {
        id: "meta-fixture.json".into(),
        provider: PROVIDER.into(),
        source: Source::File("/fixture/meta-fixture.json".into()),
        disabled: false,
        label: String::new(),
        attributes: Default::default(),
        metadata,
        revision: 0,
        next_refresh_after: None,
    };
    c.refresh_derived();
    c.attributes = replace_origin(&fx["attributes"], origin, url)
        .as_object()
        .map(|attrs| {
            attrs
                .iter()
                .map(|(k, v)| (k.clone(), v.as_str().unwrap_or_default().to_owned()))
                .collect()
        })
        .unwrap_or_default();
    // cpa-core's config loader labels config API keys `<provider>-apikey`.
    if c.attributes.get("source").is_some_and(|s| s.starts_with("config:")) {
        c.label = format!("{PROVIDER}-apikey");
    }
    c
}

struct Run {
    usage: std::sync::Arc<crate::kimi_fixture::UsageLog>,
    capture: std::sync::Arc<crate::kimi_fixture::CaptureLog>,
    fx: Value,
    origin: String,
    url: String,
    credential: Credential,
    captured: Vec<Captured>,
    body: Option<String>,
    chunks: Vec<String>,
    error: Option<ExecError>,
}

async fn run(name: &str) -> Run {
    let fx = fixture("meta", name);
    let origin = go_origin(&fx).expect("fixture names its capture server");
    let mock = Mock::start_replacing(&fx["responses"], Some(&origin)).await;
    let credential = meta_credential(&fx, &origin, &mock.url);
    let exec = MetaExecutor::with_client(default_client()).with_mint_url(&format!("{}/muse-code/key", mock.url));
    let (mut body, mut chunks, mut error) = (None, Vec::new(), None);
    let cfg = Config::parse(fx["request"]["config"].as_str().unwrap_or_default()).unwrap();
    let usage = std::sync::Arc::new(crate::kimi_fixture::UsageLog::default());
    let capture = std::sync::Arc::new(crate::kimi_fixture::CaptureLog::default());
    let mut req = request(&fx, "");
    req.usage = usage.sink().with_capture(capture.sink());
    match exec.execute(&credential, req, &cfg).await {
        Err(e) => error = Some(e),
        Ok(response) => match response.body {
            ResponseBody::Buffered(b) => body = Some(String::from_utf8(b.to_vec()).unwrap()),
            ResponseBody::Stream(mut s) => {
                while let Some(item) = s.next().await {
                    match item {
                        Ok(chunk) => chunks.push(String::from_utf8(chunk.to_vec()).unwrap()),
                        Err(e) => error = Some(e),
                    }
                }
            }
        },
    }
    Run {
        usage,
        capture,
        captured: mock.captured(),
        url: mock.url,
        fx,
        origin,
        credential,
        body,
        chunks,
        error,
    }
}

fn assert_upstream(r: &Run, name: &str) {
    let go: Vec<Captured> = r.fx["upstream"]
        .as_array()
        .map(Vec::as_slice)
        .unwrap_or_default()
        .iter()
        .map(|c| Captured::from_fixture(&replace_origin(c, &r.origin, &r.url)))
        .collect();
    assert_eq!(r.captured.len(), go.len(), "{name}: upstream request count");
    for (go, rust) in go.iter().zip(&r.captured) {
        assert_same_request(name, go, rust, &["Host"]);
    }
}

fn assert_downstream(r: &Run, name: &str) {
    let down = &r.fx["downstream"];
    if let Some(body) = down["body"].as_str().filter(|b| !b.is_empty()) {
        assert_eq!(r.body.as_deref(), Some(body), "{name}: response body");
    }
    // Stream output is client framing: Go's chunks joined by its Responses route
    // (responsesSSEFramer, before route repair), recorded as `frames`; other clients get
    // the chunks as they are.
    let key = if r.fx["request"]["source"] == "openai-response" {
        "frames"
    } else {
        "chunks"
    };
    let go_frames: Vec<&str> = down[key]
        .as_array()
        .map(|c| c.iter().filter_map(Value::as_str).collect())
        .unwrap_or_default();
    assert_eq!(r.chunks, go_frames, "{name}: stream frames");
    let go_error = down["stream_err"].as_str().or(down["err_body"].as_str());
    match (&r.error, down["err_status"].as_i64()) {
        (None, None) => {}
        (Some(e), Some(-1)) => {
            // A plain Go error (no status): the handler answers 500 with its text. The
            // upstream body Go appends is withheld (see MintError::redacted).
            let rust = String::from_utf8_lossy(&e.body);
            assert_eq!(e.status, 500, "{name}: plain errors are 500");
            assert!(
                go_error.unwrap().starts_with(&format!("{rust}: ")),
                "{name}: {rust:?} must be Go's message without the upstream body"
            );
        }
        (Some(e), Some(status)) => {
            assert_eq!(i64::from(e.status), status, "{name}: error status");
            assert_eq!(
                String::from_utf8_lossy(&e.body),
                go_error.unwrap(),
                "{name}: error body"
            );
        }
        (rust, go) => panic!("{name}: rust error {rust:?}, go status {go:?}"),
    }
}

#[tokio::test]
async fn execution_matches_go_byte_for_byte() {
    for name in [
        "responses-nonstream-collected",
        "responses-stream",
        "responses-nonstream-json-body",
        "error-429-subscription-quota",
        "error-429-plain",
        "error-404-model",
        "error-404-resets",
        "stream-error-event",
        "stream-error-after-data-only",
        "nonstream-response-failed",
        "nonstream-incomplete-fallback-items",
        "nonstream-disconnect-before-completed",
        "stream-plain-json-lines",
        "compact-rejected",
        "count-tokens",
        "config-apikey-headers",
        "payload-rules-and-headers",
        "config-apikey-dca-only",
        "remint-from-dca",
        "remint-access-token-dca-minted-base",
        "remint-failure",
        "apply-patch-stream",
        "apply-patch-nonstream",
        "apply-patch-invalid-stream",
        "apply-patch-invalid-nonstream",
        "apply-patch-eof-stream",
        "stream-completed-then-error",
        "stream-done-only",
        "apply-patch-stream-event-lines",
        "stream-tier-merge",
        "stream-nbsp-data",
        "claude-stream-input-estimate",
    ] {
        let r = run(name).await;
        assert_upstream(&r, name);
        assert_downstream(&r, name);
    }
}

#[tokio::test]
async fn error_signals_follow_go_scopes_and_retry_hints() {
    for name in [
        "error-429-subscription-quota",
        "error-429-plain",
        "error-404-model",
        "error-404-resets",
        "stream-error-event",
        "nonstream-response-failed",
    ] {
        let r = run(name).await;
        let e = r.error.as_ref().unwrap_or_else(|| panic!("{name}: error expected"));
        let extra = &r.fx["extra"];
        let credential_scoped = extra["credential_scoped"].as_bool().unwrap();
        let expected_scope = match (e.status, credential_scoped) {
            (_, true) => FailureScope::Credential,
            (404 | 429, false) => FailureScope::Model,
            _ => FailureScope::Credential,
        };
        assert_eq!(e.scope, expected_scope, "{name}: scope");
        match extra["retry_after_secs"].as_f64() {
            None => assert_eq!(e.retry_after, None, "{name}: no retry hint"),
            Some(300.0) => assert_eq!(e.retry_after, Some(Duration::from_secs(300)), "{name}"),
            Some(go_secs) => {
                let elapsed = chrono::Utc::now().timestamp() - extra["now_unix"].as_i64().unwrap();
                let expected = go_secs - elapsed as f64;
                let got = e.retry_after.unwrap().as_secs_f64();
                assert!((got - expected).abs() < 5.0, "{name}: retry {got} vs {expected}");
            }
        }
    }
}

/// The minted key the fixture's mint endpoint answered with.
fn minted(r: &Run, index: usize) -> MintedKey {
    let body = replace_origin(&r.fx["responses"][index]["body"], &r.origin, &r.url);
    MintedKey::decode(body.as_str().unwrap().as_bytes()).unwrap()
}

fn assert_metadata_after(r: &Run, name: &str, patch: &MetadataPatch) {
    let mut after = r.credential.metadata.clone();
    patch.apply(&mut after);
    let mut go = replace_origin(&r.fx["extra"]["metadata_after"], &r.origin, &r.url)
        .as_object()
        .cloned()
        .unwrap();
    let stamp = after.remove("last_refresh").and_then(|v| v.as_str().map(str::to_owned));
    assert!(
        stamp.is_some_and(|s| chrono::DateTime::parse_from_rfc3339(&s).is_ok()),
        "{name}: last_refresh is RFC3339"
    );
    go.remove("last_refresh");
    assert_eq!(
        Value::Object(after),
        Value::Object(go),
        "{name}: metadata after refresh"
    );
}

#[tokio::test]
async fn remint_patch_matches_go_metadata() {
    for name in ["remint-from-dca", "remint-access-token-dca-minted-base"] {
        let r = run(name).await;
        let dca = dca_token(&r.credential).unwrap();
        let patch = refresh_patch(&r.credential, &dca, &minted(&r, 0), "2026-10-02T00:00:00Z".into());
        assert_metadata_after(&r, name, &patch);
    }
}

#[tokio::test]
async fn prepare_remints_and_matches_go_refresh() {
    let fx = fixture("meta", "refresh-direct");
    let origin = go_origin(&fx).unwrap();
    let mock = Mock::start_replacing(&fx["responses"], Some(&origin)).await;
    let credential = meta_credential(&fx, &origin, &mock.url);
    let exec = MetaExecutor::with_client(default_client()).with_mint_url(&format!("{}/muse-code/key", mock.url));
    assert!(
        !exec.needs_prepare(&credential, &cfg()),
        "a usable key and no refresh interval: nothing to prepare (RefreshLead nil)"
    );
    let patch = exec.prepare(&credential, &cfg()).await.unwrap();
    let r = Run {
        usage: Default::default(),
        capture: Default::default(),
        captured: mock.captured(),
        url: mock.url,
        fx,
        origin,
        credential,
        body: None,
        chunks: Vec::new(),
        error: None,
    };
    assert_upstream(&r, "refresh-direct");
    assert_metadata_after(&r, "refresh-direct", &patch);
}

#[test]
fn needs_prepare_matches_should_prepare_request_auth() {
    // Cases from meta_executor_test.go TestMetaExecutor_RequestAuthPreparer.
    let cred = |meta: Value, attrs: &[(&str, &str)]| {
        let mut c = Credential::from_file(
            std::path::Path::new("/a"),
            std::path::Path::new("/a/meta.json"),
            meta.as_object().unwrap().clone(),
        )
        .unwrap();
        c.provider = PROVIDER.into();
        c.attributes = attrs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
        c
    };
    let exec = MetaExecutor::default();
    let cfg = cfg();
    assert!(!exec.needs_prepare(&cred(json!({"type":"meta"}), &[("api_key", "exists")]), &cfg));
    assert!(!exec.needs_prepare(&cred(json!({"type":"meta"}), &[]), &cfg));
    let config_dca = cred(
        json!({"type":"meta"}),
        &[("api_key", "dca:invalid-for-config"), ("source", "config:meta[0]")],
    );
    assert!(is_config_api_key(&config_dca));
    // Go `AuthSourceKind` folds with strings.ToLower and EqualFold, which map U+0130 to
    // `i` (outputs of Go's IsConfigAPIKeyAuth at ae3ee3be).
    for (attrs, want) in [
        (&[("auth_kind", "apikey"), ("source_backend", "CONFİG")][..], true),
        (&[("auth_kind", "apikey"), ("source", "CONFİG:meta[0]")][..], true),
        (&[("auth_kind", "apikey"), ("source", " Config ")][..], true),
        (
            &[("auth_kind", "apikey"), ("source", "config"), ("runtime_only", "TRUE")][..],
            false,
        ),
        (
            &[
                ("auth_kind", "apikey"),
                ("source", "config:meta[0]"),
                ("source_backend", "Fİle"),
            ][..],
            false,
        ),
    ] {
        assert_eq!(
            is_config_api_key(&cred(json!({"type":"meta"}), attrs)),
            want,
            "{attrs:?}"
        );
    }
    assert!(!exec.needs_prepare(&config_dca, &cfg));
    assert!(exec.needs_prepare(
        &cred(
            json!({"type":"meta","dca_token":"dca:valid","auth_kind":"oauth"}),
            &[("base_url", "http://x")]
        ),
        &cfg
    ));
    // A due refresh_interval re-mints even with a key (shouldRefresh's preferred interval).
    assert!(exec.needs_prepare(
        &cred(
            json!({"type":"meta","api_key":"k","dca_token":"dca:v","refresh_interval":60,"last_refresh":"2020-01-01T00:00:00Z"}),
            &[]
        ),
        &cfg
    ));
}

#[test]
fn creds_resolution_matches_go() {
    // Cases from meta_executor_test.go TestMetaExecutor_MetaCredsResolution.
    let mut c = Credential::from_file(
        std::path::Path::new("/a"),
        std::path::Path::new("/a/meta.json"),
        json!({"type":"meta"}).as_object().unwrap().clone(),
    )
    .unwrap();
    c.attributes.insert("api_key".into(), "attr-key".into());
    c.attributes
        .insert("base_url".into(), "https://custom.meta.com/v1".into());
    assert_eq!(creds(&c), ("https://custom.meta.com/v1".into(), "attr-key".into()));
    c.attributes.clear();
    c.metadata.insert("access_token".into(), "meta-oauth-token".into());
    assert_eq!(creds(&c), (DEFAULT_API_BASE_URL.into(), "meta-oauth-token".into()));
    // DCA tokens are never used as keys but are the mint source.
    c.metadata.insert("access_token".into(), " dca:x ".into());
    c.metadata.insert("api_base_url".into(), "https://alt/v1".into());
    assert_eq!(creds(&c), ("https://alt/v1".into(), String::new()));
    assert_eq!(dca_token(&c).as_deref(), Some("dca:x"));
}

#[test]
fn retry_hint_follows_resets_at() {
    // TestMetaExecutor_ParseRetryAfter: a future resets_at about 45 minutes out.
    let future = chrono::Utc::now().timestamp() + 45 * 60;
    let body = format!(
        r#"{{"error":{{"code":"rate_limit_exceeded","message":"Subscription quota exhausted.","resets_at":{future},"type":"rate_limit_error"}}}}"#
    );
    let e = upstream_error(429, body.as_bytes());
    let secs = e.retry_after.unwrap().as_secs();
    assert!((40 * 60..=50 * 60).contains(&secs));
    assert_eq!(e.scope, FailureScope::Credential);
    let past = chrono::Utc::now().timestamp() - 600;
    let e = upstream_error(429, format!(r#"{{"error":{{"resets_at":{past}}}}}"#).as_bytes());
    assert_eq!(e.retry_after, None);
    assert_eq!(e.scope, FailureScope::Model);
    assert_eq!(upstream_error(400, body.as_bytes()).retry_after, None);
}

#[test]
fn file_names_and_writer_match_go() {
    let fx = fixture("meta", "writer");
    for case in fx["extra"]["file_names"].as_array().unwrap() {
        assert_eq!(
            credential_file_name(case["email"].as_str().unwrap(), case["sub"].as_str().unwrap()),
            case["out"].as_str().unwrap()
        );
    }
    let dir = TempDir::new();
    for case in fx["extra"]["cases"].as_array().unwrap() {
        let name = case["name"].as_str().unwrap();
        let storage: TokenStorage = serde_json::from_value(case["storage"].clone()).unwrap();
        let snapshot: Option<GoMap> = case["snapshot"]
            .as_object()
            .map(|m| go_map_from_json(&serde_json::to_vec(m).unwrap()).unwrap().0);
        let disk = case["disk"].as_str().unwrap();
        let out = case["out"].as_str().unwrap();
        assert_eq!(
            encode_token_file(&storage, snapshot.as_ref(), Some(disk.as_bytes())),
            out,
            "{name}"
        );
        // The file path: disk is read only without a snapshot, then atomically replaced.
        let path = dir.path().join(format!("{name}.json"));
        std::fs::write(&path, disk).unwrap();
        meta_auth::save_token_file(&path, &storage, snapshot.as_ref()).unwrap();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), out, "{name}: file");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
        }
    }
    let leftovers: Vec<_> = std::fs::read_dir(dir.path())
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with('.'))
        .collect();
    assert!(leftovers.is_empty(), "no temporary files survive");
}

fn login_auth(url: &str) -> MetaAuth {
    MetaAuth::new(default_client())
        .with_auth_host(url)
        .with_mint_url(&format!("{url}/muse-code/key"))
        .with_poll_unit(Duration::from_millis(10))
}

#[tokio::test]
async fn login_matches_go_requests_and_file() {
    for name in ["login", "login-no-mint"] {
        let fx = fixture("meta", name);
        let mock = Mock::start(&fx["responses"]).await;
        let dir = TempDir::new();
        let go_file = fx["extra"]["file_name"].as_str().unwrap();
        if let Some(stale) = fx["request"]["stale_file"].as_str().filter(|s| !s.is_empty()) {
            std::fs::write(dir.path().join(go_file), stale).unwrap();
        }
        let go_raw = fx["extra"]["file_raw"].as_str().unwrap();
        let stamp = gj::get(go_raw.as_bytes(), "last_refresh").str().into_owned();
        let now = chrono::DateTime::parse_from_rfc3339(&stamp).unwrap().to_utc();
        let outcome = login_with(login_auth(&mock.url).with_fixed_now(now), dir.path(), true)
            .await
            .unwrap();
        let go: Vec<Captured> = fx["upstream"]
            .as_array()
            .unwrap()
            .iter()
            .map(Captured::from_fixture)
            .collect();
        let rust = mock.captured();
        assert_eq!(rust.len(), go.len(), "{name}: request count");
        for (go, rust) in go.iter().zip(&rust) {
            assert_same_request(name, go, rust, &["Host"]);
        }
        assert_eq!(outcome.path, dir.path().join(go_file), "{name}: file name");
        assert_eq!(outcome.label, fx["extra"]["label"].as_str().unwrap(), "{name}: label");
        assert_eq!(
            std::fs::read_to_string(&outcome.path).unwrap(),
            go_raw,
            "{name}: file bytes"
        );
    }
}

#[tokio::test]
async fn failed_login_mint_logs_no_response_body() {
    // login-no-mint's flow, with a mint endpoint whose error body carries key material.
    let fx = fixture("meta", "login-no-mint");
    let mut responses = fx["responses"].clone();
    let secret = "sk-mint-SECRET-0123456789";
    responses[2]["body"] = json!(format!(r#"{{"error":"bad","api_key":"{secret}"}}"#));
    let mock = Mock::start(&responses).await;
    let dir = TempDir::new();
    let capture = crate::kimi_fixture::LogCapture::default();
    let guard = capture.install();
    let outcome = login_with(login_auth(&mock.url), dir.path(), true).await;
    drop(guard);
    assert!(outcome.is_ok(), "a failed mint does not fail the login");
    let logs = capture.0.lock().unwrap().clone();
    assert!(
        logs.iter()
            .any(|l| l.contains("could not mint api_key from dca_token: meta auth: mint key failed (HTTP 500)")),
        "the mint failure is logged: {logs:?}"
    );
    for line in &logs {
        assert!(
            !line.contains(secret) && !line.contains("\"bad\""),
            "body logged: {line}"
        );
    }
}

#[tokio::test]
async fn device_flow_errors_and_slow_down_follow_go() {
    let device = json!({"status":200,"body":r#"{"device_code":"d","user_code":"u","interval":1,"expires_in":600}"#});
    let poll = |status: u16, body: &str| json!({"status":status,"body":body});
    let cases = [
        (
            poll(400, r#"{"error":"access_denied"}"#),
            "meta auth: access was denied by user",
        ),
        (
            poll(400, r#"{"error":"expired_token"}"#),
            "meta auth: device code has expired",
        ),
        (
            poll(400, r#"{"error":"invalid_client","error_description":"bad client"}"#),
            "meta auth: error from authorization server: invalid_client: bad client",
        ),
        (
            poll(200, r#"{"token_type":"bearer"}"#),
            "meta auth: response missing access_token",
        ),
    ];
    for (answer, message) in cases {
        let mock = Mock::start(&json!([device, answer])).await;
        let auth = login_auth(&mock.url);
        let code = auth.start_device_flow().await.unwrap();
        assert_eq!(auth.wait_for_authorization(&code).await.unwrap_err(), message);
    }
    // slow_down adds five server seconds; unknown non-JSON answers keep polling.
    let mock = Mock::start(&json!([
        device,
        poll(400, r#"{"error":"slow_down"}"#),
        poll(502, "bad gateway"),
        poll(200, r#"{"access_token":"dca:t","expires_in":0}"#),
        poll(500, "mint down"),
    ]))
    .await;
    let auth = login_auth(&mock.url);
    let code = auth.start_device_flow().await.unwrap();
    let started = tokio::time::Instant::now();
    let bundle = auth.wait_for_authorization(&code).await.unwrap();
    assert!(
        started.elapsed() >= Duration::from_millis(10 + 60 + 60),
        "slow_down widened the interval"
    );
    assert_eq!(bundle.token.access_token, "dca:t");
    assert_eq!(bundle.minted, None, "a failed mint keeps the DCA-only bundle");
    // The deadline is the device code's expires_in.
    let mock = Mock::start(&json!([
        {"status":200,"body":r#"{"device_code":"d","user_code":"u","interval":1,"expires_in":3}"#},
        poll(400, r#"{"error":"authorization_pending"}"#),
        poll(400, r#"{"error":"authorization_pending"}"#),
        poll(400, r#"{"error":"authorization_pending"}"#),
    ]))
    .await;
    let auth = login_auth(&mock.url);
    let code = auth.start_device_flow().await.unwrap();
    assert_eq!(
        auth.wait_for_authorization(&code).await.unwrap_err(),
        "meta auth: authorization timed out or canceled: context deadline exceeded"
    );
    // Device authorization failures.
    let mock = Mock::start(&json!([
        poll(400, " nope "),
        poll(200, r#"{"device_code":"d","user_code":" "}"#),
        poll(200, r#"{"device_code":"d","user_code":"u","interval":1.5}"#),
    ]))
    .await;
    let auth = login_auth(&mock.url);
    crate::kimi_fixture::assert_go_message_without_body(
        "device flow 400",
        &auth.start_device_flow().await.unwrap_err(),
        "meta device flow failed (HTTP 400): nope",
    );
    assert_eq!(
        auth.start_device_flow().await.unwrap_err(),
        "meta device flow: response missing required device_code or user_code"
    );
    assert!(
        auth.start_device_flow()
            .await
            .unwrap_err()
            .starts_with("meta device flow: parse response: ")
    );
}

#[test]
fn auth_records_decode_like_go_json_unmarshal() {
    // Go json.Unmarshal into DeviceCodeResponse, TokenData and MintedKeyResponse.
    let fx = fixture("meta", "decode");
    let string = |v: &Value, k: &str| v[k].as_str().unwrap_or_default().to_owned();
    let int = |v: &Value, k: &str| v[k].as_i64().unwrap_or_default();
    let boolean = |v: &Value, k: &str| v[k].as_bool().unwrap_or_default();
    for case in fx["extra"]["cases"].as_array().unwrap() {
        let input = case["input"].as_str().unwrap();
        let raw = input.as_bytes();
        let err = |r: &Value| r["err"].as_str().unwrap().to_owned();

        let go = &case["device"];
        match crate::meta_auth::DeviceCode::decode_for_test(raw) {
            Ok(c) => {
                assert_eq!(err(go), "", "device {input}");
                let v = &go["value"];
                assert_eq!(
                    (
                        c.device_code,
                        c.user_code,
                        c.verification_uri,
                        c.verification_uri_complete
                    ),
                    (
                        string(v, "device_code"),
                        string(v, "user_code"),
                        string(v, "verification_uri"),
                        string(v, "verification_uri_complete")
                    ),
                    "device {input}"
                );
                assert_eq!(
                    (c.expires_in, c.interval),
                    (int(v, "expires_in"), int(v, "interval")),
                    "device {input}"
                );
            }
            Err(e) => assert_eq!(e, err(go), "device {input}"),
        }

        let go = &case["token"];
        let (t, result) = crate::meta_auth::TokenData::decode_for_test(raw);
        assert_eq!(result.err().unwrap_or_default(), err(go), "token {input}");
        let v = &go["value"];
        assert_eq!(
            (t.access_token, t.token_type, t.error, t.error_description),
            (
                string(v, "access_token"),
                string(v, "token_type"),
                string(v, "error"),
                string(v, "error_description")
            ),
            "token {input}"
        );
        assert_eq!(
            (t.expires_in, t.expires_at),
            (int(v, "expires_in"), int(v, "expires_at")),
            "token {input}"
        );

        let go = &case["mint"];
        match MintedKey::decode(raw) {
            Ok(m) => {
                assert_eq!(err(go), "", "mint {input}");
                let v = &go["value"];
                assert_eq!(
                    (
                        m.api_key,
                        m.base_url,
                        m.user_email,
                        m.user_full_name,
                        m.subs_tier_name,
                        m.subs_tier_id
                    ),
                    (
                        string(v, "api_key"),
                        string(v, "base_url"),
                        string(v, "user_email"),
                        string(v, "user_full_name"),
                        string(v, "subs_tier_name"),
                        string(v, "subs_tier_id")
                    ),
                    "mint {input}"
                );
                assert_eq!(
                    (
                        m.is_subs_active,
                        m.has_payment_method,
                        m.require_payment,
                        m.can_subscribe
                    ),
                    (
                        boolean(v, "is_subs_active"),
                        boolean(v, "has_payment_method"),
                        boolean(v, "require_payment"),
                        boolean(v, "can_subscribe")
                    ),
                    "mint {input}"
                );
            }
            Err(e) => assert_eq!(e, err(go), "mint {input}"),
        }
    }
}

#[test]
fn syntax_errors_quote_every_byte_like_go() {
    // json.Unmarshal of each single byte: scanner messages and quoteChar.
    let fx = fixture("meta", "decode");
    for case in fx["extra"]["bytes"].as_array().unwrap() {
        let byte = case["byte"].as_u64().unwrap() as u8;
        let go = case["err"].as_str().unwrap();
        let rust = crate::meta_wire::check_valid(&[byte]);
        if go.starts_with("json: cannot unmarshal") {
            assert_eq!(rust, Ok(()), "byte {byte}");
        } else {
            assert_eq!(rust.unwrap_err(), go, "byte {byte}");
        }
    }
}

#[tokio::test]
async fn poll_errors_use_go_partial_decoding_and_key_folding() {
    // `{"error":5,"ERROR":"access_denied"}`: Go records the type error, keeps decoding,
    // and the folded key still denies access.
    let device = json!({"status":200,"body":r#"{"DEVICE_CODE":"d","User_Code":"u","interval":1}"#});
    let mock = Mock::start(&json!([device, {"status":400,"body":r#"{"error":5,"ERROR":"access_denied"}"#}])).await;
    let auth = login_auth(&mock.url);
    let code = auth.start_device_flow().await.unwrap();
    assert_eq!(
        auth.wait_for_authorization(&code).await.unwrap_err(),
        "meta auth: access was denied by user"
    );
    // A null mint body decodes to an empty record: Go's "missing api_key".
    let mock = Mock::start(
        &json!([{"status":200,"body":"null"}, {"status":200,"body":r#"{"api_key":"first","api_key":"second"}"#}]),
    )
    .await;
    let auth = login_auth(&mock.url);
    assert_eq!(
        auth.mint_api_key("dca:n").await.unwrap_err().to_string(),
        "meta auth: mint response missing api_key"
    );
    assert_eq!(auth.mint_api_key("dca:d").await.unwrap().api_key, "second");
}

#[tokio::test]
async fn failed_error_body_read_is_not_classified_by_status() {
    // Go returns io.ReadAll's error before wrapMetaUpstreamError: a truncated 429 body
    // must not become a credential-wide quota cooldown.
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let url = format!("http://{}", listener.local_addr().unwrap());
    tokio::spawn(async move {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let (mut socket, _) = listener.accept().await.unwrap();
        let mut buf = vec![0u8; 65536];
        let _ = socket.read(&mut buf).await;
        let body = r#"{"error":{"message":"subscription quota exhausted","resets_at":4102444800}}"#;
        let head = format!(
            "HTTP/1.1 429 Too Many Requests\r\nContent-Length: {}\r\n\r\n",
            body.len() + 100
        );
        let _ = socket.write_all(head.as_bytes()).await;
        let _ = socket.write_all(body.as_bytes()).await;
    });
    let fx = fixture("meta", "error-429-subscription-quota");
    let origin = go_origin(&fx).unwrap();
    let credential = meta_credential(&fx, &origin, &url);
    let error = MetaExecutor::with_client(default_client())
        .execute(&credential, request(&fx, ""), &cfg())
        .await
        .err()
        .unwrap();
    assert_ne!(error.status, 429);
    assert_eq!(error.scope, FailureScope::Transport);
    assert_eq!(error.retry_after, None);
}

#[tokio::test]
async fn empty_original_request_falls_back_to_the_payload() {
    // prepareResponsesRequest: originalPayload is req.Payload when OriginalRequest is empty,
    // so response.created carries the client model with its suffix.
    let fx = fixture("meta", "responses-stream");
    let origin = go_origin(&fx).unwrap();
    let mock = Mock::start(&json!([{"status":200,"headers":[["Content-Type","text/event-stream"]],"body":"data: {\"type\":\"response.created\",\"response\":{}}\n\n"}])).await;
    let credential = meta_credential(&fx, &origin, &mock.url);
    let mut req = request(&fx, "");
    req.original_body = Bytes::new();
    let response = MetaExecutor::with_client(default_client())
        .execute(&credential, req, &cfg())
        .await
        .unwrap();
    let ResponseBody::Stream(mut stream) = response.body else {
        panic!("stream expected");
    };
    let first = stream.next().await.unwrap().unwrap();
    assert_eq!(
        String::from_utf8(first.to_vec()).unwrap(),
        "data: {\"type\":\"response.created\",\"response\":{\"model\":\"muse-spark-1.3(high)\"}}\n\n"
    );
}

#[test]
fn login_merge_skips_an_existing_file_go_cannot_decode() {
    // Manager.Login ignores an existing file whose map decode fails (float64 overflow);
    // the standalone writer keeps Go's partial map with null.
    let dir = TempDir::new();
    let bundle = meta_auth::Bundle {
        token: meta_auth::TokenData {
            access_token: "dca:x".into(),
            ..Default::default()
        },
        ..Default::default()
    };
    let name = credential_file_name("", "dca:x");
    std::fs::write(dir.path().join(&name), r#"{"type":"meta","custom":1e400,"prefix":"p"}"#).unwrap();
    let now = chrono::DateTime::parse_from_rfc3339("2026-10-02T00:00:00Z")
        .unwrap()
        .to_utc();
    let outcome = meta_auth::save_login(dir.path(), &bundle, now).unwrap();
    let written = std::fs::read_to_string(&outcome.path).unwrap();
    assert!(serde_json::from_str::<Value>(&written).is_ok(), "valid JSON: {written}");
    assert!(!written.contains("prefix") && !written.contains("custom"), "{written}");
    let storage = TokenStorage {
        access_token: "a".into(),
        ..Default::default()
    };
    assert_eq!(
        encode_token_file(&storage, None, Some(br#"{"custom":1e400,"n":1.0}"#)),
        "{\n  \"access_token\": \"a\",\n  \"auth_kind\": \"oauth\",\n  \"custom\": null,\n  \"n\": 1,\n  \"type\": \"meta\"\n}\n"
    );
}

#[tokio::test]
async fn login_skips_existing_file_with_an_overwritten_overflow() {
    // Go records the 1e400 decode error even though "x" is overwritten by 0, so
    // Manager.Login merges nothing from the old file (no disabled, no prefix).
    let fx = fixture("meta", "login-existing-overflow");
    let mock = Mock::start(&fx["responses"]).await;
    let dir = TempDir::new();
    let go_file = fx["extra"]["file_name"].as_str().unwrap();
    std::fs::write(dir.path().join(go_file), fx["request"]["stale_file"].as_str().unwrap()).unwrap();
    let go_raw = fx["extra"]["file_raw"].as_str().unwrap();
    let now = chrono::DateTime::parse_from_rfc3339(&gj::get(go_raw.as_bytes(), "last_refresh").str())
        .unwrap()
        .to_utc();
    let outcome = login_with(login_auth(&mock.url).with_fixed_now(now), dir.path(), true)
        .await
        .unwrap();
    let written = std::fs::read_to_string(&outcome.path).unwrap();
    // dca_expired/dca_expires_at derive from the poll time, which differs per run.
    let strip = |s: &str| {
        let mut v: Value = serde_json::from_str(s).unwrap();
        for key in ["dca_expired", "dca_expires_at"] {
            v.as_object_mut().unwrap().remove(key);
        }
        v
    };
    assert_eq!(strip(&written), strip(go_raw));
}

#[test]
fn strict_error_body_read_surfaces_errors_past_the_kept_prefix() {
    let chunks: Vec<Result<Bytes, ExecError>> = vec![
        Ok(Bytes::from_static(b"0123456789")),
        Ok(Bytes::from_static(b"abcdef")),
        Err(ExecError::local(502, FailureScope::Transport, "unexpected EOF")),
    ];
    let body = futures_util::stream::iter(chunks).boxed();
    let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
    let error = rt.block_on(crate::kimi_http::read_all_strict(body, 4)).unwrap_err();
    assert_eq!(error.scope, FailureScope::Transport);
    let ok = futures_util::stream::iter(vec![Ok(Bytes::from_static(b"0123456789"))]).boxed();
    assert_eq!(rt.block_on(crate::kimi_http::read_all_strict(ok, 4)).unwrap(), "0123");
}

#[tokio::test]
async fn mint_errors_follow_go() {
    let mock = Mock::start(&json!([
        {"status":200,"body":r#"{"api_key":""}"#},
        {"status":200,"body":r#"{"api_key":"k","is_subs_active":"yes"}"#},
        {"status":403,"body":" denied "},
    ]))
    .await;
    let auth = login_auth(&mock.url);
    assert_eq!(
        auth.mint_api_key("dca:1").await.unwrap_err().to_string(),
        "meta auth: mint response missing api_key"
    );
    assert!(
        auth.mint_api_key("dca:2")
            .await
            .unwrap_err()
            .to_string()
            .starts_with("meta auth: parse mint response: ")
    );
    // Go: "meta auth: mint key failed (HTTP 403): denied"; the body is withheld, in every
    // formatting of the error.
    let e = auth.mint_api_key("dca:3").await.unwrap_err();
    crate::kimi_fixture::assert_go_message_without_body(
        "mint 403",
        &e.to_string(),
        "meta auth: mint key failed (HTTP 403): denied",
    );
    assert_eq!(e.redacted(), e.to_string());
    assert!(!format!("{e:?}").contains("denied"));
    assert_eq!(
        auth.mint_api_key("  ").await.unwrap_err().to_string(),
        "meta auth: missing dca token"
    );
}

#[tokio::test]
async fn apply_patch_failures_end_meta_streams_like_go() {
    // Go's Meta loop: StopApplyPatchStream after each translated line; at EOF only the
    // translator's flush (no FinalizeApplyPatchStream, no [DONE]).
    async fn run(lines: Vec<&'static str>, fail_on_finalize: bool) -> (Vec<String>, Vec<String>) {
        let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let translator = Box::new(crate::kimi_fixture::PatchProbe {
            failed: false,
            fail_on_finalize,
            log: log.clone(),
        });
        let upstream =
            futures_util::stream::iter(lines.into_iter().map(|l| Ok(Bytes::from_static(l.as_bytes())))).boxed();
        let inactive = cpa_translate::apply_patch_responses::State::new(Format::OpenAIResponse, b"{}", b"{}");
        let out: Vec<String> = stream_events(
            upstream,
            translator,
            crate::gemini_stream::ClaudeInputTokens::new(
                Format::OpenAIResponse,
                Format::Codex,
                Format::OpenAIResponse,
                Bytes::new(),
            ),
            false,
            inactive,
            Default::default(),
            Default::default(),
        )
        .map(|item| match item {
            Ok(b) => String::from_utf8(b.to_vec()).unwrap(),
            Err(e) => format!("ERR {} {}", e.status, String::from_utf8_lossy(&e.body)),
        })
        .collect()
        .await;
        let log = log.lock().unwrap().clone();
        (out, log)
    }
    let patch = format!("ERR 502 {}", cpa_translate::APPLY_PATCH_UPSTREAM_ERROR);
    let (out, log) = run(
        vec!["data: {\"a\":1}", "data: {\"BAD_PATCH\":1}", "data: {\"c\":1}"],
        false,
    )
    .await;
    assert_eq!(
        out,
        [
            "frame data: {\"a\":1}",
            "frame data: {\"BAD_PATCH\":1}",
            "flushed",
            patch.as_str()
        ]
    );
    assert_eq!(log.len(), 2);
    let (out, log) = run(vec!["data: {\"a\":1}"], true).await;
    assert_eq!(out, ["frame data: {\"a\":1}", "finished"]);
    assert_eq!(log, ["event data: {\"a\":1}", "finish"]);
}

#[tokio::test]
async fn usage_reports_match_go_records() {
    for name in [
        "responses-nonstream-collected",
        "responses-stream",
        "responses-nonstream-json-body",
        "stream-error-event",
        "nonstream-response-failed",
        "nonstream-incomplete-fallback-items",
        "payload-rules-and-headers",
        "remint-from-dca",
        "error-429-plain",
        "apply-patch-stream",
        "apply-patch-nonstream",
        "apply-patch-invalid-stream",
        "apply-patch-invalid-nonstream",
        "apply-patch-eof-stream",
        "stream-completed-then-error",
        "stream-done-only",
        "apply-patch-stream-event-lines",
        "stream-tier-merge",
        "stream-nbsp-data",
        "claude-stream-input-estimate",
    ] {
        let r = run(name).await;
        let failure = r.error.as_ref().map(crate::kimi_fixture::go_failure);
        crate::kimi_fixture::assert_usage_like_go(name, &r.fx, &r.usage, failure.as_ref());
    }
}

#[tokio::test]
async fn request_capture_matches_go() {
    // meta_executor_execute.go's recordMetaRequest site with its response metadata,
    // chunks and errors, rendered as Go's request log and compared with Go's text.
    let names = crate::kimi_fixture::captured_fixtures("meta");
    assert!(names.len() >= 30, "{names:?}");
    for name in names.iter().filter(|n| n.as_str() != "refresh-direct") {
        let r = run(name).await;
        crate::kimi_fixture::assert_capture_like_go(name, &r.fx, &r.capture, &r.url, &["Host"]);
    }
}

/// Go ignores a refusal only the original (baseline) body hits
/// (TranslateRequestWithAPIKeyModelCompatibility returns no error): the working body is
/// the one sent, and only its own refusal refuses the request.
#[tokio::test]
async fn a_refused_baseline_alone_does_not_refuse_the_request() {
    let fx = fixture("meta", "responses-nonstream-collected");
    let origin = go_origin(&fx).unwrap();
    let hi = br#"{"model":"muse-spark-1.3","max_tokens":16,"messages":[{"role":"user","content":[{"type":"text","text":"hi"}]}]}"#;
    let refused = br#"{"model":"muse-spark-1.3","max_tokens":16,"messages":[{"role":"user","content":[{"type":"container_upload","source":{"type":"file","file_id":"f1"}}]}]}"#;
    for baseline_only in [true, false] {
        let mock = Mock::start(&fx["responses"]).await;
        let credential = meta_credential(&fx, &origin, &mock.url);
        let mut req = request(&fx, "");
        req.source_format = Format::Claude;
        req.response_format = Format::Claude;
        let (body, original): (&'static [u8], &'static [u8]) =
            if baseline_only { (hi, refused) } else { (refused, hi) };
        req.body = Bytes::from_static(body);
        req.original_body = Bytes::from_static(original);
        let result = MetaExecutor::with_client(default_client())
            .execute(&credential, req, &cfg())
            .await;
        assert_eq!(result.is_ok(), baseline_only, "baseline_only={baseline_only}");
        let captured = mock.captured();
        assert_eq!(captured.len(), usize::from(baseline_only));
        if let Some(sent) = captured.first() {
            assert!(String::from_utf8_lossy(&sent.body).contains(r#""text":"hi""#));
        }
    }
}