Skip to main content

runner_manager_github/
lib.rs

1// owner: c2-device-flow-auth
2//
3// c2 also owns the shared authenticated HTTP client that lives at this crate
4// root; c3 owns `rest`, and c4 owns `demand` and `jit`.
5
6//! The GitHub gateway.
7//!
8//! This crate holds every line of code in the product that talks to GitHub, and
9//! the crate root holds the one client all of it goes through.
10//!
11//! * [`device_flow`] — the OAuth 2.0 Device Authorization Grant, which is the
12//!   *only* way this product ever obtains a credential (D3, D16).
13//! * [`AuthenticatedClient`] — the shared `api.github.com` client. Every request
14//!   in this crate is built by it, which is what makes "sets
15//!   `X-GitHub-Api-Version` and an explicit `Accept`" a property of the design
16//!   rather than of each call site, and what lets the authentication-failure
17//!   taxonomy be implemented exactly once.
18//! * [`rest`], [`demand`], [`jit`] — typed adapters owned by `c3` and `c4`,
19//!   built on [`AuthenticatedClient`].
20//!
21//! # Three properties this crate is required to keep
22//!
23//! **It holds no client secret, and it renews without one.** This paragraph
24//! used to say the opposite — that the App opts out of user-token expiration,
25//! that no renewal token is ever issued, and that renewing would require a
26//! client secret a public client cannot hold. All three were wrong, and a test
27//! in this crate enforced the error by forbidding the word "refresh token".
28//!
29//! The published App has user-token expiration **on**: a device-flow exchange
30//! returns `expires_in: 28800` and a `refresh_token`. GitHub requires the
31//! client secret to refresh *"unless the user access token was generated using
32//! the device flow"*, and every one of this product's is. So the credential
33//! renews itself, no server appears in the design, and the eight-hour life of
34//! an access token is invisible to a daemon that runs for months. See
35//! [`AuthenticatedClient::renew_once`], and
36//! `docs/spikes/token-expiry-and-renewal.md` for the two renewals that
37//! confirmed it on real hosts.
38//!
39//! [`AuthenticatedClient::revalidate`] is what still happens on a `401` for a
40//! credential with no refresh half — every one issued before 0.1.11.
41//!
42//! **It persists nothing.** [`device_flow::DeviceFlow::complete`] *returns* the
43//! token; it never writes it anywhere. The machine-scoped secret store is `d2`
44//! and the wiring is `f1`. That boundary is why this crate has no dependency on
45//! `runner-manager-platform` and performs no filesystem write outside its own
46//! tests — and it is what lets the whole gateway be tested with no platform
47//! dependency at all.
48//!
49//! **It never renders a secret.** The device code, the user access token, and
50//! every header carrying either are absent from `Debug`, from `Display`, from
51//! errors, and from tracing output. Every type here that holds one wraps it in
52//! [`secrecy::SecretString`] *and* implements [`fmt::Debug`] by hand, because a
53//! `#[derive(Debug)]` added later to a struct with a plain `String` field is
54//! precisely how this control is lost. `tests/no_secret_reaches_the_logs.rs`
55//! drives a whole login and an authenticated round trip through a capturing
56//! `tracing` subscriber and fails if any of the three appears.
57//!
58//! That scan is a **separate test binary**, and deliberately so. As a unit test
59//! it silently stopped working: `tracing` caches each callsite's `Interest`
60//! process-wide while `with_default` installs a subscriber on one *thread*, and
61//! run **concurrently** with the crate's other unit tests the scan captured
62//! only its own handful of events — passing with a real device-code leak on the
63//! live path. A binary holding one test has no concurrency to be poisoned by.
64//! The word "concurrently" is load-bearing and was measured;
65//! `tests/no_secret_reaches_the_logs.rs` records the numbers and what they rule
66//! out.
67
68pub mod demand;
69pub mod device_flow;
70pub mod jit;
71pub mod rest;
72
73use std::{
74    fmt,
75    sync::{
76        Arc,
77        atomic::{AtomicU64, Ordering},
78    },
79    time::Duration,
80};
81
82use chrono::{DateTime, Utc};
83use reqwest::{Method, StatusCode};
84use runner_manager_domain::model::{Clock, Org, OwnerRepo, Timestamp};
85
86/// Re-exported because [`GithubError::headers`] and [`ApiResponse::headers`]
87/// return one, and a consumer cannot *name* a type it has no path to.
88///
89/// `a1` owns every manifest in this workspace, so a crate outside this one that
90/// wanted to hold a `HeaderMap` from this seam would otherwise need `reqwest`
91/// added to its own dependencies — turning a `c2` seam into an `a1` change, and
92/// putting `reqwest`'s version in two places at once. [`GithubError::retry_after`]
93/// and [`GithubError::rate_limit`] exist precisely so that the common cases need
94/// no path at all; this is for the ones that do.
95///
96/// It is re-exported under its own name rather than an alias so that the type a
97/// consumer imports is the type the signatures already show.
98pub use reqwest::header::HeaderMap;
99use secrecy::{ExposeSecret, SecretString};
100use serde::{Deserialize, Serialize, de::DeserializeOwned};
101use url::Url;
102
103// ---------------------------------------------------------------------------
104// Constants
105// ---------------------------------------------------------------------------
106
107/// The REST API version every request pins.
108///
109/// `04-subsystem-contracts.md`: "All requests set `X-GitHub-Api-Version` and an
110/// explicit `Accept` header." Both spikes ran against this version.
111pub const GITHUB_API_VERSION: &str = "2022-11-28";
112
113/// The media type every request asks for, stated rather than defaulted.
114pub const GITHUB_ACCEPT: &str = "application/vnd.github+json";
115
116/// Production `api.github.com`.
117pub const GITHUB_API_BASE: &str = "https://api.github.com/";
118
119/// Production `github.com`, which hosts the device-flow endpoints. They are on
120/// the web host, not the API host.
121pub const GITHUB_WEB_BASE: &str = "https://github.com/";
122
123/// The canonical page a user types their code into.
124///
125/// This constant *is* the phishing control (`07-security.md`, threat table): the
126/// tool prints this URL and never proxies, embeds, or imitates the approval
127/// page. [`Endpoints::verification_url`] derives from the configured web base so
128/// a test server can be pointed at, and
129/// [`device_flow::DeviceAuthorization::verification_uri`] is checked against it
130/// so a response that tries to send the user somewhere else is rejected rather
131/// than displayed.
132pub const DEVICE_VERIFICATION_PATH: &str = "login/device";
133
134/// What a `401` re-validates the held credential against.
135///
136/// `GET /user/installations` rather than `GET /user`, because it is the call the
137/// D18 spike actually made with a user-to-server token and observed `200` from
138/// (`docs/spikes/d18-org-jit-verification.md`, "The permission that authorized
139/// it"), and because a successful re-validation then carries the same answer
140/// [`AuthenticatedClient::discover_installations`] needs.
141pub const REVALIDATION_PATH: &str = "/user/installations";
142
143/// How long a lockout backs off for when GitHub sends no `retry-after`.
144///
145/// `03-control-flows.md` flow 4.3 requires a back-off but names no duration.
146/// Sixty seconds is GitHub's own documented floor for its secondary rate limits.
147pub const DEFAULT_LOCKOUT_BACKOFF: Duration = Duration::from_secs(60);
148
149/// The longest a lockout may silence this client, whatever `Retry-After` said.
150///
151/// A back-off is a *safety* mechanism, and an unclamped one is a denial of
152/// service with extra steps: `Retry-After: 86400` would latch a silent
153/// twenty-four-hour outage of the agent's reconciliation loop, clearable only by
154/// [`AuthenticatedClient::clear_lockout`]. Fifteen minutes is far longer than any
155/// back-off GitHub documents for the authentication lockout this latches on, and
156/// short enough that a hostile or simply wrong header cannot take the product
157/// down for a shift. Honouring a header without a ceiling is trusting a remote
158/// party with the product's availability.
159pub const MAX_LOCKOUT_BACKOFF: Duration = Duration::from_secs(15 * 60);
160
161/// The most pages either pagination loop follows before giving up.
162///
163/// A `Link: rel="next"` that points back at the page it arrived on — a proxy
164/// rewriting the header, or a bug at the other end — is an infinite loop inside
165/// the agent's reconciliation loop, which is the one place in this product that
166/// must not be able to wedge. At `per_page=100` this ceiling is ten thousand
167/// installations or repositories, past any real account by orders of magnitude,
168/// so it bounds the pathological case without truncating a legitimate one.
169pub const MAX_PAGES: usize = 100;
170
171/// Per-request ceiling, so one wedged connection cannot stall the agent's
172/// reconciliation loop forever.
173pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
174
175/// The `User-Agent` GitHub requires on every API request.
176pub const USER_AGENT: &str = concat!("runner-manager/", env!("CARGO_PKG_VERSION"));
177
178// ---------------------------------------------------------------------------
179// The published App
180// ---------------------------------------------------------------------------
181
182/// The published GitHub App this product authenticates as (D3, D16).
183///
184/// Both fields are **public by design**. `07-security.md`'s credential inventory
185/// lists the `client_id` as "Not secret … may appear in logs and documentation",
186/// which is exactly what makes the device flow serverless: a public client
187/// cannot secure a client secret, and this design never tries to.
188///
189/// The concrete values are *not* compiled in here. Registering and publishing
190/// the App is Phase 0 of `06-migration-rollout.md` and has not happened, so
191/// there is no honest value to write; `f1` supplies both when it wires the CLI.
192/// Committing a placeholder that looked real would be worse than requiring the
193/// caller to pass one.
194#[derive(Debug, Clone, PartialEq, Eq)]
195pub struct AppRegistration {
196    client_id: String,
197    slug: String,
198}
199
200impl AppRegistration {
201    /// # Errors
202    /// An empty `client_id` or an empty `slug`.
203    pub fn new(client_id: impl Into<String>, slug: impl Into<String>) -> Result<Self, ConfigError> {
204        let client_id = client_id.into();
205        let slug = slug.into();
206        if client_id.trim().is_empty() {
207            return Err(ConfigError::Empty { what: "client_id" });
208        }
209        if slug.trim().is_empty() {
210            return Err(ConfigError::Empty { what: "app slug" });
211        }
212        Ok(Self { client_id, slug })
213    }
214
215    #[must_use]
216    pub fn client_id(&self) -> &str {
217        &self.client_id
218    }
219
220    #[must_use]
221    pub fn slug(&self) -> &str {
222        &self.slug
223    }
224
225    /// The canonical URL a user with no installation must visit.
226    ///
227    /// `03-control-flows.md` flow 1.1: "If the published App is not yet installed
228    /// on any repository, it prints the installation URL."
229    ///
230    /// # Panics
231    /// Never, for a registration built through [`AppRegistration::new`]: the slug
232    /// is non-empty and is percent-encoded into the path.
233    #[must_use]
234    pub fn install_url(&self, endpoints: &Endpoints) -> Url {
235        endpoints
236            .web_base
237            .join("apps/")
238            .and_then(|u| u.join(&format!("{}/", encode_path_segment(&self.slug))))
239            .and_then(|u| u.join("installations/new"))
240            .expect("a non-empty encoded slug always joins onto the web base")
241    }
242}
243
244fn encode_path_segment(raw: &str) -> String {
245    raw.chars()
246        .map(|c| {
247            if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '~') {
248                c.to_string()
249            } else {
250                let mut buf = [0_u8; 4];
251                c.encode_utf8(&mut buf)
252                    .as_bytes()
253                    .iter()
254                    .map(|b| format!("%{b:02X}"))
255                    .collect()
256            }
257        })
258        .collect()
259}
260
261/// Where GitHub is.
262///
263/// Two bases rather than one, because the device grant lives on `github.com`
264/// while every API call lives on `api.github.com`. Tests point both at one
265/// `wiremock` server; the paths do not collide.
266#[derive(Debug, Clone, PartialEq, Eq)]
267pub struct Endpoints {
268    api_base: Url,
269    web_base: Url,
270}
271
272impl Endpoints {
273    /// Production GitHub.
274    ///
275    /// # Panics
276    /// Never: both constants are parsed at every call and are valid URLs.
277    #[must_use]
278    pub fn production() -> Self {
279        Self {
280            api_base: Url::parse(GITHUB_API_BASE).expect("GITHUB_API_BASE is a valid URL"),
281            web_base: Url::parse(GITHUB_WEB_BASE).expect("GITHUB_WEB_BASE is a valid URL"),
282        }
283    }
284
285    /// Both bases are normalised to end in `/` so that relative joins keep the
286    /// whole base path instead of replacing its last segment.
287    #[must_use]
288    pub fn new(api_base: Url, web_base: Url) -> Self {
289        Self {
290            api_base: with_trailing_slash(api_base),
291            web_base: with_trailing_slash(web_base),
292        }
293    }
294
295    /// Point every endpoint at one test server.
296    ///
297    /// # Errors
298    /// `root` not being a parseable absolute URL.
299    pub fn for_test_server(root: &str) -> Result<Self, ConfigError> {
300        let root = Url::parse(root).map_err(|_| ConfigError::Empty {
301            what: "test server URL",
302        })?;
303        Ok(Self::new(root.clone(), root))
304    }
305
306    #[must_use]
307    pub fn api_base(&self) -> &Url {
308        &self.api_base
309    }
310
311    #[must_use]
312    pub fn web_base(&self) -> &Url {
313        &self.web_base
314    }
315
316    /// # Panics
317    /// Never: the path is a constant and the base ends in `/`.
318    #[must_use]
319    pub fn device_code_url(&self) -> Url {
320        self.web_base
321            .join("login/device/code")
322            .expect("a constant path joins onto a normalised base")
323    }
324
325    /// # Panics
326    /// Never: the path is a constant and the base ends in `/`.
327    #[must_use]
328    pub fn access_token_url(&self) -> Url {
329        self.web_base
330            .join("login/oauth/access_token")
331            .expect("a constant path joins onto a normalised base")
332    }
333
334    /// The canonical page the user code is typed into, and the only device-flow
335    /// URL this product ever prints.
336    ///
337    /// # Panics
338    /// Never: the path is a constant and the base ends in `/`.
339    #[must_use]
340    pub fn verification_url(&self) -> Url {
341        self.web_base
342            .join(DEVICE_VERIFICATION_PATH)
343            .expect("a constant path joins onto a normalised base")
344    }
345}
346
347impl Default for Endpoints {
348    fn default() -> Self {
349        Self::production()
350    }
351}
352
353fn with_trailing_slash(mut url: Url) -> Url {
354    if !url.path().ends_with('/') {
355        let path = format!("{}/", url.path());
356        url.set_path(&path);
357    }
358    url
359}
360
361/// A configuration value this crate refuses to start with.
362#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
363pub enum ConfigError {
364    #[error("{what} must not be empty")]
365    Empty { what: &'static str },
366}
367
368// ---------------------------------------------------------------------------
369// The credential
370// ---------------------------------------------------------------------------
371
372/// A user access token obtained from the device flow.
373///
374/// **Non-expiring, and non-renewable.** The published App opts out of
375/// user-token expiration, so GitHub issues no renewal token alongside this one
376/// and there is nothing to renew — see the crate documentation. The token is
377/// invalidated only by the user uninstalling the App or revoking the
378/// authorization at GitHub.
379///
380/// `Debug` is written by hand. Deriving it here would put the token into every
381/// `tracing` field, every `unwrap()` panic message, and every `anyhow` chain
382/// that ever carries one, which is the exact leak `07-security.md` gates on.
383#[derive(Clone)]
384pub struct UserAccessToken {
385    token: SecretString,
386    token_type: String,
387    scope: Option<String>,
388    /// The renewal half, when the App issues one.
389    ///
390    /// # Why this is an `Option` rather than a second type
391    ///
392    /// Whether a credential can renew itself is a setting on the *App*, not a
393    /// property of this build: an App with user-token expiration off returns an
394    /// access token and nothing else, and one with it on returns a pair. Both
395    /// shapes reach this type, and a host holding either must keep working --
396    /// otherwise flipping that setting would strand every installation that had
397    /// not upgraded, which for a published product is an outage nobody asked
398    /// for.
399    ///
400    /// `None` is therefore not a defect. It is the credential this product held
401    /// for its whole life until now: non-expiring, unrenewable, replaced only
402    /// by an interactive `auth login`.
403    renewal: Option<Renewal>,
404}
405
406/// What a token needs in order to replace itself without a person.
407#[derive(Clone)]
408pub struct Renewal {
409    refresh_token: SecretString,
410    /// When the access token stops being accepted, if it was stated.
411    pub access_expires_at: Option<DateTime<Utc>>,
412    /// When the *refresh* token stops working. Past this, only an interactive
413    /// sign-in helps -- and it is six months from the last renewal, not from
414    /// the first sign-in, so a host that runs at all never reaches it.
415    pub refresh_expires_at: Option<DateTime<Utc>>,
416}
417
418impl Renewal {
419    /// The refresh token itself. Kept behind a method for the same reason the
420    /// access token is: it is the more dangerous half of the pair, because it
421    /// mints access tokens indefinitely.
422    #[must_use]
423    pub fn refresh_token(&self) -> &SecretString {
424        &self.refresh_token
425    }
426}
427
428impl fmt::Debug for Renewal {
429    /// Written by hand, like [`UserAccessToken`]'s, and for a stronger reason:
430    /// a leaked refresh token does not expire in eight hours.
431    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
432        f.debug_struct("Renewal")
433            .field("refresh_token", &"[redacted]")
434            .field("access_expires_at", &self.access_expires_at)
435            .field("refresh_expires_at", &self.refresh_expires_at)
436            .finish()
437    }
438}
439
440impl UserAccessToken {
441    #[must_use]
442    pub fn new(token: SecretString) -> Self {
443        Self {
444            token,
445            token_type: "bearer".to_string(),
446            scope: None,
447            renewal: None,
448        }
449    }
450
451    /// The whole credential as the token endpoint returned it. `pub(crate)`
452    /// because [`device_flow`] is the only thing in the product entitled to mint
453    /// one — every other path receives a token rather than constructing it.
454    pub(crate) fn from_parts(
455        token: SecretString,
456        token_type: String,
457        scope: Option<String>,
458    ) -> Self {
459        Self {
460            token,
461            token_type,
462            scope,
463            renewal: None,
464        }
465    }
466
467    /// Attach the renewal half, if the App issued one.
468    ///
469    /// The two durations are seconds-from-now as GitHub states them, turned
470    /// into instants here so that nothing downstream has to remember when
471    /// "now" was.
472    #[must_use]
473    pub(crate) fn with_renewal(
474        mut self,
475        refresh_token: Option<SecretString>,
476        access_expires_in: Option<u64>,
477        refresh_expires_in: Option<u64>,
478    ) -> Self {
479        self.renewal = refresh_token.map(|refresh_token| {
480            let at = |secs: Option<u64>| {
481                secs.and_then(|s| i64::try_from(s).ok())
482                    .and_then(|s| Utc::now().checked_add_signed(chrono::TimeDelta::seconds(s)))
483            };
484            Renewal {
485                refresh_token,
486                access_expires_at: at(access_expires_in),
487                refresh_expires_at: at(refresh_expires_in),
488            }
489        });
490        self
491    }
492
493    /// The renewal half, when there is one.
494    #[must_use]
495    pub fn renewal(&self) -> Option<&Renewal> {
496        self.renewal.as_ref()
497    }
498
499    /// Rebuild the credential `d2` handed back, for `f1`.
500    #[must_use]
501    pub fn from_stored(token: SecretString) -> Self {
502        Self::from_stored_document(&token)
503    }
504
505    /// Reads whichever of the two stored shapes is there.
506    ///
507    /// # Why the store holds a document now, and why the old shape still loads
508    ///
509    /// A renewable credential is three values -- access token, refresh token,
510    /// and when each stops working -- where there used to be one string. The
511    /// secret store takes one opaque value per host, so the document goes
512    /// inside it rather than the store growing a schema: no platform change, no
513    /// migration step, and the same DPAPI blob or keychain item as before.
514    ///
515    /// **A value that is not this document is a bare access token**, which is
516    /// what every host stored until now. That is not a fallback for tidiness:
517    /// upgrading must not log anybody out, and the App's expiration setting can
518    /// be turned on -- or back off -- without stranding hosts that are mid-way
519    /// through either. A token has no internal structure to confuse with JSON,
520    /// so the discrimination is unambiguous.
521    #[must_use]
522    pub fn from_stored_document(stored: &SecretString) -> Self {
523        #[derive(Deserialize)]
524        struct Document {
525            access_token: String,
526            #[serde(default)]
527            refresh_token: Option<String>,
528            #[serde(default)]
529            access_expires_at: Option<DateTime<Utc>>,
530            #[serde(default)]
531            refresh_expires_at: Option<DateTime<Utc>>,
532        }
533
534        match serde_json::from_str::<Document>(stored.expose_secret()) {
535            Ok(document) => Self {
536                token: SecretString::from(document.access_token),
537                token_type: "bearer".to_string(),
538                scope: None,
539                renewal: document.refresh_token.map(|refresh_token| Renewal {
540                    refresh_token: SecretString::from(refresh_token),
541                    access_expires_at: document.access_expires_at,
542                    refresh_expires_at: document.refresh_expires_at,
543                }),
544            },
545            Err(_) => Self::new(stored.clone()),
546        }
547    }
548
549    /// The value to hand the secret store.
550    ///
551    /// Always the document, even for a credential with no renewal half: one
552    /// shape written means one shape to reason about, and reading still accepts
553    /// the bare token that older versions wrote.
554    #[must_use]
555    pub fn to_stored_document(&self) -> SecretString {
556        #[derive(Serialize)]
557        struct Document<'a> {
558            access_token: &'a str,
559            #[serde(skip_serializing_if = "Option::is_none")]
560            refresh_token: Option<&'a str>,
561            #[serde(skip_serializing_if = "Option::is_none")]
562            access_expires_at: Option<DateTime<Utc>>,
563            #[serde(skip_serializing_if = "Option::is_none")]
564            refresh_expires_at: Option<DateTime<Utc>>,
565        }
566
567        let document = Document {
568            access_token: self.token.expose_secret(),
569            refresh_token: self
570                .renewal
571                .as_ref()
572                .map(|r| r.refresh_token.expose_secret()),
573            access_expires_at: self.renewal.as_ref().and_then(|r| r.access_expires_at),
574            refresh_expires_at: self.renewal.as_ref().and_then(|r| r.refresh_expires_at),
575        };
576        // Serialising a struct of `&str` cannot fail; the fallback keeps the
577        // access token usable rather than inventing an error path nobody can
578        // act on.
579        SecretString::from(
580            serde_json::to_string(&document)
581                .unwrap_or_else(|_| self.token.expose_secret().to_string()),
582        )
583    }
584
585    /// The token itself. Every call site of this is a place a secret can escape,
586    /// so there are deliberately few: the `Authorization` header, and `d2`'s
587    /// store call.
588    #[must_use]
589    pub fn secret(&self) -> &SecretString {
590        &self.token
591    }
592
593    #[must_use]
594    pub fn token_type(&self) -> &str {
595        &self.token_type
596    }
597
598    #[must_use]
599    pub fn scope(&self) -> Option<&str> {
600        self.scope.as_deref()
601    }
602
603    /// The token's four-character family prefix — `ghu_` for an App
604    /// user-to-server token — and nothing else.
605    ///
606    /// This exists so diagnostics can answer "did the device flow return the
607    /// kind of token we expected?" without exposing the token. The D17 spike
608    /// asserted exactly this and no more.
609    #[must_use]
610    pub fn family(&self) -> &str {
611        let raw = self.token.expose_secret();
612        match raw.find('_') {
613            Some(idx) if idx < 8 => &raw[..=idx],
614            _ => "",
615        }
616    }
617
618    /// `true` for the `ghu_` family the published App issues.
619    #[must_use]
620    pub fn is_user_to_server(&self) -> bool {
621        self.family() == "ghu_"
622    }
623}
624
625impl fmt::Debug for UserAccessToken {
626    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
627        f.debug_struct("UserAccessToken")
628            .field("token", &"[REDACTED]")
629            .field("family", &self.family())
630            .finish_non_exhaustive()
631    }
632}
633
634impl PartialEq for UserAccessToken {
635    /// Equality exists so [`device_flow::PollOutcome`] can carry a token and
636    /// still be compared in a test. Production code never compares two
637    /// credentials, and this is not a constant-time comparison.
638    fn eq(&self, other: &Self) -> bool {
639        self.token.expose_secret() == other.token.expose_secret()
640            && self.token_type == other.token_type
641            && self.scope == other.scope
642    }
643}
644
645impl Eq for UserAccessToken {}
646
647// ---------------------------------------------------------------------------
648// Errors
649// ---------------------------------------------------------------------------
650
651/// Everything [`AuthenticatedClient`] can fail with.
652///
653/// The first three variants are the taxonomy `03-control-flows.md` flow 4.3
654/// requires, and they are separate variants because `c3` and `f1` both act on
655/// the distinction: [`GithubError::AuthenticationFailed`] moves a policy to
656/// `authentication_failed` and tells the operator to run `auth login`,
657/// [`GithubError::AuthenticationLockout`] must *wait* and tell the operator
658/// nothing is wrong with their credential, and [`GithubError::Forbidden`] is a
659/// permissions answer that re-authenticating will not change.
660///
661/// # Why the failing variants carry response headers
662///
663/// Rate-limit *policy* is `c3`'s and is deliberately not implemented here. But a
664/// policy needs evidence, and the evidence — `retry-after`,
665/// `x-ratelimit-remaining`, `x-ratelimit-reset` — only exists on the response
666/// that failed. An error taxonomy that dropped those headers would leave `c3`
667/// with no way to honour a `429` except by editing this file, which is exactly
668/// the conflict the `c2`/`c3` ownership split exists to prevent. So
669/// [`GithubError::Status`] and [`GithubError::Forbidden`] carry the headers
670/// verbatim and interpret none of them; see [`GithubError::headers`].
671#[derive(Debug, thiserror::Error)]
672pub enum GithubError {
673    /// GitHub rejected the credential and a single re-validation confirmed it.
674    /// Terminal: only an interactive `auth login` clears this.
675    #[error(
676        "GitHub rejected the stored credential; run `runner-manager auth login` to sign in again"
677    )]
678    AuthenticationFailed,
679
680    /// GitHub answered `403` after `401`s — its temporary authentication
681    /// lockout, not a permissions change. Back off; do not re-authenticate and
682    /// do not retry.
683    #[error(
684        "GitHub has temporarily locked out authentication for this credential; \
685         back off for {}s and do not retry — the credential itself is not the problem",
686        retry_after.as_secs()
687    )]
688    AuthenticationLockout { retry_after: Duration },
689
690    /// A `403` that is not the lockout: a permissions answer, or GitHub's own
691    /// rate limit. `c3` tells the two apart from `headers`; this crate does not,
692    /// because which of them is worth retrying is rate-limit policy.
693    #[error(
694        "GitHub denied {method} {path}: the App installation does not grant it{}",
695        message.as_deref().map(|m| format!(" ({m})")).unwrap_or_default()
696    )]
697    Forbidden {
698        method: String,
699        path: String,
700        message: Option<String>,
701        /// The response headers, verbatim and uninterpreted.
702        headers: Box<HeaderMap>,
703    },
704
705    #[error(
706        "GitHub returned {status} for {method} {path}{}",
707        message.as_deref().map(|m| format!(": {m}")).unwrap_or_default()
708    )]
709    Status {
710        status: u16,
711        method: String,
712        path: String,
713        message: Option<String>,
714        /// The response headers, verbatim and uninterpreted. A `429` reaches
715        /// `c3` through this variant, and its `retry-after` survives with it.
716        headers: Box<HeaderMap>,
717    },
718
719    /// The request never got an answer. The URL is stripped from the source
720    /// error before it is stored: a device-flow URL never carries a secret, but
721    /// stripping it costs nothing and removes a whole class of future leak.
722    #[error("GitHub was unreachable")]
723    Transport(#[source] reqwest::Error),
724
725    #[error("a {what} response from GitHub could not be decoded as {expected}")]
726    Decode {
727        what: &'static str,
728        expected: &'static str,
729        #[source]
730        source: serde_json::Error,
731    },
732
733    #[error("GitHub returned {value:?} for {what}, which this client cannot use")]
734    Malformed { what: &'static str, value: String },
735
736    #[error(transparent)]
737    Config(#[from] ConfigError),
738}
739
740impl GithubError {
741    /// `true` for the two authentication outcomes, which callers handle
742    /// differently from every other failure.
743    #[must_use]
744    pub fn is_authentication(&self) -> bool {
745        matches!(
746            self,
747            Self::AuthenticationFailed | Self::AuthenticationLockout { .. }
748        )
749    }
750
751    /// `true` only for the lockout, which is the one authentication outcome that
752    /// resolves by waiting rather than by signing in again.
753    #[must_use]
754    pub fn is_lockout(&self) -> bool {
755        matches!(self, Self::AuthenticationLockout { .. })
756    }
757
758    /// The failing response's headers, for the variants that have them.
759    ///
760    /// This is the whole of `c2`'s contribution to rate limiting: it hands `c3`
761    /// the evidence and stops there. Nothing in this crate reads
762    /// `x-ratelimit-remaining` to decide anything.
763    #[must_use]
764    pub fn headers(&self) -> Option<&HeaderMap> {
765        match self {
766            Self::Status { headers, .. } | Self::Forbidden { headers, .. } => Some(headers),
767            _ => None,
768        }
769    }
770
771    /// The failing response's `retry-after`, in seconds, if it sent one.
772    ///
773    /// Reading a documented header is evidence, not policy: what to *do* with a
774    /// `retry-after` — wait, shed load, surface it to an operator — is `c3`'s.
775    #[must_use]
776    pub fn retry_after(&self) -> Option<Duration> {
777        self.headers().and_then(retry_after)
778    }
779
780    /// The `x-ratelimit-remaining` / `x-ratelimit-reset` pair, when present.
781    ///
782    /// Returned as the raw numbers GitHub sent. `reset` is a Unix timestamp in
783    /// seconds, which is what the header carries; it is deliberately not turned
784    /// into a [`Timestamp`] here, because comparing it against a clock is the
785    /// first step of a policy decision and that decision is `c3`'s.
786    #[must_use]
787    pub fn rate_limit(&self) -> Option<RateLimitEvidence> {
788        let headers = self.headers()?;
789        let read = |name: &str| {
790            headers
791                .get(name)
792                .and_then(|v| v.to_str().ok())
793                .and_then(|v| v.trim().parse::<u64>().ok())
794        };
795        let remaining = read("x-ratelimit-remaining");
796        let reset = read("x-ratelimit-reset");
797        if remaining.is_none() && reset.is_none() {
798            return None;
799        }
800        Some(RateLimitEvidence {
801            remaining,
802            reset_unix_secs: reset,
803            retry_after: self.retry_after(),
804        })
805    }
806}
807
808/// What GitHub said about its own rate limit on a response that failed.
809///
810/// Evidence, carried across the `c2`/`c3` seam. Every field is what the wire
811/// said, and none of them has been interpreted.
812#[derive(Debug, Clone, Copy, PartialEq, Eq)]
813pub struct RateLimitEvidence {
814    /// `x-ratelimit-remaining`. Zero is GitHub's primary rate limit.
815    pub remaining: Option<u64>,
816    /// `x-ratelimit-reset`, a Unix timestamp in seconds.
817    pub reset_unix_secs: Option<u64>,
818    /// `retry-after`, which secondary rate limits send instead.
819    pub retry_after: Option<Duration>,
820}
821
822fn transport(err: reqwest::Error) -> GithubError {
823    GithubError::Transport(err.without_url())
824}
825
826// ---------------------------------------------------------------------------
827// Requests and responses
828// ---------------------------------------------------------------------------
829
830/// One `api.github.com` request, before authentication headers are applied.
831///
832/// `Debug` is written by hand and never renders the body: `c4` posts
833/// `generate-jitconfig` requests through this type, and a JIT configuration is
834/// a sensitive short-lived value (`07-security.md`, credential inventory).
835#[derive(Clone)]
836pub struct ApiRequest {
837    method: Method,
838    /// Either a path relative to the API base, or an absolute URL — which is
839    /// what a `Link: rel="next"` page is.
840    path: String,
841    query: Vec<(String, String)>,
842    body: Option<serde_json::Value>,
843}
844
845impl ApiRequest {
846    #[must_use]
847    pub fn get(path: impl Into<String>) -> Self {
848        Self::new(Method::GET, path)
849    }
850
851    #[must_use]
852    pub fn delete(path: impl Into<String>) -> Self {
853        Self::new(Method::DELETE, path)
854    }
855
856    #[must_use]
857    pub fn new(method: Method, path: impl Into<String>) -> Self {
858        Self {
859            method,
860            path: path.into(),
861            query: Vec::new(),
862            body: None,
863        }
864    }
865
866    /// # Errors
867    /// `body` failing to serialize.
868    pub fn post_json<T: Serialize>(path: impl Into<String>, body: &T) -> Result<Self, GithubError> {
869        let value = serde_json::to_value(body).map_err(|source| GithubError::Decode {
870            what: "request",
871            expected: "JSON",
872            source,
873        })?;
874        Ok(Self {
875            method: Method::POST,
876            path: path.into(),
877            query: Vec::new(),
878            body: Some(value),
879        })
880    }
881
882    #[must_use]
883    pub fn query(mut self, key: impl Into<String>, value: impl fmt::Display) -> Self {
884        self.query.push((key.into(), value.to_string()));
885        self
886    }
887
888    #[must_use]
889    pub fn method(&self) -> &Method {
890        &self.method
891    }
892
893    #[must_use]
894    pub fn path(&self) -> &str {
895        &self.path
896    }
897}
898
899impl fmt::Debug for ApiRequest {
900    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
901        f.debug_struct("ApiRequest")
902            .field("method", &self.method.as_str())
903            .field("path", &self.path)
904            .field(
905                "query_keys",
906                &self.query.iter().map(|(k, _)| k).collect::<Vec<_>>(),
907            )
908            .field(
909                "body",
910                &self.body.as_ref().map_or("none", |_| "[REDACTED JSON]"),
911            )
912            .finish()
913    }
914}
915
916/// One buffered `api.github.com` response.
917///
918/// Buffered rather than streamed because every API response this crate reads is
919/// small JSON. The one large download in the product — the runner package — is
920/// `e2`'s and uses its own streaming client.
921///
922/// `Debug` renders the status and the body's *length*, never the body: a
923/// `generate-jitconfig` response body is an encoded JIT configuration.
924#[derive(Clone)]
925pub struct ApiResponse {
926    status: StatusCode,
927    headers: HeaderMap,
928    body: Vec<u8>,
929}
930
931impl ApiResponse {
932    #[must_use]
933    pub fn status(&self) -> StatusCode {
934        self.status
935    }
936
937    #[must_use]
938    pub fn headers(&self) -> &HeaderMap {
939        &self.headers
940    }
941
942    #[must_use]
943    pub fn header(&self, name: &str) -> Option<&str> {
944        self.headers.get(name).and_then(|v| v.to_str().ok())
945    }
946
947    /// # Errors
948    /// A body that is not the expected JSON shape.
949    pub fn json<T: DeserializeOwned>(&self) -> Result<T, GithubError> {
950        serde_json::from_slice(&self.body).map_err(|source| GithubError::Decode {
951            what: "response",
952            expected: std::any::type_name::<T>(),
953            source,
954        })
955    }
956
957    /// The next page of a paginated collection, from the `Link` header.
958    ///
959    /// `04-subsystem-contracts.md`: "Pagination is mandatory; the dashboard must
960    /// not treat a first page as a complete inventory." It lives on the shared
961    /// response type so that `c3`'s inventory and this module's installation
962    /// discovery cannot disagree about how a `Link` header is read.
963    #[must_use]
964    pub fn next_page(&self) -> Option<Url> {
965        self.header("link").and_then(parse_link_next)
966    }
967}
968
969impl fmt::Debug for ApiResponse {
970    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
971        f.debug_struct("ApiResponse")
972            .field("status", &self.status.as_u16())
973            .field("body_bytes", &self.body.len())
974            .finish_non_exhaustive()
975    }
976}
977
978/// The `rel="next"` target of an RFC 8288 `Link` header, or `None`.
979///
980/// # Why this scans rather than splits
981///
982/// A comma separates one link-value from the next, but a comma is also a legal
983/// character *inside* a URL, and GitHub sends such URLs routinely — a runner
984/// query carries `labels=self-hosted,windows`. Splitting the whole header on `,`
985/// first tears that URL in half, neither half parses as `<...>`, and the
986/// relation is silently lost. The caller then treats page 1 as the whole
987/// inventory, which is the specific outcome `04-subsystem-contracts.md` forbids:
988/// "the dashboard must not treat a first page as a complete inventory".
989///
990/// So the target is located by its `<`…`>` delimiters, and only a comma that
991/// actually begins the next link-value — one followed by optional whitespace and
992/// `<` — ends the parameter section.
993fn parse_link_next(link: &str) -> Option<Url> {
994    let mut rest = link;
995    while let Some(open) = rest.find('<') {
996        let after_open = &rest[open + 1..];
997        let Some(close) = after_open.find('>') else {
998            // An unterminated `<` cannot be a link-value; nothing after it is
999            // interpretable either.
1000            return None;
1001        };
1002        let target = after_open[..close].trim();
1003        let tail = &after_open[close + 1..];
1004
1005        // The parameters run to the start of the next link-value.
1006        let cut = tail
1007            .match_indices(',')
1008            .find(|(i, _)| tail[i + 1..].trim_start().starts_with('<'))
1009            .map_or(tail.len(), |(i, _)| i);
1010        let (params, next) = tail.split_at(cut);
1011
1012        let is_next = params.split(';').any(|param| {
1013            let param = param.trim().replace(['"', '\''], "");
1014            param.eq_ignore_ascii_case("rel=next")
1015        });
1016        if is_next {
1017            return Url::parse(target).ok();
1018        }
1019        rest = next.strip_prefix(',').unwrap_or(next);
1020    }
1021    None
1022}
1023
1024#[derive(Debug, Deserialize)]
1025struct ErrorEnvelope {
1026    message: Option<String>,
1027}
1028
1029/// GitHub's own message for a failure, and never the raw body.
1030fn error_message(body: &[u8]) -> Option<String> {
1031    serde_json::from_slice::<ErrorEnvelope>(body)
1032        .ok()
1033        .and_then(|e| e.message)
1034        .filter(|m| !m.is_empty())
1035}
1036
1037fn retry_after(headers: &HeaderMap) -> Option<Duration> {
1038    headers
1039        .get("retry-after")
1040        .and_then(|v| v.to_str().ok())
1041        .and_then(|v| v.trim().parse::<u64>().ok())
1042        .map(Duration::from_secs)
1043}
1044
1045// ---------------------------------------------------------------------------
1046// Sleeping
1047// ---------------------------------------------------------------------------
1048
1049/// The one way anything in this crate waits.
1050///
1051/// A port rather than a direct `tokio::time::sleep`, for the same reason the
1052/// domain has a `Clock`: the device flow's `slow_down` handling is a *timing*
1053/// behaviour, and a timing behaviour tested by actually waiting is either
1054/// untested or slow. A test substitutes a sleeper that records the requested
1055/// durations and returns immediately, which turns "`slow_down` increases the
1056/// poll interval" into an equality assertion on a `Vec<Duration>` rather than a
1057/// stopwatch reading.
1058#[async_trait::async_trait]
1059pub trait Sleeper: Send + Sync + fmt::Debug {
1060    async fn sleep(&self, duration: Duration);
1061}
1062
1063/// The production adapter.
1064#[derive(Debug, Clone, Copy, Default)]
1065pub struct TokioSleeper;
1066
1067#[async_trait::async_trait]
1068impl Sleeper for TokioSleeper {
1069    async fn sleep(&self, duration: Duration) {
1070        tokio::time::sleep(duration).await;
1071    }
1072}
1073
1074// ---------------------------------------------------------------------------
1075// The shared authenticated client
1076// ---------------------------------------------------------------------------
1077
1078/// What a single re-validation of the held credential concluded.
1079#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1080pub enum Revalidation {
1081    /// GitHub still accepts the credential, so the `401` was about the request
1082    /// rather than about the token. One retry is warranted.
1083    Valid,
1084    /// GitHub rejects the credential. Terminal; only `auth login` clears it.
1085    Rejected,
1086    /// The probe itself could not be completed — GitHub was unreachable, or
1087    /// answered something neither `2xx` nor `401`. Nothing was learned, so the
1088    /// caller still gets its one retry.
1089    Unavailable,
1090}
1091
1092#[derive(Debug)]
1093struct LockoutState {
1094    until: Option<Timestamp>,
1095    backoff: Duration,
1096}
1097
1098/// The one client every `api.github.com` request in this crate goes through.
1099///
1100/// It exists to make four things structural rather than remembered:
1101///
1102/// 1. `X-GitHub-Api-Version`, `Accept`, `User-Agent`, and `Authorization` are
1103///    set on every request because they are set *here*.
1104/// 2. The `401` / `403` taxonomy of `03-control-flows.md` flow 4.3 is
1105///    implemented once. `c3` and `f1` both branch on the distinction, and two
1106///    implementations of it would eventually disagree.
1107/// 3. A `401` storm produces **one** credential re-validation, not one per
1108///    caller — see [`AuthenticatedClient::revalidate`].
1109/// 4. A lockout stops traffic. Once GitHub answers `403` after `401`s, this
1110///    client issues no further HTTP at all until the back-off elapses.
1111pub struct AuthenticatedClient {
1112    http: reqwest::Client,
1113    endpoints: Endpoints,
1114    /// Swappable, because a renewable credential replaces itself while this
1115    /// client is in use. A `Mutex` rather than a lock-free cell: it is read
1116    /// once per request and written once every eight hours, so contention is
1117    /// not the concern -- being obviously correct is.
1118    credential: std::sync::Mutex<UserAccessToken>,
1119    /// Where to re-read the credential when a `401` outlives renewal.
1120    ///
1121    /// `None` for a short-lived client, which is every one that is not the
1122    /// daemon's: a command that runs for a second cannot be outlived by a
1123    /// sign-in.
1124    source: Option<Arc<dyn CredentialSource>>,
1125    /// How a credential replaces itself, when it can.
1126    ///
1127    /// `None` for a client whose credential has no renewal half, which is every
1128    /// client until an App turns user-token expiration on, and for the paths
1129    /// that hold a token for one call and never outlive its eight hours.
1130    renewal: Option<Arc<dyn CredentialRenewal>>,
1131    clock: Arc<dyn Clock>,
1132
1133    /// Bumped once per completed re-validation. A caller that took a `401`
1134    /// samples this *before* queuing on the gate; if it changed while the caller
1135    /// waited, some other caller already did the work and this one must not
1136    /// repeat it. This is the whole single-flight mechanism.
1137    revalidation_generation: AtomicU64,
1138    revalidation_gate: tokio::sync::Mutex<()>,
1139    last_revalidation: std::sync::Mutex<Revalidation>,
1140    revalidations_performed: AtomicU64,
1141
1142    /// `401`s seen since the last successful caller response.
1143    ///
1144    /// **Nothing in production reads this.** It is incremented on every `401`
1145    /// and cleared by a successful caller response, and that is the whole of
1146    /// what it does. It used to be documented as the lockout's test — "a `403`
1147    /// while this is non-zero is a lockout" — and
1148    /// [`AuthenticatedClient::is_lockout_403`] stopped consulting it when that
1149    /// rule was replaced by position plus GitHub's own evidence:
1150    /// [`Attempt::Retry`] already implies this request's own `401` incremented
1151    /// it moments ago, so reading it added no signal, and it did add a race that
1152    /// failed open — a concurrent success clearing the count downgraded a real
1153    /// lockout to a permissions answer.
1154    ///
1155    /// The field is kept on purpose, and only the tests read it: they drive it
1156    /// to values that *would* change the answer if it were still consulted, and
1157    /// assert that the answer does not change. Deleting it would delete the
1158    /// ability to make that assertion, which is the only thing standing between
1159    /// the conjunct and its reintroduction. See
1160    /// `a_concurrent_success_cannot_downgrade_a_lockout_to_a_permissions_answer`.
1161    consecutive_unauthorized: AtomicU64,
1162    lockout: std::sync::Mutex<LockoutState>,
1163}
1164
1165impl fmt::Debug for AuthenticatedClient {
1166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1167        // `try_lock`, not `is_locked_out()`. `std::sync::Mutex` is not
1168        // reentrant, and `latch_lockout` holds this one; the moment anybody adds
1169        // a `tracing` call inside that function — which is a natural thing to
1170        // want there — rendering the client would deadlock the whole agent. A
1171        // `Debug` impl must never be able to block, so it reports what it can
1172        // see and says so when it cannot.
1173        let locked_out = match self.lockout.try_lock() {
1174            Ok(state) => {
1175                if state.until.is_some_and(|until| self.clock.now() < until) {
1176                    "yes"
1177                } else {
1178                    "no"
1179                }
1180            }
1181            Err(_) => "unknown (the lockout state is being updated)",
1182        };
1183        f.debug_struct("AuthenticatedClient")
1184            .field("api_base", &self.endpoints.api_base.as_str())
1185            .field(
1186                "credential",
1187                &self
1188                    .credential
1189                    .try_lock()
1190                    .map_or("[in use]", |_| "[redacted]"),
1191            )
1192            .field(
1193                "revalidations_performed",
1194                &self.revalidations_performed.load(Ordering::Relaxed),
1195            )
1196            .field("locked_out", &locked_out)
1197            .finish_non_exhaustive()
1198    }
1199}
1200
1201/// How a credential replaces itself.
1202///
1203/// # Why this is a port rather than a method
1204///
1205/// Renewal is two acts that must happen in one order: exchange the refresh
1206/// token with GitHub, then **persist the new pair before anything uses it**.
1207/// GitHub rotates on use -- the old pair dies the instant the new one is
1208/// issued -- so a response that is used but not stored leaves the host holding
1209/// a credential it will forget, and the one it forgot is already dead. There
1210/// is no retry: a spent refresh token answers `incorrect_client_credentials`,
1211/// a message about the client id and secret that is about neither.
1212///
1213/// The exchange belongs to `c2` and the store belongs to `d2`, and this crate
1214/// owns neither. So the ordering lives with whoever implements this, in one
1215/// place, rather than being a rule each caller has to remember.
1216#[async_trait::async_trait]
1217pub trait CredentialRenewal: fmt::Debug + Send + Sync {
1218    /// Exchange `refresh_token` for a fresh pair and persist it.
1219    ///
1220    /// # Errors
1221    /// Any failure; the caller treats every one the same way, by keeping the
1222    /// credential it has and letting the next `401` try again.
1223    async fn renew(&self, refresh_token: &SecretString) -> Result<UserAccessToken, String>;
1224}
1225
1226/// Where a client can go to find out that the stored credential changed under
1227/// it.
1228///
1229/// # Why a long-running client needs this
1230///
1231/// A daemon reads the store once, at startup, and holds the result for as long
1232/// as it runs. That was invisible while the only way to change the store was to
1233/// stop the daemon — but `auth login` does not stop anything, so a host whose
1234/// credential died before its daemon started stays dead through every sign-in
1235/// meant to fix it. The operator does the right thing, watches it not work, and
1236/// has nothing to tell them why.
1237///
1238/// Watched on 2026-08-29: a Windows daemon started at `04:08Z` holding an
1239/// already-expired token, a sign-in at `10:43Z` that wrote a good pair, and 180
1240/// `unauthorized` events an hour for 28 hours without a single minute's pause
1241/// across the sign-in. See `docs/spikes/token-expiry-and-renewal.md`.
1242///
1243/// # Why it is not a file watch
1244///
1245/// This is consulted on `401` and nowhere else, so a store that never changes
1246/// costs nothing and a daemon that is working never reads the disk. It also
1247/// covers the case a watch would miss on macOS, where the credential lives in a
1248/// keychain rather than at a path.
1249pub trait CredentialSource: fmt::Debug + Send + Sync {
1250    /// The credential the store holds *now*, or `None` if it cannot be read.
1251    ///
1252    /// Infallible by design: every failure — missing, unreadable, corrupt —
1253    /// means the same thing to the caller, which is that there is nothing new
1254    /// to try and the `401` stands.
1255    fn reload(&self) -> Option<UserAccessToken>;
1256}
1257
1258impl AuthenticatedClient {
1259    /// # Errors
1260    /// The HTTP client failing to build — a TLS backend that will not
1261    /// initialise, in practice.
1262    pub fn new(
1263        endpoints: Endpoints,
1264        credential: UserAccessToken,
1265        clock: Arc<dyn Clock>,
1266    ) -> Result<Self, GithubError> {
1267        let http = reqwest::Client::builder()
1268            .timeout(DEFAULT_REQUEST_TIMEOUT)
1269            .build()
1270            .map_err(transport)?;
1271        Ok(Self::with_http_client(http, endpoints, credential, clock))
1272    }
1273
1274    #[must_use]
1275    pub fn with_http_client(
1276        http: reqwest::Client,
1277        endpoints: Endpoints,
1278        credential: UserAccessToken,
1279        clock: Arc<dyn Clock>,
1280    ) -> Self {
1281        Self {
1282            http,
1283            endpoints,
1284            credential: std::sync::Mutex::new(credential),
1285            source: None,
1286            renewal: None,
1287            clock,
1288            revalidation_generation: AtomicU64::new(0),
1289            revalidation_gate: tokio::sync::Mutex::new(()),
1290            last_revalidation: std::sync::Mutex::new(Revalidation::Valid),
1291            revalidations_performed: AtomicU64::new(0),
1292            consecutive_unauthorized: AtomicU64::new(0),
1293            lockout: std::sync::Mutex::new(LockoutState {
1294                until: None,
1295                backoff: DEFAULT_LOCKOUT_BACKOFF,
1296            }),
1297        }
1298    }
1299
1300    #[must_use]
1301    pub fn endpoints(&self) -> &Endpoints {
1302        &self.endpoints
1303    }
1304
1305    /// How many credential re-validations this client has performed.
1306    ///
1307    /// Public because it is the observable the single-flight requirement is
1308    /// stated in terms of: "concurrent callers hitting `401` together produce
1309    /// **one** attempt, not N".
1310    #[must_use]
1311    pub fn revalidations_performed(&self) -> u64 {
1312        self.revalidations_performed.load(Ordering::SeqCst)
1313    }
1314
1315    /// `true` while a lockout back-off is still running, during which this
1316    /// client issues no HTTP at all.
1317    ///
1318    /// # Panics
1319    /// If a previous holder panicked while the lockout lock was held.
1320    #[must_use]
1321    pub fn is_locked_out(&self) -> bool {
1322        self.lockout_remaining().is_some()
1323    }
1324
1325    /// How much of the lockout back-off is left, or `None` when not locked out.
1326    ///
1327    /// # Panics
1328    /// If a previous holder panicked while the lockout lock was held.
1329    #[must_use]
1330    pub fn lockout_remaining(&self) -> Option<Duration> {
1331        let state = self.lockout.lock().expect("lockout lock poisoned");
1332        let until = state.until?;
1333        let now = self.clock.now();
1334        if now >= until {
1335            return None;
1336        }
1337        (until - now).to_std().ok()
1338    }
1339
1340    /// Clear a lockout early. `f1` does not need this — the back-off expires on
1341    /// its own against the clock — but a successful interactive `auth login`
1342    /// legitimately invalidates the whole lockout premise.
1343    ///
1344    /// # Panics
1345    /// If a previous holder panicked while the lockout lock was held.
1346    pub fn clear_lockout(&self) {
1347        self.lockout.lock().expect("lockout lock poisoned").until = None;
1348        self.consecutive_unauthorized.store(0, Ordering::SeqCst);
1349    }
1350
1351    /// Send one request, applying the authentication taxonomy.
1352    ///
1353    /// On `401` this performs a single-flight credential re-validation and then
1354    /// **one** retry — never more, and never a token renewal, because there is
1355    /// nothing to renew (see [`AuthenticatedClient::revalidate`]).
1356    ///
1357    /// # Errors
1358    /// Every variant of [`GithubError`].
1359    pub async fn send(&self, request: &ApiRequest) -> Result<ApiResponse, GithubError> {
1360        if let Some(remaining) = self.lockout_remaining() {
1361            // "backs off without further attempts": no socket is opened at all.
1362            tracing::debug!(
1363                method = request.method.as_str(),
1364                path = %request.path,
1365                remaining_secs = remaining.as_secs(),
1366                "suppressed a request: GitHub authentication lockout is still backing off"
1367            );
1368            return Err(GithubError::AuthenticationLockout {
1369                retry_after: remaining,
1370            });
1371        }
1372
1373        let first = self.send_raw(request).await?;
1374        match self.classify(request, &first, Attempt::First) {
1375            Classified::Ok => Ok(first),
1376            Classified::Unauthorized => self.revalidate_and_retry_once(request).await,
1377            Classified::Error(err) => Err(err),
1378        }
1379    }
1380
1381    /// Deserialize a `GET` in one step.
1382    ///
1383    /// # Errors
1384    /// Every variant of [`GithubError`].
1385    pub async fn get_json<T: DeserializeOwned>(&self, path: &str) -> Result<T, GithubError> {
1386        self.send(&ApiRequest::get(path)).await?.json()
1387    }
1388
1389    /// The access token to send, as a string, for exactly one request.
1390    ///
1391    /// Cloned out of the lock rather than borrowed through it: the value is
1392    /// about to go into a header, and holding the lock across the request would
1393    /// serialise every call in the process behind one mutex.
1394    fn bearer(&self) -> String {
1395        self.credential
1396            .lock()
1397            .unwrap_or_else(std::sync::PoisonError::into_inner)
1398            .secret()
1399            .expose_secret()
1400            .to_string()
1401    }
1402
1403    /// Attach a way for this client's credential to replace itself.
1404    #[must_use]
1405    pub fn with_renewal(mut self, renewal: Arc<dyn CredentialRenewal>) -> Self {
1406        self.renewal = Some(renewal);
1407        self
1408    }
1409
1410    /// Attach the store this client's credential came from, so a `401` it
1411    /// cannot renew its way out of can still notice a sign-in that already
1412    /// happened.
1413    #[must_use]
1414    pub fn with_credential_source(mut self, source: Arc<dyn CredentialSource>) -> Self {
1415        self.source = Some(source);
1416        self
1417    }
1418
1419    /// Replace the credential with whatever `produce` finds, once, however many
1420    /// callers asked at the same moment.
1421    ///
1422    /// Answers whether the credential in hand is now a *different* one, which
1423    /// is the caller's cue to retry. `false` means there was nothing new, and
1424    /// the `401` stands.
1425    ///
1426    /// # Why both ways in share this
1427    ///
1428    /// [`Self::renew_once`] and [`Self::reload_once`] ask one question —
1429    /// *can this `401` be retried with something else* — and differ only in
1430    /// where the something else comes from. Written separately they were two
1431    /// copies of the same `SeqCst` generation protocol, and the copies had
1432    /// already drifted: the equality check below existed in one of them and not
1433    /// the other, so a renewal that handed back an identical token reported a
1434    /// change that had not happened.
1435    ///
1436    /// # Why the comparison, and not just a swap
1437    ///
1438    /// A swap on every `401` would answer `true` forever and turn the one retry
1439    /// into an endless pair of requests against a credential that is genuinely
1440    /// dead. Only a different token is evidence that retrying might go
1441    /// differently.
1442    async fn swap_credential_once<F>(&self, produce: F, note: &'static str) -> bool
1443    where
1444        F: AsyncFnOnce(&Self) -> Option<UserAccessToken>,
1445    {
1446        let before = self.revalidation_generation.load(Ordering::SeqCst);
1447        let _gate = self.revalidation_gate.lock().await;
1448        if self.revalidation_generation.load(Ordering::SeqCst) != before {
1449            // Somebody swapped while this caller queued, so there is already
1450            // something new to retry with. Producing again would be wasted at
1451            // best and, for a renewal, would burn the pair they just minted.
1452            return true;
1453        }
1454
1455        let Some(fresh) = produce(self).await else {
1456            return false;
1457        };
1458        {
1459            let mut guard = self
1460                .credential
1461                .lock()
1462                .unwrap_or_else(std::sync::PoisonError::into_inner);
1463            if guard.secret().expose_secret() == fresh.secret().expose_secret() {
1464                return false;
1465            }
1466            *guard = fresh;
1467        }
1468        self.revalidation_generation.fetch_add(1, Ordering::SeqCst);
1469        tracing::info!("{note}");
1470        true
1471    }
1472
1473    /// Pick up a credential somebody else stored.
1474    ///
1475    /// `false` when there is no source, the store cannot be read, or what it
1476    /// holds is the token that just failed.
1477    async fn reload_once(&self) -> bool {
1478        let Some(source) = self.source.clone() else {
1479            return false;
1480        };
1481        self.swap_credential_once(
1482            async |_| source.reload(),
1483            "the stored credential changed and was picked up without a restart",
1484        )
1485        .await
1486    }
1487
1488    /// Spend the refresh half for a fresh pair.
1489    ///
1490    /// # Ordering
1491    ///
1492    /// The implementation of [`CredentialRenewal::renew`] persists before
1493    /// returning, so by the time the swap happens the new pair is already
1494    /// durable. A crash between the two loses nothing: the store holds the pair
1495    /// that works, and the next start reads it.
1496    async fn renew_once(&self) -> bool {
1497        let Some(renewal) = self.renewal.clone() else {
1498            return false;
1499        };
1500        self.swap_credential_once(
1501            async |client: &Self| {
1502                let refresh = {
1503                    let guard = client
1504                        .credential
1505                        .lock()
1506                        .unwrap_or_else(std::sync::PoisonError::into_inner);
1507                    guard.renewal().map(|r| r.refresh_token().clone())
1508                }?;
1509                match renewal.renew(&refresh).await {
1510                    Ok(fresh) => Some(fresh),
1511                    Err(error) => {
1512                        tracing::warn!(
1513                            %error,
1514                            "the user access token could not be renewed; an interactive \
1515                             sign-in may be required"
1516                        );
1517                        None
1518                    }
1519                }
1520            },
1521            "the user access token was renewed",
1522        )
1523        .await
1524    }
1525
1526    /// Serialize, `POST`, and deserialize in one step.
1527    ///
1528    /// # Errors
1529    /// Every variant of [`GithubError`].
1530    pub async fn post_json<B: Serialize, T: DeserializeOwned>(
1531        &self,
1532        path: &str,
1533        body: &B,
1534    ) -> Result<T, GithubError> {
1535        self.send(&ApiRequest::post_json(path, body)?).await?.json()
1536    }
1537
1538    /// Re-validate the credential once, no matter how many callers ask at once.
1539    ///
1540    /// # This is not a token renewal — renewal is [`Self::renew_once`]
1541    ///
1542    /// `03-control-flows.md` flow 4.3 says a `401` "triggers one refresh under
1543    /// a single-flight mutex, then one retry", and that is implemented
1544    /// literally: one attempt shared by every concurrent caller, then one retry
1545    /// each.
1546    ///
1547    /// This method used to claim the word "refresh" could not be meant, because
1548    /// renewing needs a client secret and the App issues no renewal token. Both
1549    /// halves were false; see this module's header. Renewal exists, it runs
1550    /// first in [`Self::revalidate_and_retry_once`], and what is left here is
1551    /// the path for a credential that has no refresh half to spend — one stored
1552    /// before 0.1.11, or issued while the App had expiration switched off.
1553    ///
1554    /// So the single thing that happens under the mutex is a re-validation of
1555    /// the credential already held: one `GET /user/installations` with the same
1556    /// token, asking GitHub whether it still accepts it. A
1557    /// [`Revalidation::Rejected`] answer is terminal
1558    /// [`GithubError::AuthenticationFailed`] requiring an interactive
1559    /// `auth login`; [`Revalidation::Valid`] and [`Revalidation::Unavailable`]
1560    /// both spend the one retry.
1561    ///
1562    /// # Position, and what it no longer decides on its own
1563    ///
1564    /// This method is the caller's own probe: it is a **first** attempt by
1565    /// construction, whatever happened on some other request minutes ago, so it
1566    /// passes [`Attempt::First`] down.
1567    ///
1568    /// That used to settle the matter. This heading read "why this entry point
1569    /// may not latch a lockout", and the text said the probe it drives *cannot*
1570    /// latch — an accurate description of the position rule as it then stood,
1571    /// and a false statement about the product. A lockout that outlives one
1572    /// back-off continues on a **first** attempt by construction, because this
1573    /// client's retry never happened: the request never reached the wire.
1574    /// Refusing to latch there stopped the back-off entirely and hammered a
1575    /// credential GitHub had asked to be left alone.
1576    ///
1577    /// So position alone no longer decides.
1578    /// [`AuthenticatedClient::is_lockout_403`] reads GitHub's own evidence in
1579    /// the first position instead: a first attempt latches when, and only when,
1580    /// the response carries `retry-after` and no parseable GitHub message body.
1581    /// A permissions refusal names what is not accessible, so it still does not
1582    /// latch, which is what keeps [`GithubError::Forbidden`] reachable from
1583    /// here.
1584    ///
1585    /// `revalidate_and_retry_once` uses the private
1586    /// [`AuthenticatedClient::revalidate_after_unauthorized`] instead, which is
1587    /// in the retry position, where any `403` that is not a rate limit is the
1588    /// lockout regardless of what the body says.
1589    ///
1590    /// # This call can latch a lockout, and then it says so
1591    ///
1592    /// Because a first attempt can latch, this call can leave the whole client
1593    /// backed off for up to [`MAX_LOCKOUT_BACKOFF`]. It reports that as
1594    /// [`GithubError::AuthenticationLockout`] rather than answering
1595    /// `Ok(`[`Revalidation::Unavailable`]`)` and leaving the caller to discover
1596    /// it through a separate [`AuthenticatedClient::is_locked_out`] call. An
1597    /// `auth status` that printed "could not determine" while the client it had
1598    /// just silenced sat mute for fifteen minutes would be reporting the wrong
1599    /// event, and reporting it as the milder one.
1600    ///
1601    /// # Errors
1602    /// [`GithubError::AuthenticationLockout`] if this client is already backing
1603    /// off when the call arrives, **or** if this call's own probe latches one.
1604    ///
1605    /// A credential GitHub has rejected outright is *not* an error here: that
1606    /// comes back as `Ok(`[`Revalidation::Rejected`]`)`, and what to do about it
1607    /// — prompt for `auth login` — is the caller's decision, not this method's.
1608    ///
1609    /// # Panics
1610    /// If a previous holder panicked while the re-validation result lock was
1611    /// held.
1612    pub async fn revalidate(&self) -> Result<Revalidation, GithubError> {
1613        self.revalidate_from(Attempt::First).await
1614    }
1615
1616    /// The re-validation that `send` runs between a `401` and its one retry.
1617    ///
1618    /// Identical to [`AuthenticatedClient::revalidate`] except for position:
1619    /// this one *is* the retry path, so a `403` on its probe is the lockout and
1620    /// is latched.
1621    async fn revalidate_after_unauthorized(&self) -> Result<Revalidation, GithubError> {
1622        self.revalidate_from(Attempt::Retry).await
1623    }
1624
1625    async fn revalidate_from(&self, attempt: Attempt) -> Result<Revalidation, GithubError> {
1626        // "A lockout stops traffic. This client issues no further HTTP at all
1627        // until the back-off elapses" is a property of the client, not of
1628        // `send`, and the probe is HTTP like any other. `send` has already
1629        // returned by the time it calls in here, so this guard only bites a
1630        // caller that probes on its own — and one that did would otherwise be
1631        // the single exception to the rule, which is how a rule stops holding.
1632        if let Some(retry_after) = self.lockout_remaining() {
1633            return Err(GithubError::AuthenticationLockout { retry_after });
1634        }
1635
1636        // Sample before queuing. If this changes while we wait for the gate,
1637        // someone else's re-validation covers us and we must not repeat it.
1638        let sampled = self.revalidation_generation.load(Ordering::SeqCst);
1639        let _guard = self.revalidation_gate.lock().await;
1640        let outcome = if self.revalidation_generation.load(Ordering::SeqCst) != sampled {
1641            let shared = *self
1642                .last_revalidation
1643                .lock()
1644                .expect("re-validation lock poisoned");
1645            tracing::debug!(
1646                outcome = ?shared,
1647                "reused an in-flight credential re-validation instead of starting another"
1648            );
1649            shared
1650        } else {
1651            self.revalidations_performed.fetch_add(1, Ordering::SeqCst);
1652            let fresh = self.probe_credential(attempt).await;
1653            *self
1654                .last_revalidation
1655                .lock()
1656                .expect("re-validation lock poisoned") = fresh;
1657            self.revalidation_generation.fetch_add(1, Ordering::SeqCst);
1658            tracing::info!(
1659                outcome = ?fresh,
1660                "re-validated the stored credential; it carries no refresh half to renew"
1661            );
1662            fresh
1663        };
1664
1665        // The probe is HTTP, and since the continuation rule re-widened
1666        // `Attempt::First`, HTTP from *this* entry point can latch a lockout.
1667        // `probe_credential` reports a `403` as `Unavailable` whether or not it
1668        // latched one, and `Unavailable` on its own reads as "this taught us
1669        // nothing about the credential" — so without this check `revalidate`
1670        // answers `Ok(Unavailable)` having just silenced the entire client for
1671        // up to `MAX_LOCKOUT_BACKOFF`, and the only way for `f1` to find that
1672        // out is a separate `is_locked_out()` call it has no reason to make.
1673        //
1674        // `revalidate_and_retry_once` has always re-checked after its own probe.
1675        // Doing it here instead makes the two entry points agree: before, being
1676        // told about the lockout depended on *who latched it* — the guard above
1677        // reports one latched by someone else's traffic, this reports one
1678        // latched by the caller's own probe — and that distinction is invisible
1679        // from outside and actionable by nobody.
1680        //
1681        // This changes what is reported, not when a lockout latches:
1682        // `latch_lockout` is reached on exactly the paths it was before.
1683        //
1684        // It also covers the shared branch above, which the retry path's own
1685        // check never could. A second caller arriving while the first one's
1686        // probe is in flight takes the cached `Unavailable` without probing at
1687        // all, and is just as silenced by the lockout that probe latched.
1688        if let Some(retry_after) = self.lockout_remaining() {
1689            return Err(GithubError::AuthenticationLockout { retry_after });
1690        }
1691        Ok(outcome)
1692    }
1693
1694    /// One `GET /user/installations` with the credential already held, asking
1695    /// GitHub whether it still accepts it.
1696    ///
1697    /// `attempt` is the *caller's* position, not the probe's own. A probe driven
1698    /// by `send`'s `401` handling is part of that request's retry; a probe a
1699    /// caller asked for through [`AuthenticatedClient::revalidate`] is a first
1700    /// attempt.
1701    ///
1702    /// Either may latch a lockout, on different evidence. This used to say "only
1703    /// the former may", which was the position rule before the continuation rule
1704    /// re-widened `Attempt::First`: a retry `403` that is not a rate limit is
1705    /// the lockout outright, and a first-attempt `403` is the lockout when
1706    /// GitHub's own evidence says so — `retry-after` present, no parseable
1707    /// message. See [`AuthenticatedClient::is_lockout_403`], which both this and
1708    /// `classify` go through, so the rule is stated once instead of twice.
1709    async fn probe_credential(&self, attempt: Attempt) -> Revalidation {
1710        let probe = ApiRequest::get(REVALIDATION_PATH).query("per_page", 1);
1711        match self.send_raw(&probe).await {
1712            // Deliberately does **not** reset `consecutive_unauthorized`. The
1713            // probe is this client's own diagnostic, not the caller's traffic,
1714            // and a successful probe is exactly the state a lockout arrives in:
1715            // GitHub still accepts the credential, and answers the *next* real
1716            // request with `403`. Only a successful caller request clears the
1717            // count, in `classify`.
1718            //
1719            // The reason used to be given as "resetting here would erase the
1720            // evidence the `403` is classified against", and that stopped being
1721            // true when `is_lockout_403` stopped consulting the count. There is
1722            // no such evidence to erase now — nothing in production reads the
1723            // field. The line stays because the field's one remaining job is to
1724            // let the tests prove it is *not* consulted, and a probe that
1725            // quietly rewrote it would make those tests assert against a counter
1726            // value no caller path actually produces.
1727            Ok(response) if response.status.is_success() => Revalidation::Valid,
1728            Ok(response) if response.status == StatusCode::UNAUTHORIZED => {
1729                self.consecutive_unauthorized.fetch_add(1, Ordering::SeqCst);
1730                Revalidation::Rejected
1731            }
1732            Ok(response) if response.status == StatusCode::FORBIDDEN => {
1733                // A `403` on a probe that *is* this request's retry is the
1734                // lockout outright. A `403` on a probe a caller asked for
1735                // directly is the lockout only when the response itself says so
1736                // — `retry-after` present, no parseable message — because that
1737                // is what a lockout continuing past one back-off looks like, and
1738                // it necessarily arrives in the first position.
1739                //
1740                // The comment that used to sit here claimed "the probe only ever
1741                // runs after a `401`, so it is always in the retry position",
1742                // and publishing `revalidate` is what made that untrue. Its
1743                // replacement then said a direct probe "is not" the lockout,
1744                // which the continuation rule in turn made untrue. Both were
1745                // position asserted as a conclusion; the position now arrives as
1746                // an argument and the conclusion is drawn in one place, by
1747                // `is_lockout_403`.
1748                if self.is_lockout_403(&response, attempt) {
1749                    self.latch_lockout(&response.headers);
1750                }
1751                Revalidation::Unavailable
1752            }
1753            Ok(_) | Err(_) => Revalidation::Unavailable,
1754        }
1755    }
1756
1757    async fn revalidate_and_retry_once(
1758        &self,
1759        request: &ApiRequest,
1760    ) -> Result<ApiResponse, GithubError> {
1761        // ------------------------------------------------------------------
1762        // RENEWAL COMES FIRST, AND IT DID NOT USED TO EXIST.
1763        // ------------------------------------------------------------------
1764        // This method's documentation once said a `401` could only ever be
1765        // re-validated, never renewed, because renewing needs a confidential
1766        // client credential and a published binary cannot carry one. The first
1767        // half of that is wrong: GitHub requires one *"unless the user access
1768        // token was generated using the device flow"*, and this product's
1769        // always are. Verified against live GitHub before this was written.
1770        //
1771        // So a credential that carries a refresh token replaces itself here,
1772        // silently, and the caller's request is retried with the new one. That
1773        // is what lets an eight-hour token serve a daemon that runs for months
1774        // -- and what lets two machines hold their own credentials at once,
1775        // because each renews its own pair instead of re-authorising and
1776        // revoking the other's.
1777        //
1778        // A credential with no refresh token falls through to exactly the
1779        // behaviour that was here before.
1780        //
1781        // ------------------------------------------------------------------
1782        // THEN THE STORE, FOR THE 401 RENEWAL CANNOT ANSWER.
1783        // ------------------------------------------------------------------
1784        // Renewal covers a token that expired under a daemon holding a
1785        // *renewable* pair. It cannot cover a daemon that started holding a
1786        // dead bare token, because there is no refresh half to spend -- and
1787        // that daemon will not recover on its own no matter how many times an
1788        // operator runs `auth login`, because it never looks at the store
1789        // again. Consulting it here is what makes the obvious remedy work.
1790        //
1791        // Second, not first: renewal is this client's own pair and costs no
1792        // disk, while a reload is a keychain or DPAPI read that would run on
1793        // every 401 of a genuinely revoked credential.
1794        if self.renew_once().await || self.reload_once().await {
1795            let second = self.send_raw(request).await?;
1796            return match self.classify(request, &second, Attempt::Retry) {
1797                Classified::Ok => Ok(second),
1798                // The renewed credential was rejected too. Nothing here can
1799                // help: this is a sign-in, not a token, that has gone.
1800                Classified::Unauthorized => Err(GithubError::AuthenticationFailed),
1801                Classified::Error(err) => Err(err),
1802            };
1803        }
1804        match self.revalidate_after_unauthorized().await? {
1805            Revalidation::Rejected => {
1806                tracing::warn!(
1807                    method = request.method.as_str(),
1808                    path = %request.path,
1809                    "GitHub rejected the stored credential; re-authentication is required"
1810                );
1811                Err(GithubError::AuthenticationFailed)
1812            }
1813            Revalidation::Valid | Revalidation::Unavailable => {
1814                // `revalidate_from` now converts a lockout that its own probe
1815                // latched, so this no longer catches that case. It stays for the
1816                // one it still catches: a *concurrent* request latching between
1817                // that check and this one. Sending the retry into a live lockout
1818                // is the thing the back-off exists to prevent, and this is the
1819                // last point at which it can be declined.
1820                if let Some(remaining) = self.lockout_remaining() {
1821                    return Err(GithubError::AuthenticationLockout {
1822                        retry_after: remaining,
1823                    });
1824                }
1825                let second = self.send_raw(request).await?;
1826                match self.classify(request, &second, Attempt::Retry) {
1827                    Classified::Ok => Ok(second),
1828                    // The one retry is spent. A second `401` is terminal.
1829                    Classified::Unauthorized => Err(GithubError::AuthenticationFailed),
1830                    Classified::Error(err) => Err(err),
1831                }
1832            }
1833        }
1834    }
1835
1836    fn classify(
1837        &self,
1838        request: &ApiRequest,
1839        response: &ApiResponse,
1840        attempt: Attempt,
1841    ) -> Classified {
1842        let status = response.status;
1843        if status.is_success() {
1844            self.consecutive_unauthorized.store(0, Ordering::SeqCst);
1845            return Classified::Ok;
1846        }
1847        if status == StatusCode::UNAUTHORIZED {
1848            self.consecutive_unauthorized.fetch_add(1, Ordering::SeqCst);
1849            return Classified::Unauthorized;
1850        }
1851        if status == StatusCode::FORBIDDEN && self.is_lockout_403(response, attempt) {
1852            let backoff = self.latch_lockout(&response.headers);
1853            tracing::warn!(
1854                method = request.method.as_str(),
1855                path = %request.path,
1856                backoff_secs = backoff.as_secs(),
1857                "GitHub answered 403 after 401s: temporary authentication lockout, backing off"
1858            );
1859            return Classified::Error(GithubError::AuthenticationLockout {
1860                retry_after: backoff,
1861            });
1862        }
1863        let headers = Box::new(response.headers.clone());
1864        let message = error_message(&response.body);
1865        if status == StatusCode::FORBIDDEN {
1866            return Classified::Error(GithubError::Forbidden {
1867                method: request.method.as_str().to_string(),
1868                path: request.path.clone(),
1869                message,
1870                headers,
1871            });
1872        }
1873        Classified::Error(GithubError::Status {
1874            status: status.as_u16(),
1875            method: request.method.as_str().to_string(),
1876            path: request.path.clone(),
1877            message,
1878            headers,
1879        })
1880    }
1881
1882    /// Whether a `403` is GitHub's temporary *authentication* lockout, as
1883    /// opposed to a permissions answer or a rate limit.
1884    ///
1885    /// # It must not be a rate limit
1886    ///
1887    /// `classify` used to reach the `403` branch before anything looked at the
1888    /// rate-limit headers, so a primary rate limit arriving during a `401` storm
1889    /// was reported as `AuthenticationLockout` — telling the operator "the
1890    /// credential itself is not the problem" about a response that never
1891    /// mentioned the credential. Recognising GitHub's own rate-limit evidence is
1892    /// not rate-limit *policy*; it is declining to make an assertion the
1893    /// evidence contradicts. What to do about the rate limit stays `c3`'s, which
1894    /// is why this only changes which variant carries the headers onward.
1895    ///
1896    /// # Then one of two positions, and the second one is a fix for the first
1897    ///
1898    /// **The retry.** `consecutive_unauthorized` counts `401`s since the last
1899    /// successful caller response and — correctly — does not decay: a request
1900    /// that ends in `404`, `422` or `500` leaves it set. In the agent's
1901    /// long-lived reconciliation loop that meant a single `401` from minutes ago
1902    /// converted the *next* genuine permissions `403` into a fake lockout: sixty
1903    /// seconds of silence plus an operator message insisting the credential is
1904    /// fine, when in truth `generate-jitconfig` was missing
1905    /// `Administration: write`. The lockout's signature is narrower than "a
1906    /// `403` while the count is set" — it is a `403` on the one retry this
1907    /// client itself issued after this request's own `401`.
1908    ///
1909    /// The count is deliberately *not* consulted. [`Attempt::Retry`] already
1910    /// means this request's own `401` incremented it moments ago, so reading it
1911    /// adds no signal — and does add a race that fails open: any concurrent
1912    /// request succeeding between the `401` and the retry `store(0)`s the
1913    /// counter, and a real lockout is then reported as a plain permissions
1914    /// refusal. A conjunct that can only ever weaken a safety check is worse
1915    /// than no conjunct.
1916    ///
1917    /// **The continuation.** Narrowing to the retry position opened a hole at
1918    /// the far end of the same back-off. When the back-off elapses and GitHub is
1919    /// still locking the credential out, the next request is a *first* attempt
1920    /// by construction — this client's retry never happened, because the request
1921    /// never reached the wire. The position rule then declined to call it a
1922    /// lockout, `classify` fell through to [`GithubError::Forbidden`] — whose
1923    /// documented reading is "the App installation does not grant it" — and the
1924    /// client **stopped backing off entirely**, hammering a credential GitHub
1925    /// had asked it to leave alone. That is the exact inverse of the
1926    /// Definition of Done's "backs off without retrying", and it failed for
1927    /// every lockout outliving one back-off.
1928    ///
1929    /// No counter is needed for that case either, because the response says so
1930    /// itself. GitHub's lockout carries `retry-after` and no parseable message;
1931    /// a permissions refusal carries a message naming what is not accessible and
1932    /// no `retry-after`. Requiring **both** halves of that signature is what
1933    /// keeps this from degenerating into "every `403` is a lockout": a
1934    /// permissions answer has a message, so it never matches, and a secondary
1935    /// rate limit has both a message and `retry-after`, so `is_rate_limited`
1936    /// takes it first.
1937    ///
1938    /// "No parseable message" is deliberately wider than "an empty body", which
1939    /// is how this used to be stated. See [`is_lockout_continuation`] for what
1940    /// else falls into it — a proxy's HTML error page most notably — and for why
1941    /// the resulting false positives are accepted rather than tightened away.
1942    ///
1943    /// This also settles a standing worry about [`MAX_LOCKOUT_BACKOFF`]. With
1944    /// the continuation recognised, the ceiling no longer decides whether the
1945    /// product ever gives up — it only decides how often it re-asks. A lockout
1946    /// longer than the ceiling now re-latches instead of being reported as a
1947    /// permissions failure, so the value is a polling interval rather than a
1948    /// deadline.
1949    fn is_lockout_403(&self, response: &ApiResponse, attempt: Attempt) -> bool {
1950        if is_rate_limited(response) {
1951            return false;
1952        }
1953        match attempt {
1954            Attempt::Retry => true,
1955            Attempt::First => is_lockout_continuation(response),
1956        }
1957    }
1958
1959    fn latch_lockout(&self, headers: &HeaderMap) -> Duration {
1960        // Clamp before latching. An unclamped `Retry-After` is a remote party
1961        // deciding how long this product stays down.
1962        let requested = retry_after(headers).unwrap_or(DEFAULT_LOCKOUT_BACKOFF);
1963        let clamped = requested.min(MAX_LOCKOUT_BACKOFF);
1964
1965        // A span too large for `chrono` must fall back to the default, never to
1966        // `None`: the old code's `.ok()` turned an absurd `Retry-After` into "no
1967        // lockout at all", which fails *open* — the exact inverse of what a
1968        // back-off is for, and reachable by a header alone. The clamp above
1969        // already makes this branch unreachable; it stays because the invariant
1970        // it protects ("latching always latches") is worth more than the line.
1971        let delta = chrono::TimeDelta::from_std(clamped).unwrap_or_else(|_| {
1972            chrono::TimeDelta::from_std(DEFAULT_LOCKOUT_BACKOFF)
1973                .expect("sixty seconds is a representable span")
1974        });
1975        // No third clamp. `clamped` is already `<= MAX_LOCKOUT_BACKOFF`, and
1976        // `TimeDelta` round-trips it exactly, so re-clamping here was dead twice
1977        // over — it could only ever re-apply a bound already applied, and the
1978        // fallback it guarded is `DEFAULT_LOCKOUT_BACKOFF`, which is smaller
1979        // than the ceiling by construction.
1980        let backoff = delta.to_std().unwrap_or(DEFAULT_LOCKOUT_BACKOFF);
1981
1982        let mut state = self.lockout.lock().expect("lockout lock poisoned");
1983        state.backoff = backoff;
1984        state.until = Some(self.clock.now() + delta);
1985        backoff
1986    }
1987
1988    /// One HTTP round trip with the standard headers applied and no
1989    /// interpretation of the result.
1990    async fn send_raw(&self, request: &ApiRequest) -> Result<ApiResponse, GithubError> {
1991        let url = self.resolve(&request.path)?;
1992        let mut builder = self
1993            .http
1994            .request(request.method.clone(), url)
1995            .header(reqwest::header::ACCEPT, GITHUB_ACCEPT)
1996            .header(reqwest::header::USER_AGENT, USER_AGENT)
1997            .header("X-GitHub-Api-Version", GITHUB_API_VERSION)
1998            // The only place the token is ever written onto the wire. It is
1999            // never logged, and `reqwest` does not render headers in its errors.
2000            .header(
2001                reqwest::header::AUTHORIZATION,
2002                format!("Bearer {}", self.bearer()),
2003            );
2004        if !request.query.is_empty() {
2005            builder = builder.query(&request.query);
2006        }
2007        if let Some(body) = &request.body {
2008            builder = builder.json(body);
2009        }
2010
2011        let response = builder.send().await.map_err(transport)?;
2012        let status = response.status();
2013        let headers = response.headers().clone();
2014        let body = response.bytes().await.map_err(transport)?.to_vec();
2015
2016        tracing::debug!(
2017            method = request.method.as_str(),
2018            path = %request.path,
2019            status = status.as_u16(),
2020            body_bytes = body.len(),
2021            "github api request"
2022        );
2023
2024        Ok(ApiResponse {
2025            status,
2026            headers,
2027            body,
2028        })
2029    }
2030
2031    fn resolve(&self, path: &str) -> Result<Url, GithubError> {
2032        if path.starts_with("http://") || path.starts_with("https://") {
2033            return Url::parse(path).map_err(|_| GithubError::Malformed {
2034                what: "an absolute request URL",
2035                value: path.to_string(),
2036            });
2037        }
2038        self.endpoints
2039            .api_base
2040            .join(path.trim_start_matches('/'))
2041            .map_err(|_| GithubError::Malformed {
2042                what: "a request path",
2043                value: path.to_string(),
2044            })
2045    }
2046}
2047
2048enum Classified {
2049    Ok,
2050    Unauthorized,
2051    Error(GithubError),
2052}
2053
2054/// Which of a request's at-most-two attempts produced a response.
2055///
2056/// The authentication lockout is defined by *position*, not just by status: it
2057/// is what GitHub answers the retry that follows a `401`. Passing this in makes
2058/// that explicit at both call sites instead of inferring it from a counter that
2059/// outlives the request.
2060#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2061enum Attempt {
2062    First,
2063    Retry,
2064}
2065
2066/// Whether GitHub attributed a failing response to its own rate limit.
2067///
2068/// Reading the evidence, and nothing else — see [`GithubError`]'s note on why
2069/// the headers travel with the error. `c3` decides what to do about it.
2070fn is_rate_limited(response: &ApiResponse) -> bool {
2071    if response.status == StatusCode::TOO_MANY_REQUESTS {
2072        return true;
2073    }
2074    // The primary rate limit's documented signature.
2075    if response
2076        .header("x-ratelimit-remaining")
2077        .is_some_and(|v| v.trim() == "0")
2078    {
2079        return true;
2080    }
2081    // A secondary rate limit sends `retry-after` — but so does the
2082    // authentication lockout, so that header alone cannot tell them apart.
2083    // GitHub's own message ("You have exceeded a secondary rate limit") can.
2084    error_message(&response.body).is_some_and(|m| m.to_ascii_lowercase().contains("rate limit"))
2085}
2086
2087/// Whether a `403` on a *first* attempt is GitHub continuing an authentication
2088/// lockout that outlived this client's back-off.
2089///
2090/// The two halves are both required, and both are GitHub's own evidence rather
2091/// than this client's memory:
2092///
2093/// * **`retry-after` is present.** GitHub sends it when it wants to be left
2094///   alone. A permissions refusal never does — there is nothing to wait for.
2095///
2096///   The header's *presence* is what is tested, not whether it parses, and that
2097///   is a fix rather than laziness. [`retry_after`] reads **integer seconds
2098///   only**, while RFC 9110 §10.2.3 also permits an HTTP-date. Gating detection
2099///   on `retry_after(..).is_some()` meant a date-form header was not recognised
2100///   as a continuation at all, and the bug this function exists to fix came
2101///   straight back for that shape — silently, since the response still looks
2102///   like an ordinary [`GithubError::Forbidden`] on the way out.
2103///
2104///   How long to wait stays a separate question, still answered by the integer
2105///   parse: [`AuthenticatedClient::latch_lockout`] already falls back to
2106///   [`DEFAULT_LOCKOUT_BACKOFF`] for a header it cannot read, so a date-form
2107///   header now latches sixty seconds instead of latching nothing. GitHub sends
2108///   integer seconds in practice; the point is not to depend on that.
2109/// * **The body carries no parseable GitHub message.** A permissions refusal
2110///   always names what is not accessible ("Resource not accessible by
2111///   integration"); the lockout's does not. This is the half that stops the rule
2112///   from swallowing [`GithubError::Forbidden`] entirely.
2113///
2114///   "No parseable GitHub message" is wider than "the body is empty", which is
2115///   how this used to be written, and the difference is worth stating because it
2116///   is what the code actually tests. [`error_message`] returns `None` for *any*
2117///   body that is not JSON carrying a non-empty `message`: an HTML error page
2118///   from a proxy or a CDN, a JSON body carrying only `documentation_url`, plain
2119///   text, a truncated response. Proxies routinely send `Retry-After` too, so a
2120///   `403` that never came from GitHub at all can read as an authentication
2121///   lockout here.
2122///
2123///   That is accepted rather than missed. The cost is bounded — the client
2124///   waits, clamped by [`MAX_LOCKOUT_BACKOFF`], then re-asks — and the direction
2125///   is the safe one: treating a strange `403` as "wait" costs latency, while
2126///   treating a real lockout as a permissions answer costs the back-off
2127///   entirely and tells the operator to fix a grant that is not missing.
2128///   Tightening it would mean asserting the body *is* GitHub's, which is
2129///   precisely the assertion an intercepting proxy makes false.
2130///
2131/// Callers reach this through [`AuthenticatedClient::is_lockout_403`], which
2132/// rules out a rate limit first — a secondary rate limit carries `retry-after`
2133/// *and* a message, so it fails this test on the second half anyway, but the
2134/// ordering makes the precedence explicit rather than incidental.
2135fn is_lockout_continuation(response: &ApiResponse) -> bool {
2136    response.headers.contains_key("retry-after") && error_message(&response.body).is_none()
2137}
2138
2139// ---------------------------------------------------------------------------
2140// Installation discovery
2141// ---------------------------------------------------------------------------
2142
2143/// Whether an installation can reach every repository on its account, or only
2144/// the ones the user picked.
2145#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2146#[serde(rename_all = "snake_case")]
2147pub enum RepositorySelection {
2148    /// Every repository on the account, including ones created later.
2149    All,
2150    /// Only the repositories the user chose at install time.
2151    Selected,
2152}
2153
2154impl RepositorySelection {
2155    /// `07-security.md`: "`auth status` shows which repositories the token can
2156    /// reach, so an over-broad installation is visible rather than assumed."
2157    /// This is the flag that makes it visible.
2158    #[must_use]
2159    pub fn is_over_broad(self) -> bool {
2160        matches!(self, Self::All)
2161    }
2162}
2163
2164/// Whose account an installation sits on.
2165#[derive(Debug, Clone, PartialEq, Eq)]
2166pub enum InstallationAccount {
2167    User(String),
2168    Organization(Org),
2169    /// An enterprise account.
2170    ///
2171    /// It is its own variant rather than a [`InstallationAccount::User`]
2172    /// because it is not one, and `auth status` says out loud whose account
2173    /// each installation sits on. Everything GitHub reports without
2174    /// `type: "Organization"` used to fall into `User`, so an enterprise was
2175    /// labelled a user — a wrong statement about the operator's own account, on
2176    /// the one screen that exists to tell them what their credential reaches.
2177    ///
2178    /// It contributes nothing to [`ReachableTargets::organizations`], and that
2179    /// is correct rather than a second bug: an enterprise is not an
2180    /// organization, and `GET /orgs/{org}/actions/runners` does not accept one.
2181    /// The distinction is only visible now because the label is.
2182    Enterprise(String),
2183}
2184
2185impl InstallationAccount {
2186    #[must_use]
2187    pub fn login(&self) -> &str {
2188        match self {
2189            Self::User(login) | Self::Enterprise(login) => login,
2190            Self::Organization(org) => org.as_str(),
2191        }
2192    }
2193
2194    /// The organization, when the account is one. An organization account is a
2195    /// reachable *target* in its own right (D18): a policy may scale for the
2196    /// whole organization.
2197    #[must_use]
2198    pub fn organization(&self) -> Option<&Org> {
2199        match self {
2200            Self::Organization(org) => Some(org),
2201            Self::User(_) | Self::Enterprise(_) => None,
2202        }
2203    }
2204
2205    /// What to call this account in `auth status`. `f1` renders it; nothing in
2206    /// this crate branches on it.
2207    #[must_use]
2208    pub fn kind(&self) -> &'static str {
2209        match self {
2210            Self::User(_) => "user",
2211            Self::Organization(_) => "organization",
2212            Self::Enterprise(_) => "enterprise",
2213        }
2214    }
2215}
2216
2217impl fmt::Display for InstallationAccount {
2218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2219        f.write_str(self.login())
2220    }
2221}
2222
2223/// One installation of the published App, and what it can actually reach.
2224#[derive(Debug, Clone, PartialEq, Eq)]
2225pub struct Installation {
2226    pub id: u64,
2227    pub account: InstallationAccount,
2228    pub repository_selection: RepositorySelection,
2229    pub repositories: Vec<OwnerRepo>,
2230    /// The permissions GitHub reports for this installation, as
2231    /// `name -> level`. Surfaced verbatim so `auth status` can show a grant the
2232    /// user did not expect rather than assert the published set was applied.
2233    pub permissions: Vec<(String, String)>,
2234}
2235
2236impl Installation {
2237    #[must_use]
2238    pub fn is_over_broad(&self) -> bool {
2239        self.repository_selection.is_over_broad()
2240    }
2241}
2242
2243/// Everything the stored credential can reach.
2244#[derive(Debug, Clone, PartialEq, Eq)]
2245pub struct ReachableTargets {
2246    installations: Vec<Installation>,
2247    skipped: usize,
2248}
2249
2250impl ReachableTargets {
2251    #[must_use]
2252    pub fn installations(&self) -> &[Installation] {
2253        &self.installations
2254    }
2255
2256    /// How many installations GitHub reported that this client could not
2257    /// describe, and therefore left out of everything above.
2258    ///
2259    /// Non-zero means this report is **incomplete**, not merely small: whatever
2260    /// those installations reach is absent from
2261    /// [`ReachableTargets::repositories`] and
2262    /// [`ReachableTargets::organizations`]. `auth status` should say so, because
2263    /// the alternative is an operator reading a short list as a complete one.
2264    #[must_use]
2265    pub fn skipped(&self) -> usize {
2266        self.skipped
2267    }
2268
2269    /// Every repository the credential can reach, sorted and de-duplicated.
2270    #[must_use]
2271    pub fn repositories(&self) -> Vec<OwnerRepo> {
2272        let mut all: Vec<OwnerRepo> = self
2273            .installations
2274            .iter()
2275            .flat_map(|i| i.repositories.iter().cloned())
2276            .collect();
2277        all.sort();
2278        all.dedup();
2279        all
2280    }
2281
2282    /// Every organization the App is installed on, sorted and de-duplicated.
2283    #[must_use]
2284    pub fn organizations(&self) -> Vec<Org> {
2285        let mut all: Vec<Org> = self
2286            .installations
2287            .iter()
2288            .filter_map(|i| i.account.organization().cloned())
2289            .collect();
2290        all.sort();
2291        all.dedup();
2292        all
2293    }
2294
2295    /// The installations that hold `repository_selection: all`.
2296    #[must_use]
2297    pub fn over_broad(&self) -> Vec<&Installation> {
2298        self.installations
2299            .iter()
2300            .filter(|i| i.is_over_broad())
2301            .collect()
2302    }
2303
2304    #[must_use]
2305    pub fn is_empty(&self) -> bool {
2306        self.repositories().is_empty() && self.organizations().is_empty()
2307    }
2308}
2309
2310/// What `auth status` and `auth login` show after a successful sign-in.
2311#[derive(Debug, Clone, PartialEq, Eq)]
2312pub enum InstallationDiscovery {
2313    /// The credential is valid, GitHub reported nothing this client could not
2314    /// describe, and still nothing is reachable: the App is installed nowhere,
2315    /// or on nothing. `03-control-flows.md` flow 1.1 requires the installation
2316    /// URL here, and the URL is the remediation.
2317    NotInstalled { install_url: Url },
2318    /// Nothing is reachable, but at least one installation was **skipped**, so
2319    /// this client cannot tell "not installed" from "installed on something it
2320    /// could not describe".
2321    ///
2322    /// # Why this variant exists at all
2323    ///
2324    /// Skipping an unnameable installation is the right trade — one odd
2325    /// installation must not take down `auth status` for every other one — but
2326    /// it was made silently, and the silence flipped a verdict. An account this
2327    /// client cannot name, on the *only* installation the credential has, used
2328    /// to collapse to [`InstallationDiscovery::NotInstalled`], and `auth status`
2329    /// then handed an already-installed operator the "install the App" URL. That
2330    /// is a wrong remediation on the only authentication path there is,
2331    /// contradicted by nothing louder than a `warn!` in a log the operator is
2332    /// not reading.
2333    ///
2334    /// So the skip stays and the verdict does not flip. There is deliberately no
2335    /// `install_url` here: the whole point is that this client does not know
2336    /// whether installing is the remedy, and offering the URL anyway would put
2337    /// the wrong answer back one field over. `f1` says "1 installation could not
2338    /// be described" and stops there, which is true.
2339    Indeterminate { skipped: usize },
2340    /// The credential reaches at least one repository or organization. It may
2341    /// still be an incomplete picture — see [`ReachableTargets::skipped`].
2342    Installed(ReachableTargets),
2343}
2344
2345impl InstallationDiscovery {
2346    #[must_use]
2347    pub fn targets(&self) -> Option<&ReachableTargets> {
2348        match self {
2349            Self::Installed(t) => Some(t),
2350            Self::NotInstalled { .. } | Self::Indeterminate { .. } => None,
2351        }
2352    }
2353
2354    /// The installation URL, and *only* when installing is actually the
2355    /// remediation. See [`InstallationDiscovery::Indeterminate`].
2356    #[must_use]
2357    pub fn install_url(&self) -> Option<&Url> {
2358        match self {
2359            Self::NotInstalled { install_url } => Some(install_url),
2360            Self::Installed(_) | Self::Indeterminate { .. } => None,
2361        }
2362    }
2363
2364    /// How many installations GitHub reported that this client could not
2365    /// describe, whichever verdict was reached. One call for `f1`, so that
2366    /// "this report is incomplete" does not depend on which variant it landed
2367    /// in.
2368    #[must_use]
2369    pub fn skipped(&self) -> usize {
2370        match self {
2371            Self::NotInstalled { .. } => 0,
2372            Self::Indeterminate { skipped } => *skipped,
2373            Self::Installed(targets) => targets.skipped(),
2374        }
2375    }
2376}
2377
2378#[derive(Debug, Deserialize)]
2379struct InstallationsPage {
2380    /// GitHub reports the size of the whole collection on every page. Decoding
2381    /// it costs nothing and turns silent under-collection into a visible
2382    /// warning — see [`under_collected`].
2383    #[serde(default)]
2384    total_count: Option<u64>,
2385    #[serde(default)]
2386    installations: Vec<RawInstallation>,
2387}
2388
2389#[derive(Debug, Deserialize)]
2390struct RawInstallation {
2391    id: u64,
2392    /// **Nullable.** GitHub's published `installation` schema types `account` as
2393    /// nullable, so a required field here would fail the *whole* decode — and
2394    /// with it all of `discover_installations`, which is all of `auth status` —
2395    /// over one installation whose account this client did not need to name.
2396    #[serde(default)]
2397    account: Option<RawAccount>,
2398    #[serde(default)]
2399    repository_selection: Option<String>,
2400    #[serde(default)]
2401    permissions: std::collections::BTreeMap<String, String>,
2402}
2403
2404/// An installation's account, which is *not* always a simple user.
2405///
2406/// GitHub's schema makes `account` either a simple-user or an enterprise, and an
2407/// enterprise carries `slug` and `name` where a user carries `login`. Requiring
2408/// `login` therefore made an enterprise installation a hard decode failure of
2409/// the entire response. All three are optional here and
2410/// [`RawAccount::display_login`] takes the first usable one.
2411#[derive(Debug, Deserialize)]
2412struct RawAccount {
2413    #[serde(default)]
2414    login: Option<String>,
2415    /// An enterprise account's stable identifier.
2416    #[serde(default)]
2417    slug: Option<String>,
2418    /// An enterprise account's display name, the last resort.
2419    #[serde(default)]
2420    name: Option<String>,
2421    #[serde(rename = "type", default)]
2422    account_type: Option<String>,
2423}
2424
2425impl RawAccount {
2426    fn display_login(&self) -> Option<&str> {
2427        [
2428            self.login.as_deref(),
2429            self.slug.as_deref(),
2430            self.name.as_deref(),
2431        ]
2432        .into_iter()
2433        .flatten()
2434        .find(|value| !value.is_empty())
2435    }
2436
2437    /// An account with no `login` that still names itself is an enterprise:
2438    /// `slug`/`name` is the enterprise shape, and every simple-user and
2439    /// organization account carries `login`.
2440    fn is_enterprise_shaped(&self) -> bool {
2441        self.login.as_deref().is_none_or(str::is_empty)
2442            && (self.slug.as_deref().is_some_and(|s| !s.is_empty())
2443                || self.name.as_deref().is_some_and(|s| !s.is_empty()))
2444    }
2445}
2446
2447#[derive(Debug, Deserialize)]
2448struct RepositoriesPage {
2449    #[serde(default)]
2450    total_count: Option<u64>,
2451    #[serde(default)]
2452    repositories: Vec<RawRepository>,
2453}
2454
2455#[derive(Debug, Deserialize)]
2456struct RawRepository {
2457    full_name: String,
2458}
2459
2460/// How many items a paginated collection said it had, when that is more than
2461/// arrived.
2462///
2463/// This is the cheapest possible check and it is worth more than it looks. The
2464/// `Link`-header parser used to lose the relation whenever a page URL contained
2465/// a comma, which stopped pagination at page 1 — and *nothing* noticed, because
2466/// a short answer and a complete answer are the same shape. Cross-checking the
2467/// count GitHub itself reported turns that class of bug from a wrong answer into
2468/// a logged warning. A collection larger than `total_count` is not reported:
2469/// GitHub can legitimately grow a collection between pages.
2470fn under_collected(collected: usize, total_count: Option<u64>) -> Option<u64> {
2471    let total = total_count?;
2472    (total > collected as u64).then_some(total)
2473}
2474
2475impl AuthenticatedClient {
2476    /// Which repositories and organizations the stored credential can actually
2477    /// reach.
2478    ///
2479    /// Two calls, both paginated: `GET /user/installations`, then
2480    /// `GET /user/installations/{id}/repositories` per installation. The shapes
2481    /// are the ones the D18 spike observed live
2482    /// (`docs/spikes/d18-org-jit-verification.md`, "The permission that
2483    /// authorized it").
2484    ///
2485    /// An installation is reported even when it is broader than the user
2486    /// expected — [`Installation::is_over_broad`] — because `07-security.md`
2487    /// requires that an over-broad installation be *visible* rather than
2488    /// assumed. Nothing here narrows or hides one.
2489    ///
2490    /// # Errors
2491    /// Every variant of [`GithubError`]. A `401` here goes through the same
2492    /// single-flight re-validation as any other request.
2493    pub async fn discover_installations(
2494        &self,
2495        app: &AppRegistration,
2496    ) -> Result<InstallationDiscovery, GithubError> {
2497        let mut installations = Vec::new();
2498        let mut skipped = 0_usize;
2499        for raw in self.all_installations().await? {
2500            // A null or nameless account is skipped rather than fatal. GitHub
2501            // types this field as nullable, and one unnameable installation must
2502            // not take down `auth status` for every other one — but it is also
2503            // not something to swallow quietly, because the repositories behind
2504            // it are then absent from the reported reach. The count is what
2505            // carries that out of here; a `warn!` alone let the skip change the
2506            // verdict with nothing to say so.
2507            let Some(login) = raw.account.as_ref().and_then(RawAccount::display_login) else {
2508                skipped += 1;
2509                tracing::warn!(
2510                    installation_id = raw.id,
2511                    "skipping an installation GitHub reported with no nameable account; \
2512                     anything it reaches is missing from this report"
2513                );
2514                continue;
2515            };
2516            let account_type = raw.account.as_ref().and_then(|a| a.account_type.as_deref());
2517            let account = match account_type {
2518                Some("Organization") => {
2519                    InstallationAccount::Organization(Org::new(login).map_err(|_| {
2520                        GithubError::Malformed {
2521                            what: "an installation account login",
2522                            value: login.to_string(),
2523                        }
2524                    })?)
2525                }
2526                Some("Enterprise") => InstallationAccount::Enterprise(login.to_string()),
2527                // An enterprise is also reported with no `type` at all, carrying
2528                // `slug`/`name` where a user carries `login` — which is the
2529                // shape D18 observed and the shape `display_login` exists for.
2530                // Recognising it by that shape is what stops it being labelled a
2531                // user by default.
2532                _ if raw
2533                    .account
2534                    .as_ref()
2535                    .is_some_and(RawAccount::is_enterprise_shaped) =>
2536                {
2537                    InstallationAccount::Enterprise(login.to_string())
2538                }
2539                _ => InstallationAccount::User(login.to_string()),
2540            };
2541            let repository_selection = match raw.repository_selection.as_deref() {
2542                Some("all") => RepositorySelection::All,
2543                _ => RepositorySelection::Selected,
2544            };
2545            installations.push(Installation {
2546                id: raw.id,
2547                account,
2548                repository_selection,
2549                repositories: self.installation_repositories(raw.id).await?,
2550                permissions: raw.permissions.into_iter().collect(),
2551            });
2552        }
2553
2554        let targets = ReachableTargets {
2555            installations,
2556            skipped,
2557        };
2558        if targets.is_empty() {
2559            // "Nothing reachable" and "nothing this client could describe" are
2560            // different answers, and only the first one is fixed by installing
2561            // the App. Reporting them as the same answer is how an
2562            // already-installed operator was handed an install URL.
2563            if skipped > 0 {
2564                tracing::warn!(
2565                    skipped,
2566                    "every installation GitHub reported was skipped; whether the App is \
2567                     installed cannot be determined from this credential"
2568                );
2569                return Ok(InstallationDiscovery::Indeterminate { skipped });
2570            }
2571            let install_url = app.install_url(&self.endpoints);
2572            tracing::info!(
2573                install_url = %install_url,
2574                "the published App is not installed on anything this credential can reach"
2575            );
2576            return Ok(InstallationDiscovery::NotInstalled { install_url });
2577        }
2578        tracing::info!(
2579            repositories = targets.repositories().len(),
2580            organizations = targets.organizations().len(),
2581            over_broad = targets.over_broad().len(),
2582            skipped,
2583            "discovered the targets this credential can reach"
2584        );
2585        Ok(InstallationDiscovery::Installed(targets))
2586    }
2587
2588    async fn all_installations(&self) -> Result<Vec<RawInstallation>, GithubError> {
2589        let mut out = Vec::new();
2590        let mut total_count = None;
2591        let mut next = Some(ApiRequest::get("/user/installations").query("per_page", 100));
2592        let mut pages = 0_usize;
2593        while let Some(request) = next.take() {
2594            let response = self.send(&request).await?;
2595            let page: InstallationsPage = response.json()?;
2596            total_count = page.total_count.or(total_count);
2597            out.extend(page.installations);
2598
2599            pages += 1;
2600            if pages >= MAX_PAGES {
2601                tracing::warn!(
2602                    pages,
2603                    collected = out.len(),
2604                    "stopped following installation pages at the ceiling; a `Link: rel=next` \
2605                     that never ends would otherwise loop forever"
2606                );
2607                break;
2608            }
2609            next = response
2610                .next_page()
2611                .map(|url| ApiRequest::get(url.as_str()));
2612        }
2613        if let Some(expected) = under_collected(out.len(), total_count) {
2614            tracing::warn!(
2615                expected,
2616                collected = out.len(),
2617                "GitHub reported more installations than pagination collected; the reported \
2618                 reach is incomplete"
2619            );
2620        }
2621        Ok(out)
2622    }
2623
2624    async fn installation_repositories(&self, id: u64) -> Result<Vec<OwnerRepo>, GithubError> {
2625        let mut out = Vec::new();
2626        let mut total_count = None;
2627        let mut next = Some(
2628            ApiRequest::get(format!("/user/installations/{id}/repositories"))
2629                .query("per_page", 100),
2630        );
2631        let mut pages = 0_usize;
2632        while let Some(request) = next.take() {
2633            let response = self.send(&request).await?;
2634            let page: RepositoriesPage = response.json()?;
2635            total_count = page.total_count.or(total_count);
2636            for repo in page.repositories {
2637                out.push(OwnerRepo::parse(&repo.full_name).map_err(|_| {
2638                    GithubError::Malformed {
2639                        what: "a repository full_name",
2640                        value: repo.full_name.clone(),
2641                    }
2642                })?);
2643            }
2644
2645            pages += 1;
2646            if pages >= MAX_PAGES {
2647                tracing::warn!(
2648                    installation_id = id,
2649                    pages,
2650                    collected = out.len(),
2651                    "stopped following repository pages at the ceiling; a `Link: rel=next` \
2652                     that never ends would otherwise loop forever"
2653                );
2654                break;
2655            }
2656            next = response
2657                .next_page()
2658                .map(|url| ApiRequest::get(url.as_str()));
2659        }
2660        if let Some(expected) = under_collected(out.len(), total_count) {
2661            tracing::warn!(
2662                installation_id = id,
2663                expected,
2664                collected = out.len(),
2665                "GitHub reported more repositories than pagination collected; this \
2666                 installation's reach is under-reported"
2667            );
2668        }
2669        Ok(out)
2670    }
2671}
2672
2673/// Test support shared by this file and [`device_flow`].
2674///
2675/// It lives inline rather than in `src/testing.rs` on purpose. `a1` laid out
2676/// this crate's five source files — `lib.rs`, `device_flow.rs`, `rest.rs`,
2677/// `demand.rs`, `jit.rs` — and owns every manifest; `c3` and `c4` are working in
2678/// the same directory in parallel, and a new file there is a merge conflict
2679/// waiting to happen for no benefit. An inline `#[cfg(test)]` module is
2680/// reachable as `crate::testing` from every module in the crate and adds nothing
2681/// to a release build.
2682///
2683/// It does not live in `runner-manager-testkit` either, and that one is
2684/// mechanical: `testkit` depends on `runner-manager-github`, so a unit test
2685/// inside this crate that used a `testkit` helper would link a *second* instance
2686/// of this library and the two instances' types would not unify — the same
2687/// hazard `testkit`'s own crate documentation records for `domain`.
2688#[cfg(test)]
2689pub(crate) mod testing {
2690    use super::*;
2691    use serde_json::{Value, json};
2692    use std::sync::{Mutex, atomic::AtomicUsize};
2693    use wiremock::{Request, Respond, ResponseTemplate};
2694
2695    /// Shaped like a real `ghu_` token, and unmistakably not one.
2696    pub const FIXTURE_TOKEN: &str = "ghu_fixtureTOKENnotARealCredential00";
2697    /// Shaped like a real device code, and unmistakably not one.
2698    pub const FIXTURE_DEVICE_CODE: &str = "fixture-device-code-0e37a9c1b4d84f2a";
2699    /// The example user code from RFC 8628.
2700    pub const FIXTURE_USER_CODE: &str = "WDJB-MJHT";
2701
2702    /// A clock the test moves.
2703    ///
2704    /// Deliberately not `runner_manager_testkit::clock::FakeClock`; see this
2705    /// module's documentation for why a `testkit` import is not available here.
2706    #[derive(Debug)]
2707    pub struct TestClock {
2708        now: Mutex<Timestamp>,
2709    }
2710
2711    impl TestClock {
2712        /// # Panics
2713        /// If a previous holder panicked while the lock was held.
2714        pub fn advance_secs(&self, secs: i64) {
2715            let mut now = self.now.lock().expect("TestClock lock poisoned");
2716            *now += chrono::TimeDelta::seconds(secs);
2717        }
2718    }
2719
2720    impl Default for TestClock {
2721        fn default() -> Self {
2722            // 2026-08-21T00:00:00Z, the date this taskflow's decisions were
2723            // locked — the same epoch `testkit`'s clock starts at.
2724            Self {
2725                now: Mutex::new(
2726                    chrono::DateTime::from_timestamp(1_787_270_400, 0).expect("a valid instant"),
2727                ),
2728            }
2729        }
2730    }
2731
2732    impl Clock for TestClock {
2733        fn now(&self) -> Timestamp {
2734            *self.now.lock().expect("TestClock lock poisoned")
2735        }
2736    }
2737
2738    /// A sleeper that records what it was asked to wait and returns at once.
2739    ///
2740    /// This is what turns "`slow_down` demonstrably increases the poll interval"
2741    /// into an equality assertion on a `Vec<Duration>`.
2742    #[derive(Debug, Default)]
2743    pub struct RecordingSleeper {
2744        recorded: Mutex<Vec<Duration>>,
2745    }
2746
2747    impl RecordingSleeper {
2748        /// # Panics
2749        /// If a previous holder panicked while the lock was held.
2750        pub fn recorded(&self) -> Vec<Duration> {
2751            self.recorded.lock().expect("sleeper lock poisoned").clone()
2752        }
2753    }
2754
2755    #[async_trait::async_trait]
2756    impl Sleeper for RecordingSleeper {
2757        async fn sleep(&self, duration: Duration) {
2758            self.recorded
2759                .lock()
2760                .expect("sleeper lock poisoned")
2761                .push(duration);
2762        }
2763    }
2764
2765    /// Answers from a fixed script, one entry per call, repeating the last.
2766    pub struct Script {
2767        responses: Vec<ResponseTemplate>,
2768        calls: AtomicUsize,
2769    }
2770
2771    impl Script {
2772        #[must_use]
2773        pub fn new(responses: Vec<ResponseTemplate>) -> Self {
2774            assert!(
2775                !responses.is_empty(),
2776                "a script needs at least one response"
2777            );
2778            Self {
2779                responses,
2780                calls: AtomicUsize::new(0),
2781            }
2782        }
2783    }
2784
2785    impl Respond for Script {
2786        fn respond(&self, _: &Request) -> ResponseTemplate {
2787            let i = self.calls.fetch_add(1, Ordering::SeqCst);
2788            self.responses[i.min(self.responses.len() - 1)].clone()
2789        }
2790    }
2791
2792    /// `POST https://github.com/login/device/code` → `200`, in the shape both
2793    /// spikes observed (`docs/spikes/d17-spike.ps1`).
2794    #[must_use]
2795    pub fn device_code_body(server_uri: &str, interval: u64, expires_in: u64) -> Value {
2796        json!({
2797            "device_code": FIXTURE_DEVICE_CODE,
2798            "user_code": FIXTURE_USER_CODE,
2799            "verification_uri": format!("{server_uri}/login/device"),
2800            "expires_in": expires_in,
2801            "interval": interval
2802        })
2803    }
2804
2805    /// `POST .../login/oauth/access_token` → `200` with an `error` field, which
2806    /// is how GitHub answers every state in the matrix.
2807    #[must_use]
2808    pub fn error_body(code: &str, interval: Option<u64>) -> Value {
2809        let mut body = json!({
2810            "error": code,
2811            "error_description": "see the OAuth 2.0 Device Authorization Grant",
2812            "error_uri": "https://docs.github.com/developers/apps/authorizing-oauth-apps"
2813        });
2814        if let Some(interval) = interval {
2815            body["interval"] = json!(interval);
2816        }
2817        body
2818    }
2819
2820    /// `POST .../login/oauth/access_token` → `200` with an approved token.
2821    #[must_use]
2822    pub fn token_body() -> Value {
2823        json!({ "access_token": FIXTURE_TOKEN, "token_type": "bearer", "scope": "" })
2824    }
2825
2826    /// `GET /user/installations` → `200`. The permission set is the one D18 read
2827    /// back from the live installation.
2828    #[must_use]
2829    pub fn installations_body(entries: &[(u64, &str, &str, &str)]) -> Value {
2830        let installations: Vec<Value> = entries
2831            .iter()
2832            .map(|(id, login, account_type, selection)| {
2833                json!({
2834                    "id": id,
2835                    "account": { "login": login, "type": account_type },
2836                    "repository_selection": selection,
2837                    "permissions": {
2838                        "actions": "read",
2839                        "administration": "write",
2840                        "metadata": "read",
2841                        "organization_self_hosted_runners": "write"
2842                    }
2843                })
2844            })
2845            .collect();
2846        json!({ "total_count": installations.len(), "installations": installations })
2847    }
2848
2849    /// `GET /user/installations/{id}/repositories` → `200`.
2850    #[must_use]
2851    pub fn repositories_body(full_names: &[&str]) -> Value {
2852        let repositories: Vec<Value> = full_names
2853            .iter()
2854            .map(|full_name| json!({ "full_name": full_name }))
2855            .collect();
2856        json!({ "total_count": repositories.len(), "repositories": repositories })
2857    }
2858
2859    // The `tracing` capture subscriber that used to live here now lives in
2860    // `tests/no_secret_reaches_the_logs.rs`, and the move is the point rather
2861    // than tidying. `tracing` caches a callsite's `Interest` process-wide while
2862    // `with_default` installs a subscriber only on the calling *thread*, so a
2863    // scan running alongside the crate's other unit tests captured nothing but
2864    // its own handful of events and passed with a real device-code leak in the
2865    // flow. A scan that is the only test in its process has no concurrent
2866    // thread to be poisoned by, and no `#[cfg(test)]` module here can offer
2867    // that guarantee.
2868    //
2869    // The blinding is a *concurrency* effect and not a permanent
2870    // first-registration one — see that file's header for the measurement that
2871    // separates the two. The distinction matters here because only the
2872    // concurrency reading implies what this comment concludes: that one test
2873    // per process is the fix.
2874}
2875
2876#[cfg(test)]
2877mod tests {
2878
2879    /// Upgrading must not log anybody out, and the App's expiration setting must
2880    /// be safe to turn on -- or back off -- with hosts mid-way through either.
2881    #[test]
2882    fn both_stored_shapes_load_and_a_pair_survives_a_round_trip() {
2883        // What every host stored before renewal existed: a bare token.
2884        let legacy = UserAccessToken::from_stored_document(&SecretString::from("ghu_legacy123"));
2885        assert_eq!(legacy.secret().expose_secret(), "ghu_legacy123");
2886        assert!(
2887            legacy.renewal().is_none(),
2888            "a bare token has no renewal half, and inventing one would make the client try to              refresh a credential the App never issued a refresh token for"
2889        );
2890
2891        // A pair, written and read back.
2892        let pair = UserAccessToken::new(SecretString::from("ghu_new")).with_renewal(
2893            Some(SecretString::from("ghr_new")),
2894            Some(28_800),
2895            Some(15_897_600),
2896        );
2897        let stored = pair.to_stored_document();
2898        let read = UserAccessToken::from_stored_document(&stored);
2899        assert_eq!(read.secret().expose_secret(), "ghu_new");
2900        let renewal = read.renewal().expect("the pair survives the round trip");
2901        assert_eq!(renewal.refresh_token().expose_secret(), "ghr_new");
2902        assert!(renewal.access_expires_at.is_some());
2903        assert!(renewal.refresh_expires_at.is_some());
2904
2905        // A credential with no renewal still writes the document shape, and
2906        // still reads back as having none.
2907        let bare_round_trip = UserAccessToken::from_stored_document(&legacy.to_stored_document());
2908        assert_eq!(bare_round_trip.secret().expose_secret(), "ghu_legacy123");
2909        assert!(bare_round_trip.renewal().is_none());
2910    }
2911
2912    /// The refresh token is the more dangerous half -- it mints access tokens
2913    /// for six months -- so it must not reach a log through `Debug`.
2914    #[test]
2915    fn a_refresh_token_never_appears_in_debug_output() {
2916        let pair = UserAccessToken::new(SecretString::from("ghu_x")).with_renewal(
2917            Some(SecretString::from("ghr_SUPERSECRET")),
2918            Some(1),
2919            Some(2),
2920        );
2921        let rendered = format!("{:?}", pair.renewal().expect("a renewal"));
2922        assert!(!rendered.contains("ghr_SUPERSECRET"), "{rendered}");
2923        assert!(rendered.contains("redacted"), "{rendered}");
2924    }
2925    use super::*;
2926    use crate::testing::{FIXTURE_TOKEN, Script, TestClock, installations_body, repositories_body};
2927    use serde_json::json;
2928    use wiremock::{
2929        Mock, MockServer, ResponseTemplate,
2930        matchers::{header, method, path},
2931    };
2932
2933    fn client(server: &MockServer, clock: Arc<TestClock>) -> AuthenticatedClient {
2934        AuthenticatedClient::new(
2935            Endpoints::for_test_server(&server.uri()).unwrap(),
2936            UserAccessToken::new(SecretString::from(FIXTURE_TOKEN)),
2937            clock,
2938        )
2939        .unwrap()
2940    }
2941
2942    fn app() -> AppRegistration {
2943        AppRegistration::new("Iv23liTESTCLIENTID", "runner-manager").unwrap()
2944    }
2945
2946    // -- picking up a credential somebody else stored -------------------------
2947
2948    /// A [`CredentialSource`] over a fixed answer, which is what a store looks
2949    /// like from here.
2950    #[derive(Debug)]
2951    struct StoreHolding(Option<&'static str>);
2952
2953    impl CredentialSource for StoreHolding {
2954        fn reload(&self) -> Option<UserAccessToken> {
2955            self.0
2956                .map(|token| UserAccessToken::new(SecretString::from(token)))
2957        }
2958    }
2959
2960    /// The 28-hour failure, as a test: a daemon holding a dead bare token, an
2961    /// operator who signs in, and nothing that tells the daemon.
2962    ///
2963    /// Bare on purpose. A pair would renew and never reach the store at all,
2964    /// which is why renewal alone did not cover this.
2965    #[tokio::test]
2966    async fn a_daemon_picks_up_a_sign_in_that_happened_after_it_started() {
2967        let server = MockServer::start().await;
2968        Mock::given(method("GET"))
2969            .and(path("/repos/acme/app"))
2970            .and(header("authorization", "Bearer ghu_dead"))
2971            .respond_with(ResponseTemplate::new(401))
2972            .expect(1)
2973            .mount(&server)
2974            .await;
2975        Mock::given(method("GET"))
2976            .and(path("/repos/acme/app"))
2977            .and(header("authorization", "Bearer ghu_freshly_signed_in"))
2978            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"id": 1})))
2979            .expect(1)
2980            .mount(&server)
2981            .await;
2982
2983        let client = AuthenticatedClient::new(
2984            Endpoints::for_test_server(&server.uri()).unwrap(),
2985            UserAccessToken::new(SecretString::from("ghu_dead")),
2986            Arc::new(TestClock::default()),
2987        )
2988        .unwrap()
2989        .with_credential_source(Arc::new(StoreHolding(Some("ghu_freshly_signed_in"))));
2990
2991        client
2992            .send(&ApiRequest::get("/repos/acme/app"))
2993            .await
2994            .expect(
2995                "the 401 is retried with what the store holds now, without anybody \n                 restarting the daemon",
2996            );
2997    }
2998
2999    /// The other half, and the reason for the comparison in `reload_once`: a
3000    /// store that still holds the token that just failed is not news.
3001    ///
3002    /// Without the check, every `401` would answer "something changed, retry"
3003    /// and a genuinely revoked credential would spend two requests per poll
3004    /// forever instead of being reported.
3005    #[tokio::test]
3006    async fn a_store_holding_the_same_dead_token_is_not_worth_a_retry() {
3007        let server = MockServer::start().await;
3008        Mock::given(method("GET"))
3009            .and(path("/repos/acme/app"))
3010            .respond_with(ResponseTemplate::new(401))
3011            .expect(1)
3012            .mount(&server)
3013            .await;
3014        // The re-validation probe that runs once reload declines.
3015        Mock::given(method("GET"))
3016            .and(path("/user/installations"))
3017            .respond_with(ResponseTemplate::new(401))
3018            .expect(1)
3019            .mount(&server)
3020            .await;
3021
3022        let client = AuthenticatedClient::new(
3023            Endpoints::for_test_server(&server.uri()).unwrap(),
3024            UserAccessToken::new(SecretString::from("ghu_revoked")),
3025            Arc::new(TestClock::default()),
3026        )
3027        .unwrap()
3028        .with_credential_source(Arc::new(StoreHolding(Some("ghu_revoked"))));
3029
3030        let failure = client
3031            .send(&ApiRequest::get("/repos/acme/app"))
3032            .await
3033            .expect_err("a revoked credential is still revoked when the store agrees");
3034        assert!(
3035            matches!(failure, GithubError::AuthenticationFailed),
3036            "{failure:?}"
3037        );
3038    }
3039
3040    /// An unreadable store leaves the `401` exactly where it was, rather than
3041    /// turning a rejection into a different kind of error.
3042    #[tokio::test]
3043    async fn an_unreadable_store_changes_nothing_about_the_rejection() {
3044        let server = MockServer::start().await;
3045        Mock::given(method("GET"))
3046            .and(path("/repos/acme/app"))
3047            .respond_with(ResponseTemplate::new(401))
3048            .expect(1)
3049            .mount(&server)
3050            .await;
3051        Mock::given(method("GET"))
3052            .and(path("/user/installations"))
3053            .respond_with(ResponseTemplate::new(401))
3054            .expect(1)
3055            .mount(&server)
3056            .await;
3057
3058        let client = AuthenticatedClient::new(
3059            Endpoints::for_test_server(&server.uri()).unwrap(),
3060            UserAccessToken::new(SecretString::from("ghu_revoked")),
3061            Arc::new(TestClock::default()),
3062        )
3063        .unwrap()
3064        .with_credential_source(Arc::new(StoreHolding(None)));
3065
3066        let failure = client
3067            .send(&ApiRequest::get("/repos/acme/app"))
3068            .await
3069            .expect_err("nothing to pick up means the rejection stands");
3070        assert!(
3071            matches!(failure, GithubError::AuthenticationFailed),
3072            "{failure:?}"
3073        );
3074    }
3075
3076    // -- headers ------------------------------------------------------------
3077
3078    #[tokio::test]
3079    async fn every_request_states_its_api_version_and_accept_header() {
3080        let server = MockServer::start().await;
3081        Mock::given(method("GET"))
3082            .and(path("/user/installations"))
3083            .and(header("x-github-api-version", GITHUB_API_VERSION))
3084            .and(header("accept", GITHUB_ACCEPT))
3085            .and(header("authorization", format!("Bearer {FIXTURE_TOKEN}")))
3086            .and(header("user-agent", USER_AGENT))
3087            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3088            .expect(1)
3089            .mount(&server)
3090            .await;
3091
3092        let client = client(&server, Arc::new(TestClock::default()));
3093        client
3094            .send(&ApiRequest::get("/user/installations"))
3095            .await
3096            .expect("the mock only matches when all four headers are present");
3097    }
3098
3099    // -- the 401 path -------------------------------------------------------
3100
3101    #[tokio::test]
3102    async fn a_401_revalidates_once_and_retries_once_then_succeeds() {
3103        let server = MockServer::start().await;
3104        Mock::given(method("GET"))
3105            .and(path("/orgs/acme/actions/runners"))
3106            .respond_with(Script::new(vec![
3107                ResponseTemplate::new(401).set_body_json(json!({"message": "Bad credentials"})),
3108                ResponseTemplate::new(200).set_body_json(json!({"total_count": 0})),
3109            ]))
3110            .expect(2)
3111            .mount(&server)
3112            .await;
3113        Mock::given(method("GET"))
3114            .and(path("/user/installations"))
3115            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3116            .expect(1)
3117            .mount(&server)
3118            .await;
3119
3120        let client = client(&server, Arc::new(TestClock::default()));
3121        let response = client
3122            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3123            .await
3124            .expect("the retry succeeds");
3125
3126        assert_eq!(response.status(), StatusCode::OK);
3127        assert_eq!(
3128            client.revalidations_performed(),
3129            1,
3130            "one 401 must produce exactly one re-validation"
3131        );
3132    }
3133
3134    #[tokio::test]
3135    async fn a_second_401_after_the_retry_is_terminal_authentication_failure() {
3136        let server = MockServer::start().await;
3137        Mock::given(method("GET"))
3138            .and(path("/orgs/acme/actions/runners"))
3139            .respond_with(ResponseTemplate::new(401))
3140            .expect(2)
3141            .mount(&server)
3142            .await;
3143        Mock::given(method("GET"))
3144            .and(path("/user/installations"))
3145            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3146            .mount(&server)
3147            .await;
3148
3149        let client = client(&server, Arc::new(TestClock::default()));
3150        let err = client
3151            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3152            .await
3153            .expect_err("two 401s is terminal");
3154
3155        assert!(matches!(err, GithubError::AuthenticationFailed), "{err:?}");
3156        assert!(err.is_authentication());
3157        assert!(!err.is_lockout());
3158    }
3159
3160    #[tokio::test]
3161    async fn a_rejected_revalidation_fails_without_spending_the_retry() {
3162        let server = MockServer::start().await;
3163        Mock::given(method("GET"))
3164            .and(path("/orgs/acme/actions/runners"))
3165            .respond_with(ResponseTemplate::new(401))
3166            // Exactly one: a credential GitHub has confirmed dead must not be
3167            // used for a retry.
3168            .expect(1)
3169            .mount(&server)
3170            .await;
3171        Mock::given(method("GET"))
3172            .and(path("/user/installations"))
3173            .respond_with(ResponseTemplate::new(401))
3174            .expect(1)
3175            .mount(&server)
3176            .await;
3177
3178        let client = client(&server, Arc::new(TestClock::default()));
3179        let err = client
3180            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3181            .await
3182            .expect_err("the credential is dead");
3183        assert!(matches!(err, GithubError::AuthenticationFailed), "{err:?}");
3184    }
3185
3186    /// The Definition of Done's concurrency claim, tested with real concurrent
3187    /// callers on a multi-threaded runtime rather than by reasoning about the
3188    /// mutex.
3189    ///
3190    /// Two things make the assertion deterministic rather than lucky. A barrier
3191    /// releases all eight callers into `send` together, so all eight take their
3192    /// `401` before any of them reaches the gate; and the re-validation endpoint
3193    /// is delayed, so the first caller still holds the gate while the other
3194    /// seven sample the generation counter. Without the delay a caller could
3195    /// legitimately arrive after the first re-validation completed, which is a
3196    /// *new* `401` storm and correctly earns its own attempt.
3197    #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
3198    async fn eight_concurrent_401s_produce_one_revalidation_not_eight() {
3199        const CALLERS: usize = 8;
3200
3201        let server = MockServer::start().await;
3202        Mock::given(method("GET"))
3203            .and(path("/orgs/acme/actions/runners"))
3204            .respond_with(ResponseTemplate::new(401))
3205            .mount(&server)
3206            .await;
3207        Mock::given(method("GET"))
3208            .and(path("/user/installations"))
3209            .respond_with(
3210                ResponseTemplate::new(200)
3211                    .set_body_json(installations_body(&[]))
3212                    .set_delay(Duration::from_millis(250)),
3213            )
3214            .expect(1)
3215            .mount(&server)
3216            .await;
3217
3218        let client = Arc::new(client(&server, Arc::new(TestClock::default())));
3219        let barrier = Arc::new(tokio::sync::Barrier::new(CALLERS));
3220        let mut tasks = Vec::new();
3221        for _ in 0..CALLERS {
3222            let client = Arc::clone(&client);
3223            let barrier = Arc::clone(&barrier);
3224            tasks.push(tokio::spawn(async move {
3225                barrier.wait().await;
3226                client
3227                    .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3228                    .await
3229                    .expect_err("every caller sees a dead endpoint")
3230            }));
3231        }
3232
3233        let mut outcomes = Vec::new();
3234        for task in tasks {
3235            outcomes.push(task.await.expect("no caller panicked"));
3236        }
3237
3238        assert_eq!(outcomes.len(), CALLERS);
3239        for err in &outcomes {
3240            assert!(matches!(err, GithubError::AuthenticationFailed), "{err:?}");
3241        }
3242        assert_eq!(
3243            client.revalidations_performed(),
3244            1,
3245            "{CALLERS} concurrent 401s must produce ONE attempt, not {CALLERS}"
3246        );
3247
3248        // The same claim, measured from the server rather than from our own
3249        // counter: the mock's `.expect(1)` is verified when the server drops.
3250        let seen = server.received_requests().await.expect("recording is on");
3251        let probes = seen
3252            .iter()
3253            .filter(|r| r.url.path() == "/user/installations")
3254            .count();
3255        assert_eq!(probes, 1, "GitHub itself saw exactly one re-validation");
3256        let attempts = seen
3257            .iter()
3258            .filter(|r| r.url.path() == "/orgs/acme/actions/runners")
3259            .count();
3260        assert_eq!(
3261            attempts,
3262            CALLERS * 2,
3263            "each caller still gets its own single retry"
3264        );
3265    }
3266
3267    // -- the 403 path -------------------------------------------------------
3268
3269    #[tokio::test]
3270    async fn a_403_after_401s_is_a_lockout_and_not_an_authentication_failure() {
3271        let server = MockServer::start().await;
3272        Mock::given(method("GET"))
3273            .and(path("/orgs/acme/actions/runners"))
3274            .respond_with(Script::new(vec![
3275                ResponseTemplate::new(401),
3276                ResponseTemplate::new(403).insert_header("retry-after", "42"),
3277            ]))
3278            .mount(&server)
3279            .await;
3280        Mock::given(method("GET"))
3281            .and(path("/user/installations"))
3282            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3283            .mount(&server)
3284            .await;
3285
3286        let client = client(&server, Arc::new(TestClock::default()));
3287        let err = client
3288            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3289            .await
3290            .expect_err("403 after a 401");
3291
3292        match err {
3293            GithubError::AuthenticationLockout { retry_after } => {
3294                assert_eq!(retry_after, Duration::from_secs(42), "honours retry-after");
3295            }
3296            other => panic!("expected a lockout, got {other:?}"),
3297        }
3298        assert!(client.is_locked_out());
3299    }
3300
3301    #[tokio::test]
3302    async fn a_403_with_no_preceding_401_is_a_permissions_answer_not_a_lockout() {
3303        let server = MockServer::start().await;
3304        Mock::given(method("GET"))
3305            .and(path("/orgs/acme/actions/runners"))
3306            .respond_with(
3307                ResponseTemplate::new(403)
3308                    .set_body_json(json!({"message": "Resource not accessible by integration"})),
3309            )
3310            .mount(&server)
3311            .await;
3312
3313        let client = client(&server, Arc::new(TestClock::default()));
3314        let err = client
3315            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3316            .await
3317            .expect_err("403");
3318
3319        assert!(matches!(err, GithubError::Forbidden { .. }), "{err:?}");
3320        assert!(!err.is_lockout());
3321        assert!(!err.is_authentication());
3322        assert!(!client.is_locked_out(), "a permissions 403 must not latch");
3323    }
3324
3325    #[tokio::test]
3326    async fn a_locked_out_client_issues_no_further_http_until_the_backoff_elapses() {
3327        let server = MockServer::start().await;
3328        Mock::given(method("GET"))
3329            .and(path("/orgs/acme/actions/runners"))
3330            .respond_with(Script::new(vec![
3331                ResponseTemplate::new(401),
3332                ResponseTemplate::new(403).insert_header("retry-after", "60"),
3333                ResponseTemplate::new(200).set_body_json(json!({"total_count": 0})),
3334            ]))
3335            .mount(&server)
3336            .await;
3337        Mock::given(method("GET"))
3338            .and(path("/user/installations"))
3339            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3340            .mount(&server)
3341            .await;
3342
3343        let clock = Arc::new(TestClock::default());
3344        let client = client(&server, Arc::clone(&clock));
3345        let request = ApiRequest::get("/orgs/acme/actions/runners");
3346
3347        let err = client.send(&request).await.expect_err("locks out");
3348        assert!(err.is_lockout(), "{err:?}");
3349
3350        let after_lockout = server.received_requests().await.unwrap().len();
3351
3352        for _ in 0..3 {
3353            let err = client.send(&request).await.expect_err("still locked out");
3354            assert!(err.is_lockout(), "{err:?}");
3355        }
3356        assert_eq!(
3357            server.received_requests().await.unwrap().len(),
3358            after_lockout,
3359            "a backed-off client must open no sockets at all"
3360        );
3361
3362        clock.advance_secs(61);
3363        assert!(!client.is_locked_out(), "the back-off expires on the clock");
3364        let response = client.send(&request).await.expect("traffic resumes");
3365        assert_eq!(response.status(), StatusCode::OK);
3366        assert_eq!(
3367            server.received_requests().await.unwrap().len(),
3368            after_lockout + 1
3369        );
3370    }
3371
3372    /// `consecutive_unauthorized` is reset only by a successful *caller*
3373    /// response, so a request ending in `404`, `422` or `5xx` leaves it set —
3374    /// and in the agent's long-lived reconciliation loop it stays set for as
3375    /// long as nothing succeeds. Before the fix, the next genuine permissions
3376    /// `403` was therefore reported as `AuthenticationLockout`: sixty seconds of
3377    /// client silence, plus an operator message asserting "the credential itself
3378    /// is not the problem" about a credential that was missing
3379    /// `Administration: write` — the failure `04-subsystem-contracts.md` names
3380    /// as the *expected* one for `generate-jitconfig`.
3381    ///
3382    /// The lockout's real signature is narrower: a `403` on the one retry this
3383    /// client issues after this request's own `401`, or a `403` whose own
3384    /// headers and body say GitHub is continuing a lockout. Neither is "the
3385    /// count is non-zero", which is what a stale `401` leaves behind — so the
3386    /// permissions `403` below is a permissions answer whatever happened minutes
3387    /// ago, and it is the *response*, not the history, that decides.
3388    #[tokio::test]
3389    async fn a_stale_401_does_not_turn_a_later_permissions_403_into_a_lockout() {
3390        let server = MockServer::start().await;
3391        // The first request ends in a 404, which leaves the 401 count set
3392        // because only a 2xx clears it.
3393        Mock::given(method("GET"))
3394            .and(path("/orgs/acme/actions/runners"))
3395            .respond_with(Script::new(vec![
3396                ResponseTemplate::new(401),
3397                ResponseTemplate::new(404).set_body_json(json!({"message": "Not Found"})),
3398            ]))
3399            .mount(&server)
3400            .await;
3401        Mock::given(method("GET"))
3402            .and(path("/user/installations"))
3403            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3404            .mount(&server)
3405            .await;
3406        // Minutes later, a different call is denied for a missing permission.
3407        Mock::given(method("POST"))
3408            .and(path("/orgs/acme/actions/runners/generate-jitconfig"))
3409            .respond_with(
3410                ResponseTemplate::new(403)
3411                    .set_body_json(json!({"message": "Resource not accessible by integration"})),
3412            )
3413            .mount(&server)
3414            .await;
3415
3416        let client = client(&server, Arc::new(TestClock::default()));
3417        let err = client
3418            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3419            .await
3420            .expect_err("404");
3421        assert!(
3422            matches!(err, GithubError::Status { status: 404, .. }),
3423            "{err:?}"
3424        );
3425
3426        let err = client
3427            .send(&ApiRequest::new(
3428                Method::POST,
3429                "/orgs/acme/actions/runners/generate-jitconfig",
3430            ))
3431            .await
3432            .expect_err("403");
3433
3434        assert!(
3435            matches!(err, GithubError::Forbidden { .. }),
3436            "a fresh first-attempt 403 is a permissions answer, not a lockout: {err:?}"
3437        );
3438        assert!(!err.is_lockout());
3439        assert!(
3440            !client.is_locked_out(),
3441            "a stale 401 must not be able to silence the client for a minute"
3442        );
3443    }
3444
3445    /// GitHub's own rate limit is not an answer about the credential, and must
3446    /// not be reported as one. `classify` reached the `403` branch before
3447    /// anything looked at the rate-limit headers, so a primary rate limit
3448    /// arriving during a `401` storm was announced as an authentication lockout
3449    /// with the message "the credential itself is not the problem" — about a
3450    /// response that never mentioned the credential.
3451    #[tokio::test]
3452    async fn a_rate_limited_403_is_not_reported_as_an_authentication_lockout() {
3453        let server = MockServer::start().await;
3454        Mock::given(method("GET"))
3455            .and(path("/orgs/acme/actions/runners"))
3456            .respond_with(Script::new(vec![
3457                ResponseTemplate::new(401),
3458                ResponseTemplate::new(403)
3459                    .insert_header("x-ratelimit-remaining", "0")
3460                    .insert_header("x-ratelimit-reset", "1787270460")
3461                    .insert_header("retry-after", "30")
3462                    .set_body_json(json!({"message": "API rate limit exceeded"})),
3463            ]))
3464            .mount(&server)
3465            .await;
3466        Mock::given(method("GET"))
3467            .and(path("/user/installations"))
3468            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3469            .mount(&server)
3470            .await;
3471
3472        let client = client(&server, Arc::new(TestClock::default()));
3473        let err = client
3474            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3475            .await
3476            .expect_err("rate limited");
3477
3478        assert!(
3479            matches!(err, GithubError::Forbidden { .. }),
3480            "a rate limit is not an authentication outcome: {err:?}"
3481        );
3482        assert!(!err.is_lockout());
3483        assert!(!err.is_authentication());
3484        assert!(
3485            !client.is_locked_out(),
3486            "a rate limit must not latch this crate's authentication back-off"
3487        );
3488
3489        // And `c3` gets the evidence it needs to apply the policy that is its
3490        // own, without editing this file.
3491        let evidence = err
3492            .rate_limit()
3493            .expect("the headers survived classification");
3494        assert_eq!(evidence.remaining, Some(0));
3495        assert_eq!(evidence.reset_unix_secs, Some(1_787_270_460));
3496        assert_eq!(evidence.retry_after, Some(Duration::from_secs(30)));
3497    }
3498
3499    /// The same claim for the variant `429` lands in.
3500    #[tokio::test]
3501    async fn a_429_carries_its_retry_after_across_the_c2_c3_seam() {
3502        let server = MockServer::start().await;
3503        Mock::given(method("GET"))
3504            .and(path("/orgs/acme/actions/runners"))
3505            .respond_with(
3506                ResponseTemplate::new(429)
3507                    .insert_header("retry-after", "17")
3508                    .insert_header("x-ratelimit-remaining", "0")
3509                    .set_body_json(json!({"message": "You have exceeded a secondary rate limit"})),
3510            )
3511            .mount(&server)
3512            .await;
3513
3514        let client = client(&server, Arc::new(TestClock::default()));
3515        let err = client
3516            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3517            .await
3518            .expect_err("429");
3519
3520        assert!(
3521            matches!(err, GithubError::Status { status: 429, .. }),
3522            "{err:?}"
3523        );
3524        assert_eq!(
3525            err.retry_after(),
3526            Some(Duration::from_secs(17)),
3527            "destroying this header is what made `c3`'s Definition of Done unmeetable"
3528        );
3529        assert_eq!(
3530            err.headers().and_then(|h| h.get("x-ratelimit-remaining")),
3531            Some(&reqwest::header::HeaderValue::from_static("0"))
3532        );
3533    }
3534
3535    /// A back-off is a safety mechanism, and this one had both failure modes at
3536    /// once: no ceiling, so `Retry-After: 86400` latched a silent twenty-four
3537    /// hour outage; and `TimeDelta::from_std(...).ok()` on a value too large to
3538    /// convert, which yielded `until = None` — *not locked out at all*, the
3539    /// exact inverse of the requirement, reachable by a header alone.
3540    #[tokio::test]
3541    async fn an_extreme_retry_after_is_clamped_and_never_fails_open() {
3542        async fn lockout_for(header: &str) -> (GithubError, bool, Option<Duration>) {
3543            let server = MockServer::start().await;
3544            Mock::given(method("GET"))
3545                .and(path("/orgs/acme/actions/runners"))
3546                .respond_with(Script::new(vec![
3547                    ResponseTemplate::new(401),
3548                    ResponseTemplate::new(403).insert_header("retry-after", header),
3549                ]))
3550                .mount(&server)
3551                .await;
3552            Mock::given(method("GET"))
3553                .and(path("/user/installations"))
3554                .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3555                .mount(&server)
3556                .await;
3557
3558            let client = AuthenticatedClient::new(
3559                Endpoints::for_test_server(&server.uri()).unwrap(),
3560                UserAccessToken::new(SecretString::from(FIXTURE_TOKEN)),
3561                Arc::new(TestClock::default()),
3562            )
3563            .unwrap();
3564            let err = client
3565                .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3566                .await
3567                .expect_err("403 after a 401");
3568            let locked = client.is_locked_out();
3569            let remaining = client.lockout_remaining();
3570            (err, locked, remaining)
3571        }
3572
3573        // A day-long back-off is clamped to the ceiling.
3574        let (err, locked, remaining) = lockout_for("86400").await;
3575        let GithubError::AuthenticationLockout { retry_after } = &err else {
3576            panic!("expected a lockout, got {err:?}");
3577        };
3578        assert_eq!(
3579            *retry_after, MAX_LOCKOUT_BACKOFF,
3580            "an unclamped Retry-After lets a remote party decide how long this product \
3581             stays down"
3582        );
3583        assert!(locked);
3584        assert!(remaining.is_some_and(|r| r <= MAX_LOCKOUT_BACKOFF));
3585
3586        // A value too large for `chrono` must still lock out. Before the fix
3587        // this produced `until = None`: the more extreme the header, the less
3588        // protection it bought.
3589        let (err, locked, remaining) = lockout_for(&u64::MAX.to_string()).await;
3590        assert!(err.is_lockout(), "{err:?}");
3591        assert!(
3592            locked,
3593            "an absurd Retry-After must not mean `not locked out at all` — that fails open"
3594        );
3595        assert!(remaining.is_some_and(|r| r <= MAX_LOCKOUT_BACKOFF));
3596    }
3597
3598    /// The lockout's own contract is "this client issues no HTTP at all", and
3599    /// `revalidate` is HTTP. It documented an `AuthenticationLockout` it could
3600    /// never return, which made the one direct entry point into the probe the
3601    /// single exception to the rule.
3602    #[tokio::test]
3603    async fn a_direct_revalidation_is_refused_while_the_lockout_is_backing_off() {
3604        let server = MockServer::start().await;
3605        Mock::given(method("GET"))
3606            .and(path("/orgs/acme/actions/runners"))
3607            .respond_with(Script::new(vec![
3608                ResponseTemplate::new(401),
3609                ResponseTemplate::new(403).insert_header("retry-after", "60"),
3610            ]))
3611            .mount(&server)
3612            .await;
3613        Mock::given(method("GET"))
3614            .and(path("/user/installations"))
3615            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3616            .mount(&server)
3617            .await;
3618
3619        let client = client(&server, Arc::new(TestClock::default()));
3620        client
3621            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3622            .await
3623            .expect_err("locks out");
3624        assert!(client.is_locked_out());
3625
3626        let before = server.received_requests().await.unwrap().len();
3627        let err = client
3628            .revalidate()
3629            .await
3630            .expect_err("the documented lockout error is now reachable");
3631        assert!(err.is_lockout(), "{err:?}");
3632        assert_eq!(
3633            server.received_requests().await.unwrap().len(),
3634            before,
3635            "a locked-out client opens no socket, and the probe is not an exception"
3636        );
3637    }
3638
3639    /// The position rule fixed `classify` and left the same defect one function
3640    /// over, behind a comment asserting it could not happen: "the probe only
3641    /// ever runs after a `401`, so it is always in the retry position". Making
3642    /// [`AuthenticatedClient::revalidate`] public — the previous round's own
3643    /// change — is exactly what made that untrue.
3644    ///
3645    /// The sequence is the agent's, not a contrivance. A request 401s, the probe
3646    /// says the credential is fine, the retry answers `404` — which does *not*
3647    /// reset the counter, by design. Minutes later `f1` renders `auth status`,
3648    /// which probes directly, and the probe meets an ordinary permissions `403`.
3649    /// A stale `401` then latched a sixty-second client-wide lockout and told
3650    /// the operator to wait, when the real answer was a missing grant.
3651    #[tokio::test]
3652    async fn a_directly_requested_probe_does_not_latch_a_lockout_from_a_stale_401() {
3653        let server = MockServer::start().await;
3654        Mock::given(method("GET"))
3655            .and(path("/orgs/acme/actions/runners"))
3656            .respond_with(Script::new(vec![
3657                ResponseTemplate::new(401),
3658                // The retry misses. A `404` leaves `consecutive_unauthorized`
3659                // set, which is the whole premise of the position rule.
3660                ResponseTemplate::new(404).set_body_json(json!({"message": "Not Found"})),
3661            ]))
3662            .mount(&server)
3663            .await;
3664        Mock::given(method("GET"))
3665            .and(path("/user/installations"))
3666            .respond_with(Script::new(vec![
3667                // The probe that accompanies the 401 above.
3668                ResponseTemplate::new(200).set_body_json(installations_body(&[])),
3669                // The direct probe, minutes later: a plain permissions answer,
3670                // with no `retry-after` and a message that names a grant.
3671                ResponseTemplate::new(403)
3672                    .set_body_json(json!({"message": "Resource not accessible by integration"})),
3673            ]))
3674            .mount(&server)
3675            .await;
3676
3677        let clock = Arc::new(TestClock::default());
3678        let client = client(&server, clock.clone());
3679        client
3680            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3681            .await
3682            .expect_err("the retry 404s");
3683        assert!(
3684            !client.is_locked_out(),
3685            "a 404 on the retry is not a lockout"
3686        );
3687
3688        clock.advance_secs(300);
3689        let outcome = client
3690            .revalidate()
3691            .await
3692            .expect("a direct probe is not a lockout error");
3693
3694        assert_eq!(
3695            outcome,
3696            Revalidation::Unavailable,
3697            "a 403 on the probe teaches this client nothing about the credential"
3698        );
3699        assert!(
3700            !client.is_locked_out(),
3701            "a caller-initiated probe is a *first* attempt, not the retry that follows a 401: \
3702             latching here converts a stale 401 into a 60-second client-wide outage and \
3703             reports a missing permission as `the credential is fine, please wait`"
3704        );
3705        assert_eq!(client.lockout_remaining(), None);
3706    }
3707
3708    /// The square the other three leave empty, and the one where a defect in the
3709    /// composition would hide.
3710    ///
3711    /// Covered elsewhere: a first-attempt continuation through `send`, a
3712    /// first-attempt permissions `403` through `send`, and a direct probe
3713    /// meeting a permissions `403` (immediately above). A direct probe meeting a
3714    /// *continuation-shaped* `403` is the fourth square, and it is the
3715    /// composition point of the two rules that pull in opposite directions —
3716    /// the narrowing to `Attempt::First` that fixed the stale-`401` lockout, and
3717    /// the continuation rule that re-widens `First` on GitHub's own evidence.
3718    ///
3719    /// If the narrowing swallowed the continuation here, every other test in
3720    /// this file would still pass, and `f1`'s `auth status` would poll a
3721    /// credential GitHub had asked it to leave alone — reporting each refusal as
3722    /// a missing grant.
3723    #[tokio::test]
3724    async fn a_directly_requested_probe_latches_a_continuation_shaped_lockout() {
3725        let server = MockServer::start().await;
3726        Mock::given(method("GET"))
3727            .and(path("/user/installations"))
3728            // The continuation's signature: `retry-after`, and a body with no
3729            // message for `error_message` to find.
3730            .respond_with(ResponseTemplate::new(403).insert_header("retry-after", "60"))
3731            .mount(&server)
3732            .await;
3733
3734        let client = client(&server, Arc::new(TestClock::default()));
3735
3736        // No preceding traffic whatsoever: a first attempt in the strongest
3737        // sense, which is exactly the position the narrowed rule refused to
3738        // latch in.
3739        let err = client
3740            .revalidate()
3741            .await
3742            .expect_err("a probe that latches a lockout reports it rather than `Unavailable`");
3743        assert!(
3744            err.is_lockout(),
3745            "`revalidate` latched a client-wide lockout and must say so; answering \
3746             `Ok(Unavailable)` leaves `f1` to discover a 15-minute outage through a separate \
3747             `is_locked_out()` call it has no reason to make: {err:?}"
3748        );
3749        assert!(
3750            client.is_locked_out(),
3751            "a 403 carrying `retry-after` with no message is GitHub continuing a lockout, \
3752             whoever asked for the request that met it"
3753        );
3754        assert_eq!(client.lockout_remaining(), Some(Duration::from_secs(60)));
3755
3756        // And the back-off is real, not just a renamed error.
3757        let before = server.received_requests().await.unwrap().len();
3758        let err = client.revalidate().await.expect_err("still locked out");
3759        assert!(err.is_lockout(), "{err:?}");
3760        assert_eq!(
3761            server.received_requests().await.unwrap().len(),
3762            before,
3763            "latching must actually stop traffic"
3764        );
3765    }
3766
3767    /// [`retry_after`] parses integer seconds only; RFC 9110 §10.2.3 also
3768    /// permits an HTTP-date. Detection used to gate on that parse succeeding, so
3769    /// a date-form `Retry-After` was not recognised as a continuation at all and
3770    /// the hole the continuation rule exists to close reopened for that shape —
3771    /// silently, because the response leaves as an ordinary `Forbidden`.
3772    ///
3773    /// GitHub sends integer seconds in practice. This pins the crate to not
3774    /// depending on that, and records where the two halves part company:
3775    /// presence decides *whether* it is a lockout, the integer parse decides
3776    /// only *how long*, and `latch_lockout` already had a default for the header
3777    /// it could not read.
3778    #[tokio::test]
3779    async fn a_date_form_retry_after_is_still_recognised_as_a_continuation() {
3780        let server = MockServer::start().await;
3781        Mock::given(method("GET"))
3782            .and(path("/user/installations"))
3783            .respond_with(
3784                ResponseTemplate::new(403)
3785                    .insert_header("retry-after", "Wed, 21 Oct 2026 07:28:00 GMT"),
3786            )
3787            .mount(&server)
3788            .await;
3789
3790        let client = client(&server, Arc::new(TestClock::default()));
3791        let err = client
3792            .revalidate()
3793            .await
3794            .expect_err("a date-form `retry-after` is still GitHub asking to be left alone");
3795        assert!(
3796            err.is_lockout(),
3797            "gating detection on an integer parse hands the continuation bug back for every \
3798             lockout GitHub chose to date-stamp: {err:?}"
3799        );
3800        assert_eq!(
3801            client.lockout_remaining(),
3802            Some(DEFAULT_LOCKOUT_BACKOFF),
3803            "the date form is recognised for detection; the duration falls back to the \
3804             default, which is what `latch_lockout` already did with a header it could not \
3805             parse as seconds"
3806        );
3807    }
3808
3809    /// The narrowing that fixed the stale-`401` lockout opened a hole at the
3810    /// other end of the same back-off.
3811    ///
3812    /// While GitHub is still locking the credential out after the back-off
3813    /// elapses, the next request is a *first* attempt by construction — this
3814    /// client's own retry never happened, because the request never reached the
3815    /// wire. So the position rule declined to call it a lockout and `classify`
3816    /// fell through to [`GithubError::Forbidden`], whose documented reading is
3817    /// "the App installation does not grant it". The client then stopped backing
3818    /// off entirely and hammered a credential GitHub had asked it to leave
3819    /// alone, which is the exact inverse of "backs off without retrying".
3820    ///
3821    /// A continuation is distinguishable from a permissions answer without any
3822    /// counter: GitHub sends `retry-after` and no message body for the lockout,
3823    /// and a message and no `retry-after` for a permissions refusal.
3824    #[tokio::test]
3825    async fn a_lockout_outliving_its_backoff_re_latches_instead_of_reporting_a_permissions_answer()
3826    {
3827        let server = MockServer::start().await;
3828        Mock::given(method("GET"))
3829            .and(path("/orgs/acme/actions/runners"))
3830            .respond_with(Script::new(vec![
3831                ResponseTemplate::new(401),
3832                // The retry: the lockout latches here, in the retry position.
3833                ResponseTemplate::new(403).insert_header("retry-after", "60"),
3834                // The continuation, once the back-off has elapsed. Same shape,
3835                // first position.
3836                ResponseTemplate::new(403).insert_header("retry-after", "60"),
3837            ]))
3838            .mount(&server)
3839            .await;
3840        Mock::given(method("GET"))
3841            .and(path("/user/installations"))
3842            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3843            .mount(&server)
3844            .await;
3845
3846        let clock = Arc::new(TestClock::default());
3847        let client = client(&server, clock.clone());
3848        let err = client
3849            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3850            .await
3851            .expect_err("403 on the retry");
3852        assert!(err.is_lockout(), "{err:?}");
3853        assert!(client.is_locked_out());
3854
3855        // The back-off elapses with GitHub unchanged.
3856        clock.advance_secs(61);
3857        assert!(!client.is_locked_out(), "the back-off has run out");
3858
3859        let err = client
3860            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3861            .await
3862            .expect_err("GitHub is still locking the credential out");
3863
3864        assert!(
3865            err.is_lockout(),
3866            "a 403 carrying `retry-after` with no message is GitHub continuing the lockout, \
3867             not the App installation refusing a permission; reporting `Forbidden` here \
3868             tells the operator to fix a grant that is not missing: {err:?}"
3869        );
3870        assert!(
3871            client.is_locked_out(),
3872            "`backs off without retrying` fails for any lockout that outlives one back-off \
3873             if the continuation does not re-latch"
3874        );
3875        let GithubError::AuthenticationLockout { retry_after } = err else {
3876            unreachable!("asserted above")
3877        };
3878        assert_eq!(
3879            retry_after,
3880            Duration::from_secs(60),
3881            "the continuation's own `retry-after` sets the new back-off"
3882        );
3883
3884        // And the next request is suppressed before a socket is opened, which is
3885        // the property the whole back-off exists for.
3886        let before = server.received_requests().await.unwrap().len();
3887        let err = client
3888            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3889            .await
3890            .expect_err("still locked out");
3891        assert!(err.is_lockout(), "{err:?}");
3892        assert_eq!(
3893            server.received_requests().await.unwrap().len(),
3894            before,
3895            "re-latching must actually stop traffic, not merely rename the error"
3896        );
3897    }
3898
3899    /// A permissions `403` on a first attempt is still a permissions answer, and
3900    /// the continuation rule above must not swallow it. This is the test that
3901    /// keeps that rule from becoming "every 403 is a lockout".
3902    #[tokio::test]
3903    async fn a_first_attempt_permissions_403_is_still_reported_as_forbidden() {
3904        let server = MockServer::start().await;
3905        Mock::given(method("GET"))
3906            .and(path("/orgs/acme/actions/runners"))
3907            .respond_with(
3908                ResponseTemplate::new(403)
3909                    .set_body_json(json!({"message": "Resource not accessible by integration"})),
3910            )
3911            .mount(&server)
3912            .await;
3913
3914        let client = client(&server, Arc::new(TestClock::default()));
3915        let err = client
3916            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3917            .await
3918            .expect_err("403");
3919
3920        assert!(
3921            matches!(err, GithubError::Forbidden { .. }),
3922            "a message and no `retry-after` is GitHub naming a missing grant: {err:?}"
3923        );
3924        assert!(!client.is_locked_out());
3925    }
3926
3927    /// The `consecutive_unauthorized > 0` conjunct that used to sit alongside
3928    /// the position rule added no signal — `Attempt::Retry` already implies this
3929    /// request's own `401` incremented the counter — and added a fail-open race:
3930    /// any concurrent success `store(0)`s the counter between the `401` and the
3931    /// retry, and a real lockout is then reported as a permissions answer.
3932    ///
3933    /// The race is driven directly rather than by scheduling two requests and
3934    /// hoping: `store(0)` is the *only* thing the concurrent success contributes,
3935    /// so performing it between the `401` and the classification reproduces the
3936    /// race deterministically and on every run.
3937    #[tokio::test]
3938    async fn a_concurrent_success_cannot_downgrade_a_lockout_to_a_permissions_answer() {
3939        let server = MockServer::start().await;
3940        let client = client(&server, Arc::new(TestClock::default()));
3941
3942        // This request's own 401 has landed: the retry position is established.
3943        client
3944            .consecutive_unauthorized
3945            .fetch_add(1, Ordering::SeqCst);
3946        // ... and a request on another task succeeds in the same instant.
3947        client.consecutive_unauthorized.store(0, Ordering::SeqCst);
3948
3949        let mut headers = HeaderMap::new();
3950        headers.insert("retry-after", "60".parse().unwrap());
3951        let lockout = ApiResponse {
3952            status: StatusCode::FORBIDDEN,
3953            headers,
3954            body: Vec::new(),
3955        };
3956
3957        assert!(
3958            client.is_lockout_403(&lockout, Attempt::Retry),
3959            "`Attempt::Retry` already means this request's own 401 incremented the counter, so \
3960             reading the counter again adds no signal and only lets an unrelated success \
3961             downgrade a real lockout to `Forbidden`"
3962        );
3963
3964        // The counter must stay irrelevant in the other direction too: a
3965        // permissions `403` on a first attempt is not a lockout however many
3966        // `401`s are on the count.
3967        client.consecutive_unauthorized.store(7, Ordering::SeqCst);
3968        let permissions = ApiResponse {
3969            status: StatusCode::FORBIDDEN,
3970            headers: HeaderMap::new(),
3971            body: br#"{"message":"Resource not accessible by integration"}"#.to_vec(),
3972        };
3973        assert!(!client.is_lockout_403(&permissions, Attempt::First));
3974    }
3975
3976    // -- installation discovery ---------------------------------------------
3977
3978    #[tokio::test]
3979    async fn discovery_returns_the_reachable_repository_and_organization_set() {
3980        let server = MockServer::start().await;
3981        Mock::given(method("GET"))
3982            .and(path("/user/installations"))
3983            .respond_with(
3984                ResponseTemplate::new(200).set_body_json(installations_body(&[
3985                    (11, "IvanMurzak", "User", "selected"),
3986                    (22, "Tap-Top-Fun", "Organization", "all"),
3987                ])),
3988            )
3989            .mount(&server)
3990            .await;
3991        Mock::given(method("GET"))
3992            .and(path("/user/installations/11/repositories"))
3993            .respond_with(
3994                ResponseTemplate::new(200)
3995                    .set_body_json(repositories_body(&["IvanMurzak/GitHub-Runner-Scaler-UI"])),
3996            )
3997            .mount(&server)
3998            .await;
3999        Mock::given(method("GET"))
4000            .and(path("/user/installations/22/repositories"))
4001            .respond_with(
4002                ResponseTemplate::new(200)
4003                    .set_body_json(repositories_body(&["Tap-Top-Fun/game", "Tap-Top-Fun/site"])),
4004            )
4005            .mount(&server)
4006            .await;
4007
4008        let client = client(&server, Arc::new(TestClock::default()));
4009        let discovery = client.discover_installations(&app()).await.unwrap();
4010
4011        let targets = discovery.targets().expect("installed");
4012        assert_eq!(
4013            targets
4014                .repositories()
4015                .iter()
4016                .map(ToString::to_string)
4017                .collect::<Vec<_>>(),
4018            [
4019                "IvanMurzak/GitHub-Runner-Scaler-UI",
4020                "Tap-Top-Fun/game",
4021                "Tap-Top-Fun/site"
4022            ]
4023        );
4024        assert_eq!(
4025            targets
4026                .organizations()
4027                .iter()
4028                .map(ToString::to_string)
4029                .collect::<Vec<_>>(),
4030            ["Tap-Top-Fun"],
4031            "a User account is not an organization target"
4032        );
4033        assert!(discovery.install_url().is_none());
4034    }
4035
4036    #[tokio::test]
4037    async fn an_over_broad_installation_is_visible_rather_than_assumed() {
4038        let server = MockServer::start().await;
4039        Mock::given(method("GET"))
4040            .and(path("/user/installations"))
4041            .respond_with(
4042                ResponseTemplate::new(200).set_body_json(installations_body(&[
4043                    (11, "IvanMurzak", "User", "selected"),
4044                    (22, "Tap-Top-Fun", "Organization", "all"),
4045                ])),
4046            )
4047            .mount(&server)
4048            .await;
4049        Mock::given(method("GET"))
4050            .and(path("/user/installations/11/repositories"))
4051            .respond_with(ResponseTemplate::new(200).set_body_json(repositories_body(&["a/b"])))
4052            .mount(&server)
4053            .await;
4054        Mock::given(method("GET"))
4055            .and(path("/user/installations/22/repositories"))
4056            .respond_with(ResponseTemplate::new(200).set_body_json(repositories_body(&["c/d"])))
4057            .mount(&server)
4058            .await;
4059
4060        let client = client(&server, Arc::new(TestClock::default()));
4061        let targets = client
4062            .discover_installations(&app())
4063            .await
4064            .unwrap()
4065            .targets()
4066            .cloned()
4067            .expect("installed");
4068
4069        let over_broad = targets.over_broad();
4070        assert_eq!(over_broad.len(), 1);
4071        assert_eq!(over_broad[0].account.login(), "Tap-Top-Fun");
4072        assert!(over_broad[0].is_over_broad());
4073        assert_eq!(
4074            over_broad[0].repository_selection,
4075            RepositorySelection::All,
4076            "`repository_selection: all` reaches repositories created later too"
4077        );
4078        assert!(
4079            targets.installations().iter().any(|i| i
4080                .permissions
4081                .iter()
4082                .any(|(k, v)| k == "administration" && v == "write")),
4083            "the grant GitHub reports is surfaced verbatim, not assumed from the design"
4084        );
4085    }
4086
4087    #[tokio::test]
4088    async fn discovery_returns_the_installation_url_when_the_set_is_empty() {
4089        let server = MockServer::start().await;
4090        Mock::given(method("GET"))
4091            .and(path("/user/installations"))
4092            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
4093            .mount(&server)
4094            .await;
4095
4096        let client = client(&server, Arc::new(TestClock::default()));
4097        let discovery = client.discover_installations(&app()).await.unwrap();
4098
4099        let url = discovery
4100            .install_url()
4101            .expect("an empty set must yield the installation URL");
4102        assert_eq!(url.path(), "/apps/runner-manager/installations/new");
4103        assert!(discovery.targets().is_none());
4104    }
4105
4106    #[tokio::test]
4107    async fn an_installation_that_reaches_no_repository_is_still_not_installed() {
4108        let server = MockServer::start().await;
4109        Mock::given(method("GET"))
4110            .and(path("/user/installations"))
4111            .respond_with(
4112                ResponseTemplate::new(200).set_body_json(installations_body(&[(
4113                    11,
4114                    "IvanMurzak",
4115                    "User",
4116                    "selected",
4117                )])),
4118            )
4119            .mount(&server)
4120            .await;
4121        Mock::given(method("GET"))
4122            .and(path("/user/installations/11/repositories"))
4123            .respond_with(ResponseTemplate::new(200).set_body_json(repositories_body(&[])))
4124            .mount(&server)
4125            .await;
4126
4127        let client = client(&server, Arc::new(TestClock::default()));
4128        let discovery = client.discover_installations(&app()).await.unwrap();
4129        assert!(
4130            discovery.install_url().is_some(),
4131            "a user installation that selected no repository reaches nothing"
4132        );
4133    }
4134
4135    #[tokio::test]
4136    async fn discovery_follows_every_page_rather_than_trusting_the_first() {
4137        let server = MockServer::start().await;
4138        let next = format!("<{}/user/installations?page=2>; rel=\"next\"", server.uri());
4139        Mock::given(method("GET"))
4140            .and(path("/user/installations"))
4141            .respond_with(Script::new(vec![
4142                ResponseTemplate::new(200)
4143                    .set_body_json(installations_body(&[(
4144                        11,
4145                        "one",
4146                        "Organization",
4147                        "selected",
4148                    )]))
4149                    .insert_header("link", next.as_str()),
4150                ResponseTemplate::new(200).set_body_json(installations_body(&[(
4151                    22,
4152                    "two",
4153                    "Organization",
4154                    "selected",
4155                )])),
4156            ]))
4157            .mount(&server)
4158            .await;
4159        Mock::given(method("GET"))
4160            .and(path("/user/installations/11/repositories"))
4161            .respond_with(ResponseTemplate::new(200).set_body_json(repositories_body(&["one/a"])))
4162            .mount(&server)
4163            .await;
4164        Mock::given(method("GET"))
4165            .and(path("/user/installations/22/repositories"))
4166            .respond_with(ResponseTemplate::new(200).set_body_json(repositories_body(&["two/b"])))
4167            .mount(&server)
4168            .await;
4169
4170        let client = client(&server, Arc::new(TestClock::default()));
4171        let targets = client
4172            .discover_installations(&app())
4173            .await
4174            .unwrap()
4175            .targets()
4176            .cloned()
4177            .expect("installed");
4178        assert_eq!(
4179            targets
4180                .organizations()
4181                .iter()
4182                .map(ToString::to_string)
4183                .collect::<Vec<_>>(),
4184            ["one", "two"],
4185            "the second page must not be dropped"
4186        );
4187    }
4188
4189    /// GitHub's published `installation` schema types `account` as **nullable**,
4190    /// and as either a simple-user *or* an enterprise — which carries
4191    /// `slug`/`name` where a user carries `login`. A required `RawAccount` with
4192    /// a required `login` made either shape a hard `response.json()` failure,
4193    /// which takes down all of `discover_installations`, which is all of
4194    /// `auth status`. One unusual installation must not blind the command that
4195    /// exists to show the user what their credential can reach.
4196    #[tokio::test]
4197    async fn an_installation_with_a_null_or_enterprise_account_does_not_fail_the_whole_decode() {
4198        let server = MockServer::start().await;
4199        Mock::given(method("GET"))
4200            .and(path("/user/installations"))
4201            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
4202                "total_count": 3,
4203                "installations": [
4204                    // Nullable, per the published schema.
4205                    { "id": 10, "account": null, "repository_selection": "selected" },
4206                    // An enterprise: no `login` at all.
4207                    {
4208                        "id": 20,
4209                        "account": { "slug": "acme-enterprise", "name": "Acme Inc" },
4210                        "repository_selection": "selected"
4211                    },
4212                    // And an ordinary user alongside them.
4213                    {
4214                        "id": 30,
4215                        "account": { "login": "IvanMurzak", "type": "User" },
4216                        "repository_selection": "selected"
4217                    }
4218                ]
4219            })))
4220            .mount(&server)
4221            .await;
4222        for (id, repo) in [(20_u64, "acme-enterprise/tools"), (30, "IvanMurzak/app")] {
4223            Mock::given(method("GET"))
4224                .and(path(format!("/user/installations/{id}/repositories")))
4225                .respond_with(ResponseTemplate::new(200).set_body_json(repositories_body(&[repo])))
4226                .mount(&server)
4227                .await;
4228        }
4229
4230        let client = client(&server, Arc::new(TestClock::default()));
4231        let targets = client
4232            .discover_installations(&app())
4233            .await
4234            .expect("one odd account must not fail the whole discovery")
4235            .targets()
4236            .cloned()
4237            .expect("installed");
4238
4239        // Membership rather than order: what matters here is that neither
4240        // installation was lost, not how `OwnerRepo` collates.
4241        let reached = targets
4242            .repositories()
4243            .iter()
4244            .map(ToString::to_string)
4245            .collect::<Vec<_>>();
4246        assert!(
4247            reached.contains(&"acme-enterprise/tools".to_string()),
4248            "the enterprise installation is named from `slug` rather than dropped: {reached:?}"
4249        );
4250        assert!(
4251            reached.contains(&"IvanMurzak/app".to_string()),
4252            "the ordinary installation alongside it survives too: {reached:?}"
4253        );
4254        assert_eq!(reached.len(), 2);
4255        assert_eq!(
4256            targets.installations().len(),
4257            2,
4258            "the null account is skipped, and only it"
4259        );
4260        assert_eq!(
4261            targets.skipped(),
4262            1,
4263            "the skip is the right trade, but it must travel with the answer: everything the \
4264             skipped installation reaches is missing from the lists above, and a short list \
4265             reads exactly like a complete one"
4266        );
4267
4268        // The enterprise is labelled an enterprise. It used to fall through to
4269        // `User`, so `auth status` told the operator their enterprise was a
4270        // personal account.
4271        let enterprise = targets
4272            .installations()
4273            .iter()
4274            .find(|i| i.id == 20)
4275            .expect("the enterprise installation survived");
4276        assert_eq!(
4277            enterprise.account,
4278            InstallationAccount::Enterprise("acme-enterprise".to_string()),
4279            "an account with no `login` that names itself through `slug` is an enterprise, \
4280             and calling it a user is a wrong statement about the operator's own account"
4281        );
4282        assert_eq!(enterprise.account.kind(), "enterprise");
4283        assert!(
4284            enterprise.account.organization().is_none(),
4285            "an enterprise is not an organization target: `GET /orgs/{{org}}/actions/runners` \
4286             does not accept one, so contributing nothing to `organizations()` is correct"
4287        );
4288        assert!(
4289            !targets
4290                .organizations()
4291                .iter()
4292                .any(|o| o.as_str() == "acme-enterprise"),
4293            "and it must not be smuggled in as one either"
4294        );
4295    }
4296
4297    /// The skip is right; the verdict flip was not.
4298    ///
4299    /// A null-account installation that is the *only* installation used to
4300    /// collapse to `NotInstalled`, so `auth status` handed an operator who **is**
4301    /// installed the "install the App" URL — a wrong remediation on the only
4302    /// authentication path there is, contradicted by nothing but a `warn!`.
4303    #[tokio::test]
4304    async fn a_credential_whose_only_installation_was_skipped_is_not_reported_as_not_installed() {
4305        let server = MockServer::start().await;
4306        Mock::given(method("GET"))
4307            .and(path("/user/installations"))
4308            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
4309                "total_count": 1,
4310                "installations": [
4311                    { "id": 10, "account": null, "repository_selection": "selected" }
4312                ]
4313            })))
4314            .mount(&server)
4315            .await;
4316
4317        let client = client(&server, Arc::new(TestClock::default()));
4318        let discovery = client.discover_installations(&app()).await.unwrap();
4319
4320        assert_eq!(
4321            discovery,
4322            InstallationDiscovery::Indeterminate { skipped: 1 },
4323            "GitHub reported an installation; this client could not describe it. That is not \
4324             the same answer as `not installed`, and only one of the two is fixed by \
4325             installing the App"
4326        );
4327        assert_eq!(
4328            discovery.install_url(),
4329            None,
4330            "offering the install URL here is the wrong remediation, and putting it one field \
4331             over from the right verdict would just relocate the defect"
4332        );
4333        assert_eq!(discovery.skipped(), 1);
4334        assert!(discovery.targets().is_none());
4335    }
4336
4337    /// The other side of the same rule: with nothing skipped, an empty reach is
4338    /// still an empty reach, and the install URL is still the remediation.
4339    #[tokio::test]
4340    async fn an_empty_reach_with_nothing_skipped_is_still_not_installed() {
4341        let server = MockServer::start().await;
4342        Mock::given(method("GET"))
4343            .and(path("/user/installations"))
4344            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
4345            .mount(&server)
4346            .await;
4347
4348        let client = client(&server, Arc::new(TestClock::default()));
4349        let discovery = client.discover_installations(&app()).await.unwrap();
4350
4351        assert!(discovery.install_url().is_some(), "{discovery:?}");
4352        assert_eq!(discovery.skipped(), 0);
4353    }
4354
4355    /// A `Link: rel="next"` that points back at the page it arrived on is an
4356    /// infinite loop inside the agent's reconciliation loop — the one place in
4357    /// this product that must not be able to wedge. The ceiling is what makes
4358    /// this test terminate at all.
4359    #[tokio::test]
4360    async fn a_self_referential_link_header_stops_at_the_page_ceiling() {
4361        let server = MockServer::start().await;
4362        let self_link = format!("<{}/user/installations?page=2>; rel=\"next\"", server.uri());
4363        Mock::given(method("GET"))
4364            .and(path("/user/installations"))
4365            .respond_with(
4366                ResponseTemplate::new(200)
4367                    .set_body_json(installations_body(&[]))
4368                    .insert_header("link", self_link.as_str()),
4369            )
4370            .mount(&server)
4371            .await;
4372
4373        let client = client(&server, Arc::new(TestClock::default()));
4374        let discovery = client
4375            .discover_installations(&app())
4376            .await
4377            .expect("the ceiling is what makes this return at all");
4378
4379        assert!(
4380            discovery.install_url().is_some(),
4381            "no installation was found"
4382        );
4383        assert_eq!(
4384            server.received_requests().await.unwrap().len(),
4385            MAX_PAGES,
4386            "pagination must stop at the ceiling rather than follow the loop forever"
4387        );
4388    }
4389
4390    #[test]
4391    fn a_link_header_yields_only_the_next_relation() {
4392        let header = "<https://api.github.com/user/installations?page=3>; rel=\"next\", \
4393                      <https://api.github.com/user/installations?page=9>; rel=\"last\"";
4394        assert_eq!(
4395            parse_link_next(header).map(|u| u.to_string()),
4396            Some("https://api.github.com/user/installations?page=3".to_string())
4397        );
4398        assert!(parse_link_next("<https://x/>; rel=\"last\"").is_none());
4399        assert!(parse_link_next("nonsense").is_none());
4400    }
4401
4402    /// A comma is legal inside a URL and GitHub sends such URLs routinely — a
4403    /// runner query carries `labels=self-hosted,windows`. Splitting the header
4404    /// on `,` before recognising `<...>` tore that URL in half, found no
4405    /// relation, and stopped paginating at page 1 while reporting success. That
4406    /// is precisely what `04-subsystem-contracts.md` forbids ("the dashboard
4407    /// must not treat a first page as a complete inventory"), in the one shared
4408    /// reader `c3`'s inventory also goes through.
4409    #[test]
4410    fn a_next_url_containing_a_comma_still_paginates() {
4411        let header = "<https://api.github.com/repos/o/r/actions/runners\
4412                      ?labels=self-hosted,windows&page=2>; rel=\"next\"";
4413        assert_eq!(
4414            parse_link_next(header).map(|u| u.to_string()),
4415            Some(
4416                "https://api.github.com/repos/o/r/actions/runners\
4417                 ?labels=self-hosted,windows&page=2"
4418                    .to_string()
4419            ),
4420            "a comma inside the URL must not end the link-value"
4421        );
4422
4423        // The same URL as the second link-value, so the scan has to walk past a
4424        // comma-bearing target to reach the relation it wants.
4425        let header = "<https://api.github.com/x?a=1,2&page=1>; rel=\"prev\", \
4426                      <https://api.github.com/x?a=1,2&page=3>; rel=\"next\"";
4427        assert_eq!(
4428            parse_link_next(header).map(|u| u.to_string()),
4429            Some("https://api.github.com/x?a=1,2&page=3".to_string())
4430        );
4431    }
4432
4433    /// `rel="next"` is not always the first link-value, and both quoted and
4434    /// unquoted forms are legal.
4435    #[test]
4436    fn the_next_relation_is_found_wherever_it_sits_in_the_header() {
4437        let not_first = "<https://api.github.com/u?page=1>; rel=\"first\", \
4438                         <https://api.github.com/u?page=9>; rel=\"last\", \
4439                         <https://api.github.com/u?page=4>; rel=\"next\"";
4440        assert_eq!(
4441            parse_link_next(not_first).map(|u| u.to_string()),
4442            Some("https://api.github.com/u?page=4".to_string())
4443        );
4444
4445        let unquoted = "<https://api.github.com/u?page=1>; rel=prev, \
4446                        <https://api.github.com/u?page=3>; rel=next";
4447        assert_eq!(
4448            parse_link_next(unquoted).map(|u| u.to_string()),
4449            Some("https://api.github.com/u?page=3".to_string())
4450        );
4451
4452        assert!(
4453            parse_link_next("<https://api.github.com/u?page=2; rel=\"next\"").is_none(),
4454            "an unterminated target is not a link-value"
4455        );
4456    }
4457
4458    /// The free cross-check that would have caught the comma bug on its own.
4459    #[test]
4460    fn a_short_collection_is_measured_against_the_count_github_reported() {
4461        assert_eq!(under_collected(1, Some(2)), Some(2), "page 2 was dropped");
4462        assert_eq!(under_collected(2, Some(2)), None, "complete");
4463        assert_eq!(
4464            under_collected(3, Some(2)),
4465            None,
4466            "a collection that grew between pages is not an under-collection"
4467        );
4468        assert_eq!(under_collected(0, None), None, "no count, no claim");
4469    }
4470
4471    // -- redaction ----------------------------------------------------------
4472
4473    #[test]
4474    fn no_type_in_this_crate_renders_a_secret_through_debug() {
4475        let token = UserAccessToken::new(SecretString::from(FIXTURE_TOKEN));
4476        let rendered = format!("{token:?}");
4477        assert!(!rendered.contains(FIXTURE_TOKEN), "{rendered}");
4478        assert!(rendered.contains("[REDACTED]"));
4479        assert!(
4480            rendered.contains("ghu_"),
4481            "the family prefix is diagnostic and is not the secret"
4482        );
4483
4484        let request = ApiRequest::post_json("/x", &json!({"encoded_jit_config": "SECRETBLOB"}))
4485            .expect("serializes");
4486        let rendered = format!("{request:?}");
4487        assert!(!rendered.contains("SECRETBLOB"), "{rendered}");
4488
4489        let response = ApiResponse {
4490            status: StatusCode::OK,
4491            headers: HeaderMap::new(),
4492            body: b"{\"encoded_jit_config\":\"SECRETBLOB\"}".to_vec(),
4493        };
4494        let rendered = format!("{response:?}");
4495        assert!(!rendered.contains("SECRETBLOB"), "{rendered}");
4496    }
4497
4498    // The Definition of Done's log scan is `tests/no_secret_reaches_the_logs.rs`
4499    // and not a unit test here. See the note at the end of `mod testing` for the
4500    // `tracing` callsite-cache reason it cannot be one.
4501
4502    // -- the crate-shape scans ----------------------------------------------
4503    //
4504    // The three gates below share these helpers on purpose. The previous round
4505    // defined `normalise` twice — once in the scan and once in the meta-test
4506    // that checks it — which left the meta-test structurally unable to notice a
4507    // change to the real one. One definition, used by both, is the only shape
4508    // in which a meta-test proves anything.
4509
4510    /// Spelled in halves so that this file's own source does not trip the scan
4511    /// it runs: normalising `concat!("refresh", "token")` leaves the
4512    /// quote-comma-quote between the halves, so no needle ever appears whole.
4513    // The renewal guard that used to live here is gone, and its absence is the
4514    // point. It forbade this crate from naming a refresh token at all, on the
4515    // reasoning that the published App opts out of user-token expiration "so
4516    // GitHub issues nothing to renew". That reasoning rested on a second claim
4517    // -- that renewing needs a confidential client credential -- which GitHub's
4518    // own documentation contradicts for the device flow, and which was then
4519    // disproved against live GitHub: a refresh exchange with `client_id` alone
4520    // answers `200`.
4521    //
4522    // What the guard below still forbids is the part that was always true and
4523    // is the reason renewal is safe here: no confidential credential in this
4524    // crate. Renewal was added *without* one, so the remaining half of this
4525    // scan is now evidence for the design rather than against it.
4526    const CONFIDENTIAL: &[&str] = &[concat!("client", "secret"), concat!("app", "secret")];
4527
4528    const MANIFEST: (&str, &str) = ("Cargo.toml", include_str!("../Cargo.toml"));
4529
4530    /// Every `.rs` file at or below `src/`, named by its `/`-joined path
4531    /// relative to `src/` — so a nested module is `("rest/runners.rs",
4532    /// include_str!("rest/runners.rs"))`, not just its file name.
4533    ///
4534    /// This list used to *be* the claim "every source file in the crate", and a
4535    /// hard-coded list is not that claim — it is a snapshot of it. `c3` and `c4`
4536    /// are the tasks that will add files to this directory, so the list was
4537    /// guaranteed to go stale on exactly the work that most needed scanning: a
4538    /// new `pagination.rs` holding a confidential credential passed silently.
4539    /// [`the_confidential_credential_scan_covers_every_source_file`] pins this
4540    /// by walking the directory tree, so adding a file — at the top level or in
4541    /// a subdirectory — and not adding it here fails.
4542    const CRATE_SOURCES: &[(&str, &str)] = &[
4543        ("demand.rs", include_str!("demand.rs")),
4544        ("device_flow.rs", include_str!("device_flow.rs")),
4545        ("jit.rs", include_str!("jit.rs")),
4546        ("lib.rs", include_str!("lib.rs")),
4547        ("rest.rs", include_str!("rest.rs")),
4548    ];
4549
4550    /// The two source files `c2` owns, plus the manifest. The renewal half of
4551    /// the scan stays inside this boundary; see the scan's own documentation.
4552    const SOURCES_OWNED_BY_C2: &[(&str, &str)] = &[
4553        ("device_flow.rs", include_str!("device_flow.rs")),
4554        ("lib.rs", include_str!("lib.rs")),
4555        MANIFEST,
4556    ];
4557
4558    /// Lower-cased with `_` removed, so that one needle catches the snake,
4559    /// camel, Pascal and screaming-snake spellings of an identifier at once.
4560    /// (Those four spellings cannot be written out here: they are exactly what
4561    /// the gate forbids, which is the constraint on documentation this scan
4562    /// imposes and defends below.)
4563    ///
4564    /// # Why `-` is *not* stripped from Rust source
4565    ///
4566    /// It used to be, and that rejected ordinary English. `c3`'s own file opens
4567    /// with a line stating that the gateway holds no such credential, written
4568    /// with the compound adjective English requires — and stripping `-` turned
4569    /// that sentence into the needle, so the gate accused `c3` of naming a
4570    /// confidential credential in the very line that says it holds none. A
4571    /// compound adjective is not an evasion; it is how the language works, and
4572    /// this brief, this crate's documentation and that line all use one.
4573    ///
4574    /// Nothing is lost, because **a Rust identifier cannot contain `-`**.
4575    /// Stripping it never bought identifier coverage: every casing an identifier
4576    /// can actually take is `_`-separated or unseparated, and all of those still
4577    /// collapse onto the needle. What it bought was coverage of a *kebab-case
4578    /// string literal*, and the residual gap is stated plainly rather than
4579    /// papered over: a `.rs` file that wrote this credential's name as a
4580    /// hyphenated string would not be caught here. That gap is narrow on
4581    /// purpose — OAuth 2.0 and GitHub both spell the field `_`-separated, which
4582    /// this catches — and it is the price of a gate that ordinary prose can
4583    /// coexist with. A gate that fires on correct English is not a stricter
4584    /// gate; it is a gate that gets deleted.
4585    ///
4586    /// The alternatives were weighed. Requiring identifier context needs a Rust
4587    /// lexer to tell `a client-secret-free design` from a TOML key, and gets the
4588    /// wrong answer for both string literals and comments. Excluding comment
4589    /// text needs the same lexer to avoid mangling `//` inside a string, and
4590    /// would stop the gate catching a `TODO` comment proposing to read the
4591    /// credential from the environment — which is precisely the drift worth
4592    /// catching early, while it is still a comment. Stripping one character
4593    /// fewer needs neither, which is why it wins.
4594    ///
4595    /// A space is not stripped either, and for the same reason: it is what lets
4596    /// this crate's prose discuss a "client secret" as two words.
4597    fn normalise_source(source: &str) -> String {
4598        source.to_ascii_lowercase().replace('_', "")
4599    }
4600
4601    /// The manifest keeps `-` stripped: TOML keys and crate names are kebab-case
4602    /// by convention, so `-` there is a word separator rather than a hyphen, and
4603    /// a manifest carries no hyphenated English for it to break.
4604    fn normalise_manifest(manifest: &str) -> String {
4605        manifest.to_ascii_lowercase().replace(['_', '-'], "")
4606    }
4607
4608    /// Which normaliser a scanned file gets. The manifest is the only file whose
4609    /// `-` is a separator rather than punctuation.
4610    fn normalise(name: &str, contents: &str) -> String {
4611        if name == MANIFEST.0 {
4612            normalise_manifest(contents)
4613        } else {
4614            normalise_source(contents)
4615        }
4616    }
4617
4618    /// The part of a source file that is not test code.
4619    ///
4620    /// The boundary is the first line that is **exactly** `#[cfg(test)]`, and
4621    /// the word "exactly" is the fix. Splitting on that literal wherever it
4622    /// appeared also split on it in *prose*, and `lib.rs` has carried such a
4623    /// mention since the `testing` module was documented — so the scan below
4624    /// already stopped nine lines early, today, with nothing to say so. A file
4625    /// whose module documentation happened to mention an inline test module
4626    /// would have had its scanned region truncated to a few dozen lines, after
4627    /// which a real `std::fs::write` in non-test code passed silently. That is
4628    /// the same class of defect as the log scan that captured only its own
4629    /// events and the credential scan that claimed a scope it did not have: a
4630    /// gate whose description outran what it did.
4631    fn non_test_prefix(source: &str) -> &str {
4632        let mut offset = 0;
4633        for line in source.split_inclusive('\n') {
4634            if line.trim() == "#[cfg(test)]" {
4635                return &source[..offset];
4636            }
4637            offset += line.len();
4638        }
4639        source
4640    }
4641
4642    /// The Definition of Done's second item, made checkable rather than
4643    /// reviewed: "no renewal token code path exists, and no client secret
4644    /// appears anywhere in the crate **or its configuration**".
4645    ///
4646    /// # Normalised, because a literal scan is evaded by naming
4647    ///
4648    /// This used to be a case-sensitive `contains` over two snake-case
4649    /// spellings, which is a gate that any ordinary Rust or JSON identifier
4650    /// walks straight through: the camel-cased, Pascal-cased and
4651    /// screaming-snake spellings of the very same two identifiers were all
4652    /// invisible to it. None of those is exotic — several are what the
4653    /// surrounding ecosystem actually calls these fields — so evading this gate
4654    /// never had to be deliberate. See [`normalise_source`] for what is
4655    /// collapsed, what is deliberately not, and why.
4656    ///
4657    /// The consequence is that this crate's *prose* may not write those
4658    /// identifiers either, in any casing: it says "renewal token" and "client
4659    /// secret" as separate words, which normalisation preserves and the scan
4660    /// therefore ignores. That is a real constraint on the documentation, and it
4661    /// is the right way round — a gate loosened until the comments compile is
4662    /// not a gate. It is a constraint on *identifier spellings*, though, and
4663    /// never on English: hyphenating a compound adjective is not writing an
4664    /// identifier, and a gate that could not tell those apart is what this round
4665    /// fixed.
4666    ///
4667    /// # Two different scopes, for two different reasons
4668    ///
4669    /// The **renewal** half stays scoped to the two files `c2` owns plus the
4670    /// manifest. A renewal path in `c3`'s or `c4`'s file would be their finding;
4671    /// failing here on their work would be this task reaching across an
4672    /// ownership boundary.
4673    ///
4674    /// The **client secret** half covers every source file in the crate. That is
4675    /// not a boundary crossing but the opposite: a public client cannot hold a
4676    /// client secret at all (D3, `07-security.md`), so one appearing *anywhere*
4677    /// in this crate is a product defect rather than a matter of whose file it
4678    /// is, and `c2` is the designated owner of that clause. "Every source file"
4679    /// is a claim about the directory, so it is checked against the directory —
4680    /// see [`the_confidential_credential_scan_covers_every_source_file`].
4681    #[test]
4682    fn no_confidential_credential_in_this_crate() {
4683        for &(name, source) in CRATE_SOURCES.iter().chain(std::iter::once(&MANIFEST)) {
4684            let haystack = normalise(name, source);
4685            for forbidden in CONFIDENTIAL {
4686                assert!(
4687                    !haystack.contains(forbidden),
4688                    "{name} names {forbidden:?} in some spelling: a public client cannot \
4689                     secure a confidential credential, and this design never tries to (D3)"
4690                );
4691            }
4692        }
4693    }
4694
4695    /// "Every source file in the crate" is a claim about a directory, and the
4696    /// scan above states it as a hard-coded list. A list is a snapshot: the
4697    /// moment `c3` or `c4` adds a file to `src/`, the claim is false and nothing
4698    /// says so. A `src/pagination.rs` holding a confidential credential passed
4699    /// the gate that exists to catch exactly that.
4700    ///
4701    /// Reading the directory here is what turns the claim back into a claim. It
4702    /// cannot be done in the scan itself — `include_str!` needs a literal path
4703    /// at compile time — so the list stays, and this pins it.
4704    ///
4705    /// # Why it walks the tree instead of listing one directory
4706    ///
4707    /// It used to call `read_dir("src")` once and keep the entries ending in
4708    /// `.rs`. That reads like a directory scan and is not one: a subdirectory
4709    /// module — `src/rest/mod.rs`, `src/rest/runners.rs` — arrives as the single
4710    /// entry `rest`, which does not end in `.rs`, so the filter dropped it and
4711    /// took the files underneath with it. The pin went on passing while those
4712    /// files were scanned by nothing at all.
4713    ///
4714    /// That defeated the pin in exactly the case it was written for. `c3` is the
4715    /// REST inventory gateway, a module directory is the ordinary Rust shape for
4716    /// it, and the failure is silent on both sides: the credential scan does not
4717    /// read the file, and the test whose whole job is to notice that reports
4718    /// success.
4719    ///
4720    /// Recursing is the fix, rather than asserting that `src/` holds no
4721    /// subdirectories. The claim being pinned is about *files*, not about
4722    /// layout; banning the directory would fail `c3` for choosing a normal
4723    /// module shape, and a gate that fails correct work is a gate the next round
4724    /// loosens to get its own work compiling — which is how the normalisation
4725    /// half of this same scan was weakened once already.
4726    ///
4727    /// Names are `/`-joined paths relative to `src/`, which is what
4728    /// `include_str!` takes on every platform, so a nested file is listed as
4729    /// `("rest/runners.rs", include_str!("rest/runners.rs"))` and the two sides
4730    /// compare directly.
4731    #[test]
4732    fn the_confidential_credential_scan_covers_every_source_file() {
4733        // Every `.rs` file at or below `dir`, named by its `/`-joined path
4734        // relative to `src/`.
4735        //
4736        // `file_type()` is deliberately not followed through symlinks: a link
4737        // cannot walk this into a cycle, and a symlinked `.rs` file still lands
4738        // in the list through the extension test. A directory is recursed into
4739        // before the extension is considered, so a directory named `foo.rs`
4740        // is walked rather than mistaken for a file.
4741        fn collect(dir: &std::path::Path, prefix: &str, found: &mut Vec<String>) {
4742            for entry in std::fs::read_dir(dir).expect("the source directory is readable") {
4743                let entry = entry.expect("a readable directory entry");
4744                let name = entry.file_name().to_string_lossy().into_owned();
4745                let relative = if prefix.is_empty() {
4746                    name.clone()
4747                } else {
4748                    format!("{prefix}/{name}")
4749                };
4750                if entry.file_type().expect("a readable entry type").is_dir() {
4751                    collect(&entry.path(), &relative, found);
4752                } else if name.ends_with(".rs") {
4753                    found.push(relative);
4754                }
4755            }
4756        }
4757
4758        let mut on_disk = Vec::new();
4759        collect(
4760            std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/src")),
4761            "",
4762            &mut on_disk,
4763        );
4764        on_disk.sort();
4765
4766        // Sorted, rather than taken in declaration order. Comparing a sorted
4767        // `on_disk` against an unsorted `scanned` made this assertion depend on
4768        // `CRATE_SOURCES` happening to be declared alphabetically. It is — but
4769        // nothing said so, and the failure that would follow from reordering the
4770        // list is a diff of two lists holding the same names, which reads as a
4771        // coverage gap rather than as the ordering nit it would actually be.
4772        let mut scanned: Vec<String> = CRATE_SOURCES
4773            .iter()
4774            .map(|(name, _)| (*name).to_string())
4775            .collect();
4776        scanned.sort();
4777
4778        assert_eq!(
4779            scanned, on_disk,
4780            "`src/` and the scanned list have diverged. Add the new file to `CRATE_SOURCES` \
4781             with an `include_str!`, naming it by its `/`-joined path relative to `src/`; \
4782             leaving it out means the confidential-credential scan silently stops covering \
4783             `every source file in the crate`, which is the claim it makes."
4784        );
4785    }
4786
4787    /// The scan above, shown to actually catch the spellings it claims to — and
4788    /// to leave alone the ones it claims to leave alone.
4789    ///
4790    /// Without this, "the gate is case-insensitive now" is a comment rather than
4791    /// a fact, and the finding that produced it was precisely a gate whose
4792    /// description outran what it did. It calls [`normalise`], the same function
4793    /// the scan calls, because a meta-test with its own private copy of the
4794    /// thing under test cannot detect a change to it.
4795    #[test]
4796    fn the_confidential_credential_scan_is_not_evaded_by_naming() {
4797        // Assembled at run time rather than written out, for the same reason the
4798        // needles are spelled in halves: a test that contained these spellings
4799        // literally would fail the scan it is checking.
4800        let source_evasions = [
4801            format!("let {}Token = fetch()", "refresh"),
4802            format!("struct {}Token;", "Refresh"),
4803            format!("{}_TOKEN", "REFRESH"),
4804            format!("{}Secret", "client"),
4805            format!("{}_SECRET", "CLIENT"),
4806            format!("{}_secret", "app"),
4807        ];
4808        for evasion in &source_evasions {
4809            let normalised = normalise("lib.rs", evasion);
4810            assert!(
4811                normalised.contains(concat!("refresh", "token"))
4812                    || normalised.contains(concat!("client", "secret"))
4813                    || normalised.contains(concat!("app", "secret")),
4814                "{evasion:?} would walk straight through the scan"
4815            );
4816        }
4817
4818        // The manifest is where kebab-case is a word separator rather than a
4819        // hyphen, so that is where it is still collapsed.
4820        let manifest_evasion = format!("{}-secret = \"...\"", "client");
4821        assert!(
4822            normalise(MANIFEST.0, &manifest_evasion).contains(concat!("client", "secret")),
4823            "a kebab-case TOML key is an identifier, and the manifest normaliser must \
4824             still collapse it"
4825        );
4826
4827        // And the prose the crate legitimately writes must still pass, or the
4828        // gate would be unusable and would be weakened again to make it usable.
4829        for allowed in [
4830            "a public client cannot hold a client secret",
4831            "the published App issues no renewal token",
4832            // The line that fails the old normalisation, quoted from `c3`'s own
4833            // file. It says the *opposite* of what the gate accused it of.
4834            "//! This gateway is deliberately client-secret-free, as D3 requires.",
4835            // The same shape, for the renewal half.
4836            "a refresh-free credential model",
4837        ] {
4838            let normalised = normalise("lib.rs", allowed);
4839            assert!(
4840                !normalised.contains(concat!("client", "secret"))
4841                    && !normalised.contains(concat!("refresh", "token")),
4842                "{allowed:?} is English, not an identifier, and must not trip the scan"
4843            );
4844        }
4845    }
4846
4847    /// The storage boundary, made checkable the same way. `c2` returns the token
4848    /// and never persists it; the machine-scoped store is `d2` and the wiring is
4849    /// `f1`. A dependency on `runner-manager-platform`, or a filesystem write,
4850    /// would silently move that boundary.
4851    #[test]
4852    fn this_crate_persists_nothing_and_does_not_depend_on_the_platform_crate() {
4853        assert!(
4854            !MANIFEST.1.contains("runner-manager-platform"),
4855            "the gateway must be testable with no platform dependency at all"
4856        );
4857
4858        for &(name, source) in SOURCES_OWNED_BY_C2 {
4859            if name == MANIFEST.0 {
4860                continue;
4861            }
4862            // Everything below `#[cfg(test)]` is test code; the boundary is about
4863            // non-test code, and the tests above legitimately read this file.
4864            let non_test = non_test_prefix(source);
4865            // `OpenOptions`, `File::options` and `std::io::Write` are on this
4866            // list because the original four named only the *obvious* ways to
4867            // write a file. A store built with `OpenOptions::new().create(true)`
4868            // would have moved the persistence boundary silently, which is the
4869            // one thing this scan exists to prevent.
4870            for forbidden in [
4871                "std::fs",
4872                "fs::write",
4873                "File::create",
4874                "File::options",
4875                "OpenOptions",
4876                "std::io::Write",
4877                "tokio::fs",
4878            ] {
4879                assert!(
4880                    !non_test.contains(forbidden),
4881                    "{name} performs a filesystem operation ({forbidden:?}) outside its tests"
4882                );
4883            }
4884        }
4885    }
4886
4887    /// The scan above, shown to be looking at what it says it is looking at.
4888    ///
4889    /// `split("#[cfg(test)]")` matched that literal **anywhere**, prose
4890    /// included. One ordinary sentence in a module's documentation truncated the
4891    /// scanned region to whatever preceded it, and every filesystem call after
4892    /// that point became invisible — with the scan still reporting `ok`. This is
4893    /// the third gate in this crate found describing more than it did, so it
4894    /// gets the same treatment as the other two: a synthetic file where the
4895    /// difference is decisive, and an assertion about the real ones.
4896    #[test]
4897    fn the_non_test_boundary_is_a_line_and_not_a_mention() {
4898        // A file shaped like this crate's own: prose that names the attribute,
4899        // then real non-test code, then the actual module.
4900        let file = "//! Test helpers live in an inline #[cfg(test)] module near the bottom.\n\
4901                    \n\
4902                    fn persist() { std::fs::write(\"x\", b\"y\").unwrap(); }\n\
4903                    \n\
4904                    #[cfg(test)]\n\
4905                    mod tests {\n\
4906                        fn helper() { std::fs::write(\"ok-in-tests\", b\"\").unwrap(); }\n\
4907                    }\n";
4908
4909        let non_test = non_test_prefix(file);
4910        assert!(
4911            non_test.contains("fn persist"),
4912            "a prose mention of the attribute truncated the scanned region, and every \
4913             filesystem call below it stopped being scanned — silently:\n{non_test}"
4914        );
4915        assert!(
4916            !non_test.contains("ok-in-tests"),
4917            "the boundary must still exclude the real test module:\n{non_test}"
4918        );
4919
4920        // And on the real files, whose module documentation contains such a
4921        // mention today. `lib.rs` has carried one since `mod testing` was
4922        // written, so this crate was shipping the truncated scan.
4923        for &(name, source) in SOURCES_OWNED_BY_C2 {
4924            if name == MANIFEST.0 {
4925                continue;
4926            }
4927            let expected = source
4928                .lines()
4929                .position(|line| line.trim() == "#[cfg(test)]")
4930                .expect("each source file has an inline test module");
4931            let scanned = non_test_prefix(source).lines().count();
4932            assert_eq!(
4933                scanned, expected,
4934                "{name}: the scanned region ends at line {scanned} but the test module starts \
4935                 at line {expected}. The gap is code that claims to be scanned and is not."
4936            );
4937        }
4938    }
4939}