coralogix-cli 0.1.38

Coralogix CLI - the observability backbone for AI agents and engineering teams.
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
//! OAuth 2.0 + OIDC browser-login flow for Coralogix.
//!
//! Implements:
//!   - OpenID Connect discovery
//!   - PKCE code-challenge / code-verifier generation
//!   - Callback HTTP listener on a randomised port from a fixed allow-list
//!   - Authorization code exchange
//!   - Token refresh
//!   - Token persistence in either the OS keyring or the profile TOML
//!     (selected by `Profile::credential_storage`)

use anyhow::{bail, Context, Result};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use rand::seq::SliceRandom;
use rand::RngExt;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::io::{BufRead, BufReader, Write};
use std::net::{Ipv4Addr, Ipv6Addr, TcpListener, TcpStream};
use std::time::Duration;

use crate::config::{CredentialStorage, StoredOAuthTokens};
use crate::keyring_store;

// ── Constants ─────────────────────────────────────────────────────────────────

const SCOPES: &[&str] = &["openid", "profile", "email", "offline_access"];

/// Candidate ports for the local OAuth callback listener, tried in random order.
/// The server does not support ephemeral port assignment, so we only use this
/// fixed list.
const CALLBACK_PORTS: &[u16] = &[21783, 24861, 27654, 31847, 38129];

// ── Per-environment metadata ──────────────────────────────────────────────────

/// A known Coralogix deployment with a hard-coded OAuth client ID.
pub struct OAuthEnvironment {
    /// Short region name used in profile TOML (e.g. `"eu2"`).
    pub name: &'static str,
    /// OAuth client ID registered in that environment's IdP.
    pub client_id: &'static str,
}

/// Known Coralogix environments with their OAuth client IDs.
pub const KNOWN_ENVIRONMENTS: &[OAuthEnvironment] = &[
    OAuthEnvironment {
        name: "us1",
        client_id: "2b6d0b5c-da8f-477e-907e-50cdad7b90e7",
    },
    OAuthEnvironment {
        name: "us2",
        client_id: "2820e159-5b12-432d-bc09-bef144f9b8c9",
    },
    OAuthEnvironment {
        name: "us3",
        client_id: "a489741c-c875-4652-9b2e-1ba680352b72",
    },
    OAuthEnvironment {
        name: "eu1",
        client_id: "cfb0915d-cb82-436c-b0fb-e8f75e4f9db4",
    },
    OAuthEnvironment {
        name: "eu2",
        client_id: "941d86ab-f652-4430-8153-9af5db5791e5",
    },
    OAuthEnvironment {
        name: "ap1",
        client_id: "091a273c-8194-4ad1-a09e-d787cc5e490a",
    },
    OAuthEnvironment {
        name: "ap2",
        client_id: "d827249c-0699-4abf-8d4c-d1d27dd8fe9a",
    },
    OAuthEnvironment {
        name: "ap3",
        client_id: "7c8d9c61-7d28-4c0f-803b-d4061f33282b",
    },
];

// ── Data types ────────────────────────────────────────────────────────────────

/// Token set returned by the IdP after a successful authorisation.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TokenResponse {
    pub access_token: String,
    pub token_type: String,
    pub expires_in: Option<u64>,
    pub refresh_token: Option<String>,
    pub id_token: Option<String>,
    pub scope: Option<String>,
}

#[derive(Deserialize)]
struct OpenIdConfig {
    authorization_endpoint: String,
    token_endpoint: String,
}

// ── Utilities ─────────────────────────────────────────────────────────────────

/// Return the hard-coded OAuth client ID for a named region (e.g. `"eu2"`), or `None`.
pub fn client_id_for_region(region_name: &str) -> Option<&'static str> {
    KNOWN_ENVIRONMENTS
        .iter()
        .find(|e| e.name == region_name)
        .map(|e| e.client_id)
}

/// Current Unix timestamp in seconds. The system clock is assumed to be after
/// 1970; if it isn't, OAuth refresh wouldn't work anyway.
fn unix_now_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs()
}

/// Seconds until the JWT access token expires (`> 0` = still valid, `< 0` = expired).
/// Returns `None` when the JWT structure or `exp` claim is not parseable.
pub fn token_seconds_remaining(access_token: &str) -> Option<i64> {
    let parts: Vec<&str> = access_token.split('.').collect();
    if parts.len() != 3 {
        return None;
    }
    let payload = URL_SAFE_NO_PAD.decode(parts[1]).ok()?;
    let json: serde_json::Value = serde_json::from_slice(&payload).ok()?;
    let exp = json.get("exp")?.as_u64()?;
    Some(exp as i64 - unix_now_secs() as i64)
}

// ── OAuth protocol helpers ────────────────────────────────────────────────────

/// Outcome of attempting to bind both loopback stacks on a single candidate port.
enum PortBind {
    /// Both `127.0.0.1` and `[::1]` bound — the ideal case.
    Both(TcpListener, TcpListener),
    /// Only `127.0.0.1` bound because IPv6 loopback is *unavailable* (`::1` is not
    /// a configured address). Safe to use: `localhost` won't reach `::1` either.
    Ipv4Only(TcpListener),
    /// Port cannot be used: IPv4 bind failed, or — critically — `[::1]:port` is
    /// already owned by *another* process. An IPv6-first browser would reach that
    /// other service instead of our callback, so this port must be skipped rather
    /// than served IPv4-only.
    Unusable,
}

