fluidattacks-core 0.19.0

Fluid Attacks Core Library
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
use std::env;
use std::sync::RwLock;
use std::time::Duration;

use secrecy::{ExposeSecret, SecretString};
use serde::Deserialize;

mod oauth;
mod store;

use store::StoredToken;

const TOKEN_ENV: &str = "INTEGRATES_API_TOKEN";
const OIDC_TOKEN_ENV: &str = "INTEGRATES_OIDC_TOKEN";
const GH_TOKEN_URL_ENV: &str = "ACTIONS_ID_TOKEN_REQUEST_URL";
const GH_REQUEST_TOKEN_ENV: &str = "ACTIONS_ID_TOKEN_REQUEST_TOKEN";
const ENDPOINT_ENV: &str = "INTEGRATES_ENDPOINT";
const DEFAULT_BASE: &str = "https://app.fluidattacks.com";
// Public first-party client id; integrates does not treat it as a secret. The platform
// allow-lists exactly this one, so it is not configurable: sending another makes the
// authorization request fail in the browser while the cli waits for a callback that
// will never come. Naming the calling program is the `User-Agent`'s job until the
// platform registers more ids.
pub(crate) const CLIENT_ID: &str = "fluidattacks-cli";
const ME_QUERY: &str = r#"{"query":"query{me{userEmail}}"}"#;
const GROUP_QUERY: &str = "query($groupName:String!){group(groupName:$groupName){name}}";
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
const UNAUTHORIZED: u16 = 401;
const FORBIDDEN: u16 = 403;
const TOO_MANY_REQUESTS: u16 = 429;

/// The code the platform sets when it rejects a credential.
///
/// It arrives in `errors[].extensions.code` on the api route, answered with HTTP
/// 400. Callers detect it in whatever GraphQL client they use, so they should
/// match on this rather than pin the string themselves.
pub const LOGIN_REQUIRED_CODE: &str = "LOGIN_REQUIRED";

// Set once per process by the host program. Explicit configuration takes precedence
// over the environment, so a program that targets more than one platform does not have
// to mutate its own environment to say which one it means, nor lock around doing so.
static SETTINGS: RwLock<Option<Settings>> = RwLock::new(None);
static SIGNING_IN: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// What a program tells the shared client about itself, once, during start-up.
///
/// Every field is optional and falls back to the environment, so a program supplies only
/// what it actually knows. A field left as `None` in a later call keeps whatever an
/// earlier one set, so configuring one thing never silently clears another.
#[derive(Clone, Debug, Default)]
pub struct Settings {
    /// The platform to talk to, overriding `INTEGRATES_ENDPOINT`.
    pub endpoint: Option<String>,
    /// The personal access token to use, overriding `INTEGRATES_API_TOKEN`. Passing it
    /// keeps it out of what subprocesses inherit.
    pub token: Option<SecretString>,
    /// The program's name and version, for the `User-Agent` it sends.
    pub client: Option<(String, String)>,
}

/// Tell the shared client which platform, credential and program this process is.
///
/// Call once during start-up, before anything authenticates. It is process wide:
/// changing it while another thread is authenticating would send that operation to the
/// platform it was not started for, so a program that needs two platforms at once needs
/// two processes.
///
/// Each operation snapshots what it needs at entry, so a later call cannot move a
/// platform out from under an operation already running.
pub fn configure(settings: Settings) {
    if let Ok(mut slot) = SETTINGS.write() {
        let current = slot.take().unwrap_or_default();
        *slot = Some(Settings {
            endpoint: settings.endpoint.or(current.endpoint),
            token: settings.token.or(current.token),
            client: settings.client.or(current.client),
        });
    }
}

// What one operation needs to know about where it is talking, read once so every step
// of it agrees: the url it calls, the stored session that belongs to that platform, and
// whether certificate checks apply.
#[derive(Clone, Debug)]
pub(crate) struct Platform {
    pub(crate) base: String,
    pub(crate) store_key: Option<String>,
    pub(crate) loopback: bool,
}

// Snapshot the platform in force. Taken at the entry of every operation and passed
// down, never re-read halfway through.
#[cfg(test)]
impl Platform {
    // The platform a test operates against, so nothing reads process state. Defined once:
    // two copies drifted on which spelling of the default base they used.
    pub(crate) fn for_tests() -> Self {
        Self {
            base: DEFAULT_BASE.to_owned(),
            store_key: None,
            loopback: false,
        }
    }
}

pub(crate) fn platform() -> Platform {
    let base = endpoint_from(
        with_settings(|settings| settings.endpoint.clone()).flatten(),
        env::var(ENDPOINT_ENV).ok(),
    );
    Platform {
        store_key: store_key_of(&base),
        loopback: base != DEFAULT_BASE && is_loopback(&base),
        base,
    }
}

// Read one field under the guard rather than cloning the record: the token lives in here,
// and this is on the per-request path.
fn with_settings<T>(read: impl FnOnce(&Settings) -> T) -> Option<T> {
    SETTINGS
        .read()
        .ok()
        .and_then(|slot| slot.as_ref().map(read))
}

// The configuration above is process wide, so tests that read or write it take this
// first: cargo runs them in parallel and they would otherwise observe each other.
#[cfg(test)]
pub(crate) static CONFIG_GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(());

// The token a program supplied. `resolve` decides whether it counts as one.
fn configured_token() -> Option<String> {
    with_settings(|settings| {
        settings
            .token
            .as_ref()
            .map(|token| token.expose_secret().to_owned())
    })
    .flatten()
}

fn user_agent() -> String {
    with_settings(|settings| {
        settings
            .client
            .as_ref()
            .map(|(name, version)| format!("{name}/{version}"))
    })
    .flatten()
    .unwrap_or_else(|| format!("{CLIENT_ID}/unknown"))
}

