fluidattacks-core 0.15.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
use std::env;
use std::sync::RwLock;
use std::time::Duration;

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

mod oauth;
mod store;

pub use oauth::{identity, login, logout, refresh, refresh_stale, token};

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, and does not have to
// lock around doing so.
static ENDPOINT: RwLock<Option<String>> = RwLock::new(None);
static PAT: RwLock<Option<String>> = RwLock::new(None);
static CLIENT: RwLock<Option<(String, String)>> = RwLock::new(None);

// 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(());

fn read<T: Clone>(lock: &RwLock<Option<T>>) -> Option<T> {
    lock.read().ok().and_then(|value| value.clone())
}

fn write<T>(lock: &RwLock<Option<T>>, value: Option<T>) {
    if let Ok(mut slot) = lock.write() {
        *slot = value;
    }
}

/// Point this process at a platform, overriding `INTEGRATES_ENDPOINT`.
///
/// Every login, refresh, validation and token store lookup derives from this, so set
/// it 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. `None` restores the environment default.
///
/// The stored session is kept per platform, so signing in to a local instance never
/// displaces a production login.
pub fn set_endpoint(endpoint: Option<&str>) {
    let normalized = endpoint
        .map(|value| value.trim().trim_end_matches('/').to_owned())
        .filter(|value| !value.is_empty());
    write(&ENDPOINT, normalized);
}

/// Supply the personal access token for this process, overriding
/// `INTEGRATES_API_TOKEN`.
///
/// For a program that holds its token somewhere other than that variable, or that
/// would otherwise rewrite it: the variable is inherited by subprocesses, so setting
/// it changes what they authenticate as too. Set this once during start-up alongside
/// [`set_endpoint`], under the same constraint: it is process wide, so it is not a
/// way to use a different token per request. `None` restores the environment
/// default.
pub fn set_pat(pat: Option<&str>) {
    write(
        &PAT,
        pat.map(|value| value.trim().to_owned())
            .filter(|value| !value.is_empty()),
    );
}

/// Name this program, for the `User-Agent` it sends and the client it logs in as.
///
/// Without it the platform sees one identity for every tool, so a consent screen
/// and an audit trail cannot say which one asked.
pub fn set_client(name: &str, version: &str) {
    write(&CLIENT, Some((name.to_owned(), version.to_owned())));
}

fn configured_pat() -> Option<String> {
    read(&PAT)
}

fn user_agent() -> String {
    read(&CLIENT).map_or_else(
        || format!("{CLIENT_ID}/unknown"),
        |(name, version)| format!("{name}/{version}"),
    )
}

/// 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.
///
/// Callers branch on this instead of inspecting variables themselves: a
/// [`Credential::Pat`] cannot be refreshed or replaced by signing in, so recovery
/// that makes sense for a browser login is pointless for it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Credential {
    /// `INTEGRATES_API_TOKEN`, or one supplied through [`set_pat`].
    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 {}

// The `INTEGRATES_API_TOKEN` personal access token tier of `authenticate_cli`.
fn authenticate() -> Result<Session, AuthError> {
    let token = resolve(configured_pat().or_else(|| env::var(TOKEN_ENV).ok()))?;
    let email = validate(&token)?;
    Ok(Session {
        email,
        token: SecretString::new(token.into_boxed_str()),
        source: Credential::Pat,
    })
}

/// 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> {
    if let Some(state) = state_before_the_store(pat_supplied(), oidc_source_available()) {
        return Ok(state);
    }
    Ok(oauth::identity()?.map_or(AuthState::Anonymous, AuthState::SignedIn))
}

// Kept in step with `resolve_cli_identity` and `resolve_after_pat`: the pat is tried
// first, then CI federation, which deliberately shadows a stored login, and only then
// the stored login itself. Reporting a different order sends a caller off recovering a
// credential that was never in play.
//
// Both tiers here answer without opening the store, so a store that cannot be read
// never fails a caller whose credential does not live in it.
const fn state_before_the_store(pat_supplied: bool, oidc_available: bool) -> Option<AuthState> {
    if pat_supplied {
        return Some(AuthState::TokenSupplied);
    }
    if oidc_available {
        return Some(AuthState::CiFederated);
    }
    None
}

// Whether a pat is available at all, however it was supplied.
fn pat_supplied() -> bool {
    configured_pat()
        .or_else(|| env::var(TOKEN_ENV).ok())
        .is_some_and(|value| !value.trim().is_empty())
}

/// 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> {
    access_token_from(
        configured_pat().or_else(|| env::var(TOKEN_ENV).ok()),
        oidc_source_available(),
    )
}

fn access_token_from(pat: Option<String>, oidc_available: bool) -> Result<SecretString, AuthError> {
    if let Ok(pat) = resolve(pat) {
        return Ok(SecretString::new(pat.into_boxed_str()));
    }
    if oidc_available {
        return Err(AuthError::NotAuthenticated);
    }
    let session = oauth::token()?;
    Ok(SecretString::new(
        session.expose_token().to_owned().into_boxed_str(),
    ))
}

/// 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> {
    match authenticate() {
        Ok(session) => finish_group(session, group, "PAT"),
        Err(AuthError::NotAuthenticated) => resolve_after_pat(group),
        Err(err) => Err(err),
    }
}

