wiremux 0.11.0

Wiremux maps Chat Completions, Messages, Responses, Gemini, and Converse through one IR.
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
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
//! Shared CLI helpers: profile flag, validate, login, status.

use std::io::{Read, Write};
use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener};
use std::time::Duration;

use wiremux_auth::{
    AnyTokenProvider, AuthScheme, LoadOptions, Login, OauthPack, ProfileError, ResolvedProfile,
    TokenProvider, Wire, list_profiles, load_profile_from_cli, persist_login_tokens,
    provider_from_profile, redact_secret_looking, redact_url_origin, sanitize_oauth_error_text,
};

/// Process exit: success.
pub const EXIT_OK: i32 = 0;
/// Process exit: hard error.
pub const EXIT_ERROR: i32 = 1;
/// Process exit: not-ready (setup-token / empty client_id / login=none).
pub const EXIT_NOT_READY: i32 = 2;

/// Load `--profile` as an id or a file path.
pub fn load_cli_profile(profile_arg: &str) -> Result<ResolvedProfile, ProfileError> {
    load_profile_from_cli(profile_arg, &LoadOptions::default())
}

/// Resolve `auth login` / `auth status` profile from `--profile` or a
/// positional id (`profile validate` is already positional).
pub fn pick_auth_profile(
    flag: Option<String>,
    positional: Option<String>,
) -> Result<String, String> {
    match (flag, positional) {
        (Some(flag), Some(positional)) if flag != positional => {
            Err("pass a profile id or --profile, not both (values differ)".into())
        }
        (Some(profile), _) | (None, Some(profile)) => Ok(profile),
        (None, None) => Err("profile id required (positional or --profile)".into()),
    }
}

/// Catalog ids from shipped presets plus user overlay dirs.
pub fn list_cli_profiles() -> Result<Vec<String>, ProfileError> {
    list_profiles(&LoadOptions::default())
}

/// Gist lint output: resolved URLs with secrets redacted.
pub fn validate_report(profile: &ResolvedProfile) -> String {
    let mut lines = Vec::new();
    lines.push(format!("id: {}", profile.id));
    lines.push(format!("schema_version: {}", profile.schema_version));
    if let Some(wire) = profile.dialect.wire {
        lines.push(format!("wire: {}", wire_name(wire)));
    }
    push_url(&mut lines, "base_url", profile.http.base_url.as_deref());
    push_url(&mut lines, "chat_path", profile.http.chat_path.as_deref());
    if let Some(oauth) = &profile.oauth {
        push_url(
            &mut lines,
            "oauth.token_url",
            Some(oauth.token_url.as_str()),
        );
        push_url(
            &mut lines,
            "oauth.token_url_fallback",
            oauth.token_url_fallback.as_deref(),
        );
        push_url(
            &mut lines,
            "oauth.authorize_url",
            oauth.authorize_url.as_deref(),
        );
        push_url(
            &mut lines,
            "oauth.device_auth_url",
            oauth.device_auth_url.as_deref(),
        );
        push_url(
            &mut lines,
            "oauth.redirect_uri",
            oauth.redirect_uri.as_deref(),
        );
    }
    lines.join("\n")
}

fn push_url(lines: &mut Vec<String>, field: &str, value: Option<&str>) {
    let Some(value) = value.filter(|s| !s.is_empty()) else {
        return;
    };
    lines.push(format!("{field}: {}", redact_printed_url(value)));
}

fn redact_printed_url(raw: &str) -> String {
    if raw.contains("://") {
        redact_secret_looking(&redact_url_origin(raw))
    } else {
        redact_secret_looking(raw)
    }
}

/// What `auth login` should do for this profile.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LoginPlan {
    /// Print hint and exit 2.
    SetupToken {
        /// Free-text hint from the profile.
        hint: String,
    },
    /// Print why and exit 2.
    NotReady {
        /// Human-readable reason.
        reason: String,
    },
    /// Try loopback PKCE (device fallback if bind fails).
    Pkce,
    /// Device authorization grant.
    Device,
}

/// Decide login without talking to a vendor.
pub fn login_plan(profile: &ResolvedProfile) -> LoginPlan {
    let Some(oauth) = profile.oauth.as_ref() else {
        return LoginPlan::NotReady {
            reason: "profile has no [oauth] table".into(),
        };
    };
    let client_id = oauth.client_id.as_deref().unwrap_or("");
    let login = oauth.login.unwrap_or(Login::None);
    match login {
        Login::SetupToken => LoginPlan::SetupToken {
            hint: redact_secret_looking(
                &oauth
                    .setup_token_hint
                    .clone()
                    .filter(|s| !s.trim().is_empty())
                    .unwrap_or_else(|| "run the vendor setup-token command".into()),
            ),
        },
        Login::None => {
            let mut reason = String::from(
                "oauth.login is none (set pkce or device; shipped openai-codex-oauth stays none until an overlay sets login)",
            );
            if client_id.is_empty() {
                reason.push_str(" and client_id is empty (set a wiremux client id)");
            }
            LoginPlan::NotReady { reason }
        }
        Login::Pkce | Login::Device => {
            if client_id.is_empty() {
                LoginPlan::NotReady {
                    reason:
                        "oauth.client_id is empty after subst (set it in the profile or overlay)"
                            .into(),
                }
            } else if matches!(login, Login::Device) {
                LoginPlan::Device
            } else {
                LoginPlan::Pkce
            }
        }
    }
}

/// Run `auth login`. Returns a process exit code.
pub async fn run_login(profile: &ResolvedProfile) -> i32 {
    match login_plan(profile) {
        LoginPlan::SetupToken { hint } => {
            println!("{hint}");
            EXIT_NOT_READY
        }
        LoginPlan::NotReady { reason } => {
            eprintln!("{reason}");
            EXIT_NOT_READY
        }
        LoginPlan::Pkce => match run_pkce_or_device(profile).await {
            Ok(()) => EXIT_OK,
            Err(err) => {
                eprintln!("{err}");
                EXIT_ERROR
            }
        },
        LoginPlan::Device => {
            if let Some(note) = copilot_tos_note(profile) {
                println!("{note}");
            }
            match run_device(profile).await {
                Ok(()) => EXIT_OK,
                Err(err) => {
                    eprintln!("{err}");
                    EXIT_ERROR
                }
            }
        }
    }
}