/// The authenticated identity plus the validated credential.
///
/// `token` is the credential that was validated — the PAT, or the short-lived
/// service token minted via OIDC — so authorization consumers (e.g. Forces) can
/// call the platform API as this identity. Identity-only consumers (finder
/// scanners) read `email` and ignore the token. It is a [`SecretString`], so it
/// is redacted from `Debug` and zeroized on drop; reach it only via
/// [`Session::expose_token`].
#[derive(Debug)]
pub struct Session {
    pub email: String,
    pub token: SecretString,
    /// Which tier answered, so callers do not re-derive it from the environment.
    pub source: Credential,
}

/// The credential tier that resolved a session.
///
/// Reported so a caller that cares can say how it authenticated. What to do when the
/// platform rejects a credential is [`recover`]'s decision, not the caller's.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Credential {
    /// `INTEGRATES_API_TOKEN`, or one supplied through [`configure`].
    Pat,
    /// A stored browser login.
    Oauth,
    /// A service token minted from CI OIDC federation.
    Oidc,
}

impl Session {
    /// Reveal the validated credential for callers that must send it to the
    /// platform (e.g. as a `Bearer` header). This is the single exposure point.
    #[must_use]
    pub fn expose_token(&self) -> &str {
        self.token.expose_secret()
    }
}

// Non-exhaustive so future variants aren't a breaking change for consumers.
#[derive(Debug)]
#[non_exhaustive]
pub enum AuthError {
    NotAuthenticated,
    Invalid,
    Transport(String),
    Local(String),
}

impl std::fmt::Display for AuthError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotAuthenticated => write!(
                f,
                "not authenticated: set {TOKEN_ENV}, or use CI OIDC \
                 ({OIDC_TOKEN_ENV} or a GitHub id-token) with a group"
            ),
            Self::Invalid => write!(
                f,
                "the credential is invalid, expired, or not authorized for the group"
            ),
            Self::Transport(detail) => {
                write!(f, "could not reach the platform to authenticate: {detail}")
            }
            Self::Local(detail) => {
                write!(f, "a local step of the login flow failed: {detail}")
            }
        }
    }
}

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

/// Log a human in through the browser and store the session for later reuse.
///
/// # Errors
/// [`AuthError::Invalid`] when the platform rejects the exchange, [`AuthError::Transport`]
/// when it is unreachable, and [`AuthError::Local`] when the loopback listener or the
/// token store fails.
pub fn login() -> Result<Session, AuthError> {
    oauth::login(&platform())
}

/// Revoke the stored session and remove it locally.
///
/// The local session goes either way, so this works offline; the flag reports whether
/// the platform confirmed the revocation, which matters on a shared machine.
///
/// # Errors
/// [`AuthError::Local`] when the token store cannot be written.
pub fn logout() -> Result<bool, AuthError> {
    oauth::logout(&platform())
}

/// A working credential after the platform rejected `stale`, or `None`.
///
/// The one recovery decision, for every caller in either language: refresh, reusing a
/// refresh another party already completed, and when the window is over sign in again if
/// `interactive` allows a browser. Only ever one browser at a time, however many callers
/// arrive at once.
///
/// `None` means nothing here can make the request succeed, so report the original
/// failure. A supplied token and a federated identity are never recovered: neither can
/// be refreshed, and signing in would not replace either.
///
/// Having no session at all is recovered when `interactive`, not refused. A session that
/// runs out mid-use is forgotten by the refresh that failed, so the next caller finds
/// nothing stored; refusing there would send someone who is sitting right in front of the
/// program back to a separate sign-in step to carry on.
///
/// The whole [`Session`] comes back, not just the token, because an interactive login can
/// complete as a different person: a caller that shows who is signed in reads `email` from
/// here rather than asking again.
///
/// # Errors
/// [`AuthError::Local`] when the token store cannot be read.
pub fn recover(stale: &str, interactive: bool) -> Result<Option<Session>, AuthError> {
    let platform = platform();
    match current(&platform)? {
        // Refreshing cannot help either, and a login would replace neither.
        Current::Supplied(_) | Current::Federated => Ok(None),
        Current::Stored(_) => match oauth::refresh_stale(&platform, stale) {
            Ok(session) => Ok(Some(session)),
            // The refresh window is over, so only a new login can help.
            Err(AuthError::NotAuthenticated) if interactive => Ok(sign_in_once(&platform)),
            // Anything else, being offline included, is not a lost session.
            Err(_) => Ok(None),
        },
        // Nothing to refresh, so a login is the only thing left to try.
        Current::Nothing => Ok(interactive.then(|| sign_in_once(&platform)).flatten()),
    }
}

// One browser at a time: concurrent callers that all saw the same token rejected would
// otherwise each open one, and a person would face several login tabs for one expiry.
// Non-blocking on purpose, since a login can take minutes and callers usually run on a
// shared worker pool that must not queue behind it.
fn sign_in_once(platform: &Platform) -> Option<Session> {
    let Ok(_guard) = SIGNING_IN.try_lock() else {
        return None;
    };
    oauth::login(platform).ok()
}

/// Which credential this process would use, decided in one place.
///
/// The order is a supplied token, then CI federation, then a stored browser login. It
/// is stated here and nowhere else: every consumer derives from this, because the one
/// way this goes wrong is two of them disagreeing about which credential is in force and
/// then acting on different ones.
///
/// Federation deliberately shadows a stored login. In CI the federated identity is the
/// authoritative one, and a person's leftover login is a different principal: using it
/// would act with that person's scope and attribute the audit trail to them.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Current {
    /// A token handed to this process, by [`configure`] or the environment.
    Supplied(String),
    /// CI federation is available. It mints a token for a named group, so it cannot
    /// answer without one.
    Federated,
    /// A stored browser login, as read from the store. Carried rather than re-read: this
    /// is the per-request path, so opening and parsing the file twice for one answer is
    /// waste the caller cannot avoid.
    Stored(Box<StoredToken>),
    /// Nothing to authenticate with.
    Nothing,
}