/// Try to bind both loopback stacks on `port`.
///
/// Binding the explicit `::1` address is IPv6-only and does not collide with the
/// `127.0.0.1` socket on the same port. An `AddrInUse` error on `::1` means another
/// process holds it (dangerous → `Unusable`); any other `::1` error means IPv6
/// loopback is absent (safe → `Ipv4Only`).
fn try_bind_port(port: u16) -> PortBind {
    let Ok(v4) = TcpListener::bind((Ipv4Addr::LOCALHOST, port)) else {
        return PortBind::Unusable;
    };
    match TcpListener::bind((Ipv6Addr::LOCALHOST, port)) {
        Ok(v6) => PortBind::Both(v4, v6),
        Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => PortBind::Unusable,
        Err(_) => PortBind::Ipv4Only(v4),
    }
}

/// Bind the first available port from `CALLBACK_PORTS`, tried in random order.
/// Returns `(listeners, port)` on success.
///
/// Binds **both** loopback stacks on the chosen port: `127.0.0.1` (IPv4, required)
/// and `[::1]` (IPv6, best-effort). The redirect URI handed to the browser uses
/// the hostname `localhost`, which on macOS/Windows resolves to `::1` *first* — so
/// browsers frequently connect over IPv6 before IPv4. Listening only on IPv4 (the
/// previous behaviour) made those callbacks fail with "This site can't be reached".
///
/// Per candidate port (see [`try_bind_port`]):
///   - both stacks bind → use it (preferred).
///   - `::1` absent (IPv6 unavailable) → usable IPv4-only, kept only as a fallback.
///   - `[::1]:port` owned by another process → **skip**, never served IPv4-only,
///     because an IPv6-first browser would otherwise hit that other service and the
///     callback would hang until timeout.
///
/// The IPv4-only fallback is used only when no candidate binds both stacks.
pub fn bind_callback_listener() -> Result<(Vec<TcpListener>, u16)> {
    let mut ports: Vec<u16> = CALLBACK_PORTS.to_vec();
    ports.shuffle(&mut rand::rng());

    // First usable IPv4-only port, kept as a fallback in case no port manages to
    // bind both stacks (e.g. IPv6 loopback disabled on the host).
    let mut ipv4_only_fallback: Option<(Vec<TcpListener>, u16)> = None;

    for &port in &ports {
        match try_bind_port(port) {
            PortBind::Both(v4, v6) => return Ok((vec![v4, v6], port)),
            PortBind::Ipv4Only(v4) if ipv4_only_fallback.is_none() => {
                ipv4_only_fallback = Some((vec![v4], port));
            }
            PortBind::Ipv4Only(_) | PortBind::Unusable => {}
        }
    }

    if let Some(result) = ipv4_only_fallback {
        return Ok(result);
    }

    bail!(
        "Could not bind any OAuth callback port. All ports in the allow-list are in use: {}",
        CALLBACK_PORTS
            .iter()
            .map(|p| p.to_string())
            .collect::<Vec<_>>()
            .join(", ")
    )
}

fn generate_pkce() -> (String, String) {
    let mut rng = rand::rng();
    let verifier_bytes: Vec<u8> = (0..32).map(|_| rng.random::<u8>()).collect();
    let verifier = URL_SAFE_NO_PAD.encode(&verifier_bytes);
    let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()));
    (verifier, challenge)
}

fn urlencode(s: &str) -> String {
    url::form_urlencoded::byte_serialize(s.as_bytes()).collect()
}

/// Block the calling thread until the browser delivers the OAuth callback.
/// Validates the `state` parameter and returns the `code`.
///
/// Polls every listener (IPv4 and IPv6 loopback) so the callback is accepted
/// regardless of which stack the browser connects over. Loops over incoming
/// connections so that browser pre-flight requests (e.g. favicon fetches) do not
/// consume a connection before the real redirect arrives.
///
/// **Note:** Uses synchronous blocking I/O.  Always call via
/// `tokio::task::spawn_blocking` to avoid stalling the async runtime.
fn wait_for_callback_blocking(
    listeners: Vec<TcpListener>,
    expected_state: String,
) -> Result<String> {
    eprintln!("Waiting for browser callback...");
    for listener in &listeners {
        listener
            .set_nonblocking(true)
            .context("Failed to set OAuth callback listener to non-blocking")?;
    }
    loop {
        for listener in &listeners {
            match listener.accept() {
                Ok((stream, _)) => {
                    // Handle the accepted connection with blocking reads/writes.
                    stream
                        .set_nonblocking(false)
                        .context("Failed to set OAuth callback stream to blocking")?;
                    if let Some(code) = extract_and_respond(stream, &expected_state)? {
                        return Ok(code);
                    }
                    // Not an OAuth callback (e.g. favicon request) - keep waiting.
                }
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
                Err(e) => return Err(e).context("OAuth callback listener accept failed"),
            }
        }
        std::thread::sleep(Duration::from_millis(50));
    }
}