async fn run_pkce_or_device(profile: &ResolvedProfile) -> Result<(), String> {
    let oauth = profile.oauth.as_ref().ok_or("missing [oauth]")?;
    let redirect = oauth
        .redirect_uri
        .as_deref()
        .ok_or("oauth.redirect_uri is required for PKCE")?;
    match bind_redirect(redirect) {
        Ok(listener) => run_pkce(oauth, listener).await,
        Err(bind_err) => {
            if oauth.device_auth_url.is_some() {
                eprintln!("loopback bind failed ({bind_err}); falling back to device flow");
                run_device(profile).await
            } else {
                Err(format!(
                    "loopback bind failed on {redirect} ({bind_err}); device_auth_url not set"
                ))
            }
        }
    }
}

fn bind_redirect(redirect_uri: &str) -> Result<TcpListener, String> {
    let addr = redirect_bind_addr(redirect_uri)?;
    TcpListener::bind(addr).map_err(|e| e.to_string())
}

/// Loopback host + port from a redirect URI. Only 127.0.0.1 / localhost.
pub fn redirect_bind_addr(redirect_uri: &str) -> Result<SocketAddr, String> {
    let rest = redirect_uri
        .strip_prefix("http://")
        .or_else(|| redirect_uri.strip_prefix("https://"))
        .ok_or_else(|| format!("redirect_uri must be http(s): {redirect_uri}"))?;
    let hostport = rest.split(['/', '?', '#']).next().unwrap_or(rest);
    let (host, port) = match hostport.rsplit_once(':') {
        Some((h, p)) => (h, p),
        None => (hostport, "80"),
    };
    let host = host.trim_start_matches('[').trim_end_matches(']');
    if host != "127.0.0.1" && !host.eq_ignore_ascii_case("localhost") {
        return Err(format!(
            "PKCE redirect_uri host must be 127.0.0.1 or localhost, got {host}"
        ));
    }
    let port: u16 = port
        .parse()
        .map_err(|_| format!("invalid redirect_uri port: {port}"))?;
    Ok(SocketAddr::from((Ipv4Addr::LOCALHOST, port)))
}

async fn run_pkce(oauth: &OauthPack, listener: TcpListener) -> Result<(), String> {
    use wiremux_auth::pkce::{build_auth_url_from_oauth, exchange_auth_code, generate_pkce};

    let pkce = generate_pkce().map_err(|e| e.to_string())?;
    let url = build_auth_url_from_oauth(oauth, &pkce).map_err(|e| e.to_string())?;
    println!("Open this URL to authorize:\n{url}");
    let local = listener.local_addr().map_err(|e| e.to_string())?;
    println!("Waiting for loopback callback on {local}");
    let _ = std::io::stdout().flush();
    listener.set_nonblocking(false).map_err(|e| e.to_string())?;
    let (mut stream, _) = listener.accept().map_err(|e| e.to_string())?;
    stream
        .set_read_timeout(Some(Duration::from_secs(5 * 60)))
        .ok();
    let mut buf = [0u8; 8192];
    let n = stream.read(&mut buf).map_err(|e| e.to_string())?;
    let req = String::from_utf8_lossy(&buf[..n]);
    let first = req.lines().next().unwrap_or("");
    let target = first.split_whitespace().nth(1).unwrap_or("");
    let query = target.split_once('?').map(|(_, q)| q).unwrap_or("");
    let code = reply_to_pkce_callback(&mut stream, query, &pkce.state)?;
    let redirect = oauth.redirect_uri.as_deref().unwrap_or("");
    let client_id = oauth.client_id.as_deref().unwrap_or("");
    let saved = async {
        let tokens = exchange_auth_code(
            &oauth.token_url,
            client_id,
            &code,
            redirect,
            &pkce.code_verifier,
        )
        .await
        .map_err(|e| e.to_string())?;
        persist_login_tokens(oauth, &tokens)
            .await
            .map_err(|e| e.to_string())
    }
    .await;
    let (ok, body) = pkce_browser_after_save(saved.map(|_| ()));
    write_pkce_browser(&mut stream, ok, &body);
    if !ok {
        return Err(body);
    }
    println!("login saved");
    Ok(())
}

fn copilot_tos_note(profile: &ResolvedProfile) -> Option<String> {
    let oauth = profile.oauth.as_ref()?;
    if oauth.creds_format != Some(wiremux_auth::CredsFormat::CopilotHosts) {
        return None;
    }
    Some("GitHub Copilot product terms apply to tokens obtained with this profile.".into())
}

async fn run_device(profile: &ResolvedProfile) -> Result<(), String> {
    use wiremux_auth::device_flow::{poll_device_token, start_device_flow_from_oauth};

    let oauth = profile.oauth.as_ref().ok_or("missing [oauth]")?;
    let started = start_device_flow_from_oauth(oauth)
        .await
        .map_err(|e| e.to_string())?;
    println!(
        "Visit {} and enter {}",
        started.verification_uri, started.user_code
    );
    if let Some(complete) = started.verification_uri_complete.as_deref() {
        println!("or open {complete}");
    }
    let _ = std::io::stdout().flush();
    let client_id = oauth.client_id.as_deref().unwrap_or("");
    let headers: Vec<(&str, &str)> = oauth
        .token_headers
        .iter()
        .map(|(k, v)| (k.as_str(), v.as_str()))
        .collect();
    let tokens = poll_device_token(
        &oauth.token_url,
        client_id,
        &started.device_code,
        started.interval,
        started.expires_in,
        if headers.is_empty() {
            None
        } else {
            Some(&headers)
        },
    )
    .await
    .map_err(|e| e.to_string())?;
    persist_login_tokens(oauth, &tokens)
        .await
        .map_err(|e| e.to_string())?;
    println!("login saved");
    Ok(())
}

/// Browser page for a PKCE callback. A bad query is HTTP 400 and `Err`.
/// A matching code does not write; the success page waits until the token is saved.
fn reply_to_pkce_callback(
    stream: &mut impl Write,
    query: &str,
    expected_state: &str,
) -> Result<String, String> {
    match pkce_callback_code(query, expected_state) {
        Ok(code) => Ok(code),
        Err(err) => {
            write_pkce_browser(stream, false, &err);
            Err(err)
        }
    }
}

/// Authorization code when `query` matches `expected_state`.
pub(crate) fn pkce_callback_code(query: &str, expected_state: &str) -> Result<String, String> {
    let (code, state) = pkce_callback_from_query(query)?;
    if state != expected_state {
        return Err("callback state mismatch".into());
    }
    Ok(code)
}

fn pkce_browser_after_save(saved: Result<(), String>) -> (bool, String) {
    match saved {
        Ok(()) => (true, "ok, you can close this tab".into()),
        Err(err) => (false, redact_secret_looking(&err)),
    }
}

fn pkce_browser_response(ok: bool, body: &str) -> Vec<u8> {
    let status = if ok { "200 OK" } else { "400 Bad Request" };
    format!("HTTP/1.1 {status}\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n{body}\n")
        .into_bytes()
}