// Answered from local state: no request leaves the machine, so this is safe on a ui
// thread and during start-up. Only the stored tier opens the token store, and it is
// reached last, so an unreadable store cannot fail a caller whose credential is
// elsewhere.
pub(crate) fn current(platform: &Platform) -> Result<Current, AuthError> {
    if let Ok(token) = resolve(configured_token().or_else(|| env::var(TOKEN_ENV).ok())) {
        return Ok(Current::Supplied(token));
    }
    if oidc_source_available() {
        return Ok(Current::Federated);
    }
    Ok(oauth::stored_session(platform)?
        .map_or(Current::Nothing, |stored| Current::Stored(Box::new(stored))))
}

/// What a program can say about the current credential without asking the platform.
///
/// Answered from local state only, so it is safe on a UI thread and on startup.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AuthState {
    /// A stored browser login, with the email to show for it.
    SignedIn(String),
    /// A token was supplied, which carries no identity until it is used.
    TokenSupplied,
    /// CI federation is available. The identity depends on the group asked for, so
    /// there is none to show until [`authenticate_cli`] resolves one.
    CiFederated,
    /// Nothing to authenticate with.
    Anonymous,
}

/// The current credential, from local state only.
///
/// One answer for every program that renders who is signed in or gates on being
/// authenticated, so each does not re-derive it from variables and reach a different
/// conclusion. It contacts nothing, so it will not report a credential the platform
/// has since rejected.
///
/// Reports the credential [`authenticate_cli`] would use, in the same order, so a
/// caller deciding how to recover from a rejected request does not act on a
/// different one: a supplied token wins over everything, and CI federation wins over
/// a stored login, because that is the order the resolution follows.
///
/// # Errors
/// [`AuthError::Local`] when the token store cannot be read, which is not the same
/// as having no login and should not be presented as one.
pub fn auth_state() -> Result<AuthState, AuthError> {
    Ok(match current(&platform())? {
        Current::Supplied(_) => AuthState::TokenSupplied,
        Current::Federated => AuthState::CiFederated,
        Current::Stored(stored) => AuthState::SignedIn(stored.email),
        Current::Nothing => AuthState::Anonymous,
    })
}

/// The credential to send with a request, without contacting the platform.
///
/// Follows the same order as [`authenticate_cli`] for the tiers that can answer from
/// local state: a supplied token, else the stored browser login, refreshed when it is
/// near expiry. Ask per request. It carries no identity, because a supplied token has
/// none until the platform is asked; use [`auth_state`] for what to show a person.
///
/// Where CI federation is available it reports [`AuthError::NotAuthenticated`] rather
/// than falling through to a stored login: federation mints a token for a named group
/// and cannot answer without one, and a person's stored login is a different principal.
/// Substituting it would act with that person's scope and attribute the audit trail to
/// them, so the caller is sent to [`authenticate_cli`] with the group instead.
///
/// # Errors
/// [`AuthError::NotAuthenticated`] when nothing is available, or when only CI
/// federation is, [`AuthError::Invalid`] when a needed refresh is rejected,
/// [`AuthError::Transport`] when the platform is unreachable and [`AuthError::Local`]
/// when the token store cannot be read.
pub fn access_token() -> Result<SecretString, AuthError> {
    let platform = platform();
    match current(&platform)? {
        Current::Supplied(token) => Ok(SecretString::from(token)),
        // Federation mints a token for a named group, and a stored login is a different
        // principal, so neither can answer here.
        Current::Federated | Current::Nothing => Err(AuthError::NotAuthenticated),
        Current::Stored(stored) => Ok(oauth::token(&platform, *stored)?.token),
    }
}

/// Resolve a caller identity for a CLI, best-effort.
///
/// Tries in order: PAT (`INTEGRATES_API_TOKEN`), then a stored OAuth login
/// (refreshed if near expiry), then CI OIDC federation for `group`, else
/// unauthenticated. This is the single entry point every Fluid Attacks scanner
/// reuses. When a `group` is given it is validated on the PAT and stored-OAuth
/// paths via a group-access check and on the OIDC path server-side via the
/// `assume` exchange, so every credential is held to the same group
/// requirement. The validated token is returned in the [`Session`].
///
/// Whether an error is fatal (enforced) or degrades to an unauthenticated run
/// (prepare phase) is the caller's decision, not this function's.
///
/// # Errors
/// Returns [`AuthError::NotAuthenticated`] when no credential is available,
/// [`AuthError::Invalid`] when a credential is rejected or lacks access to the
/// group, and [`AuthError::Transport`] when the platform cannot be reached.
pub fn authenticate_cli(group: Option<&str>) -> Result<Session, AuthError> {
    let outcome = resolve_cli_identity(group);
    if matches!(&outcome, Err(AuthError::NotAuthenticated)) {
        tracing::warn!("no credential found; resolved as unauthenticated");
    }
    outcome
}

// Try each credential in turn: PAT, stored OAuth login, then CI OIDC.
fn resolve_cli_identity(group: Option<&str>) -> Result<Session, AuthError> {
    let platform = platform();
    match current(&platform)? {
        Current::Supplied(token) => {
            finish_group(&platform, supplied_session(&platform, token)?, group, "PAT")
        }
        Current::Federated => resolve_via_oidc(&platform, group),
        Current::Stored(stored) => finish_group(
            &platform,
            oauth::validated_token(&platform, *stored)?,
            group,
            "stored OAuth token",
        ),
        Current::Nothing => Err(AuthError::NotAuthenticated),
    }
}

// The supplied-token tier: unlike the others this has no identity of its own, so the
// platform is asked who it belongs to.
fn supplied_session(platform: &Platform, token: String) -> Result<Session, AuthError> {
    let email = validate(platform, &token)?;
    Ok(Session {
        email,
        token: SecretString::from(token),
        source: Credential::Pat,
    })
}