/// HTML returned to the browser after a successful OAuth login.
///
const SUCCESS_PAGE_HTML: &str = r##"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Authentication successful</title>
<style>
  :root {
    --text-primary: #0e141d;
    --text-secondary: #5e6164;
    --green-badge: #02763a;
  }
  * { box-sizing: border-box; }
  html, body { height: 100%; margin: 0; }
  body {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
    padding: 24px;
    background: linear-gradient(160deg, #edeff1 0%, #f7f8f9 45%, #ffffff 100%);
    color: var(--text-primary);
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    text-rendering: optimizeLegibility;
  }
  .card {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: fit-content;
    max-width: calc(100vw - 48px);
    text-align: center;
  }
  .badge {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 42px;
    height: 42px;
    margin-bottom: 8px;
    border-radius: 50%;
    background: var(--green-badge);
  }
  .badge svg { display: block; }
  h1 {
    margin: 0;
    font-size: 20px;
    font-weight: 700;
    line-height: 1.5;
    color: var(--text-primary);
  }
  .subtitle {
    margin: 8px 0 0;
    font-size: 14px;
    font-weight: 500;
    line-height: 1.5;
    color: var(--text-secondary);
    white-space: nowrap;
  }
  @media (max-width: 340px) { .subtitle { white-space: normal; } }
</style>
</head>
<body>
  <main class="card">
    <div class="badge">
      <svg width="24" height="24" viewBox="0 0 24 24" fill="none" aria-hidden="true" focusable="false">
        <path d="M5 12.5L10 17.5L19.5 7" stroke="#ffffff" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
      </svg>
    </div>
    <h1>Authentication successful</h1>
    <p class="subtitle">You are now connected to Coralogix.<br>You may close this tab and return to your application.</p>
  </main>
</body>
</html>"##;

/// Parse one HTTP connection and send an appropriate response.
///
/// Returns `Ok(Some(code))` when a valid OAuth callback is received,
/// `Ok(None)` for unrelated requests, and `Err` on a CSRF state mismatch.
fn extract_and_respond(stream: TcpStream, expected_state: &str) -> Result<Option<String>> {
    let mut reader = BufReader::new(&stream);
    let mut request_line = String::new();
    reader.read_line(&mut request_line)?;
    drop(reader); // release the borrow so we can write below

    let path = request_line
        .split_whitespace()
        .nth(1)
        .context("Malformed HTTP request in OAuth callback")?;

    let Some(query) = path.split('?').nth(1) else {
        // No query string - not an OAuth redirect (e.g. GET / or GET /favicon.ico).
        send_http_response(&stream, 204, "");
        return Ok(None);
    };

    let params: std::collections::HashMap<String, String> =
        url::form_urlencoded::parse(query.as_bytes())
            .into_owned()
            .collect();

    let (code, returned_state) = match (params.get("code"), params.get("state")) {
        (Some(c), Some(s)) => (c.clone(), s.clone()),
        _ => {
            // Query string present but missing code/state - not an OAuth redirect.
            send_http_response(&stream, 204, "");
            return Ok(None);
        }
    };

    if returned_state != expected_state {
        send_http_response(&stream, 400, "State mismatch.");
        bail!("OAuth state mismatch – possible CSRF attempt, aborting.");
    }

    send_http_response(&stream, 200, SUCCESS_PAGE_HTML);
    Ok(Some(code))
}

fn send_http_response(mut stream: &TcpStream, status: u16, body: &str) {
    let status_text = match status {
        200 => "200 OK",
        204 => "204 No Content",
        400 => "400 Bad Request",
        _ => "200 OK",
    };
    let response = if body.is_empty() {
        format!("HTTP/1.1 {status_text}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
    } else {
        format!(
            "HTTP/1.1 {status_text}\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
            body.len(),
            body
        )
    };
    let _ = stream.write_all(response.as_bytes());
    let _ = stream.flush();
}

async fn fetch_openid_config(base_url: &str) -> Result<OpenIdConfig> {
    let url = format!(
        "{}/oauth/.well-known/openid-configuration",
        base_url.trim_end_matches('/')
    );
    reqwest::get(&url)
        .await?
        .error_for_status()
        .with_context(|| format!("OpenID discovery endpoint returned an error: {url}"))?
        .json::<OpenIdConfig>()
        .await
        .with_context(|| format!("Failed to parse OpenID configuration from {url}"))
}

async fn exchange_code(
    token_endpoint: &str,
    client_id: &str,
    code: &str,
    code_verifier: &str,
    redirect_uri: &str,
) -> Result<TokenResponse> {
    let client = reqwest::Client::new();
    let resp = client
        .post(token_endpoint)
        .form(&[
            ("grant_type", "authorization_code"),
            ("client_id", client_id),
            ("code", code),
            ("redirect_uri", redirect_uri),
            ("code_verifier", code_verifier),
        ])
        .send()
        .await?;

    if !resp.status().is_success() {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        bail!("Token exchange failed ({status}): {body}");
    }
    resp.json::<TokenResponse>()
        .await
        .context("Failed to parse token exchange response")
}

async fn do_token_refresh(
    token_endpoint: &str,
    client_id: &str,
    refresh_token: &str,
) -> Result<TokenResponse> {
    let client = reqwest::Client::new();
    let resp = client
        .post(token_endpoint)
        .form(&[
            ("grant_type", "refresh_token"),
            ("client_id", client_id),
            ("refresh_token", refresh_token),
        ])
        .send()
        .await?;

    if !resp.status().is_success() {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        // 400/401 mean the refresh token was rejected. A 5xx or a transport
        // error leaves the refresh token usable, so those must not force a
        // browser login.
        if matches!(status.as_u16(), 400 | 401) {
            return Err(RefreshRejected { status, body }.into());
        }
        bail!("Token refresh failed ({status}): {body}");
    }
    resp.json::<TokenResponse>()
        .await
        .context("Failed to parse token refresh response")
}

// ── Public API ────────────────────────────────────────────────────────────────

/// Options that shape the consent page a [`browser_login`] opens.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LoginOptions {
    /// Adds `prompt=select_account` to the authorisation URL. Pass it on a
    /// retry after a wrong-team sign-in: the browser still holds the wrong
    /// team's SSO session, which would otherwise complete silently into the
    /// same team without showing the picker.
    pub force_account_selection: bool,
    /// Restricts the consent page to this team and preselects it, via the
    /// `cx_team_ids` query parameter the authorize page accepts. Set it to the
    /// team a profile last used so an expired-session re-login lands back in
    /// that team instead of whichever team the user clicks first. The page
    /// shows "Team not available" when the signed-in user is not a member;
    /// it never widens to the full list. Unknown to the IdP for clients with
    /// `cx_teams:all_user_teams`, where it is ignored.
    pub team_id: Option<i64>,
    /// Adds `prompt=create`, so a signed-out user lands on Coralogix signup
    /// instead of sign-in and comes back here once their team exists. Signup
    /// includes reading a verification email, so the callback waits longer.
    pub signup: bool,
}

/// The sign-up hint names no command: `cx init` and `cx profiles add` both
/// take `--signup`, and only the user's own command carries their region and
/// profile name.
fn timeout_message(options: &LoginOptions, timeout: Duration) -> String {
    let minutes = timeout.as_secs() / 60;
    if options.signup {
        format!(
            "OAuth sign-up timed out after {minutes} minutes. If you finished signing up, \
             run the same command again without `--signup` to sign in with your new account."
        )
    } else {
        format!("OAuth login timed out after {minutes} minutes")
    }
}

/// How long [`browser_login`] waits for the browser to come back.
fn callback_timeout(options: &LoginOptions) -> Duration {
    if options.signup {
        Duration::from_secs(30 * 60)
    } else {
        Duration::from_secs(5 * 60)
    }
}

/// Assemble the `/authorize` URL for one sign-in attempt.
///
/// `challenge` and `state` are already URL-safe base64; everything else is
/// form-encoded here.
fn build_authorization_url(
    authorization_endpoint: &str,
    client_id: &str,
    redirect_uri: &str,
    challenge: &str,
    state: &str,
    options: &LoginOptions,
) -> String {
    let scopes = SCOPES.join(" ");
    let mut auth_url = format!(
        "{}?response_type=code&client_id={}&redirect_uri={}&scope={}&code_challenge={}&code_challenge_method=S256&state={}",
        authorization_endpoint,
        urlencode(client_id),
        urlencode(redirect_uri),
        urlencode(&scopes),
        challenge,
        state,
    );
    // One prompt value: signup has no account to select yet.
    if options.signup {
        auth_url.push_str("&prompt=create");
    } else if options.force_account_selection {
        auth_url.push_str("&prompt=select_account");
    }
    if let Some(team_id) = options.team_id {
        // One key, comma-separated ids: STS forwards unknown params through a
        // single-valued map, so a repeated key would keep only one value.
        auth_url.push_str(&format!("&cx_team_ids={team_id}"));
    }
    auth_url
}

/// Run the full interactive browser-based OAuth sign-in flow.
///
/// 1. Fetches the OpenID Connect discovery document from `{base_url}/oauth/.well-known/…`
/// 2. Generates a PKCE challenge and a random `state` value
/// 3. Binds a local callback port (randomised from the fixed allow-list)
/// 4. Opens the browser at the authorisation URL
/// 5. Waits for the callback, validates `state`, extracts the code
/// 6. Exchanges the code for tokens and returns them
///
/// See [`LoginOptions`] for the knobs that shape the consent page.
pub async fn browser_login(
    base_url: &str,
    client_id: &str,
    options: LoginOptions,
) -> Result<TokenResponse> {
    let oidc = fetch_openid_config(base_url).await?;
    let (verifier, challenge) = generate_pkce();

    // Generate an independent random state for CSRF protection.
    // Must NOT reuse the PKCE challenge - state and code_challenge serve
    // distinct roles and using the same value leaks information.
    let state = {
        let mut rng = rand::rng();
        let bytes: Vec<u8> = (0..32).map(|_| rng.random::<u8>()).collect();
        URL_SAFE_NO_PAD.encode(bytes)
    };

    let (listeners, port) = bind_callback_listener()?;
    let redirect_uri = format!("http://localhost:{port}/callback");

    let auth_url = build_authorization_url(
        &oidc.authorization_endpoint,
        client_id,
        &redirect_uri,
        &challenge,
        &state,
        &options,
    );

    // Always print the URL: when the browser can't be opened (headless run,
    // or cx driven by a coding agent), it is the user's only way in — the
    // agent relays it and the callback still lands on localhost.
    eprintln!("Sign in by visiting:\n  {auth_url}");
    if open::that(&auth_url).is_ok() {
        eprintln!("(opened in your default browser)");
    }

    // Run the blocking TCP listener on a dedicated thread so it does not
    // stall the async runtime, and give up after `callback_timeout`.
    let timeout = callback_timeout(&options);
    let code = tokio::time::timeout(
        timeout,
        tokio::task::spawn_blocking(move || wait_for_callback_blocking(listeners, state)),
    )
    .await
    .with_context(|| timeout_message(&options, timeout))?
    .context("OAuth callback task failed")??;

    eprintln!("Authorization code received, exchanging for tokens...");

    exchange_code(
        &oidc.token_endpoint,
        client_id,
        &code,
        &verifier,
        &redirect_uri,
    )
    .await
}

/// Convert a freshly received `TokenResponse` into the form persisted in the
/// profile TOML when `credential_storage = "file"`.
///
/// `expiry` is computed from `expires_in` when present. When absent, it stays
/// `None` and `resolve_token` falls back to parsing the JWT `exp` claim.
pub fn tokens_to_stored(tokens: &TokenResponse) -> StoredOAuthTokens {
    let expiry = tokens.expires_in.map(|exp_in| unix_now_secs() + exp_in);
    StoredOAuthTokens {
        access_token: tokens.access_token.clone(),
        refresh_token: tokens.refresh_token.clone(),
        id_token: tokens.id_token.clone(),
        expiry,
    }
}

/// Persist an OAuth token set to the OS keyring for `profile`.
///
/// Stores: `oauth_access_token`, `oauth_refresh_token`, `oauth_id_token`,
/// `oauth_token_expiry` (Unix timestamp, computed from `expires_in`).
pub fn store_tokens_keyring(profile: &str, tokens: &TokenResponse) -> Result<()> {
    keyring_store::store_secret(profile, "oauth_access_token", &tokens.access_token)?;
    if let Some(ref rt) = tokens.refresh_token {
        keyring_store::store_secret(profile, "oauth_refresh_token", rt)?;
    }
    if let Some(ref it) = tokens.id_token {
        keyring_store::store_secret(profile, "oauth_id_token", it)?;
    }
    // Only store the expiry timestamp when the server provides `expires_in`.
    // When absent, `resolve_token` falls back to parsing the JWT `exp` claim directly.
    // Storing a sentinel `0` would make every cached token appear permanently expired.
    if let Some(exp_in) = tokens.expires_in {
        let expiry = unix_now_secs() + exp_in;
        keyring_store::store_secret(profile, "oauth_token_expiry", &expiry.to_string())?;
    }
    Ok(())
}

/// Persist tokens read from a file-backed profile into the OS credential store.
///
/// Unlike [`store_tokens_keyring`], the expiry is already an absolute Unix
/// timestamp and must not be recomputed. The file holds the profile's whole
/// token set, so keyring entries for fields it lacks are deleted: an older
/// refresh token or expiry left there would otherwise be read back with the
/// new access token. Deletes run only after every write has succeeded.
pub fn store_stored_tokens_keyring(profile: &str, tokens: &StoredOAuthTokens) -> Result<()> {
    let expiry = tokens.expiry.map(|expiry| expiry.to_string());
    let secrets = [
        ("oauth_access_token", Some(tokens.access_token.as_str())),
        ("oauth_refresh_token", tokens.refresh_token.as_deref()),
        ("oauth_id_token", tokens.id_token.as_deref()),
        ("oauth_token_expiry", expiry.as_deref()),
    ];
    for (key_name, value) in secrets {
        if let Some(value) = value {
            keyring_store::store_secret(profile, key_name, value)?;
        }
    }
    for (key_name, value) in secrets {
        if value.is_none() {
            keyring_store::delete_secret(profile, key_name);
        }
    }
    Ok(())
}

/// Result of resolving an OAuth bearer token.
///
/// When `os_store_fallback_reason` is set, the caller must persist
/// `refreshed_tokens` in the profile file and switch the profile's credential
/// storage to `file`.
#[derive(Debug)]
pub struct TokenResolution {
    pub bearer: String,
    pub refreshed_tokens: Option<StoredOAuthTokens>,
    pub os_store_fallback_reason: Option<String>,
}

fn os_store_refresh_result(tokens: &TokenResponse, store_result: Result<()>) -> TokenResolution {
    match store_result {
        Ok(()) => TokenResolution {
            bearer: tokens.access_token.clone(),
            refreshed_tokens: None,
            os_store_fallback_reason: None,
        },
        Err(err) => TokenResolution {
            bearer: tokens.access_token.clone(),
            refreshed_tokens: Some(tokens_to_stored(tokens)),
            os_store_fallback_reason: Some(format!("{err:#}")),
        },
    }
}

fn cached_token_is_valid(token: &str, expiry: Option<u64>) -> bool {
    if let Some(exp) = expiry {
        exp > unix_now_secs() + 30
    } else {
        token_seconds_remaining(token)
            .map(|s| s > 30)
            .unwrap_or(false)
    }
}

/// Why a stored OAuth session cannot be refreshed and the user must sign in again.
#[derive(Debug)]
enum ReauthKind {
    TokensMissing,
    SessionExpired,
    RefreshFailed,
}

#[derive(Debug)]
struct ReauthRequired {
    profile_name: String,
    kind: ReauthKind,
    /// Present when a refresh was attempted and the IdP rejected it. Kept as
    /// the error source so the response body is still printed.
    source: Option<anyhow::Error>,
}

impl std::fmt::Display for ReauthRequired {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let profile_name = &self.profile_name;
        let detail = match self.kind {
            ReauthKind::TokensMissing => "OAuth tokens missing",
            ReauthKind::SessionExpired => "OAuth session expired",
            ReauthKind::RefreshFailed => "OAuth token refresh failed",
        };
        write!(
            f,
            "{detail} for profile '{profile_name}'.\n\
             Run `cx profiles refresh {profile_name}` to sign in again."
        )
    }
}