fn write_pkce_browser(stream: &mut impl Write, ok: bool, body: &str) {
    let _ = stream.write_all(&pkce_browser_response(ok, body));
}

/// Read `code`/`state` from a PKCE loopback query. Surfaces vendor `error`.
pub(crate) fn pkce_callback_from_query(query: &str) -> Result<(String, String), String> {
    let mut code = None;
    let mut state = None;
    let mut error = None;
    let mut error_description = None;
    for pair in query.split('&') {
        if pair.is_empty() {
            continue;
        }
        if let Some((k, v)) = pair.split_once('=') {
            match k {
                "code" => code = Some(url_decode(v)),
                "state" => state = Some(url_decode(v)),
                "error" => error = Some(url_decode(v)),
                "error_description" => error_description = Some(url_decode(v)),
                _ => {}
            }
        }
    }
    let code_ok = code.as_ref().is_some_and(|c| !c.is_empty());
    let state_ok = state.as_ref().is_some_and(|s| !s.is_empty());
    if code_ok && state_ok {
        return Ok((code.unwrap(), state.unwrap()));
    }
    if error.is_some() || error_description.is_some() {
        return Err(format_pkce_vendor_error(
            error.as_deref(),
            error_description.as_deref(),
        ));
    }
    if !code_ok {
        return Err("callback missing code".into());
    }
    Err("callback missing state".into())
}

fn format_pkce_vendor_error(error: Option<&str>, description: Option<&str>) -> String {
    let err = error.filter(|s| !s.is_empty()).unwrap_or("error");
    let raw = match description.filter(|s| !s.is_empty()) {
        Some(desc) => format!("{err}: {desc}"),
        None => err.to_owned(),
    };
    let summary = sanitize_oauth_error_text(&raw);
    if summary.is_empty() {
        "callback error".into()
    } else {
        format!("callback error {summary}")
    }
}

pub(crate) fn url_decode(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'+' => {
                out.push(b' ');
                i += 1;
            }
            b'%' if i + 2 < bytes.len() => {
                let hex = &bytes[i + 1..i + 3];
                if let Ok(hex) = std::str::from_utf8(hex)
                    && let Ok(v) = u8::from_str_radix(hex, 16)
                {
                    out.push(v);
                    i += 3;
                } else {
                    out.push(b'%');
                    i += 1;
                }
            }
            c => {
                out.push(c);
                i += 1;
            }
        }
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// Whether a token can be loaded. Never includes the token value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TokenStatus {
    /// Catalog id.
    pub id: String,
    /// True when a credential source yielded a token, or auth is none.
    pub available: bool,
    /// Short reason when unavailable.
    pub detail: String,
}

/// Check local credential sources. Does not print secrets.
pub async fn token_status(profile: &ResolvedProfile) -> TokenStatus {
    let aws = profile
        .http
        .aws_service
        .as_deref()
        .is_some_and(|service| !service.is_empty());
    // Auth none with aws_service still signs. SigV4 replaces Authorization
    // because bearer_token_applied is false for AuthScheme::None.
    if matches!(profile.http.auth_scheme, Some(AuthScheme::None)) && profile.oauth.is_none() && aws
    {
        return aws_chain_status(profile).await;
    }
    if profile
        .http
        .headers
        .iter()
        .any(|(k, v)| is_profile_auth_header(profile, k) && !v.trim().is_empty())
    {
        return TokenStatus {
            id: profile.id.clone(),
            available: true,
            detail: "header credential present".into(),
        };
    }
    if matches!(profile.http.auth_scheme, Some(AuthScheme::None)) && profile.oauth.is_none() {
        return TokenStatus {
            id: profile.id.clone(),
            available: true,
            detail: "auth_scheme is none".into(),
        };
    }
    let gcp = profile
        .http
        .gcp_key_env
        .as_deref()
        .is_some_and(|name| !name.is_empty());
    if profile.oauth.is_some() || !profile.access_env.is_empty() || gcp {
        match provider_from_profile(profile) {
            Ok(_) => {
                return TokenStatus {
                    id: profile.id.clone(),
                    available: true,
                    detail: "credentials loaded".into(),
                };
            }
            Err(err) if !aws => {
                return TokenStatus {
                    id: profile.id.clone(),
                    available: false,
                    detail: redact_secret_looking(&err.to_string()),
                };
            }
            Err(_) => {}
        }
    }
    if aws {
        return aws_chain_status(profile).await;
    }
    TokenStatus {
        id: profile.id.clone(),
        available: false,
        detail: "no credentials (set [headers] Authorization or x-api-key, [oauth], or auth_scheme = \"none\")".into(),
    }
}

#[cfg(any(feature = "proxy", feature = "client"))]
async fn aws_chain_status(profile: &ResolvedProfile) -> TokenStatus {
    let service = profile.http.aws_service.as_deref().unwrap_or("bedrock");
    match crate::aws_creds::resolve_aws_credentials().await {
        Ok(Some(_)) => TokenStatus {
            id: profile.id.clone(),
            available: true,
            detail: format!("aws sigv4 ({service})"),
        },
        Ok(None) => TokenStatus {
            id: profile.id.clone(),
            available: false,
            detail: crate::aws_creds::missing_creds_message(profile),
        },
        Err(err) => TokenStatus {
            id: profile.id.clone(),
            available: false,
            detail: redact_secret_looking(&err.to_string()),
        },
    }
}

/// `aws_creds` is compiled only for the proxy and client features.
#[cfg(not(any(feature = "proxy", feature = "client")))]
async fn aws_chain_status(profile: &ResolvedProfile) -> TokenStatus {
    let service = profile.http.aws_service.as_deref().unwrap_or("bedrock");
    TokenStatus {
        id: profile.id.clone(),
        available: false,
        detail: format!(
            "profile `{}` aws_service={service} needs a bearer token or IAM credentials",
            profile.id
        ),
    }
}

fn is_profile_auth_header(profile: &ResolvedProfile, name: &str) -> bool {
    crate::profile_auth::is_profile_auth_header(profile, name)
}

/// Format status without leaking the token.
pub fn format_status(status: &TokenStatus) -> String {
    if status.available && status.detail == "auth_scheme is none" {
        return format!(
            "profile: {}\ntoken: not required\n{}",
            status.id, status.detail
        );
    }
    if status.available {
        format!("profile: {}\ntoken: available", status.id)
    } else {
        format!(
            "profile: {}\ntoken: unavailable\n{}",
            status.id, status.detail
        )
    }
}