fn oidc_source_available() -> bool {
    oidc_source_present(
        env::var(GH_TOKEN_URL_ENV).ok(),
        env::var(GH_REQUEST_TOKEN_ENV).ok(),
        env::var(OIDC_TOKEN_ENV).ok(),
    )
}

// A CI OIDC id-token source: a GitHub id-token endpoint or `INTEGRATES_OIDC_TOKEN`.
fn oidc_source_present(
    github_url: Option<String>,
    github_request_token: Option<String>,
    oidc_token: Option<String>,
) -> bool {
    non_empty(oidc_token).is_some()
        || (non_empty(github_url).is_some() && non_empty(github_request_token).is_some())
}

fn resolve_via_oidc(platform: &Platform, group: Option<&str>) -> Result<Session, AuthError> {
    let Some(group) = group else {
        return Err(AuthError::NotAuthenticated);
    };
    let session = authenticate_oidc(platform, group)?;
    tracing::info!(group, "authenticated via CI OIDC; group is active");
    Ok(session)
}

// Validate group access when required and log the method.
fn finish_group(
    platform: &Platform,
    session: Session,
    group: Option<&str>,
    method: &str,
) -> Result<Session, AuthError> {
    if let Some(group) = group {
        validate_group_access(platform, session.expose_token(), group)?;
        tracing::info!(
            group,
            method,
            "authenticated; group is active and accessible"
        );
    } else {
        tracing::info!(method, "authenticated");
    }
    Ok(session)
}

fn resolve(token: Option<String>) -> Result<String, AuthError> {
    match token {
        Some(token) if !token.trim().is_empty() => Ok(token.trim().to_owned()),
        _ => Err(AuthError::NotAuthenticated),
    }
}

fn validate(platform: &Platform, token: &str) -> Result<String, AuthError> {
    let body = post_me(platform, token)?;
    parse_me_email(&body)
}

// Explicit configuration first, then the environment, then production. Blank counts as
// absent at every level, so a stray empty value cannot point this at nothing.
fn endpoint_from(explicit: Option<String>, from_env: Option<String>) -> String {
    explicit
        .or(from_env)
        .map(|value| value.trim().trim_end_matches('/').to_owned())
        .filter(|value| !value.is_empty())
        .unwrap_or_else(|| DEFAULT_BASE.to_owned())
}

fn store_key_of(base: &str) -> Option<String> {
    (base != DEFAULT_BASE).then(|| {
        base.trim_start_matches("https://")
            .trim_start_matches("http://")
            .to_owned()
    })
}

fn api_endpoint(platform: &Platform) -> String {
    format!("{}/api", platform.base)
}

fn assume_endpoint(platform: &Platform) -> String {
    format!("{}/auth/oidc/assume", platform.base)
}

// Whether the base points at loopback, i.e. a local dev integrates (which serves
// a self-signed cert).
fn is_loopback(base: &str) -> bool {
    reqwest::Url::parse(base)
        .ok()
        .and_then(|url| {
            url.host_str()
                .map(|host| matches!(host, "127.0.0.1" | "localhost" | "::1"))
        })
        .unwrap_or(false)
}

fn build_client(platform: &Platform) -> Result<reqwest::blocking::Client, AuthError> {
    let mut builder = reqwest::blocking::Client::builder()
        .redirect(reqwest::redirect::Policy::none())
        .timeout(REQUEST_TIMEOUT);
    if platform.loopback {
        // A local dev integrates serves a self-signed cert; trust it for loopback
        // only, never a remote host.
        builder = builder.danger_accept_invalid_certs(true);
    }
    builder
        .build()
        .map_err(|err| AuthError::Transport(err.without_url().to_string()))
}

fn post_me(platform: &Platform, token: &str) -> Result<String, AuthError> {
    let response = build_client(platform)?
        .post(api_endpoint(platform))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/json")
        .header("User-Agent", user_agent())
        .body(ME_QUERY)
        .send()
        .map_err(|err| AuthError::Transport(err.without_url().to_string()))?;
    let status = response.status();
    let body = response
        .text()
        .map_err(|err| AuthError::Transport(err.without_url().to_string()))?;
    if !status.is_success() {
        return Err(classify_api_status(status.as_u16(), &body));
    }
    Ok(body)
}

#[derive(Deserialize)]
struct MeResponse {
    data: Option<MeData>,
}

#[derive(Deserialize)]
struct ErrorsResponse {
    errors: Option<Vec<GraphqlError>>,
}

#[derive(Deserialize)]
struct GraphqlError {
    extensions: Option<ErrorExtensions>,
}

#[derive(Deserialize)]
struct ErrorExtensions {
    code: Option<String>,
}

#[derive(Deserialize)]
struct MeData {
    me: Option<Me>,
}

#[derive(Deserialize)]
struct Me {
    #[serde(rename = "userEmail")]
    user_email: Option<String>,
}

// A rejected token does not reach here: the platform answers the API route with
// HTTP 400 and `extensions.code` = `LOGIN_REQUIRED`, which the status check above
// classifies. This still guards the case of a parseable body with no email, and
// treats a body we cannot parse as an unexpected (transport-level) response, e.g.
// a proxy or outage page, rather than a rejected token.
fn parse_me_email(body: &str) -> Result<String, AuthError> {
    let parsed: MeResponse = serde_json::from_str(body)
        .map_err(|_| AuthError::Transport("unexpected response from the platform".to_owned()))?;
    parsed
        .data
        .and_then(|data| data.me)
        .and_then(|me| me.user_email)
        .map(|email| email.trim().to_owned())
        .filter(|email| !email.is_empty())
        .ok_or(AuthError::Invalid)
}