impl std::error::Error for ReauthRequired {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source.as_ref().map(AsRef::as_ref)
    }
}

/// The IdP rejected the refresh token (HTTP 400 or 401). Transport failures
/// and 5xx responses are ordinary errors and must not start a browser login.
#[derive(Debug)]
struct RefreshRejected {
    status: reqwest::StatusCode,
    body: String,
}

impl std::fmt::Display for RefreshRejected {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Token refresh failed ({}): {}", self.status, self.body)
    }
}

impl std::error::Error for RefreshRejected {}

fn is_refresh_rejected(err: &anyhow::Error) -> bool {
    err.chain()
        .any(|cause| cause.downcast_ref::<RefreshRejected>().is_some())
}

fn reauth_required(profile_name: &str, kind: ReauthKind) -> anyhow::Error {
    ReauthRequired {
        profile_name: profile_name.to_string(),
        kind,
        source: None,
    }
    .into()
}

fn reauth_required_with_source(
    profile_name: &str,
    kind: ReauthKind,
    source: anyhow::Error,
) -> anyhow::Error {
    ReauthRequired {
        profile_name: profile_name.to_string(),
        kind,
        source: Some(source),
    }
    .into()
}

/// True when `err` means the stored session is dead and browser sign-in is the
/// only recovery. Network failures while a refresh token is still present are
/// not included.
pub fn is_reauth_required(err: &anyhow::Error) -> bool {
    err.chain()
        .any(|cause| cause.downcast_ref::<ReauthRequired>().is_some())
}