fn resolve_after_pat(group: Option<&str>) -> Result<Session, AuthError> {
    // In CI the OIDC identity is authoritative; skip any ambient stored login so
    // it cannot shadow or block it.
    if oidc_source_available() {
        return resolve_via_oidc(group);
    }
    match oauth::validated_token() {
        Ok(session) => finish_group(session, group, "stored OAuth token"),
        // No usable stored login; fall through to CI OIDC.
        Err(AuthError::NotAuthenticated | AuthError::Local(_)) => resolve_via_oidc(group),
        Err(err) => Err(err),
    }
}

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(group: Option<&str>) -> Result<Session, AuthError> {
    let Some(group) = group else {
        return Err(AuthError::NotAuthenticated);
    };
    let session = authenticate_oidc(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(session: Session, group: Option<&str>, method: &str) -> Result<Session, AuthError> {
    if let Some(group) = group {
        validate_group_access(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(token: &str) -> Result<String, AuthError> {
    let body = post_me(token)?;
    parse_me_email(&body)
}

// The integrates base URL: `INTEGRATES_ENDPOINT` (e.g. a local dev instance) or
// the production default. Every endpoint derives from it.
fn base_url() -> String {
    endpoint_from(read(&ENDPOINT), env::var(ENDPOINT_ENV).ok())
}

// 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())
}

// Which stored session belongs to the platform in force: `None` for the default, so
// its file name is unchanged and logins that predate per-platform storage still work.
pub(crate) fn store_key() -> Option<String> {
    store_key_of(&base_url())
}

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() -> String {
    format!("{}/api", base_url())
}

fn audience() -> String {
    base_url()
}

fn assume_endpoint() -> String {
    format!("{}/auth/oidc/assume", base_url())
}

// 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() -> Result<reqwest::blocking::Client, AuthError> {
    let mut builder = reqwest::blocking::Client::builder()
        .redirect(reqwest::redirect::Policy::none())
        .timeout(REQUEST_TIMEOUT);
    if is_loopback(&base_url()) {
        // 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(token: &str) -> Result<String, AuthError> {
    let response = build_client()?
        .post(api_endpoint())
        .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(token: &str, group: &str) -> Result<(), AuthError> {
    let body = post_group(token, group)?;
    parse_group_access(&body)
}

fn post_group(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()?
        .post(api_endpoint())
        .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(group: &str) -> Result<Session, AuthError> {
    let id_token = acquire_id_token(
        env::var(GH_TOKEN_URL_ENV).ok(),
        env::var(GH_REQUEST_TOKEN_ENV).ok(),
        env::var(OIDC_TOKEN_ENV).ok(),
    )?;
    let service_token = exchange(&id_token, group)?;
    let email = validate(&service_token)?;
    Ok(Session {
        email,
        token: SecretString::new(service_token.into_boxed_str()),
        source: Credential::Oidc,
    })
}

fn acquire_id_token(
    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(&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}"))
}

// The same contract `LOGIN_REQUIRED_CODE` documents, checked rather than assumed.
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(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()
        .append_pair("audience", &audience());
    let response = build_client()?
        .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(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()?
        .post(assume_endpoint())
        .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(None, None, Some("  idtok\n".to_owned())).unwrap(),
            "idtok"
        );
    }

    #[test]
    fn acquire_rejects_when_no_source() {
        assert!(matches!(
            acquire_id_token(None, None, None),
            Err(AuthError::NotAuthenticated)
        ));
        assert!(matches!(
            acquire_id_token(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 base_url_defaults_to_prod_and_honours_override() {
        let _guard = CONFIG_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
        std::env::remove_var(ENDPOINT_ENV);
        assert_eq!(base_url(), "https://app.fluidattacks.com");
        assert!(!is_loopback(&base_url()));

        std::env::set_var(ENDPOINT_ENV, "https://localhost:8001/");
        assert_eq!(base_url(), "https://localhost:8001");
        assert_eq!(api_endpoint(), "https://localhost:8001/api");
        assert_eq!(assume_endpoint(), "https://localhost:8001/auth/oidc/assume");
        assert!(is_loopback(&base_url()));
        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 default platform shares one file; anything else gets its own, so a dev
    // login cannot silently replace a production one.
    // A supplied token is what `authenticate_cli` would use, so it has to be what is
    // reported: saying "oauth" here sends a caller off refreshing a login for a
    // failure the token caused.
    #[test]
    fn state_reports_the_credential_that_would_be_used() {
        // A supplied token wins over everything else that is present.
        assert_eq!(
            state_before_the_store(true, true),
            Some(AuthState::TokenSupplied)
        );
        assert_eq!(
            state_before_the_store(true, false),
            Some(AuthState::TokenSupplied)
        );
        // In CI the federated identity shadows a stored login, so saying "signed in"
        // here would send a caller off refreshing a session that is not in use, and
        // then opening a browser on a machine that has nobody at it.
        assert_eq!(
            state_before_the_store(false, true),
            Some(AuthState::CiFederated)
        );
        // Only with neither is the store worth opening.
        assert_eq!(state_before_the_store(false, false), None);
    }

    // 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() {
        assert!(matches!(
            access_token_from(None, true),
            Err(AuthError::NotAuthenticated)
        ));
        // A supplied token still answers, and without opening the store.
        let token = access_token_from(Some("  a-pat  ".to_owned()), true)
            .expect("a supplied token answers");
        assert_eq!(token.expose_secret(), "a-pat");
    }

    #[test]
    fn client_identity_falls_back_to_the_shared_id() {
        let _guard = CONFIG_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
        write(&CLIENT, None);
        assert!(user_agent().starts_with(CLIENT_ID));
        set_client("signals", "1.2.3");
        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");
        write(&CLIENT, None);
    }

    #[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(_))
        ));
    }
}