// The PAT-path group gate used by `authenticate_cli`: confirm the caller can
// reach `group`, rejecting one they cannot access (including a deleted or
// unknown one), which mirrors the server-side gate OIDC gets from `assume`.
fn validate_group_access(platform: &Platform, token: &str, group: &str) -> Result<(), AuthError> {
    let body = post_group(platform, token, group)?;
    parse_group_access(&body)
}

fn post_group(platform: &Platform, token: &str, group: &str) -> Result<String, AuthError> {
    let payload = serde_json::to_string(&GroupRequest {
        query: GROUP_QUERY,
        variables: GroupVariables { group_name: group },
    })
    .map_err(|err| AuthError::Transport(err.to_string()))?;
    let response = build_client(platform)?
        .post(api_endpoint(platform))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/json")
        .header("User-Agent", user_agent())
        .body(payload)
        .send()
        .map_err(|err| AuthError::Transport(err.without_url().to_string()))?;
    let status = response.status();
    let body = response
        .text()
        .map_err(|err| AuthError::Transport(err.without_url().to_string()))?;
    if !status.is_success() {
        return Err(classify_api_status(status.as_u16(), &body));
    }
    Ok(body)
}

#[derive(serde::Serialize)]
struct GroupRequest<'a> {
    query: &'a str,
    variables: GroupVariables<'a>,
}

#[derive(serde::Serialize)]
struct GroupVariables<'a> {
    #[serde(rename = "groupName")]
    group_name: &'a str,
}

#[derive(Deserialize)]
struct GroupResponse {
    data: Option<GroupData>,
}

#[derive(Deserialize)]
struct GroupData {
    group: Option<GroupNode>,
}

#[derive(Deserialize)]
struct GroupNode {
    name: Option<String>,
}

// A rejected request (no access, deleted or unknown group) comes back as HTTP
// 200 with a null `group` (and a GraphQL `errors` array), mirroring the `me`
// path; an unparseable body is a transport-level response, not a rejection.
fn parse_group_access(body: &str) -> Result<(), AuthError> {
    let parsed: GroupResponse = serde_json::from_str(body)
        .map_err(|_| AuthError::Transport("unexpected response from the platform".to_owned()))?;
    parsed
        .data
        .and_then(|data| data.group)
        .and_then(|group| group.name)
        .filter(|name| !name.trim().is_empty())
        .map(|_| ())
        .ok_or(AuthError::Invalid)
}

// The CI OIDC federation tier of `authenticate_cli`. The id-token comes from the
// CI provider: on GitHub Actions it is fetched at runtime (the job needs
// `id-token: write`), otherwise it is read from `INTEGRATES_OIDC_TOKEN`. It is
// exchanged for a short-lived service token for `group`, never logged or printed.
fn authenticate_oidc(platform: &Platform, group: &str) -> Result<Session, AuthError> {
    let id_token = acquire_id_token(
        platform,
        env::var(GH_TOKEN_URL_ENV).ok(),
        env::var(GH_REQUEST_TOKEN_ENV).ok(),
        env::var(OIDC_TOKEN_ENV).ok(),
    )?;
    let service_token = exchange(platform, &id_token, group)?;
    let email = validate(platform, &service_token)?;
    Ok(Session {
        email,
        token: SecretString::from(service_token),
        source: Credential::Oidc,
    })
}

fn acquire_id_token(
    platform: &Platform,
    github_url: Option<String>,
    github_request_token: Option<String>,
    oidc_token: Option<String>,
) -> Result<String, AuthError> {
    match (non_empty(github_url), non_empty(github_request_token)) {
        (Some(url), Some(request_token)) => fetch_github_id_token(platform, &url, &request_token),
        _ => resolve(oidc_token),
    }
}

fn non_empty(value: Option<String>) -> Option<String> {
    value
        .map(|value| value.trim().to_owned())
        .filter(|value| !value.is_empty())
}

fn classify_status(status: u16) -> AuthError {
    // 429 is deliberately not a rejected credential: `refresh_stored` deletes the
    // stored login when it sees one, so treating a rate limit that way would sign a
    // person out for waiting too little.
    if matches!(status, 400..=499) && status != TOO_MANY_REQUESTS {
        AuthError::Invalid
    } else {
        AuthError::Transport(format!("platform returned HTTP {status}"))
    }
}

// The api route reports a rejected credential as 400 carrying `LOGIN_REQUIRED`. Any
// other 4xx there is a request or service problem, a wrong endpoint or a rate limit,
// and calling those a rejected credential sends a caller off re-authenticating for
// something re-authenticating cannot fix.
fn classify_api_status(status: u16, body: &str) -> AuthError {
    if says_login_required(body) || matches!(status, UNAUTHORIZED | FORBIDDEN) {
        return AuthError::Invalid;
    }
    AuthError::Transport(format!("platform returned HTTP {status}"))
}

/// Whether a GraphQL response body says the credential was rejected.
///
/// The same contract [`LOGIN_REQUIRED_CODE`] names, checked rather than assumed, so a
/// caller detects a rejection without walking the payload itself. Pass the response body;
/// anything unparseable is not a rejection.
#[must_use]
pub fn says_login_required(body: &str) -> bool {
    serde_json::from_str::<ErrorsResponse>(body)
        .ok()
        .and_then(|parsed| parsed.errors)
        .is_some_and(|errors| {
            errors.iter().any(|error| {
                error
                    .extensions
                    .as_ref()
                    .and_then(|extensions| extensions.code.as_deref())
                    == Some(LOGIN_REQUIRED_CODE)
            })
        })
}