/// `127.0.0.1` only. `localhost` is that address. Ephemeral port allowed.
pub fn parse_listen(s: &str) -> Result<SocketAddr, String> {
    let candidate = match s.rsplit_once(':') {
        Some((host, port)) if host.eq_ignore_ascii_case("localhost") => {
            format!("127.0.0.1:{port}")
        }
        _ => s.to_string(),
    };
    let addr: SocketAddr = candidate
        .parse()
        .map_err(|_| format!("proxy listen address must be 127.0.0.1 ({s})"))?;
    match addr.ip() {
        IpAddr::V4(ip) if ip == Ipv4Addr::LOCALHOST => Ok(addr),
        _ => Err(format!("proxy listen address must be 127.0.0.1 ({s})")),
    }
}

/// Parse `--from` dialect name (`chat-completions` / `chat`, `messages`, `responses`, `gemini`, `converse`).
pub fn parse_wire(s: &str) -> Result<Wire, String> {
    match s {
        "responses" => Ok(Wire::Responses),
        "messages" => Ok(Wire::Messages),
        "chat-completions" | "chat" => Ok(Wire::ChatCompletions),
        "gemini" => Ok(Wire::Gemini),
        "converse" => Ok(Wire::Converse),
        other => {
            let listed = "responses|messages|chat-completions|gemini|converse";
            let mut msg = format!("unknown --from `{other}` ({listed})");
            if let Some(suggest) = suggest_from(other) {
                msg.push_str(&format!("; did you mean `{suggest}`"));
            }
            Err(msg)
        }
    }
}

fn suggest_from(s: &str) -> Option<&'static str> {
    if let Some(name) = Wire::suggest(s) {
        return Some(name);
    }
    let folded: String = s
        .chars()
        .filter(|c| *c != '_' && *c != '-')
        .flat_map(char::to_lowercase)
        .collect();
    if folded.starts_with("chat") {
        Some("chat")
    } else {
        None
    }
}

pub fn wire_name(wire: Wire) -> &'static str {
    match wire {
        Wire::ChatCompletions => "chat-completions",
        Wire::Messages => "messages",
        Wire::Responses => "responses",
        Wire::Gemini => "gemini",
        Wire::Converse => "converse",
        _ => wire.as_str(),
    }
}

/// Resolve an API token for the proxy. Empty means send no auth header.
pub async fn proxy_token(
    profile: &ResolvedProfile,
    provider: &AnyTokenProvider,
) -> Result<Option<String>, String> {
    if matches!(profile.http.auth_scheme, Some(AuthScheme::None)) && profile.oauth.is_none() {
        return Ok(None);
    }
    if let Some((_, value)) = profile
        .http
        .headers
        .iter()
        .find(|(k, v)| is_profile_auth_header(profile, k) && !v.trim().is_empty())
    {
        let token = value
            .strip_prefix("Bearer ")
            .or_else(|| value.strip_prefix("bearer "))
            .unwrap_or(value)
            .to_string();
        return Ok(Some(token));
    }
    if profile.oauth.is_some() || !profile.access_env.is_empty() || provider_has_token(provider) {
        let token = provider.get_token().await.map_err(|e| e.to_string())?;
        if token.trim().is_empty() {
            return Ok(None);
        }
        return Ok(Some(token));
    }
    Ok(None)
}

fn provider_has_token(provider: &AnyTokenProvider) -> bool {
    !matches!(provider, AnyTokenProvider::Static(_))
}

pub use crate::upstream::upstream_url_for_model;

/// Join `base_url` + `chat_path` for the upstream request.
pub fn upstream_url(profile: &ResolvedProfile) -> Result<String, String> {
    upstream_url_for_model(profile, None, false)
}

#[cfg(test)]
mod tests {
    use super::*;
    use wiremux_auth::{AnyTokenProvider, IsolatedHome, StaticToken, parse_profile_str};

    #[test]
    fn redact_printed_url_keeps_origin_only() {
        let redacted = redact_printed_url(
            "https://user:s3cret@api.example.invalid/v1?api_key=supersecret#frag",
        );
        assert_eq!(redacted, "https://api.example.invalid");
        assert!(!redacted.contains("s3cret"));
        assert!(!redacted.contains("supersecret"));
        assert!(!redacted.contains("/v1"));
    }

    fn shipped(id: &str) -> ResolvedProfile {
        wiremux_auth::load_profile(
            id,
            &LoadOptions {
                include_user_config: false,
                ..LoadOptions::default()
            },
        )
        .expect("shipped")
    }

    #[test]
    fn login_plan_anthropic_is_setup_token() {
        let profile = shipped("anthropic-oauth");
        match login_plan(&profile) {
            LoginPlan::SetupToken { hint } => {
                assert!(hint.contains("claude setup-token"));
            }
            other => panic!("expected setup-token, got {other:?}"),
        }
    }

    #[test]
    fn login_plan_copilot_gist_device_needs_client_id() {
        let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../wiremux-auth/tests/gists/github-copilot-device.toml");
        let profile =
            parse_profile_str(&std::fs::read_to_string(&path).expect("gist")).expect("parse");
        match login_plan(&profile) {
            LoginPlan::NotReady { reason } => {
                assert!(
                    reason.contains("oauth.client_id"),
                    "device/pkce empty client_id must name oauth.client_id, got {reason}"
                );
                assert!(
                    reason.contains("empty after subst"),
                    "must say empty after subst, got {reason}"
                );
                assert!(
                    reason.contains("profile") && reason.contains("overlay"),
                    "must say set it in the profile or overlay, got {reason}"
                );
            }
            other => panic!("empty client_id must be not-ready, got {other:?}"),
        }
        assert_eq!(
            profile.oauth.as_ref().and_then(|o| o.creds_format),
            Some(wiremux_auth::CredsFormat::CopilotHosts)
        );
        assert!(
            copilot_tos_note(&profile)
                .unwrap()
                .contains("Copilot product terms")
        );
    }

    #[test]
    fn login_plan_openai_is_not_ready() {
        let profile = shipped("openai-codex-oauth");
        match login_plan(&profile) {
            LoginPlan::NotReady { reason } => {
                assert_login_none_names_field_and_values(&reason);
                assert!(
                    reason.contains("client_id"),
                    "openai login plan must keep the empty-client_id hint, got {reason}"
                );
            }
            other => panic!("expected not-ready, got {other:?}"),
        }
    }