/// The OS-store session needs new tokens, but the OS credential store cannot
/// be written in this process.
#[derive(Debug)]
struct OsStoreRefreshBlocked {
    profile_name: String,
}

impl std::fmt::Display for OsStoreRefreshBlocked {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "OAuth tokens for profile '{}' cannot be refreshed because the OS credential store \
             is read-only",
            self.profile_name
        )
    }
}

impl std::error::Error for OsStoreRefreshBlocked {}

/// True when `err` means [`resolve_token`] skipped a refresh because the new
/// tokens could not have been saved to the OS credential store.
pub fn is_os_store_refresh_blocked(err: &anyhow::Error) -> bool {
    err.chain()
        .any(|cause| cause.downcast_ref::<OsStoreRefreshBlocked>().is_some())
}

/// Resolve a usable bearer token for an OAuth profile.
///
/// Reads the cached access token from the chosen storage backend and returns it
/// if it is still valid (≥ 30 s remaining). Otherwise, uses the cached refresh
/// token to obtain a fresh token set.
///
/// For `OsStore`, the keyring is updated in place. If that write fails, the
/// returned [`TokenResolution`] asks the caller to migrate the profile to file
/// storage and persist the refreshed token set. For `File`, the caller
/// persists the returned token set when a refresh occurred.
///
/// When the session cannot be refreshed, the error satisfies
/// [`is_reauth_required`]. Callers on an interactive terminal may run
/// [`browser_login`] instead of surfacing it.
///
/// Without `os_store_writable`, an `OsStore` session that needs new tokens
/// fails with [`is_os_store_refresh_blocked`] before contacting the IdP: a
/// macOS sandbox that blocks Keychain writes can answer the write with a
/// dialog that the user cannot respond to.
pub async fn resolve_token(
    profile_name: &str,
    base_url: &str,
    client_id: &str,
    storage: CredentialStorage,
    file_tokens: Option<&StoredOAuthTokens>,
    os_store_writable: bool,
) -> Result<TokenResolution> {
    let (cached_access, cached_expiry, cached_refresh) = match storage {
        CredentialStorage::OsStore => (
            keyring_store::get_secret(profile_name, "oauth_access_token")?,
            keyring_store::get_secret(profile_name, "oauth_token_expiry")?
                .and_then(|s| s.parse::<u64>().ok()),
            keyring_store::get_secret(profile_name, "oauth_refresh_token")?,
        ),
        CredentialStorage::File => {
            let t = file_tokens
                .ok_or_else(|| reauth_required(profile_name, ReauthKind::TokensMissing))?;
            (
                Some(t.access_token.clone()),
                t.expiry,
                t.refresh_token.clone(),
            )
        }
    };

    if let Some(ref token) = cached_access {
        if cached_token_is_valid(token, cached_expiry) {
            return Ok(TokenResolution {
                bearer: token.clone(),
                refreshed_tokens: None,
                os_store_fallback_reason: None,
            });
        }
    }

    // A refresh and the browser sign-in that replaces a dead session both
    // save new tokens to the store.
    if storage == CredentialStorage::OsStore && !os_store_writable {
        return Err(OsStoreRefreshBlocked {
            profile_name: profile_name.to_string(),
        }
        .into());
    }

    let refresh_token =
        cached_refresh.ok_or_else(|| reauth_required(profile_name, ReauthKind::SessionExpired))?;

    let oidc = fetch_openid_config(base_url).await.with_context(|| {
        format!(
            "Failed to contact OAuth server while refreshing token for profile '{profile_name}'."
        )
    })?;

    let tokens = match do_token_refresh(&oidc.token_endpoint, client_id, &refresh_token).await {
        Ok(tokens) => tokens,
        Err(err) if is_refresh_rejected(&err) => {
            return Err(reauth_required_with_source(
                profile_name,
                ReauthKind::RefreshFailed,
                err,
            ));
        }
        Err(err) => {
            return Err(err.context(format!(
                "Failed to refresh OAuth token for profile '{profile_name}'."
            )));
        }
    };

    match storage {
        CredentialStorage::OsStore => Ok(os_store_refresh_result(
            &tokens,
            store_tokens_keyring(profile_name, &tokens),
        )),
        CredentialStorage::File => {
            let stored = tokens_to_stored(&tokens);
            Ok(TokenResolution {
                bearer: tokens.access_token,
                refreshed_tokens: Some(stored),
                os_store_fallback_reason: None,
            })
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::TcpStream;

    #[test]
    fn bind_callback_listener_serves_loopback_on_every_bound_stack() {
        let (listeners, port) = bind_callback_listener().expect("a callback port must bind");
        assert!(!listeners.is_empty(), "must bind at least one listener");

        // Every listener shares the single chosen port.
        for l in &listeners {
            assert_eq!(
                l.local_addr().expect("local_addr").port(),
                port,
                "all listeners must share the chosen callback port"
            );
        }

        // IPv4 loopback is mandatory and must accept a connection.
        TcpStream::connect((Ipv4Addr::LOCALHOST, port))
            .expect("IPv4 loopback callback must be connectable");

        // When a `::1` listener was bound (IPv6 loopback available), the browser's
        // IPv6-first `localhost` connection must succeed too — this is the fix for
        // the "site can't be reached" callback failure.
        let has_ipv6 = listeners
            .iter()
            .any(|l| l.local_addr().map(|a| a.is_ipv6()).unwrap_or(false));
        if has_ipv6 {
            TcpStream::connect((Ipv6Addr::LOCALHOST, port))
                .expect("IPv6 loopback callback must be connectable when ::1 is bound");
        }
    }

    #[test]
    fn try_bind_port_does_not_fall_back_to_ipv4_when_ipv6_is_occupied() {
        // Squat on an IPv6 loopback port; its IPv4 counterpart stays free.
        let Ok(v6_squatter) = TcpListener::bind((Ipv6Addr::LOCALHOST, 0)) else {
            // No IPv6 loopback on this host — the dangerous scenario can't occur.
            return;
        };
        let port = v6_squatter.local_addr().expect("local_addr").port();

        // `[::1]:port` is owned by another process, so the port must be reported
        // Unusable — NOT served IPv4-only, which an IPv6-first browser would miss.
        match try_bind_port(port) {
            PortBind::Unusable => {}
            PortBind::Both(..) => panic!("::1 was occupied; must not report Both"),
            PortBind::Ipv4Only(_) => {
                panic!("must not fall back to IPv4-only while another process owns ::1")
            }
        }
    }

    fn sample_token_response(expires_in: Option<u64>, refresh: Option<&str>) -> TokenResponse {
        TokenResponse {
            access_token: "access-abc".to_string(),
            token_type: "Bearer".to_string(),
            expires_in,
            refresh_token: refresh.map(str::to_string),
            id_token: Some("id-xyz".to_string()),
            scope: None,
        }
    }

    #[test]
    fn tokens_to_stored_sets_expiry_when_expires_in_present() {
        let before = unix_now_secs();
        let stored = tokens_to_stored(&sample_token_response(Some(3600), Some("refresh-1")));
        let after = unix_now_secs();

        let expiry = stored.expiry.expect("expiry computed from expires_in");
        assert!(expiry >= before + 3600 && expiry <= after + 3600);
        assert_eq!(stored.access_token, "access-abc");
        assert_eq!(stored.refresh_token.as_deref(), Some("refresh-1"));
        assert_eq!(stored.id_token.as_deref(), Some("id-xyz"));
    }

    #[test]
    fn tokens_to_stored_leaves_expiry_none_when_expires_in_absent() {
        let stored = tokens_to_stored(&sample_token_response(None, None));
        assert!(stored.expiry.is_none());
        assert!(stored.refresh_token.is_none());
    }

    #[test]
    fn os_store_refresh_falls_back_to_file_storage() {
        let tokens = sample_token_response(Some(3600), Some("refresh-1"));
        let resolved = os_store_refresh_result(
            &tokens,
            Err(anyhow::anyhow!("credential blob exceeds the limit")),
        );

        assert_eq!(resolved.bearer, tokens.access_token);
        assert_eq!(
            resolved
                .refreshed_tokens
                .as_ref()
                .and_then(|stored| stored.refresh_token.as_deref()),
            Some("refresh-1")
        );
        assert!(resolved
            .os_store_fallback_reason
            .as_deref()
            .is_some_and(|reason| reason.contains("credential blob exceeds the limit")));
    }

    #[test]
    fn cached_token_is_valid_uses_expiry_when_present() {
        let now = unix_now_secs();
        // 5 minutes left -> valid.
        assert!(cached_token_is_valid("ignored", Some(now + 300)));
        // Inside the 30 s skew window -> not valid.
        assert!(!cached_token_is_valid("ignored", Some(now + 10)));
        // Already expired.
        assert!(!cached_token_is_valid("ignored", Some(now - 1)));
    }

    #[test]
    fn cached_token_is_valid_falls_back_to_jwt_exp_without_expiry() {
        // Token is not a JWT and there's no separate expiry -> conservatively invalid.
        assert!(!cached_token_is_valid("not-a-jwt", None));
    }

    #[tokio::test]
    async fn resolve_token_file_mode_errors_when_tokens_missing() {
        let err = resolve_token(
            "myprofile",
            "https://example.invalid",
            "client-id",
            CredentialStorage::File,
            None,
            true,
        )
        .await
        .expect_err("missing file_tokens must error");
        let msg = format!("{err:#}");
        assert!(msg.contains("OAuth tokens missing"), "got: {msg}");
        assert!(msg.contains("myprofile"), "got: {msg}");
        assert!(is_reauth_required(&err));
    }

    #[test]
    #[ignore = "requires system keyring access"]
    fn stored_tokens_replace_stale_keyring_entries() {
        let profile = "cx_keyring_test_stored_tokens";
        keyring_store::store_secret(profile, "oauth_refresh_token", "stale-refresh").unwrap();
        keyring_store::store_secret(profile, "oauth_token_expiry", "1").unwrap();
        let tokens = StoredOAuthTokens {
            access_token: "access".to_string(),
            refresh_token: None,
            id_token: Some("id".to_string()),
            expiry: None,
        };

        store_stored_tokens_keyring(profile, &tokens).unwrap();

        let secret = |key_name| keyring_store::get_secret(profile, key_name).unwrap();
        assert_eq!(secret("oauth_access_token").as_deref(), Some("access"));
        assert_eq!(secret("oauth_id_token").as_deref(), Some("id"));
        assert_eq!(secret("oauth_refresh_token"), None);
        assert_eq!(secret("oauth_token_expiry"), None);
        keyring_store::delete_profile(profile);
    }

    #[tokio::test]
    async fn resolve_token_file_mode_returns_cached_when_valid() {
        let tokens = StoredOAuthTokens {
            access_token: "still-good".to_string(),
            refresh_token: Some("refresh".to_string()),
            id_token: None,
            expiry: Some(unix_now_secs() + 600),
        };
        // base_url is never contacted because the cached token is valid.
        let resolved = resolve_token(
            "myprofile",
            "https://example.invalid",
            "client-id",
            CredentialStorage::File,
            Some(&tokens),
            true,
        )
        .await
        .expect("cached path must not hit the network");
        assert_eq!(resolved.bearer, "still-good");
        assert!(resolved.refreshed_tokens.is_none());
        assert!(resolved.os_store_fallback_reason.is_none());
    }

    #[tokio::test]
    async fn resolve_token_file_mode_errors_when_expired_without_refresh() {
        let tokens = StoredOAuthTokens {
            access_token: "expired".to_string(),
            refresh_token: None,
            id_token: None,
            expiry: Some(unix_now_secs() - 1),
        };
        let err = resolve_token(
            "myprofile",
            "https://example.invalid",
            "client-id",
            CredentialStorage::File,
            Some(&tokens),
            true,
        )
        .await
        .expect_err("expired access + no refresh token must error");
        let msg = format!("{err:#}");
        assert!(msg.contains("OAuth session expired"), "got: {msg}");
        assert!(is_reauth_required(&err));
    }

    #[tokio::test]
    async fn resolve_token_file_mode_ignores_a_read_only_os_store() {
        let tokens = StoredOAuthTokens {
            access_token: "expired".to_string(),
            refresh_token: None,
            id_token: None,
            expiry: Some(unix_now_secs() - 1),
        };
        let err = resolve_token(
            "myprofile",
            "https://example.invalid",
            "client-id",
            CredentialStorage::File,
            Some(&tokens),
            false,
        )
        .await
        .expect_err("expired access + no refresh token must error");
        assert!(is_reauth_required(&err), "got: {err:#}");
        assert!(!is_os_store_refresh_blocked(&err), "got: {err:#}");
    }

    #[test]
    fn refresh_rejection_requires_reauth() {
        let err = reauth_required_with_source(
            "myprofile",
            ReauthKind::RefreshFailed,
            RefreshRejected {
                status: reqwest::StatusCode::BAD_REQUEST,
                body: "invalid_grant".to_string(),
            }
            .into(),
        );
        let msg = format!("{err:?}");
        assert!(msg.contains("OAuth token refresh failed"), "got: {msg}");
        assert!(msg.contains("invalid_grant"), "got: {msg}");
        assert!(is_reauth_required(&err));
        assert!(is_refresh_rejected(&err));
    }

    #[test]
    fn refresh_server_error_does_not_require_reauth() {
        let err = anyhow::anyhow!(
            "Failed to refresh OAuth token for profile 'myprofile'.\n\
             Token refresh failed (503): unavailable"
        );
        assert!(!is_refresh_rejected(&err));
        assert!(!is_reauth_required(&err));
    }

    #[test]
    fn authorization_url_has_no_optional_params_by_default() {
        let url = build_authorization_url(
            "https://example.com/oauth/authorize",
            "cli-client",
            "http://localhost:21783/callback",
            "CHALLENGE",
            "STATE",
            &LoginOptions::default(),
        );
        assert_eq!(
            url,
            "https://example.com/oauth/authorize?response_type=code&client_id=cli-client\
             &redirect_uri=http%3A%2F%2Flocalhost%3A21783%2Fcallback\
             &scope=openid+profile+email+offline_access\
             &code_challenge=CHALLENGE&code_challenge_method=S256&state=STATE"
        );
        assert!(!url.contains("prompt="));
        assert!(!url.contains("cx_team_ids="));
    }

    #[test]
    fn authorization_url_restricts_to_the_profile_team() {
        let url = build_authorization_url(
            "https://example.com/oauth/authorize",
            "cli-client",
            "http://localhost:21783/callback",
            "CHALLENGE",
            "STATE",
            &LoginOptions {
                force_account_selection: false,
                team_id: Some(53623),
                signup: false,
            },
        );
        assert!(
            url.ends_with("&state=STATE&cx_team_ids=53623"),
            "got: {url}"
        );
        assert!(!url.contains("prompt="));
    }

    #[test]
    fn authorization_url_combines_account_picker_and_team_restriction() {
        let url = build_authorization_url(
            "https://example.com/oauth/authorize",
            "cli-client",
            "http://localhost:21783/callback",
            "CHALLENGE",
            "STATE",
            &LoginOptions {
                force_account_selection: true,
                team_id: Some(7),
                signup: false,
            },
        );
        assert!(
            url.ends_with("&state=STATE&prompt=select_account&cx_team_ids=7"),
            "got: {url}"
        );
    }

    #[test]
    fn authorization_url_asks_for_signup_instead_of_an_account_picker() {
        let url = build_authorization_url(
            "https://example.com/oauth/authorize",
            "cli-client",
            "http://localhost:21783/callback",
            "CHALLENGE",
            "STATE",
            &LoginOptions {
                force_account_selection: true,
                team_id: None,
                signup: true,
            },
        );
        assert!(url.ends_with("&state=STATE&prompt=create"), "got: {url}");
        assert!(!url.contains("select_account"));
    }

    #[test]
    fn signup_timeout_tells_the_user_to_rerun_their_own_command() {
        let message = timeout_message(
            &LoginOptions {
                signup: true,
                ..LoginOptions::default()
            },
            Duration::from_secs(30 * 60),
        );

        assert!(
            message.contains("same command again without `--signup`"),
            "{message}"
        );
        assert!(!message.contains("cx init"), "{message}");
    }

    #[test]
    fn signup_waits_long_enough_to_read_the_verification_email() {
        let login = callback_timeout(&LoginOptions::default());
        let signup = callback_timeout(&LoginOptions {
            signup: true,
            ..LoginOptions::default()
        });
        assert_eq!(login, Duration::from_secs(5 * 60));
        assert_eq!(signup, Duration::from_secs(30 * 60));
    }
}