fn fetch_github_id_token(
    platform: &Platform,
    url: &str,
    request_token: &str,
) -> Result<String, AuthError> {
    let mut request_url =
        reqwest::Url::parse(url).map_err(|err| AuthError::Transport(err.to_string()))?;
    request_url
        .query_pairs_mut()
        // The audience is the platform being addressed.
        .append_pair("audience", &platform.base);
    let response = build_client(platform)?
        .get(request_url)
        .header("Authorization", format!("Bearer {request_token}"))
        .send()
        .map_err(|err| AuthError::Transport(err.without_url().to_string()))?;
    let status = response.status();
    if !status.is_success() {
        return Err(classify_status(status.as_u16()));
    }
    let body = response
        .text()
        .map_err(|err| AuthError::Transport(err.without_url().to_string()))?;
    parse_github_token(&body)
}

fn exchange(platform: &Platform, id_token: &str, group: &str) -> Result<String, AuthError> {
    let payload = serde_json::to_string(&AssumeRequest {
        token: id_token,
        group_name: group,
    })
    .map_err(|err| AuthError::Transport(err.to_string()))?;
    let response = build_client(platform)?
        .post(assume_endpoint(platform))
        .header("Content-Type", "application/json")
        .header("User-Agent", user_agent())
        .body(payload)
        .send()
        .map_err(|err| AuthError::Transport(err.without_url().to_string()))?;
    let status = response.status();
    if !status.is_success() {
        return Err(classify_status(status.as_u16()));
    }
    let body = response
        .text()
        .map_err(|err| AuthError::Transport(err.without_url().to_string()))?;
    parse_assume_token(&body)
}

#[derive(serde::Serialize)]
struct AssumeRequest<'a> {
    token: &'a str,
    group_name: &'a str,
}

#[derive(Deserialize)]
struct AssumeResponse {
    token: Option<String>,
}

fn parse_assume_token(body: &str) -> Result<String, AuthError> {
    let parsed: AssumeResponse = serde_json::from_str(body)
        .map_err(|_| AuthError::Transport("unexpected response from the platform".to_owned()))?;
    parsed
        .token
        .map(|token| token.trim().to_owned())
        .filter(|token| !token.is_empty())
        .ok_or(AuthError::Invalid)
}

#[derive(Deserialize)]
struct GithubTokenResponse {
    value: Option<String>,
}

fn parse_github_token(body: &str) -> Result<String, AuthError> {
    let parsed: GithubTokenResponse = serde_json::from_str(body)
        .map_err(|_| AuthError::Transport("unexpected response from GitHub".to_owned()))?;
    parsed
        .value
        .map(|value| value.trim().to_owned())
        .filter(|value| !value.is_empty())
        .ok_or_else(|| AuthError::Transport("GitHub returned no id-token".to_owned()))
}

#[cfg(test)]
mod tests {
    use std::sync::PoisonError;

    use super::*;

    #[test]
    fn resolve_accepts_and_trims_a_non_empty_token() {
        assert_eq!(resolve(Some("tok".to_owned())).unwrap(), "tok");
        assert_eq!(resolve(Some("  tok\n".to_owned())).unwrap(), "tok");
    }

    #[test]
    fn resolve_rejects_empty_or_missing() {
        assert!(matches!(
            resolve(Some("   ".to_owned())),
            Err(AuthError::NotAuthenticated)
        ));
        assert!(matches!(resolve(None), Err(AuthError::NotAuthenticated)));
    }

    #[test]
    fn parse_me_email_extracts_and_trims_the_email() {
        let body = r#"{"data":{"me":{"userEmail":"u@fluidattacks.com"}}}"#;
        assert_eq!(parse_me_email(body).unwrap(), "u@fluidattacks.com");
        let padded = r#"{"data":{"me":{"userEmail":"  u@fluidattacks.com  "}}}"#;
        assert_eq!(parse_me_email(padded).unwrap(), "u@fluidattacks.com");
    }