    #[test]
    fn login_plan_none_with_client_id_names_oauth_login() {
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "x"
[oauth]
token_url = "https://auth.example.invalid/token"
client_id = "already-set"
login = "none"
"#,
        )
        .expect("parse");
        match login_plan(&profile) {
            LoginPlan::NotReady { reason } => {
                assert_login_none_names_field_and_values(&reason);
                assert!(
                    !reason.contains("client_id is empty"),
                    "set client_id must not keep the empty-client_id hint, got {reason}"
                );
            }
            other => panic!("expected not-ready, got {other:?}"),
        }
    }

    fn assert_login_none_names_field_and_values(reason: &str) {
        assert!(
            reason.contains("oauth.login"),
            "login=none must name oauth.login, got {reason}"
        );
        assert!(
            reason.contains("pkce") && reason.contains("device"),
            "login=none must list pkce and device, got {reason}"
        );
        assert!(
            reason.contains("openai-codex-oauth"),
            "must say shipped openai-codex-oauth stays none, got {reason}"
        );
        assert!(
            reason.contains("overlay"),
            "must say overlay sets login, got {reason}"
        );
    }

    #[test]
    fn pick_auth_profile_accepts_positional_or_flag() {
        assert_eq!(
            pick_auth_profile(None, Some("anthropic-oauth".into())).unwrap(),
            "anthropic-oauth"
        );
        assert_eq!(
            pick_auth_profile(Some("openai-codex".into()), None).unwrap(),
            "openai-codex"
        );
        assert_eq!(
            pick_auth_profile(Some("xai-oauth".into()), Some("xai-oauth".into())).unwrap(),
            "xai-oauth"
        );
        let err = pick_auth_profile(None, None).expect_err("neither");
        assert!(
            err.contains("positional") && err.contains("--profile"),
            "{err}"
        );
        let err = pick_auth_profile(Some("a".into()), Some("b".into())).expect_err("both");
        assert!(err.contains("not both"), "{err}");
    }

    #[test]
    fn parse_wire_accepts_gemini() {
        assert_eq!(parse_wire("gemini").unwrap(), Wire::Gemini);
        assert_eq!(wire_name(Wire::Gemini), "gemini");
    }

    #[test]
    fn parse_wire_typo_suggests_close_matches() {
        assert_eq!(parse_wire("chat").unwrap(), Wire::ChatCompletions);

        for (input, want) in [
            ("chat_completions", "chat-completions"),
            ("ChatCompletions", "chat-completions"),
            ("response", "responses"),
            ("chatt", "chat"),
        ] {
            let err = parse_wire(input).expect_err(input);
            assert!(
                err.contains(&format!("unknown --from `{input}`")),
                "{input} must echo the unknown value, got {err}"
            );
            assert!(
                err.contains("responses")
                    && err.contains("messages")
                    && err.contains("chat-completions")
                    && err.contains("gemini"),
                "{input} must list legal --from values, got {err}"
            );
            assert!(
                err.to_ascii_lowercase().contains("did you mean")
                    && err.contains(&format!("`{want}`")),
                "{input} should suggest {want}, got {err}"
            );
        }
    }

    #[test]
    fn gemini_upstream_url_substitutes_model() {
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "g"
wire = "gemini"
base_url = "https://generativelanguage.googleapis.com"
"#,
        )
        .expect("parse");
        let url = upstream_url_for_model(&profile, Some("gemini-2.5-flash"), false).expect("url");
        assert!(
            url.ends_with("/v1beta/models/gemini-2.5-flash:generateContent"),
            "{url}"
        );
        let stream = upstream_url_for_model(&profile, Some("gemini-2.5-flash"), true).expect("url");
        assert!(
            stream.ends_with("/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"),
            "{stream}"
        );
    }

    #[test]
    fn missing_model_does_not_call_the_placeholder() {
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "g"
wire = "gemini"
base_url = "https://generativelanguage.googleapis.com"
"#,
        )
        .expect("parse");
        for model in [None, Some("")] {
            let err = upstream_url_for_model(&profile, model, false)
                .expect_err("placeholder must not be a url");
            assert!(
                err.contains("{model}"),
                "missing model must name the placeholder, got {err}"
            );
        }
        let fixed = parse_profile_str(
            r#"
schema_version = 1
id = "c"
wire = "chat-completions"
base_url = "https://example.invalid"
chat_path = "/v1/chat/completions"
"#,
        )
        .expect("parse fixed");
        let url = upstream_url_for_model(&fixed, None, false).expect("fixed path");
        assert!(url.ends_with("/v1/chat/completions"), "{url}");
        assert!(!url.contains("{model}"), "{url}");
        let absolute = parse_profile_str(
            r#"
schema_version = 1
id = "c"
wire = "chat-completions"
base_url = "https://example.invalid"
chat_path = "HTTPS://api.example/v1/chat/completions"
"#,
        )
        .expect("uppercase scheme parses");
        let url = upstream_url_for_model(&absolute, None, false).expect("absolute");
        assert_eq!(
            url, "HTTPS://api.example/v1/chat/completions",
            "an absolute chat_path must not be joined onto base_url, got {url}"
        );
    }

    #[test]
    fn model_segment_encodes_slash_query_and_fragment() {
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "g"
wire = "gemini"
base_url = "https://generativelanguage.googleapis.com"
"#,
        )
        .expect("parse");
        let traversed = upstream_url_for_model(&profile, Some("../x"), false).expect("url");
        assert!(
            traversed.contains("/v1beta/models/..%2Fx:generateContent"),
            "slash in model must stay one segment, got {traversed}"
        );
        assert!(
            !traversed.contains("/models/../x"),
            "unencoded traversal must not appear, got {traversed}"
        );
        let query = upstream_url_for_model(&profile, Some("a?b"), false).expect("url");
        assert!(
            query.contains("/v1beta/models/a%3Fb:generateContent"),
            "query delimiter must encode, got {query}"
        );
        assert!(!query.contains("?b:generateContent"), "{query}");
        let frag = upstream_url_for_model(&profile, Some("a#b"), false).expect("url");
        assert!(
            frag.contains("/v1beta/models/a%23b:generateContent"),
            "fragment delimiter must encode, got {frag}"
        );
        let percent = upstream_url_for_model(&profile, Some("a%b"), false).expect("url");
        assert!(
            percent.contains("/v1beta/models/a%25b:generateContent"),
            "percent must encode, got {percent}"
        );
        let backslash = upstream_url_for_model(&profile, Some("a\\b"), false).expect("url");
        assert!(
            backslash.contains("/v1beta/models/a%5Cb:generateContent"),
            "backslash must encode, got {backslash}"
        );
        let control = upstream_url_for_model(&profile, Some("a\nb"), false).expect("url");
        assert!(
            control.contains("/v1beta/models/a%0Ab:generateContent"),
            "control must encode, got {control}"
        );
    }

    #[test]
    fn bedrock_arn_model_encodes_slash_as_one_segment() {
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "amazon-bedrock"
wire = "converse"
base_url = "https://bedrock-runtime.us-east-1.amazonaws.com"
chat_path = "/model/{model}/converse"
"#,
        )
        .expect("parse");
        let arn = "arn:aws:bedrock:us-east-1:123:inference-profile/us.anthropic.claude";
        let url = upstream_url_for_model(&profile, Some(arn), false).expect("url");
        assert!(
            url.ends_with(
                "/model/arn:aws:bedrock:us-east-1:123:inference-profile%2Fus.anthropic.claude/converse"
            ),
            "{url}"
        );
    }

    #[test]
    fn converse_stream_url_uses_converse_stream() {
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "amazon-bedrock"
wire = "converse"
base_url = "https://bedrock-runtime.us-east-1.amazonaws.com"
chat_path = "/model/{model}/converse"
"#,
        )
        .expect("parse");
        let url =
            upstream_url_for_model(&profile, Some("amazon.nova-lite-v1:0"), false).expect("url");
        assert!(
            url.ends_with("/model/amazon.nova-lite-v1:0/converse"),
            "{url}"
        );
        let stream =
            upstream_url_for_model(&profile, Some("amazon.nova-lite-v1:0"), true).expect("stream");
        assert!(
            stream.ends_with("/model/amazon.nova-lite-v1:0/converse-stream"),
            "{stream}"
        );
    }

    #[test]
    fn vertex_global_host_rewrites_to_aiplatform() {
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "vertex-gemini-global"
wire = "gemini"
base_url = "https://global-aiplatform.googleapis.com"
chat_path = "/v1/projects/p/locations/global/publishers/google/models/{model}:generateContent"
"#,
        )
        .expect("parse");
        let url = upstream_url_for_model(&profile, Some("gemini-2.5-flash"), false).expect("url");
        assert!(
            url.starts_with("https://aiplatform.googleapis.com/"),
            "global host must drop the global- prefix, got {url}"
        );
        assert!(
            !url.contains("global-aiplatform.googleapis.com"),
            "joined URL must not keep the invalid global host, got {url}"
        );
        assert!(
            url.contains("/locations/global/"),
            "path must keep /locations/global/, got {url}"
        );
        assert!(
            url.ends_with("/v1/projects/p/locations/global/publishers/google/models/gemini-2.5-flash:generateContent"),
            "{url}"
        );
    }

    #[test]
    fn vertex_regional_host_stays_prefixed() {
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "vertex-gemini-regional"
wire = "gemini"
base_url = "https://us-central1-aiplatform.googleapis.com"
chat_path = "/v1/projects/p/locations/us-central1/publishers/google/models/{model}:generateContent"
"#,
        )
        .expect("parse");
        let url = upstream_url_for_model(&profile, Some("gemini-2.5-flash"), false).expect("url");
        assert!(
            url.starts_with("https://us-central1-aiplatform.googleapis.com/"),
            "regional host must stay prefixed, got {url}"
        );
        assert!(url.contains("/locations/us-central1/"), "{url}");
    }

    #[test]
    fn vertex_messages_stream_rewrites_raw_predict() {
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "vertex-anthropic"
wire = "messages"
base_url = "https://us-central1-aiplatform.googleapis.com"
chat_path = "/v1/projects/p/locations/us-central1/publishers/anthropic/models/{model}:rawPredict"
"#,
        )
        .expect("parse");
        let unary = upstream_url_for_model(&profile, Some("claude-sonnet-4"), false).expect("url");
        assert!(
            unary.ends_with(":rawPredict"),
            "unary must stay :rawPredict, got {unary}"
        );
        assert!(
            !unary.contains(":streamRawPredict"),
            "unary must not rewrite to stream, got {unary}"
        );
        let stream =
            upstream_url_for_model(&profile, Some("claude-sonnet-4"), true).expect("stream");
        assert!(
            stream.ends_with(":streamRawPredict"),
            "stream=true must rewrite :rawPredict to :streamRawPredict, got {stream}"
        );
        assert!(
            !stream.contains("?alt=sse"),
            "Messages Vertex stream must not add ?alt=sse, got {stream}"
        );
    }

    #[test]
    fn parse_listen_rejects_wildcard() {
        assert!(parse_listen("0.0.0.0:0").is_err());
        let addr = parse_listen("127.0.0.1:0").expect("loopback ephemeral listen");
        assert_eq!(addr, "127.0.0.1:0".parse().expect("socket addr"));
    }

    #[test]
    fn parse_listen_accepts_localhost() {
        let addr = parse_listen("localhost:8787").expect("localhost");
        assert_eq!(addr, "127.0.0.1:8787".parse().expect("socket addr"));
        let upper = parse_listen("LOCALHOST:9").expect("LOCALHOST");
        assert_eq!(upper, "127.0.0.1:9".parse().expect("socket addr"));
        let err = parse_listen("example.com:8787").expect_err("public name");
        assert!(
            err.contains("example.com:8787"),
            "error should name the input, got {err}"
        );
        assert!(parse_listen("[::1]:8787").is_err());
    }

    #[tokio::test]
    async fn token_status_access_env_is_available() {
        let _home = IsolatedHome::new();
        _home.set_env("XAI_API_KEY", "xai-status-must-not-print");
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "xai"
wire = "chat-completions"
auth_scheme = "bearer"
access_env = ["XAI_API_KEY", "GROK_API_KEY"]
base_url = "https://api.x.ai"
"#,
        )
        .expect("parse");
        let status = token_status(&profile).await;
        assert!(status.available, "{}", status.detail);
        assert!(
            !status.detail.contains("xai-status-must-not-print"),
            "status leaked the token: {}",
            status.detail
        );
    }

    #[tokio::test]
    async fn token_status_no_credentials_names_what_to_set() {
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "no-creds"
wire = "chat-completions"
base_url = "http://127.0.0.1:9"
"#,
        )
        .expect("parse");
        let status = token_status(&profile).await;
        assert!(!status.available);
        let detail = &status.detail;
        assert!(detail.contains("no credentials"), "{detail}");
        assert!(
            detail.contains("[headers]")
                && detail.contains("Authorization")
                && detail.contains("x-api-key"),
            "must name [headers] Authorization or x-api-key, got {detail}"
        );
        assert!(
            detail.contains("[oauth]"),
            "must name [oauth], got {detail}"
        );
        assert!(
            detail.contains("auth_scheme") && detail.contains("none"),
            "must name auth_scheme = none, got {detail}"
        );
        let text = format_status(&status);
        assert!(text.contains("unavailable"), "{text}");
        assert!(text.contains("[headers]"), "{text}");
    }

    #[tokio::test]
    async fn goog_api_key_header_is_the_credential() {
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "goog"
wire = "gemini"
base_url = "http://127.0.0.1"
auth_scheme = "header:x-goog-api-key"
access_env = ["GEMINI_API_KEY"]
[headers]
x-goog-api-key = "goog-secret"
"#,
        )
        .expect("parse");
        let status = token_status(&profile).await;
        assert!(status.available, "{}", status.detail);
        assert_eq!(status.detail, "header credential present");
        assert!(!format_status(&status).contains("goog-secret"));
        let provider = AnyTokenProvider::from(StaticToken::new("env-secret"));
        let token = proxy_token(&profile, &provider).await.expect("token");
        assert_eq!(token.as_deref(), Some("goog-secret"));
    }

    #[tokio::test]
    async fn token_status_none_auth_is_available() {
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "none-auth"
wire = "chat-completions"
auth_scheme = "none"
base_url = "http://127.0.0.1:9"
"#,
        )
        .expect("parse");
        let status = token_status(&profile).await;
        assert!(status.available);
        let text = format_status(&status);
        assert!(text.contains("token: not required"), "{text}");
        assert!(text.contains("auth_scheme is none"), "{text}");
        assert!(!text.contains("token: available"), "{text}");
        assert!(!text.contains("http://"));
    }

    #[cfg(any(feature = "proxy", feature = "client"))]
    #[tokio::test]
    async fn token_status_auth_none_with_aws_keys_is_sigv4() {
        let home = IsolatedHome::new();
        crate::aws_creds::clear_aws_credential_cache();
        home.set_env("AWS_ACCESS_KEY_ID", "status-probe-key");
        home.set_env("AWS_SECRET_ACCESS_KEY", "status-probe-secret");
        home.set_env("AWS_EC2_METADATA_DISABLED", "true");
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "bedrock-iam"
wire = "converse"
auth_scheme = "none"
aws_service = "bedrock"
aws_region = "us-east-1"
base_url = "https://bedrock-runtime.us-east-1.amazonaws.com"
"#,
        )
        .expect("parse");
        let status = token_status(&profile).await;
        assert!(status.available, "{}", status.detail);
        assert!(
            status.detail.contains("aws sigv4"),
            "expected sigv4, got {}",
            status.detail
        );
        let text = format_status(&status);
        assert!(!text.contains("not required"), "{text}");
        assert!(
            !status.detail.contains("status-probe-key"),
            "{}",
            status.detail
        );
        let _ = home;
    }

    #[cfg(any(feature = "proxy", feature = "client"))]
    #[tokio::test]
    async fn token_status_auth_none_without_aws_keys_names_chain() {
        let home = IsolatedHome::new();
        crate::aws_creds::clear_aws_credential_cache();
        home.set_env("AWS_EC2_METADATA_DISABLED", "true");
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "bedrock-iam"
wire = "converse"
auth_scheme = "none"
aws_service = "bedrock"
aws_region = "us-east-1"
base_url = "https://bedrock-runtime.us-east-1.amazonaws.com"
"#,
        )
        .expect("parse");
        let status = token_status(&profile).await;
        assert!(!status.available, "{}", status.detail);
        assert_eq!(
            status.detail,
            crate::aws_creds::missing_creds_message(&profile)
        );
        assert!(!status.detail.contains("not required"), "{}", status.detail);
        assert!(
            !status.detail.contains("auth_scheme is none"),
            "{}",
            status.detail
        );
        let _ = home;
    }

    #[cfg(any(feature = "proxy", feature = "client"))]
    #[tokio::test]
    async fn token_status_bedrock_bearer_falls_through_to_sigv4() {
        let home = IsolatedHome::new();
        crate::aws_creds::clear_aws_credential_cache();
        home.set_env("AWS_ACCESS_KEY_ID", "status-probe-key");
        home.set_env("AWS_SECRET_ACCESS_KEY", "status-probe-secret");
        home.set_env("AWS_EC2_METADATA_DISABLED", "true");
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "amazon-bedrock"
wire = "converse"
auth_scheme = "bearer"
access_env = ["AWS_BEARER_TOKEN_BEDROCK"]
aws_service = "bedrock"
aws_region = "us-east-1"
base_url = "https://bedrock-runtime.us-east-1.amazonaws.com"
"#,
        )
        .expect("parse");
        let status = token_status(&profile).await;
        assert!(status.available, "{}", status.detail);
        assert!(status.detail.contains("aws sigv4"), "{}", status.detail);
        assert!(
            !status.detail.contains("AWS_BEARER_TOKEN_BEDROCK"),
            "{}",
            status.detail
        );
        let _ = home;
    }

    #[cfg(any(feature = "proxy", feature = "client"))]
    #[tokio::test]
    async fn token_status_bedrock_bearer_wins_over_sigv4() {
        let home = IsolatedHome::new();
        crate::aws_creds::clear_aws_credential_cache();
        home.set_env("AWS_BEARER_TOKEN_BEDROCK", "bearer-must-not-print");
        home.set_env("AWS_ACCESS_KEY_ID", "status-probe-key");
        home.set_env("AWS_SECRET_ACCESS_KEY", "status-probe-secret");
        home.set_env("AWS_EC2_METADATA_DISABLED", "true");
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "amazon-bedrock"
wire = "converse"
auth_scheme = "bearer"
access_env = ["AWS_BEARER_TOKEN_BEDROCK"]
aws_service = "bedrock"
aws_region = "us-east-1"
base_url = "https://bedrock-runtime.us-east-1.amazonaws.com"
"#,
        )
        .expect("parse");
        let status = token_status(&profile).await;
        assert!(status.available, "{}", status.detail);
        assert_eq!(status.detail, "credentials loaded");
        assert!(!status.detail.contains("bearer-must-not-print"));
        assert!(!status.detail.contains("status-probe-key"));
        let _ = home;
    }

    #[cfg(any(feature = "proxy", feature = "client"))]
    #[tokio::test]
    async fn token_status_auth_none_aws_ignores_header() {
        let home = IsolatedHome::new();
        crate::aws_creds::clear_aws_credential_cache();
        home.set_env("AWS_ACCESS_KEY_ID", "status-probe-key");
        home.set_env("AWS_SECRET_ACCESS_KEY", "status-probe-secret");
        home.set_env("AWS_EC2_METADATA_DISABLED", "true");
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "bedrock-iam"
wire = "converse"
auth_scheme = "none"
aws_service = "bedrock"
aws_region = "us-east-1"
base_url = "https://bedrock-runtime.us-east-1.amazonaws.com"
[headers]
Authorization = "Bearer header-secret"
"#,
        )
        .expect("parse");
        let status = token_status(&profile).await;
        assert!(status.available, "{}", status.detail);
        assert!(status.detail.contains("aws sigv4"), "{}", status.detail);
        assert_ne!(status.detail, "header credential present");
        assert!(!status.detail.contains("header-secret"));
        let _ = home;
    }

    #[tokio::test]
    async fn token_status_none_auth_header_is_present() {
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "header-none"
wire = "chat-completions"
auth_scheme = "none"
base_url = "http://127.0.0.1:9"
[headers]
Authorization = "Bearer header-secret"
"#,
        )
        .expect("parse");
        let status = token_status(&profile).await;
        assert!(status.available, "{}", status.detail);
        assert_eq!(status.detail, "header credential present");
        let text = format_status(&status);
        assert!(!text.contains("not required"), "{text}");
        assert!(!text.contains("header-secret"), "{text}");
    }

    #[tokio::test]
    async fn token_status_gcp_key_file_is_loaded() {
        let home = IsolatedHome::new();
        let path = home.path().join("adc.json");
        std::fs::write(
            &path,
            r#"{"type":"authorized_user","client_id":"123.apps.googleusercontent.com","client_secret":"user-secret","refresh_token":"1//refresh-me"}"#,
        )
        .expect("write adc");
        home.set_env(
            "GOOGLE_APPLICATION_CREDENTIALS",
            path.to_str().expect("utf8"),
        );
        let profile = parse_profile_str(
            r#"
schema_version = 1
id = "vertex-adc"
wire = "gemini"
gcp_key_env = "GOOGLE_APPLICATION_CREDENTIALS"
base_url = "https://example.googleapis.com"
"#,
        )
        .expect("parse");
        let status = token_status(&profile).await;
        assert!(status.available, "{}", status.detail);
        assert_eq!(status.detail, "credentials loaded");
        assert!(!status.detail.contains("user-secret"), "{}", status.detail);
        assert!(!status.detail.contains("refresh-me"), "{}", status.detail);
        let _ = home;
    }

    #[test]
    fn format_pkce_vendor_error_redacts_secret_looking() {
        let sk = format_pkce_vendor_error(
            Some("invalid_request"),
            Some("rejected token sk-ant-oat01-LEAKED"),
        );
        assert!(!sk.contains("sk-ant-oat01-LEAKED"), "API key leaked: {sk}");
        assert!(sk.contains("invalid_request"), "{sk}");

        let jwt = format_pkce_vendor_error(
            Some("invalid_request"),
            Some("bad jwt eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIn0.sig"),
        );
        assert!(
            !jwt.contains("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"),
            "{jwt}"
        );
        assert!(!jwt.contains("eyJzdWIiOiIxIn0"), "{jwt}");
    }

    #[test]
    fn pkce_callback_surfaces_vendor_error_and_description() {
        let err = pkce_callback_from_query("error=access_denied&error_description=user+denied")
            .expect_err("vendor error query");
        assert!(
            err.contains("access_denied"),
            "callback should surface vendor error, got {err}"
        );
        assert!(
            err.contains("user denied"),
            "callback should surface error_description, got {err}"
        );
    }

    #[test]
    fn pkce_callback_accepts_code_and_state() {
        let (code, state) = pkce_callback_from_query("code=abc&state=xyz").expect("code and state");
        assert_eq!(code, "abc");
        assert_eq!(state, "xyz");
    }

    #[test]
    fn pkce_vendor_error_is_http_400_not_the_success_page() {
        let mut body = Vec::new();
        let err = reply_to_pkce_callback(
            &mut body,
            "error=access_denied&error_description=user+denied",
            "xyz",
        )
        .expect_err("vendor error");
        let text = String::from_utf8(body).expect("utf8");
        assert!(text.starts_with("HTTP/1.1 400 "), "{text}");
        assert!(text.contains("access_denied"), "{text}");
        assert!(
            !text.contains("ok, you can close this tab"),
            "failed login must not tell the browser to close, got {text}"
        );
        assert!(err.contains("access_denied"), "{err}");
    }

    #[test]
    fn pkce_state_mismatch_is_http_400() {
        let mut body = Vec::new();
        let err =
            reply_to_pkce_callback(&mut body, "code=abc&state=other", "xyz").expect_err("state");
        assert_eq!(err, "callback state mismatch");
        let text = String::from_utf8(body).expect("utf8");
        assert!(text.starts_with("HTTP/1.1 400 "), "{text}");
        assert!(text.contains("callback state mismatch"), "{text}");
        assert!(!text.contains("ok, you can close this tab"), "{text}");
    }

    #[test]
    fn pkce_matching_callback_does_not_write_the_success_page() {
        let mut body = Vec::new();
        let code = reply_to_pkce_callback(&mut body, "code=abc&state=xyz", "xyz").expect("code");
        assert_eq!(code, "abc");
        assert!(
            body.is_empty(),
            "success page waits until the token is saved, wrote {body:?}"
        );
    }

    #[test]
    fn pkce_success_page_follows_a_saved_token() {
        let (ok, body) = pkce_browser_after_save(Ok(()));
        assert!(ok);
        assert_eq!(body, "ok, you can close this tab");
        let text = String::from_utf8(pkce_browser_response(ok, &body)).expect("utf8");
        assert!(text.starts_with("HTTP/1.1 200 "), "{text}");
    }

    #[test]
    fn pkce_save_failure_page_redacts_and_is_not_success() {
        let (ok, body) = pkce_browser_after_save(Err("token sk-live-secret".into()));
        assert!(!ok);
        assert!(!body.contains("sk-live-secret"), "{body}");
        assert!(body.contains("[redacted]"), "{body}");
        let text = String::from_utf8(pkce_browser_response(ok, &body)).expect("utf8");
        assert!(text.starts_with("HTTP/1.1 400 "), "{text}");
        assert!(!text.contains("ok, you can close this tab"), "{text}");
        assert!(!text.contains("sk-live-secret"), "{text}");
    }

    #[test]
    fn url_decode_percent_then_multibyte_utf8_does_not_panic() {
        let decoded = url_decode("%完");
        assert_eq!(decoded, "%完");
        let callback = pkce_callback_from_query("code=%完&state=xyz");
        assert!(
            callback.is_ok(),
            "hostile query must not abort: {callback:?}"
        );
        assert_eq!(url_decode("%FF"), "\u{FFFD}");
        assert_eq!(url_decode("a+b%20c"), "a b c");
        assert_eq!(url_decode("%E2%82%AC"), "€");
    }
}