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

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

mod oauth;
mod store;

pub use oauth::{authenticate_oauth, logout, resolve_oauth_session, whoami};

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";
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);

/// 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,
}

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 {}

/// Authenticate with the `INTEGRATES_API_TOKEN` personal access token and
/// return the authenticated stakeholder identity. For CI OIDC federation use
/// [`authenticate_oidc`].
///
/// # Errors
/// Returns [`AuthError::NotAuthenticated`] when no token is set,
/// [`AuthError::Invalid`] when the platform rejects it, and
/// [`AuthError::Transport`] when the platform cannot be reached.
pub fn authenticate() -> Result<Session, AuthError> {
    let token = resolve(env::var(TOKEN_ENV).ok())?;
    let email = validate(&token)?;
    Ok(Session {
        email,
        token: SecretString::new(token.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::resolve_oauth_session() {
        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 {
    env::var(ENDPOINT_ENV)
        .ok()
        .map(|value| value.trim().trim_end_matches('/').to_owned())
        .filter(|value| !value.is_empty())
        .unwrap_or_else(|| DEFAULT_BASE.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")
        .body(ME_QUERY)
        .send()
        .map_err(|err| AuthError::Transport(err.without_url().to_string()))?;
    let status = response.status();
    if !status.is_success() {
        return Err(AuthError::Transport(format!(
            "platform returned HTTP {}",
            status.as_u16()
        )));
    }
    response
        .text()
        .map_err(|err| AuthError::Transport(err.without_url().to_string()))
}

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

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

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

// integrates answers a rejected token with HTTP 200 and a null `me`, so a
// parseable body with no email is an auth failure; a body we cannot parse is an
// unexpected (transport-level) response — e.g. a proxy/outage page — not 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")
        .body(payload)
        .send()
        .map_err(|err| AuthError::Transport(err.without_url().to_string()))?;
    let status = response.status();
    if !status.is_success() {
        return Err(AuthError::Transport(format!(
            "platform returned HTTP {}",
            status.as_u16()
        )));
    }
    response
        .text()
        .map_err(|err| AuthError::Transport(err.without_url().to_string()))
}

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

/// Authenticate via CI OIDC federation for `group`, returning the group's
/// service identity.
///
/// The OIDC id-token is obtained 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` (e.g. a GitLab `id_tokens` entry with audience
/// `https://app.fluidattacks.com`). The id-token is exchanged for a short-lived
/// service token, which is validated and returned in the [`Session`] alongside
/// the identity so authorization consumers can call the platform API as the
/// group. The token is never logged or printed.
///
/// # Errors
/// Returns [`AuthError::NotAuthenticated`] when no id-token source is
/// available, [`AuthError::Invalid`] when the platform rejects the token or the
/// group is not federated, and [`AuthError::Transport`] when a service cannot
/// be reached.
pub 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()),
    })
}

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 {
    if matches!(status, 400..=499) {
        AuthError::Invalid
    } else {
        AuthError::Transport(format!("platform returned HTTP {status}"))
    }
}

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")
        .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 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() {
        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(_))
        ));
    }

    #[test]
    fn classify_status_maps_4xx_to_invalid_else_transport() {
        assert!(matches!(classify_status(401), AuthError::Invalid));
        assert!(matches!(classify_status(403), AuthError::Invalid));
        assert!(matches!(classify_status(500), AuthError::Transport(_)));
    }

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