    #[test]
    fn parse_me_email_rejects_unauthenticated_or_blank() {
        assert!(matches!(
            parse_me_email(r#"{"data":{"me":null}}"#),
            Err(AuthError::Invalid)
        ));
        assert!(matches!(
            parse_me_email(r#"{"data":null}"#),
            Err(AuthError::Invalid)
        ));
        assert!(matches!(
            parse_me_email(r#"{"data":{"me":{"userEmail":"   "}}}"#),
            Err(AuthError::Invalid)
        ));
    }

    #[test]
    fn parse_me_email_non_json_is_transport() {
        assert!(matches!(
            parse_me_email("<html>502 Bad Gateway</html>"),
            Err(AuthError::Transport(_))
        ));
    }

    #[test]
    fn not_authenticated_message_names_the_env_var() {
        assert!(AuthError::NotAuthenticated
            .to_string()
            .contains("INTEGRATES_API_TOKEN"));
    }

    #[test]
    fn acquire_reads_the_oidc_env_var_when_no_github() {
        assert_eq!(
            acquire_id_token(
                &Platform::for_tests(),
                None,
                None,
                Some("  idtok\n".to_owned())
            )
            .unwrap(),
            "idtok"
        );
    }

    #[test]
    fn acquire_rejects_when_no_source() {
        assert!(matches!(
            acquire_id_token(&Platform::for_tests(), None, None, None),
            Err(AuthError::NotAuthenticated)
        ));
        assert!(matches!(
            acquire_id_token(
                &Platform::for_tests(),
                Some(String::new()),
                Some("   ".to_owned()),
                None
            ),
            Err(AuthError::NotAuthenticated)
        ));
    }

    #[test]
    fn oidc_source_present_detects_each_source() {
        assert!(oidc_source_present(None, None, Some("tok".to_owned())));
        assert!(oidc_source_present(
            Some("url".to_owned()),
            Some("req".to_owned()),
            None
        ));
        // GitHub needs both the endpoint and the request token.
        assert!(!oidc_source_present(Some("url".to_owned()), None, None));
        assert!(!oidc_source_present(None, None, None));
        assert!(!oidc_source_present(
            Some(String::new()),
            Some("  ".to_owned()),
            Some(String::new())
        ));
    }

    #[test]
    fn is_loopback_detects_local_hosts() {
        assert!(is_loopback("https://127.0.0.1:8001"));
        assert!(is_loopback("https://localhost:8001"));
        assert!(!is_loopback("https://app.fluidattacks.com"));
        assert!(!is_loopback("not a url"));
    }

    // nextest runs each test in its own process, so the env writes here don't
    // leak into other tests.
    #[test]
    fn the_platform_defaults_to_prod_and_honours_an_override() {
        let _guard = CONFIG_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
        std::env::remove_var(ENDPOINT_ENV);
        assert_eq!(platform().base, "https://app.fluidattacks.com");
        assert!(!platform().loopback);

        std::env::set_var(ENDPOINT_ENV, "https://localhost:8001/");
        let local = platform();
        assert_eq!(local.base, "https://localhost:8001");
        assert_eq!(api_endpoint(&local), "https://localhost:8001/api");
        assert_eq!(
            assume_endpoint(&local),
            "https://localhost:8001/auth/oidc/assume"
        );
        // A local platform gets certificate checks relaxed, and only a local one.
        assert!(local.loopback);
        // Its stored session is kept apart from production's.
        assert!(local.store_key.is_some());
        std::env::remove_var(ENDPOINT_ENV);
    }

    #[test]
    fn parse_assume_token_extracts_and_trims() {
        assert_eq!(
            parse_assume_token(r#"{"token":"  svc.tok  "}"#).unwrap(),
            "svc.tok"
        );
    }

    #[test]
    fn parse_assume_token_rejects_missing_or_blank() {
        assert!(matches!(
            parse_assume_token(r#"{"token":null}"#),
            Err(AuthError::Invalid)
        ));
        assert!(matches!(
            parse_assume_token(r#"{"token":"  "}"#),
            Err(AuthError::Invalid)
        ));
    }

    #[test]
    fn parse_assume_token_non_json_is_transport() {
        assert!(matches!(
            parse_assume_token("<html>500</html>"),
            Err(AuthError::Transport(_))
        ));
    }

    #[test]
    fn parse_github_token_extracts_and_trims() {
        assert_eq!(
            parse_github_token(r#"{"value":"  gh.jwt  "}"#).unwrap(),
            "gh.jwt"
        );
    }

    #[test]
    fn parse_github_token_rejects_missing_or_non_json() {
        assert!(matches!(
            parse_github_token(r#"{"value":null}"#),
            Err(AuthError::Transport(_))
        ));
        assert!(matches!(
            parse_github_token("not json"),
            Err(AuthError::Transport(_))
        ));
    }

    // On the api route only the platform's own code means the credential was refused.
    // A wrong endpoint or a rate limit must stay a transport problem, or a caller
    // re-authenticates for something re-authenticating cannot fix.
    #[test]
    fn api_status_is_invalid_only_when_the_platform_says_so() {
        let rejected =
            r#"{"errors":[{"message":"Login required","extensions":{"code":"LOGIN_REQUIRED"}}]}"#;
        assert!(matches!(
            classify_api_status(400, rejected),
            AuthError::Invalid
        ));
        assert!(matches!(classify_api_status(401, ""), AuthError::Invalid));
        assert!(matches!(classify_api_status(403, ""), AuthError::Invalid));
        // A malformed query is our bug, not a rejected credential.
        let other = r#"{"errors":[{"message":"Syntax Error"}]}"#;
        assert!(matches!(
            classify_api_status(400, other),
            AuthError::Transport(_)
        ));
        assert!(matches!(
            classify_api_status(404, ""),
            AuthError::Transport(_)
        ));
        assert!(matches!(
            classify_api_status(429, ""),
            AuthError::Transport(_)
        ));
    }

    // `refresh_stored` deletes the stored login on `Invalid`, so a rate limit reaching
    // that branch would sign a person out for waiting too little.
    #[test]
    fn a_rate_limit_is_never_a_rejected_credential() {
        assert!(matches!(
            classify_status(TOO_MANY_REQUESTS),
            AuthError::Transport(_)
        ));
    }

    #[test]
    fn classify_status_maps_4xx_to_invalid_else_transport() {
        // 400 is the one the platform actually sends for a rejected credential on
        // the api route, so it must read as invalid and not as an outage.
        assert!(matches!(classify_status(400), AuthError::Invalid));
        assert!(matches!(classify_status(401), AuthError::Invalid));
        assert!(matches!(classify_status(403), AuthError::Invalid));
        assert!(matches!(classify_status(500), AuthError::Transport(_)));
    }

    // The whole point of `current`: one ordering, so no two consumers can disagree about
    // which credential is in force and act on different ones. The store is pointed at a
    // temporary directory, so this does not depend on whether whoever runs it is logged
    // in.
    #[test]
    fn one_ordering_decides_which_credential_is_in_force() {
        let _guard = CONFIG_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
        let dir = tempfile::tempdir().expect("a temporary config directory");
        let restore = std::env::var("XDG_CONFIG_HOME").ok();
        std::env::set_var("XDG_CONFIG_HOME", dir.path());
        std::env::remove_var(TOKEN_ENV);
        std::env::remove_var(OIDC_TOKEN_ENV);
        let platform = Platform::for_tests();

        configure(Settings::default());
        assert_eq!(current(&platform).unwrap(), Current::Nothing);

        // Federation shadows a stored login, and there is none here either way.
        std::env::set_var(OIDC_TOKEN_ENV, "an-id-token");
        assert_eq!(current(&platform).unwrap(), Current::Federated);

        // A supplied token wins over everything else that is present.
        configure(Settings {
            token: Some(SecretString::from("a-token")),
            ..Settings::default()
        });
        assert_eq!(
            current(&platform).unwrap(),
            Current::Supplied("a-token".to_owned())
        );

        configure(Settings::default());
        std::env::remove_var(OIDC_TOKEN_ENV);
        match restore {
            Some(value) => std::env::set_var("XDG_CONFIG_HOME", value),
            None => std::env::remove_var("XDG_CONFIG_HOME"),
        }
    }

    // A browser prompt must never be offered for a credential a login would not replace:
    // the person would sign in and the request would keep sending the same rejected token.
    // Each of these returns before anything is sent, so no platform is involved.
    #[test]
    fn recovery_refuses_credentials_a_login_would_not_replace() {
        let _guard = CONFIG_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
        let dir = tempfile::tempdir().expect("a temporary config directory");
        let restore = std::env::var("XDG_CONFIG_HOME").ok();
        std::env::set_var("XDG_CONFIG_HOME", dir.path());
        std::env::remove_var(TOKEN_ENV);
        std::env::remove_var(OIDC_TOKEN_ENV);

        // A supplied token cannot be refreshed, and a login would not displace it.
        configure(Settings {
            token: Some(SecretString::from("a-token")),
            ..Settings::default()
        });
        assert!(recover("stale", true).unwrap().is_none());

        // In CI there is nobody to answer a browser, whatever `interactive` says.
        configure(Settings::default());
        std::env::set_var(OIDC_TOKEN_ENV, "an-id-token");
        assert!(recover("stale", true).unwrap().is_none());

        // Nothing stored and nobody watching: a prompt has to be asked for.
        std::env::remove_var(OIDC_TOKEN_ENV);
        assert!(recover("stale", false).unwrap().is_none());

        match restore {
            Some(value) => std::env::set_var("XDG_CONFIG_HOME", value),
            None => std::env::remove_var("XDG_CONFIG_HOME"),
        }
    }

    // Explicit beats the environment beats production, and blank counts as absent at
    // every level rather than pointing at nothing. Pure, so it needs no environment.
    #[test]
    fn endpoint_precedence_and_normalisation() {
        assert_eq!(
            endpoint_from(Some("https://explicit.test".to_owned()), None),
            "https://explicit.test"
        );
        assert_eq!(
            endpoint_from(None, Some("  https://from-env.test/  ".to_owned())),
            "https://from-env.test"
        );
        assert_eq!(endpoint_from(None, None), DEFAULT_BASE);
        assert_eq!(endpoint_from(Some(String::new()), None), DEFAULT_BASE);
        assert_eq!(endpoint_from(Some("   ".to_owned()), None), DEFAULT_BASE);
    }

    // The default platform keeps the original file so an existing login survives;
    // anything else gets its own, so a dev login cannot displace production.
    #[test]
    fn store_key_is_none_only_for_the_default_platform() {
        assert_eq!(store_key_of(DEFAULT_BASE), None);
        assert_eq!(
            store_key_of("https://localhost:8001").as_deref(),
            Some("localhost:8001")
        );
    }

    // Federation mints a token per group, so a stored login is a different principal.
    // Handing that over would act with a person's scope and bill the audit trail to
    // them, so the accessor refuses and the caller goes to `authenticate_cli(group)`.
    #[test]
    fn access_token_refuses_to_stand_in_for_federation() {
        let _guard = CONFIG_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
        let dir = tempfile::tempdir().expect("a temporary config directory");
        let restore = std::env::var("XDG_CONFIG_HOME").ok();
        std::env::set_var("XDG_CONFIG_HOME", dir.path());
        std::env::remove_var(TOKEN_ENV);
        std::env::set_var(OIDC_TOKEN_ENV, "an-id-token");
        configure(Settings::default());

        assert!(matches!(access_token(), Err(AuthError::NotAuthenticated)));

        std::env::remove_var(OIDC_TOKEN_ENV);
        match restore {
            Some(value) => std::env::set_var("XDG_CONFIG_HOME", value),
            None => std::env::remove_var("XDG_CONFIG_HOME"),
        }
    }
    #[test]
    fn client_identity_falls_back_to_the_shared_id() {
        let _guard = CONFIG_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
        configure(Settings::default());
        assert!(user_agent().starts_with(CLIENT_ID));
        configure(Settings {
            client: Some(("signals".to_owned(), "1.2.3".to_owned())),
            ..Settings::default()
        });
        assert_eq!(user_agent(), "signals/1.2.3");
        // The client id is not configurable: the platform allow-lists exactly one, and
        // sending another leaves the cli waiting for a callback that never comes.
        assert_eq!(CLIENT_ID, "fluidattacks-cli");
        configure(Settings::default());
    }

    #[test]
    fn login_required_code_matches_the_platform() {
        assert_eq!(LOGIN_REQUIRED_CODE, "LOGIN_REQUIRED");
    }

    #[test]
    fn not_authenticated_message_mentions_oidc() {
        assert!(AuthError::NotAuthenticated
            .to_string()
            .contains("INTEGRATES_OIDC_TOKEN"));
    }

    #[test]
    fn parse_group_access_ok_when_group_returned() {
        assert!(parse_group_access(r#"{"data":{"group":{"name":"daimon"}}}"#).is_ok());
    }

    #[test]
    fn parse_group_access_rejects_no_access_or_missing() {
        assert!(matches!(
            parse_group_access(r#"{"data":{"group":null},"errors":[{"message":"Access denied"}]}"#),
            Err(AuthError::Invalid)
        ));
        assert!(matches!(
            parse_group_access(r#"{"data":null}"#),
            Err(AuthError::Invalid)
        ));
        assert!(matches!(
            parse_group_access(r#"{"data":{"group":{"name":"   "}}}"#),
            Err(AuthError::Invalid)
        ));
    }

    #[test]
    fn parse_group_access_non_json_is_transport() {
        assert!(matches!(
            parse_group_access("<html>502 Bad Gateway</html>"),
            Err(AuthError::Transport(_))
        ));
    }
}