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        // First, not second: if multiple processes (e.g., daemon and TUI) share the
1792        // same token, they will both get 401 at the same time. The first one to renew
1793        // will write the new token to disk. If the second process tries to renew with
1794        // its in-memory refresh token *before* reloading, GitHub will detect a refresh
1795        // token replay and instantly revoke the entire token chain. So we must always
1796        // check disk for a newer token first.
1797        //
1798        // To further prevent a race condition if two processes hit 401 at the exact
1799        // same millisecond, we introduce a pseudo-random jitter based on the OS
1800        // process ID. This ensures one process wakes up first, finishes the renewal,
1801        // and writes to disk, so the second process sees the new file during its
1802        // `reload_once()`. All threads in the *same* process compute the exact same
1803        // jitter, preserving their ability to coalesce behind `revalidation_gate`.
1804        let jitter = (std::process::id() % 1500) as u64 + 50;
1805        tokio::time::sleep(std::time::Duration::from_millis(jitter)).await;
1806
1807        if self.reload_once().await || self.renew_once().await {
1808            let second = self.send_raw(request).await?;
1809            return match self.classify(request, &second, Attempt::Retry) {
1810                Classified::Ok => Ok(second),
1811                // The renewed credential was rejected too. Nothing here can
1812                // help: this is a sign-in, not a token, that has gone.
1813                Classified::Unauthorized => Err(GithubError::AuthenticationFailed),
1814                Classified::Error(err) => Err(err),
1815            };
1816        }
1817        match self.revalidate_after_unauthorized().await? {
1818            Revalidation::Rejected => {
1819                tracing::warn!(
1820                    method = request.method.as_str(),
1821                    path = %request.path,
1822                    "GitHub rejected the stored credential; re-authentication is required"
1823                );
1824                Err(GithubError::AuthenticationFailed)
1825            }
1826            Revalidation::Valid | Revalidation::Unavailable => {
1827                // `revalidate_from` now converts a lockout that its own probe
1828                // latched, so this no longer catches that case. It stays for the
1829                // one it still catches: a *concurrent* request latching between
1830                // that check and this one. Sending the retry into a live lockout
1831                // is the thing the back-off exists to prevent, and this is the
1832                // last point at which it can be declined.
1833                if let Some(remaining) = self.lockout_remaining() {
1834                    return Err(GithubError::AuthenticationLockout {
1835                        retry_after: remaining,
1836                    });
1837                }
1838                let second = self.send_raw(request).await?;
1839                match self.classify(request, &second, Attempt::Retry) {
1840                    Classified::Ok => Ok(second),
1841                    // The one retry is spent. A second `401` is terminal.
1842                    Classified::Unauthorized => Err(GithubError::AuthenticationFailed),
1843                    Classified::Error(err) => Err(err),
1844                }
1845            }
1846        }
1847    }
1848
1849    fn classify(
1850        &self,
1851        request: &ApiRequest,
1852        response: &ApiResponse,
1853        attempt: Attempt,
1854    ) -> Classified {
1855        let status = response.status;
1856        if status.is_success() {
1857            self.consecutive_unauthorized.store(0, Ordering::SeqCst);
1858            return Classified::Ok;
1859        }
1860        if status == StatusCode::UNAUTHORIZED {
1861            self.consecutive_unauthorized.fetch_add(1, Ordering::SeqCst);
1862            return Classified::Unauthorized;
1863        }
1864        if status == StatusCode::FORBIDDEN && self.is_lockout_403(response, attempt) {
1865            let backoff = self.latch_lockout(&response.headers);
1866            tracing::warn!(
1867                method = request.method.as_str(),
1868                path = %request.path,
1869                backoff_secs = backoff.as_secs(),
1870                "GitHub answered 403 after 401s: temporary authentication lockout, backing off"
1871            );
1872            return Classified::Error(GithubError::AuthenticationLockout {
1873                retry_after: backoff,
1874            });
1875        }
1876        let headers = Box::new(response.headers.clone());
1877        let message = error_message(&response.body);
1878        if status == StatusCode::FORBIDDEN {
1879            return Classified::Error(GithubError::Forbidden {
1880                method: request.method.as_str().to_string(),
1881                path: request.path.clone(),
1882                message,
1883                headers,
1884            });
1885        }
1886        Classified::Error(GithubError::Status {
1887            status: status.as_u16(),
1888            method: request.method.as_str().to_string(),
1889            path: request.path.clone(),
1890            message,
1891            headers,
1892        })
1893    }
1894
1895    /// Whether a `403` is GitHub's temporary *authentication* lockout, as
1896    /// opposed to a permissions answer or a rate limit.
1897    ///
1898    /// # It must not be a rate limit
1899    ///
1900    /// `classify` used to reach the `403` branch before anything looked at the
1901    /// rate-limit headers, so a primary rate limit arriving during a `401` storm
1902    /// was reported as `AuthenticationLockout` — telling the operator "the
1903    /// credential itself is not the problem" about a response that never
1904    /// mentioned the credential. Recognising GitHub's own rate-limit evidence is
1905    /// not rate-limit *policy*; it is declining to make an assertion the
1906    /// evidence contradicts. What to do about the rate limit stays `c3`'s, which
1907    /// is why this only changes which variant carries the headers onward.
1908    ///
1909    /// # Then one of two positions, and the second one is a fix for the first
1910    ///
1911    /// **The retry.** `consecutive_unauthorized` counts `401`s since the last
1912    /// successful caller response and — correctly — does not decay: a request
1913    /// that ends in `404`, `422` or `500` leaves it set. In the agent's
1914    /// long-lived reconciliation loop that meant a single `401` from minutes ago
1915    /// converted the *next* genuine permissions `403` into a fake lockout: sixty
1916    /// seconds of silence plus an operator message insisting the credential is
1917    /// fine, when in truth `generate-jitconfig` was missing
1918    /// `Administration: write`. The lockout's signature is narrower than "a
1919    /// `403` while the count is set" — it is a `403` on the one retry this
1920    /// client itself issued after this request's own `401`.
1921    ///
1922    /// The count is deliberately *not* consulted. [`Attempt::Retry`] already
1923    /// means this request's own `401` incremented it moments ago, so reading it
1924    /// adds no signal — and does add a race that fails open: any concurrent
1925    /// request succeeding between the `401` and the retry `store(0)`s the
1926    /// counter, and a real lockout is then reported as a plain permissions
1927    /// refusal. A conjunct that can only ever weaken a safety check is worse
1928    /// than no conjunct.
1929    ///
1930    /// **The continuation.** Narrowing to the retry position opened a hole at
1931    /// the far end of the same back-off. When the back-off elapses and GitHub is
1932    /// still locking the credential out, the next request is a *first* attempt
1933    /// by construction — this client's retry never happened, because the request
1934    /// never reached the wire. The position rule then declined to call it a
1935    /// lockout, `classify` fell through to [`GithubError::Forbidden`] — whose
1936    /// documented reading is "the App installation does not grant it" — and the
1937    /// client **stopped backing off entirely**, hammering a credential GitHub
1938    /// had asked it to leave alone. That is the exact inverse of the
1939    /// Definition of Done's "backs off without retrying", and it failed for
1940    /// every lockout outliving one back-off.
1941    ///
1942    /// No counter is needed for that case either, because the response says so
1943    /// itself. GitHub's lockout carries `retry-after` and no parseable message;
1944    /// a permissions refusal carries a message naming what is not accessible and
1945    /// no `retry-after`. Requiring **both** halves of that signature is what
1946    /// keeps this from degenerating into "every `403` is a lockout": a
1947    /// permissions answer has a message, so it never matches, and a secondary
1948    /// rate limit has both a message and `retry-after`, so `is_rate_limited`
1949    /// takes it first.
1950    ///
1951    /// "No parseable message" is deliberately wider than "an empty body", which
1952    /// is how this used to be stated. See [`is_lockout_continuation`] for what
1953    /// else falls into it — a proxy's HTML error page most notably — and for why
1954    /// the resulting false positives are accepted rather than tightened away.
1955    ///
1956    /// This also settles a standing worry about [`MAX_LOCKOUT_BACKOFF`]. With
1957    /// the continuation recognised, the ceiling no longer decides whether the
1958    /// product ever gives up — it only decides how often it re-asks. A lockout
1959    /// longer than the ceiling now re-latches instead of being reported as a
1960    /// permissions failure, so the value is a polling interval rather than a
1961    /// deadline.
1962    fn is_lockout_403(&self, response: &ApiResponse, attempt: Attempt) -> bool {
1963        if is_rate_limited(response) {
1964            return false;
1965        }
1966        match attempt {
1967            Attempt::Retry => true,
1968            Attempt::First => is_lockout_continuation(response),
1969        }
1970    }
1971
1972    fn latch_lockout(&self, headers: &HeaderMap) -> Duration {
1973        // Clamp before latching. An unclamped `Retry-After` is a remote party
1974        // deciding how long this product stays down.
1975        let requested = retry_after(headers).unwrap_or(DEFAULT_LOCKOUT_BACKOFF);
1976        let clamped = requested.min(MAX_LOCKOUT_BACKOFF);
1977
1978        // A span too large for `chrono` must fall back to the default, never to
1979        // `None`: the old code's `.ok()` turned an absurd `Retry-After` into "no
1980        // lockout at all", which fails *open* — the exact inverse of what a
1981        // back-off is for, and reachable by a header alone. The clamp above
1982        // already makes this branch unreachable; it stays because the invariant
1983        // it protects ("latching always latches") is worth more than the line.
1984        let delta = chrono::TimeDelta::from_std(clamped).unwrap_or_else(|_| {
1985            chrono::TimeDelta::from_std(DEFAULT_LOCKOUT_BACKOFF)
1986                .expect("sixty seconds is a representable span")
1987        });
1988        // No third clamp. `clamped` is already `<= MAX_LOCKOUT_BACKOFF`, and
1989        // `TimeDelta` round-trips it exactly, so re-clamping here was dead twice
1990        // over — it could only ever re-apply a bound already applied, and the
1991        // fallback it guarded is `DEFAULT_LOCKOUT_BACKOFF`, which is smaller
1992        // than the ceiling by construction.
1993        let backoff = delta.to_std().unwrap_or(DEFAULT_LOCKOUT_BACKOFF);
1994
1995        let mut state = self.lockout.lock().expect("lockout lock poisoned");
1996        state.backoff = backoff;
1997        state.until = Some(self.clock.now() + delta);
1998        backoff
1999    }
2000
2001    /// One HTTP round trip with the standard headers applied and no
2002    /// interpretation of the result.
2003    async fn send_raw(&self, request: &ApiRequest) -> Result<ApiResponse, GithubError> {
2004        let url = self.resolve(&request.path)?;
2005        let mut builder = self
2006            .http
2007            .request(request.method.clone(), url)
2008            .header(reqwest::header::ACCEPT, GITHUB_ACCEPT)
2009            .header(reqwest::header::USER_AGENT, USER_AGENT)
2010            .header("X-GitHub-Api-Version", GITHUB_API_VERSION)
2011            // The only place the token is ever written onto the wire. It is
2012            // never logged, and `reqwest` does not render headers in its errors.
2013            .header(
2014                reqwest::header::AUTHORIZATION,
2015                format!("Bearer {}", self.bearer()),
2016            );
2017        if !request.query.is_empty() {
2018            builder = builder.query(&request.query);
2019        }
2020        if let Some(body) = &request.body {
2021            builder = builder.json(body);
2022        }
2023
2024        let response = builder.send().await.map_err(transport)?;
2025        let status = response.status();
2026        let headers = response.headers().clone();
2027        let body = response.bytes().await.map_err(transport)?.to_vec();
2028
2029        tracing::debug!(
2030            method = request.method.as_str(),
2031            path = %request.path,
2032            status = status.as_u16(),
2033            body_bytes = body.len(),
2034            "github api request"
2035        );
2036
2037        Ok(ApiResponse {
2038            status,
2039            headers,
2040            body,
2041        })
2042    }
2043
2044    fn resolve(&self, path: &str) -> Result<Url, GithubError> {
2045        if path.starts_with("http://") || path.starts_with("https://") {
2046            return Url::parse(path).map_err(|_| GithubError::Malformed {
2047                what: "an absolute request URL",
2048                value: path.to_string(),
2049            });
2050        }
2051        self.endpoints
2052            .api_base
2053            .join(path.trim_start_matches('/'))
2054            .map_err(|_| GithubError::Malformed {
2055                what: "a request path",
2056                value: path.to_string(),
2057            })
2058    }
2059}
2060
2061enum Classified {
2062    Ok,
2063    Unauthorized,
2064    Error(GithubError),
2065}
2066
2067/// Which of a request's at-most-two attempts produced a response.
2068///
2069/// The authentication lockout is defined by *position*, not just by status: it
2070/// is what GitHub answers the retry that follows a `401`. Passing this in makes
2071/// that explicit at both call sites instead of inferring it from a counter that
2072/// outlives the request.
2073#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2074enum Attempt {
2075    First,
2076    Retry,
2077}
2078
2079/// Whether GitHub attributed a failing response to its own rate limit.
2080///
2081/// Reading the evidence, and nothing else — see [`GithubError`]'s note on why
2082/// the headers travel with the error. `c3` decides what to do about it.
2083fn is_rate_limited(response: &ApiResponse) -> bool {
2084    if response.status == StatusCode::TOO_MANY_REQUESTS {
2085        return true;
2086    }
2087    // The primary rate limit's documented signature.
2088    if response
2089        .header("x-ratelimit-remaining")
2090        .is_some_and(|v| v.trim() == "0")
2091    {
2092        return true;
2093    }
2094    // A secondary rate limit sends `retry-after` — but so does the
2095    // authentication lockout, so that header alone cannot tell them apart.
2096    // GitHub's own message ("You have exceeded a secondary rate limit") can.
2097    error_message(&response.body).is_some_and(|m| m.to_ascii_lowercase().contains("rate limit"))
2098}
2099
2100/// Whether a `403` on a *first* attempt is GitHub continuing an authentication
2101/// lockout that outlived this client's back-off.
2102///
2103/// The two halves are both required, and both are GitHub's own evidence rather
2104/// than this client's memory:
2105///
2106/// * **`retry-after` is present.** GitHub sends it when it wants to be left
2107///   alone. A permissions refusal never does — there is nothing to wait for.
2108///
2109///   The header's *presence* is what is tested, not whether it parses, and that
2110///   is a fix rather than laziness. [`retry_after`] reads **integer seconds
2111///   only**, while RFC 9110 §10.2.3 also permits an HTTP-date. Gating detection
2112///   on `retry_after(..).is_some()` meant a date-form header was not recognised
2113///   as a continuation at all, and the bug this function exists to fix came
2114///   straight back for that shape — silently, since the response still looks
2115///   like an ordinary [`GithubError::Forbidden`] on the way out.
2116///
2117///   How long to wait stays a separate question, still answered by the integer
2118///   parse: [`AuthenticatedClient::latch_lockout`] already falls back to
2119///   [`DEFAULT_LOCKOUT_BACKOFF`] for a header it cannot read, so a date-form
2120///   header now latches sixty seconds instead of latching nothing. GitHub sends
2121///   integer seconds in practice; the point is not to depend on that.
2122/// * **The body carries no parseable GitHub message.** A permissions refusal
2123///   always names what is not accessible ("Resource not accessible by
2124///   integration"); the lockout's does not. This is the half that stops the rule
2125///   from swallowing [`GithubError::Forbidden`] entirely.
2126///
2127///   "No parseable GitHub message" is wider than "the body is empty", which is
2128///   how this used to be written, and the difference is worth stating because it
2129///   is what the code actually tests. [`error_message`] returns `None` for *any*
2130///   body that is not JSON carrying a non-empty `message`: an HTML error page
2131///   from a proxy or a CDN, a JSON body carrying only `documentation_url`, plain
2132///   text, a truncated response. Proxies routinely send `Retry-After` too, so a
2133///   `403` that never came from GitHub at all can read as an authentication
2134///   lockout here.
2135///
2136///   That is accepted rather than missed. The cost is bounded — the client
2137///   waits, clamped by [`MAX_LOCKOUT_BACKOFF`], then re-asks — and the direction
2138///   is the safe one: treating a strange `403` as "wait" costs latency, while
2139///   treating a real lockout as a permissions answer costs the back-off
2140///   entirely and tells the operator to fix a grant that is not missing.
2141///   Tightening it would mean asserting the body *is* GitHub's, which is
2142///   precisely the assertion an intercepting proxy makes false.
2143///
2144/// Callers reach this through [`AuthenticatedClient::is_lockout_403`], which
2145/// rules out a rate limit first — a secondary rate limit carries `retry-after`
2146/// *and* a message, so it fails this test on the second half anyway, but the
2147/// ordering makes the precedence explicit rather than incidental.
2148fn is_lockout_continuation(response: &ApiResponse) -> bool {
2149    response.headers.contains_key("retry-after") && error_message(&response.body).is_none()
2150}
2151
2152// ---------------------------------------------------------------------------
2153// Installation discovery
2154// ---------------------------------------------------------------------------
2155
2156/// Whether an installation can reach every repository on its account, or only
2157/// the ones the user picked.
2158#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2159#[serde(rename_all = "snake_case")]
2160pub enum RepositorySelection {
2161    /// Every repository on the account, including ones created later.
2162    All,
2163    /// Only the repositories the user chose at install time.
2164    Selected,
2165}
2166
2167impl RepositorySelection {
2168    /// `07-security.md`: "`auth status` shows which repositories the token can
2169    /// reach, so an over-broad installation is visible rather than assumed."
2170    /// This is the flag that makes it visible.
2171    #[must_use]
2172    pub fn is_over_broad(self) -> bool {
2173        matches!(self, Self::All)
2174    }
2175}
2176
2177/// Whose account an installation sits on.
2178#[derive(Debug, Clone, PartialEq, Eq)]
2179pub enum InstallationAccount {
2180    User(String),
2181    Organization(Org),
2182    /// An enterprise account.
2183    ///
2184    /// It is its own variant rather than a [`InstallationAccount::User`]
2185    /// because it is not one, and `auth status` says out loud whose account
2186    /// each installation sits on. Everything GitHub reports without
2187    /// `type: "Organization"` used to fall into `User`, so an enterprise was
2188    /// labelled a user — a wrong statement about the operator's own account, on
2189    /// the one screen that exists to tell them what their credential reaches.
2190    ///
2191    /// It contributes nothing to [`ReachableTargets::organizations`], and that
2192    /// is correct rather than a second bug: an enterprise is not an
2193    /// organization, and `GET /orgs/{org}/actions/runners` does not accept one.
2194    /// The distinction is only visible now because the label is.
2195    Enterprise(String),
2196}
2197
2198impl InstallationAccount {
2199    #[must_use]
2200    pub fn login(&self) -> &str {
2201        match self {
2202            Self::User(login) | Self::Enterprise(login) => login,
2203            Self::Organization(org) => org.as_str(),
2204        }
2205    }
2206
2207    /// The organization, when the account is one. An organization account is a
2208    /// reachable *target* in its own right (D18): a policy may scale for the
2209    /// whole organization.
2210    #[must_use]
2211    pub fn organization(&self) -> Option<&Org> {
2212        match self {
2213            Self::Organization(org) => Some(org),
2214            Self::User(_) | Self::Enterprise(_) => None,
2215        }
2216    }
2217
2218    /// What to call this account in `auth status`. `f1` renders it; nothing in
2219    /// this crate branches on it.
2220    #[must_use]
2221    pub fn kind(&self) -> &'static str {
2222        match self {
2223            Self::User(_) => "user",
2224            Self::Organization(_) => "organization",
2225            Self::Enterprise(_) => "enterprise",
2226        }
2227    }
2228}
2229
2230impl fmt::Display for InstallationAccount {
2231    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2232        f.write_str(self.login())
2233    }
2234}
2235
2236/// One installation of the published App, and what it can actually reach.
2237#[derive(Debug, Clone, PartialEq, Eq)]
2238pub struct Installation {
2239    pub id: u64,
2240    pub account: InstallationAccount,
2241    pub repository_selection: RepositorySelection,
2242    pub repositories: Vec<OwnerRepo>,
2243    /// The permissions GitHub reports for this installation, as
2244    /// `name -> level`. Surfaced verbatim so `auth status` can show a grant the
2245    /// user did not expect rather than assert the published set was applied.
2246    pub permissions: Vec<(String, String)>,
2247}
2248
2249impl Installation {
2250    #[must_use]
2251    pub fn is_over_broad(&self) -> bool {
2252        self.repository_selection.is_over_broad()
2253    }
2254}
2255
2256/// Everything the stored credential can reach.
2257#[derive(Debug, Clone, PartialEq, Eq)]
2258pub struct ReachableTargets {
2259    installations: Vec<Installation>,
2260    skipped: usize,
2261}
2262
2263impl ReachableTargets {
2264    #[must_use]
2265    pub fn installations(&self) -> &[Installation] {
2266        &self.installations
2267    }
2268
2269    /// How many installations GitHub reported that this client could not
2270    /// describe, and therefore left out of everything above.
2271    ///
2272    /// Non-zero means this report is **incomplete**, not merely small: whatever
2273    /// those installations reach is absent from
2274    /// [`ReachableTargets::repositories`] and
2275    /// [`ReachableTargets::organizations`]. `auth status` should say so, because
2276    /// the alternative is an operator reading a short list as a complete one.
2277    #[must_use]
2278    pub fn skipped(&self) -> usize {
2279        self.skipped
2280    }
2281
2282    /// Every repository the credential can reach, sorted and de-duplicated.
2283    #[must_use]
2284    pub fn repositories(&self) -> Vec<OwnerRepo> {
2285        let mut all: Vec<OwnerRepo> = self
2286            .installations
2287            .iter()
2288            .flat_map(|i| i.repositories.iter().cloned())
2289            .collect();
2290        all.sort();
2291        all.dedup();
2292        all
2293    }
2294
2295    /// Every organization the App is installed on, sorted and de-duplicated.
2296    #[must_use]
2297    pub fn organizations(&self) -> Vec<Org> {
2298        let mut all: Vec<Org> = self
2299            .installations
2300            .iter()
2301            .filter_map(|i| i.account.organization().cloned())
2302            .collect();
2303        all.sort();
2304        all.dedup();
2305        all
2306    }
2307
2308    /// The installations that hold `repository_selection: all`.
2309    #[must_use]
2310    pub fn over_broad(&self) -> Vec<&Installation> {
2311        self.installations
2312            .iter()
2313            .filter(|i| i.is_over_broad())
2314            .collect()
2315    }
2316
2317    #[must_use]
2318    pub fn is_empty(&self) -> bool {
2319        self.repositories().is_empty() && self.organizations().is_empty()
2320    }
2321}
2322
2323/// What `auth status` and `auth login` show after a successful sign-in.
2324#[derive(Debug, Clone, PartialEq, Eq)]
2325pub enum InstallationDiscovery {
2326    /// The credential is valid, GitHub reported nothing this client could not
2327    /// describe, and still nothing is reachable: the App is installed nowhere,
2328    /// or on nothing. `03-control-flows.md` flow 1.1 requires the installation
2329    /// URL here, and the URL is the remediation.
2330    NotInstalled { install_url: Url },
2331    /// Nothing is reachable, but at least one installation was **skipped**, so
2332    /// this client cannot tell "not installed" from "installed on something it
2333    /// could not describe".
2334    ///
2335    /// # Why this variant exists at all
2336    ///
2337    /// Skipping an unnameable installation is the right trade — one odd
2338    /// installation must not take down `auth status` for every other one — but
2339    /// it was made silently, and the silence flipped a verdict. An account this
2340    /// client cannot name, on the *only* installation the credential has, used
2341    /// to collapse to [`InstallationDiscovery::NotInstalled`], and `auth status`
2342    /// then handed an already-installed operator the "install the App" URL. That
2343    /// is a wrong remediation on the only authentication path there is,
2344    /// contradicted by nothing louder than a `warn!` in a log the operator is
2345    /// not reading.
2346    ///
2347    /// So the skip stays and the verdict does not flip. There is deliberately no
2348    /// `install_url` here: the whole point is that this client does not know
2349    /// whether installing is the remedy, and offering the URL anyway would put
2350    /// the wrong answer back one field over. `f1` says "1 installation could not
2351    /// be described" and stops there, which is true.
2352    Indeterminate { skipped: usize },
2353    /// The credential reaches at least one repository or organization. It may
2354    /// still be an incomplete picture — see [`ReachableTargets::skipped`].
2355    Installed(ReachableTargets),
2356}
2357
2358impl InstallationDiscovery {
2359    #[must_use]
2360    pub fn targets(&self) -> Option<&ReachableTargets> {
2361        match self {
2362            Self::Installed(t) => Some(t),
2363            Self::NotInstalled { .. } | Self::Indeterminate { .. } => None,
2364        }
2365    }
2366
2367    /// The installation URL, and *only* when installing is actually the
2368    /// remediation. See [`InstallationDiscovery::Indeterminate`].
2369    #[must_use]
2370    pub fn install_url(&self) -> Option<&Url> {
2371        match self {
2372            Self::NotInstalled { install_url } => Some(install_url),
2373            Self::Installed(_) | Self::Indeterminate { .. } => None,
2374        }
2375    }
2376
2377    /// How many installations GitHub reported that this client could not
2378    /// describe, whichever verdict was reached. One call for `f1`, so that
2379    /// "this report is incomplete" does not depend on which variant it landed
2380    /// in.
2381    #[must_use]
2382    pub fn skipped(&self) -> usize {
2383        match self {
2384            Self::NotInstalled { .. } => 0,
2385            Self::Indeterminate { skipped } => *skipped,
2386            Self::Installed(targets) => targets.skipped(),
2387        }
2388    }
2389}
2390
2391#[derive(Debug, Deserialize)]
2392struct InstallationsPage {
2393    /// GitHub reports the size of the whole collection on every page. Decoding
2394    /// it costs nothing and turns silent under-collection into a visible
2395    /// warning — see [`under_collected`].
2396    #[serde(default)]
2397    total_count: Option<u64>,
2398    #[serde(default)]
2399    installations: Vec<RawInstallation>,
2400}
2401
2402#[derive(Debug, Deserialize)]
2403struct RawInstallation {
2404    id: u64,
2405    /// **Nullable.** GitHub's published `installation` schema types `account` as
2406    /// nullable, so a required field here would fail the *whole* decode — and
2407    /// with it all of `discover_installations`, which is all of `auth status` —
2408    /// over one installation whose account this client did not need to name.
2409    #[serde(default)]
2410    account: Option<RawAccount>,
2411    #[serde(default)]
2412    repository_selection: Option<String>,
2413    #[serde(default)]
2414    permissions: std::collections::BTreeMap<String, String>,
2415}
2416
2417/// An installation's account, which is *not* always a simple user.
2418///
2419/// GitHub's schema makes `account` either a simple-user or an enterprise, and an
2420/// enterprise carries `slug` and `name` where a user carries `login`. Requiring
2421/// `login` therefore made an enterprise installation a hard decode failure of
2422/// the entire response. All three are optional here and
2423/// [`RawAccount::display_login`] takes the first usable one.
2424#[derive(Debug, Deserialize)]
2425struct RawAccount {
2426    #[serde(default)]
2427    login: Option<String>,
2428    /// An enterprise account's stable identifier.
2429    #[serde(default)]
2430    slug: Option<String>,
2431    /// An enterprise account's display name, the last resort.
2432    #[serde(default)]
2433    name: Option<String>,
2434    #[serde(rename = "type", default)]
2435    account_type: Option<String>,
2436}
2437
2438impl RawAccount {
2439    fn display_login(&self) -> Option<&str> {
2440        [
2441            self.login.as_deref(),
2442            self.slug.as_deref(),
2443            self.name.as_deref(),
2444        ]
2445        .into_iter()
2446        .flatten()
2447        .find(|value| !value.is_empty())
2448    }
2449
2450    /// An account with no `login` that still names itself is an enterprise:
2451    /// `slug`/`name` is the enterprise shape, and every simple-user and
2452    /// organization account carries `login`.
2453    fn is_enterprise_shaped(&self) -> bool {
2454        self.login.as_deref().is_none_or(str::is_empty)
2455            && (self.slug.as_deref().is_some_and(|s| !s.is_empty())
2456                || self.name.as_deref().is_some_and(|s| !s.is_empty()))
2457    }
2458}
2459
2460#[derive(Debug, Deserialize)]
2461struct RepositoriesPage {
2462    #[serde(default)]
2463    total_count: Option<u64>,
2464    #[serde(default)]
2465    repositories: Vec<RawRepository>,
2466}
2467
2468#[derive(Debug, Deserialize)]
2469struct RawRepository {
2470    full_name: String,
2471}
2472
2473/// How many items a paginated collection said it had, when that is more than
2474/// arrived.
2475///
2476/// This is the cheapest possible check and it is worth more than it looks. The
2477/// `Link`-header parser used to lose the relation whenever a page URL contained
2478/// a comma, which stopped pagination at page 1 — and *nothing* noticed, because
2479/// a short answer and a complete answer are the same shape. Cross-checking the
2480/// count GitHub itself reported turns that class of bug from a wrong answer into
2481/// a logged warning. A collection larger than `total_count` is not reported:
2482/// GitHub can legitimately grow a collection between pages.
2483fn under_collected(collected: usize, total_count: Option<u64>) -> Option<u64> {
2484    let total = total_count?;
2485    (total > collected as u64).then_some(total)
2486}
2487
2488impl AuthenticatedClient {
2489    /// Which repositories and organizations the stored credential can actually
2490    /// reach.
2491    ///
2492    /// Two calls, both paginated: `GET /user/installations`, then
2493    /// `GET /user/installations/{id}/repositories` per installation. The shapes
2494    /// are the ones the D18 spike observed live
2495    /// (`docs/spikes/d18-org-jit-verification.md`, "The permission that
2496    /// authorized it").
2497    ///
2498    /// An installation is reported even when it is broader than the user
2499    /// expected — [`Installation::is_over_broad`] — because `07-security.md`
2500    /// requires that an over-broad installation be *visible* rather than
2501    /// assumed. Nothing here narrows or hides one.
2502    ///
2503    /// # Errors
2504    /// Every variant of [`GithubError`]. A `401` here goes through the same
2505    /// single-flight re-validation as any other request.
2506    pub async fn discover_installations(
2507        &self,
2508        app: &AppRegistration,
2509    ) -> Result<InstallationDiscovery, GithubError> {
2510        let mut installations = Vec::new();
2511        let mut skipped = 0_usize;
2512        for raw in self.all_installations().await? {
2513            // A null or nameless account is skipped rather than fatal. GitHub
2514            // types this field as nullable, and one unnameable installation must
2515            // not take down `auth status` for every other one — but it is also
2516            // not something to swallow quietly, because the repositories behind
2517            // it are then absent from the reported reach. The count is what
2518            // carries that out of here; a `warn!` alone let the skip change the
2519            // verdict with nothing to say so.
2520            let Some(login) = raw.account.as_ref().and_then(RawAccount::display_login) else {
2521                skipped += 1;
2522                tracing::warn!(
2523                    installation_id = raw.id,
2524                    "skipping an installation GitHub reported with no nameable account; \
2525                     anything it reaches is missing from this report"
2526                );
2527                continue;
2528            };
2529            let account_type = raw.account.as_ref().and_then(|a| a.account_type.as_deref());
2530            let account = match account_type {
2531                Some("Organization") => {
2532                    InstallationAccount::Organization(Org::new(login).map_err(|_| {
2533                        GithubError::Malformed {
2534                            what: "an installation account login",
2535                            value: login.to_string(),
2536                        }
2537                    })?)
2538                }
2539                Some("Enterprise") => InstallationAccount::Enterprise(login.to_string()),
2540                // An enterprise is also reported with no `type` at all, carrying
2541                // `slug`/`name` where a user carries `login` — which is the
2542                // shape D18 observed and the shape `display_login` exists for.
2543                // Recognising it by that shape is what stops it being labelled a
2544                // user by default.
2545                _ if raw
2546                    .account
2547                    .as_ref()
2548                    .is_some_and(RawAccount::is_enterprise_shaped) =>
2549                {
2550                    InstallationAccount::Enterprise(login.to_string())
2551                }
2552                _ => InstallationAccount::User(login.to_string()),
2553            };
2554            let repository_selection = match raw.repository_selection.as_deref() {
2555                Some("all") => RepositorySelection::All,
2556                _ => RepositorySelection::Selected,
2557            };
2558            installations.push(Installation {
2559                id: raw.id,
2560                account,
2561                repository_selection,
2562                repositories: self.installation_repositories(raw.id).await?,
2563                permissions: raw.permissions.into_iter().collect(),
2564            });
2565        }
2566
2567        let targets = ReachableTargets {
2568            installations,
2569            skipped,
2570        };
2571        if targets.is_empty() {
2572            // "Nothing reachable" and "nothing this client could describe" are
2573            // different answers, and only the first one is fixed by installing
2574            // the App. Reporting them as the same answer is how an
2575            // already-installed operator was handed an install URL.
2576            if skipped > 0 {
2577                tracing::warn!(
2578                    skipped,
2579                    "every installation GitHub reported was skipped; whether the App is \
2580                     installed cannot be determined from this credential"
2581                );
2582                return Ok(InstallationDiscovery::Indeterminate { skipped });
2583            }
2584            let install_url = app.install_url(&self.endpoints);
2585            tracing::info!(
2586                install_url = %install_url,
2587                "the published App is not installed on anything this credential can reach"
2588            );
2589            return Ok(InstallationDiscovery::NotInstalled { install_url });
2590        }
2591        tracing::info!(
2592            repositories = targets.repositories().len(),
2593            organizations = targets.organizations().len(),
2594            over_broad = targets.over_broad().len(),
2595            skipped,
2596            "discovered the targets this credential can reach"
2597        );
2598        Ok(InstallationDiscovery::Installed(targets))
2599    }
2600
2601    async fn all_installations(&self) -> Result<Vec<RawInstallation>, GithubError> {
2602        let mut out = Vec::new();
2603        let mut total_count = None;
2604        let mut next = Some(ApiRequest::get("/user/installations").query("per_page", 100));
2605        let mut pages = 0_usize;
2606        while let Some(request) = next.take() {
2607            let response = self.send(&request).await?;
2608            let page: InstallationsPage = response.json()?;
2609            total_count = page.total_count.or(total_count);
2610            out.extend(page.installations);
2611
2612            pages += 1;
2613            if pages >= MAX_PAGES {
2614                tracing::warn!(
2615                    pages,
2616                    collected = out.len(),
2617                    "stopped following installation pages at the ceiling; a `Link: rel=next` \
2618                     that never ends would otherwise loop forever"
2619                );
2620                break;
2621            }
2622            next = response
2623                .next_page()
2624                .map(|url| ApiRequest::get(url.as_str()));
2625        }
2626        if let Some(expected) = under_collected(out.len(), total_count) {
2627            tracing::warn!(
2628                expected,
2629                collected = out.len(),
2630                "GitHub reported more installations than pagination collected; the reported \
2631                 reach is incomplete"
2632            );
2633        }
2634        Ok(out)
2635    }
2636
2637    async fn installation_repositories(&self, id: u64) -> Result<Vec<OwnerRepo>, GithubError> {
2638        let mut out = Vec::new();
2639        let mut total_count = None;
2640        let mut next = Some(
2641            ApiRequest::get(format!("/user/installations/{id}/repositories"))
2642                .query("per_page", 100),
2643        );
2644        let mut pages = 0_usize;
2645        while let Some(request) = next.take() {
2646            let response = self.send(&request).await?;
2647            let page: RepositoriesPage = response.json()?;
2648            total_count = page.total_count.or(total_count);
2649            for repo in page.repositories {
2650                out.push(OwnerRepo::parse(&repo.full_name).map_err(|_| {
2651                    GithubError::Malformed {
2652                        what: "a repository full_name",
2653                        value: repo.full_name.clone(),
2654                    }
2655                })?);
2656            }
2657
2658            pages += 1;
2659            if pages >= MAX_PAGES {
2660                tracing::warn!(
2661                    installation_id = id,
2662                    pages,
2663                    collected = out.len(),
2664                    "stopped following repository pages at the ceiling; a `Link: rel=next` \
2665                     that never ends would otherwise loop forever"
2666                );
2667                break;
2668            }
2669            next = response
2670                .next_page()
2671                .map(|url| ApiRequest::get(url.as_str()));
2672        }
2673        if let Some(expected) = under_collected(out.len(), total_count) {
2674            tracing::warn!(
2675                installation_id = id,
2676                expected,
2677                collected = out.len(),
2678                "GitHub reported more repositories than pagination collected; this \
2679                 installation's reach is under-reported"
2680            );
2681        }
2682        Ok(out)
2683    }
2684}
2685
2686/// Test support shared by this file and [`device_flow`].
2687///
2688/// It lives inline rather than in `src/testing.rs` on purpose. `a1` laid out
2689/// this crate's five source files — `lib.rs`, `device_flow.rs`, `rest.rs`,
2690/// `demand.rs`, `jit.rs` — and owns every manifest; `c3` and `c4` are working in
2691/// the same directory in parallel, and a new file there is a merge conflict
2692/// waiting to happen for no benefit. An inline `#[cfg(test)]` module is
2693/// reachable as `crate::testing` from every module in the crate and adds nothing
2694/// to a release build.
2695///
2696/// It does not live in `runner-manager-testkit` either, and that one is
2697/// mechanical: `testkit` depends on `runner-manager-github`, so a unit test
2698/// inside this crate that used a `testkit` helper would link a *second* instance
2699/// of this library and the two instances' types would not unify — the same
2700/// hazard `testkit`'s own crate documentation records for `domain`.
2701#[cfg(test)]
2702pub(crate) mod testing {
2703    use super::*;
2704    use serde_json::{Value, json};
2705    use std::sync::{Mutex, atomic::AtomicUsize};
2706    use wiremock::{Request, Respond, ResponseTemplate};
2707
2708    /// Shaped like a real `ghu_` token, and unmistakably not one.
2709    pub const FIXTURE_TOKEN: &str = "ghu_fixtureTOKENnotARealCredential00";
2710    /// Shaped like a real device code, and unmistakably not one.
2711    pub const FIXTURE_DEVICE_CODE: &str = "fixture-device-code-0e37a9c1b4d84f2a";
2712    /// The example user code from RFC 8628.
2713    pub const FIXTURE_USER_CODE: &str = "WDJB-MJHT";
2714
2715    /// A clock the test moves.
2716    ///
2717    /// Deliberately not `runner_manager_testkit::clock::FakeClock`; see this
2718    /// module's documentation for why a `testkit` import is not available here.
2719    #[derive(Debug)]
2720    pub struct TestClock {
2721        now: Mutex<Timestamp>,
2722    }
2723
2724    impl TestClock {
2725        /// # Panics
2726        /// If a previous holder panicked while the lock was held.
2727        pub fn advance_secs(&self, secs: i64) {
2728            let mut now = self.now.lock().expect("TestClock lock poisoned");
2729            *now += chrono::TimeDelta::seconds(secs);
2730        }
2731    }
2732
2733    impl Default for TestClock {
2734        fn default() -> Self {
2735            // 2026-08-21T00:00:00Z, the date this taskflow's decisions were
2736            // locked — the same epoch `testkit`'s clock starts at.
2737            Self {
2738                now: Mutex::new(
2739                    chrono::DateTime::from_timestamp(1_787_270_400, 0).expect("a valid instant"),
2740                ),
2741            }
2742        }
2743    }
2744
2745    impl Clock for TestClock {
2746        fn now(&self) -> Timestamp {
2747            *self.now.lock().expect("TestClock lock poisoned")
2748        }
2749    }
2750
2751    /// A sleeper that records what it was asked to wait and returns at once.
2752    ///
2753    /// This is what turns "`slow_down` demonstrably increases the poll interval"
2754    /// into an equality assertion on a `Vec<Duration>`.
2755    #[derive(Debug, Default)]
2756    pub struct RecordingSleeper {
2757        recorded: Mutex<Vec<Duration>>,
2758    }
2759
2760    impl RecordingSleeper {
2761        /// # Panics
2762        /// If a previous holder panicked while the lock was held.
2763        pub fn recorded(&self) -> Vec<Duration> {
2764            self.recorded.lock().expect("sleeper lock poisoned").clone()
2765        }
2766    }
2767
2768    #[async_trait::async_trait]
2769    impl Sleeper for RecordingSleeper {
2770        async fn sleep(&self, duration: Duration) {
2771            self.recorded
2772                .lock()
2773                .expect("sleeper lock poisoned")
2774                .push(duration);
2775        }
2776    }
2777
2778    /// Answers from a fixed script, one entry per call, repeating the last.
2779    pub struct Script {
2780        responses: Vec<ResponseTemplate>,
2781        calls: AtomicUsize,
2782    }
2783
2784    impl Script {
2785        #[must_use]
2786        pub fn new(responses: Vec<ResponseTemplate>) -> Self {
2787            assert!(
2788                !responses.is_empty(),
2789                "a script needs at least one response"
2790            );
2791            Self {
2792                responses,
2793                calls: AtomicUsize::new(0),
2794            }
2795        }
2796    }
2797
2798    impl Respond for Script {
2799        fn respond(&self, _: &Request) -> ResponseTemplate {
2800            let i = self.calls.fetch_add(1, Ordering::SeqCst);
2801            self.responses[i.min(self.responses.len() - 1)].clone()
2802        }
2803    }
2804
2805    /// `POST https://github.com/login/device/code` → `200`, in the shape both
2806    /// spikes observed (`docs/spikes/d17-spike.ps1`).
2807    #[must_use]
2808    pub fn device_code_body(server_uri: &str, interval: u64, expires_in: u64) -> Value {
2809        json!({
2810            "device_code": FIXTURE_DEVICE_CODE,
2811            "user_code": FIXTURE_USER_CODE,
2812            "verification_uri": format!("{server_uri}/login/device"),
2813            "expires_in": expires_in,
2814            "interval": interval
2815        })
2816    }
2817
2818    /// `POST .../login/oauth/access_token` → `200` with an `error` field, which
2819    /// is how GitHub answers every state in the matrix.
2820    #[must_use]
2821    pub fn error_body(code: &str, interval: Option<u64>) -> Value {
2822        let mut body = json!({
2823            "error": code,
2824            "error_description": "see the OAuth 2.0 Device Authorization Grant",
2825            "error_uri": "https://docs.github.com/developers/apps/authorizing-oauth-apps"
2826        });
2827        if let Some(interval) = interval {
2828            body["interval"] = json!(interval);
2829        }
2830        body
2831    }
2832
2833    /// `POST .../login/oauth/access_token` → `200` with an approved token.
2834    #[must_use]
2835    pub fn token_body() -> Value {
2836        json!({ "access_token": FIXTURE_TOKEN, "token_type": "bearer", "scope": "" })
2837    }
2838
2839    /// `GET /user/installations` → `200`. The permission set is the one D18 read
2840    /// back from the live installation.
2841    #[must_use]
2842    pub fn installations_body(entries: &[(u64, &str, &str, &str)]) -> Value {
2843        let installations: Vec<Value> = entries
2844            .iter()
2845            .map(|(id, login, account_type, selection)| {
2846                json!({
2847                    "id": id,
2848                    "account": { "login": login, "type": account_type },
2849                    "repository_selection": selection,
2850                    "permissions": {
2851                        "actions": "read",
2852                        "administration": "write",
2853                        "metadata": "read",
2854                        "organization_self_hosted_runners": "write"
2855                    }
2856                })
2857            })
2858            .collect();
2859        json!({ "total_count": installations.len(), "installations": installations })
2860    }
2861
2862    /// `GET /user/installations/{id}/repositories` → `200`.
2863    #[must_use]
2864    pub fn repositories_body(full_names: &[&str]) -> Value {
2865        let repositories: Vec<Value> = full_names
2866            .iter()
2867            .map(|full_name| json!({ "full_name": full_name }))
2868            .collect();
2869        json!({ "total_count": repositories.len(), "repositories": repositories })
2870    }
2871
2872    // The `tracing` capture subscriber that used to live here now lives in
2873    // `tests/no_secret_reaches_the_logs.rs`, and the move is the point rather
2874    // than tidying. `tracing` caches a callsite's `Interest` process-wide while
2875    // `with_default` installs a subscriber only on the calling *thread*, so a
2876    // scan running alongside the crate's other unit tests captured nothing but
2877    // its own handful of events and passed with a real device-code leak in the
2878    // flow. A scan that is the only test in its process has no concurrent
2879    // thread to be poisoned by, and no `#[cfg(test)]` module here can offer
2880    // that guarantee.
2881    //
2882    // The blinding is a *concurrency* effect and not a permanent
2883    // first-registration one — see that file's header for the measurement that
2884    // separates the two. The distinction matters here because only the
2885    // concurrency reading implies what this comment concludes: that one test
2886    // per process is the fix.
2887}
2888
2889#[cfg(test)]
2890mod tests {
2891
2892    /// Upgrading must not log anybody out, and the App's expiration setting must
2893    /// be safe to turn on -- or back off -- with hosts mid-way through either.
2894    #[test]
2895    fn both_stored_shapes_load_and_a_pair_survives_a_round_trip() {
2896        // What every host stored before renewal existed: a bare token.
2897        let legacy = UserAccessToken::from_stored_document(&SecretString::from("ghu_legacy123"));
2898        assert_eq!(legacy.secret().expose_secret(), "ghu_legacy123");
2899        assert!(
2900            legacy.renewal().is_none(),
2901            "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"
2902        );
2903
2904        // A pair, written and read back.
2905        let pair = UserAccessToken::new(SecretString::from("ghu_new")).with_renewal(
2906            Some(SecretString::from("ghr_new")),
2907            Some(28_800),
2908            Some(15_897_600),
2909        );
2910        let stored = pair.to_stored_document();
2911        let read = UserAccessToken::from_stored_document(&stored);
2912        assert_eq!(read.secret().expose_secret(), "ghu_new");
2913        let renewal = read.renewal().expect("the pair survives the round trip");
2914        assert_eq!(renewal.refresh_token().expose_secret(), "ghr_new");
2915        assert!(renewal.access_expires_at.is_some());
2916        assert!(renewal.refresh_expires_at.is_some());
2917
2918        // A credential with no renewal still writes the document shape, and
2919        // still reads back as having none.
2920        let bare_round_trip = UserAccessToken::from_stored_document(&legacy.to_stored_document());
2921        assert_eq!(bare_round_trip.secret().expose_secret(), "ghu_legacy123");
2922        assert!(bare_round_trip.renewal().is_none());
2923    }
2924
2925    /// The refresh token is the more dangerous half -- it mints access tokens
2926    /// for six months -- so it must not reach a log through `Debug`.
2927    #[test]
2928    fn a_refresh_token_never_appears_in_debug_output() {
2929        let pair = UserAccessToken::new(SecretString::from("ghu_x")).with_renewal(
2930            Some(SecretString::from("ghr_SUPERSECRET")),
2931            Some(1),
2932            Some(2),
2933        );
2934        let rendered = format!("{:?}", pair.renewal().expect("a renewal"));
2935        assert!(!rendered.contains("ghr_SUPERSECRET"), "{rendered}");
2936        assert!(rendered.contains("redacted"), "{rendered}");
2937    }
2938    use super::*;
2939    use crate::testing::{FIXTURE_TOKEN, Script, TestClock, installations_body, repositories_body};
2940    use serde_json::json;
2941    use wiremock::{
2942        Mock, MockServer, ResponseTemplate,
2943        matchers::{header, method, path},
2944    };
2945
2946    fn client(server: &MockServer, clock: Arc<TestClock>) -> AuthenticatedClient {
2947        AuthenticatedClient::new(
2948            Endpoints::for_test_server(&server.uri()).unwrap(),
2949            UserAccessToken::new(SecretString::from(FIXTURE_TOKEN)),
2950            clock,
2951        )
2952        .unwrap()
2953    }
2954
2955    fn app() -> AppRegistration {
2956        AppRegistration::new("Iv23liTESTCLIENTID", "runner-manager").unwrap()
2957    }
2958
2959    // -- picking up a credential somebody else stored -------------------------
2960
2961    /// A [`CredentialSource`] over a fixed answer, which is what a store looks
2962    /// like from here.
2963    #[derive(Debug)]
2964    struct StoreHolding(Option<&'static str>);
2965
2966    impl CredentialSource for StoreHolding {
2967        fn reload(&self) -> Option<UserAccessToken> {
2968            self.0
2969                .map(|token| UserAccessToken::new(SecretString::from(token)))
2970        }
2971    }
2972
2973    /// The 28-hour failure, as a test: a daemon holding a dead bare token, an
2974    /// operator who signs in, and nothing that tells the daemon.
2975    ///
2976    /// Bare on purpose. A pair would renew and never reach the store at all,
2977    /// which is why renewal alone did not cover this.
2978    #[tokio::test]
2979    async fn a_daemon_picks_up_a_sign_in_that_happened_after_it_started() {
2980        let server = MockServer::start().await;
2981        Mock::given(method("GET"))
2982            .and(path("/repos/acme/app"))
2983            .and(header("authorization", "Bearer ghu_dead"))
2984            .respond_with(ResponseTemplate::new(401))
2985            .expect(1)
2986            .mount(&server)
2987            .await;
2988        Mock::given(method("GET"))
2989            .and(path("/repos/acme/app"))
2990            .and(header("authorization", "Bearer ghu_freshly_signed_in"))
2991            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"id": 1})))
2992            .expect(1)
2993            .mount(&server)
2994            .await;
2995
2996        let client = AuthenticatedClient::new(
2997            Endpoints::for_test_server(&server.uri()).unwrap(),
2998            UserAccessToken::new(SecretString::from("ghu_dead")),
2999            Arc::new(TestClock::default()),
3000        )
3001        .unwrap()
3002        .with_credential_source(Arc::new(StoreHolding(Some("ghu_freshly_signed_in"))));
3003
3004        client
3005            .send(&ApiRequest::get("/repos/acme/app"))
3006            .await
3007            .expect(
3008                "the 401 is retried with what the store holds now, without anybody \n                 restarting the daemon",
3009            );
3010    }
3011
3012    /// The other half, and the reason for the comparison in `reload_once`: a
3013    /// store that still holds the token that just failed is not news.
3014    ///
3015    /// Without the check, every `401` would answer "something changed, retry"
3016    /// and a genuinely revoked credential would spend two requests per poll
3017    /// forever instead of being reported.
3018    #[tokio::test]
3019    async fn a_store_holding_the_same_dead_token_is_not_worth_a_retry() {
3020        let server = MockServer::start().await;
3021        Mock::given(method("GET"))
3022            .and(path("/repos/acme/app"))
3023            .respond_with(ResponseTemplate::new(401))
3024            .expect(1)
3025            .mount(&server)
3026            .await;
3027        // The re-validation probe that runs once reload declines.
3028        Mock::given(method("GET"))
3029            .and(path("/user/installations"))
3030            .respond_with(ResponseTemplate::new(401))
3031            .expect(1)
3032            .mount(&server)
3033            .await;
3034
3035        let client = AuthenticatedClient::new(
3036            Endpoints::for_test_server(&server.uri()).unwrap(),
3037            UserAccessToken::new(SecretString::from("ghu_revoked")),
3038            Arc::new(TestClock::default()),
3039        )
3040        .unwrap()
3041        .with_credential_source(Arc::new(StoreHolding(Some("ghu_revoked"))));
3042
3043        let failure = client
3044            .send(&ApiRequest::get("/repos/acme/app"))
3045            .await
3046            .expect_err("a revoked credential is still revoked when the store agrees");
3047        assert!(
3048            matches!(failure, GithubError::AuthenticationFailed),
3049            "{failure:?}"
3050        );
3051    }
3052
3053    /// An unreadable store leaves the `401` exactly where it was, rather than
3054    /// turning a rejection into a different kind of error.
3055    #[tokio::test]
3056    async fn an_unreadable_store_changes_nothing_about_the_rejection() {
3057        let server = MockServer::start().await;
3058        Mock::given(method("GET"))
3059            .and(path("/repos/acme/app"))
3060            .respond_with(ResponseTemplate::new(401))
3061            .expect(1)
3062            .mount(&server)
3063            .await;
3064        Mock::given(method("GET"))
3065            .and(path("/user/installations"))
3066            .respond_with(ResponseTemplate::new(401))
3067            .expect(1)
3068            .mount(&server)
3069            .await;
3070
3071        let client = AuthenticatedClient::new(
3072            Endpoints::for_test_server(&server.uri()).unwrap(),
3073            UserAccessToken::new(SecretString::from("ghu_revoked")),
3074            Arc::new(TestClock::default()),
3075        )
3076        .unwrap()
3077        .with_credential_source(Arc::new(StoreHolding(None)));
3078
3079        let failure = client
3080            .send(&ApiRequest::get("/repos/acme/app"))
3081            .await
3082            .expect_err("nothing to pick up means the rejection stands");
3083        assert!(
3084            matches!(failure, GithubError::AuthenticationFailed),
3085            "{failure:?}"
3086        );
3087    }
3088
3089    // -- headers ------------------------------------------------------------
3090
3091    #[tokio::test]
3092    async fn every_request_states_its_api_version_and_accept_header() {
3093        let server = MockServer::start().await;
3094        Mock::given(method("GET"))
3095            .and(path("/user/installations"))
3096            .and(header("x-github-api-version", GITHUB_API_VERSION))
3097            .and(header("accept", GITHUB_ACCEPT))
3098            .and(header("authorization", format!("Bearer {FIXTURE_TOKEN}")))
3099            .and(header("user-agent", USER_AGENT))
3100            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3101            .expect(1)
3102            .mount(&server)
3103            .await;
3104
3105        let client = client(&server, Arc::new(TestClock::default()));
3106        client
3107            .send(&ApiRequest::get("/user/installations"))
3108            .await
3109            .expect("the mock only matches when all four headers are present");
3110    }
3111
3112    // -- the 401 path -------------------------------------------------------
3113
3114    #[tokio::test]
3115    async fn a_401_revalidates_once_and_retries_once_then_succeeds() {
3116        let server = MockServer::start().await;
3117        Mock::given(method("GET"))
3118            .and(path("/orgs/acme/actions/runners"))
3119            .respond_with(Script::new(vec![
3120                ResponseTemplate::new(401).set_body_json(json!({"message": "Bad credentials"})),
3121                ResponseTemplate::new(200).set_body_json(json!({"total_count": 0})),
3122            ]))
3123            .expect(2)
3124            .mount(&server)
3125            .await;
3126        Mock::given(method("GET"))
3127            .and(path("/user/installations"))
3128            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3129            .expect(1)
3130            .mount(&server)
3131            .await;
3132
3133        let client = client(&server, Arc::new(TestClock::default()));
3134        let response = client
3135            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3136            .await
3137            .expect("the retry succeeds");
3138
3139        assert_eq!(response.status(), StatusCode::OK);
3140        assert_eq!(
3141            client.revalidations_performed(),
3142            1,
3143            "one 401 must produce exactly one re-validation"
3144        );
3145    }
3146
3147    #[tokio::test]
3148    async fn a_second_401_after_the_retry_is_terminal_authentication_failure() {
3149        let server = MockServer::start().await;
3150        Mock::given(method("GET"))
3151            .and(path("/orgs/acme/actions/runners"))
3152            .respond_with(ResponseTemplate::new(401))
3153            .expect(2)
3154            .mount(&server)
3155            .await;
3156        Mock::given(method("GET"))
3157            .and(path("/user/installations"))
3158            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3159            .mount(&server)
3160            .await;
3161
3162        let client = client(&server, Arc::new(TestClock::default()));
3163        let err = client
3164            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3165            .await
3166            .expect_err("two 401s is terminal");
3167
3168        assert!(matches!(err, GithubError::AuthenticationFailed), "{err:?}");
3169        assert!(err.is_authentication());
3170        assert!(!err.is_lockout());
3171    }
3172
3173    #[tokio::test]
3174    async fn a_rejected_revalidation_fails_without_spending_the_retry() {
3175        let server = MockServer::start().await;
3176        Mock::given(method("GET"))
3177            .and(path("/orgs/acme/actions/runners"))
3178            .respond_with(ResponseTemplate::new(401))
3179            // Exactly one: a credential GitHub has confirmed dead must not be
3180            // used for a retry.
3181            .expect(1)
3182            .mount(&server)
3183            .await;
3184        Mock::given(method("GET"))
3185            .and(path("/user/installations"))
3186            .respond_with(ResponseTemplate::new(401))
3187            .expect(1)
3188            .mount(&server)
3189            .await;
3190
3191        let client = client(&server, Arc::new(TestClock::default()));
3192        let err = client
3193            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3194            .await
3195            .expect_err("the credential is dead");
3196        assert!(matches!(err, GithubError::AuthenticationFailed), "{err:?}");
3197    }
3198
3199    /// The Definition of Done's concurrency claim, tested with real concurrent
3200    /// callers on a multi-threaded runtime rather than by reasoning about the
3201    /// mutex.
3202    ///
3203    /// Two things make the assertion deterministic rather than lucky. A barrier
3204    /// releases all eight callers into `send` together, so all eight take their
3205    /// `401` before any of them reaches the gate; and the re-validation endpoint
3206    /// is delayed, so the first caller still holds the gate while the other
3207    /// seven sample the generation counter. Without the delay a caller could
3208    /// legitimately arrive after the first re-validation completed, which is a
3209    /// *new* `401` storm and correctly earns its own attempt.
3210    #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
3211    async fn eight_concurrent_401s_produce_one_revalidation_not_eight() {
3212        const CALLERS: usize = 8;
3213
3214        let server = MockServer::start().await;
3215        Mock::given(method("GET"))
3216            .and(path("/orgs/acme/actions/runners"))
3217            .respond_with(ResponseTemplate::new(401))
3218            .mount(&server)
3219            .await;
3220        Mock::given(method("GET"))
3221            .and(path("/user/installations"))
3222            .respond_with(
3223                ResponseTemplate::new(200)
3224                    .set_body_json(installations_body(&[]))
3225                    .set_delay(Duration::from_millis(250)),
3226            )
3227            .expect(1)
3228            .mount(&server)
3229            .await;
3230
3231        let client = Arc::new(client(&server, Arc::new(TestClock::default())));
3232        let barrier = Arc::new(tokio::sync::Barrier::new(CALLERS));
3233        let mut tasks = Vec::new();
3234        for _ in 0..CALLERS {
3235            let client = Arc::clone(&client);
3236            let barrier = Arc::clone(&barrier);
3237            tasks.push(tokio::spawn(async move {
3238                barrier.wait().await;
3239                client
3240                    .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3241                    .await
3242                    .expect_err("every caller sees a dead endpoint")
3243            }));
3244        }
3245
3246        let mut outcomes = Vec::new();
3247        for task in tasks {
3248            outcomes.push(task.await.expect("no caller panicked"));
3249        }
3250
3251        assert_eq!(outcomes.len(), CALLERS);
3252        for err in &outcomes {
3253            assert!(matches!(err, GithubError::AuthenticationFailed), "{err:?}");
3254        }
3255        assert_eq!(
3256            client.revalidations_performed(),
3257            1,
3258            "{CALLERS} concurrent 401s must produce ONE attempt, not {CALLERS}"
3259        );
3260
3261        // The same claim, measured from the server rather than from our own
3262        // counter: the mock's `.expect(1)` is verified when the server drops.
3263        let seen = server.received_requests().await.expect("recording is on");
3264        let probes = seen
3265            .iter()
3266            .filter(|r| r.url.path() == "/user/installations")
3267            .count();
3268        assert_eq!(probes, 1, "GitHub itself saw exactly one re-validation");
3269        let attempts = seen
3270            .iter()
3271            .filter(|r| r.url.path() == "/orgs/acme/actions/runners")
3272            .count();
3273        assert_eq!(
3274            attempts,
3275            CALLERS * 2,
3276            "each caller still gets its own single retry"
3277        );
3278    }
3279
3280    // -- the 403 path -------------------------------------------------------
3281
3282    #[tokio::test]
3283    async fn a_403_after_401s_is_a_lockout_and_not_an_authentication_failure() {
3284        let server = MockServer::start().await;
3285        Mock::given(method("GET"))
3286            .and(path("/orgs/acme/actions/runners"))
3287            .respond_with(Script::new(vec![
3288                ResponseTemplate::new(401),
3289                ResponseTemplate::new(403).insert_header("retry-after", "42"),
3290            ]))
3291            .mount(&server)
3292            .await;
3293        Mock::given(method("GET"))
3294            .and(path("/user/installations"))
3295            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3296            .mount(&server)
3297            .await;
3298
3299        let client = client(&server, Arc::new(TestClock::default()));
3300        let err = client
3301            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3302            .await
3303            .expect_err("403 after a 401");
3304
3305        match err {
3306            GithubError::AuthenticationLockout { retry_after } => {
3307                assert_eq!(retry_after, Duration::from_secs(42), "honours retry-after");
3308            }
3309            other => panic!("expected a lockout, got {other:?}"),
3310        }
3311        assert!(client.is_locked_out());
3312    }
3313
3314    #[tokio::test]
3315    async fn a_403_with_no_preceding_401_is_a_permissions_answer_not_a_lockout() {
3316        let server = MockServer::start().await;
3317        Mock::given(method("GET"))
3318            .and(path("/orgs/acme/actions/runners"))
3319            .respond_with(
3320                ResponseTemplate::new(403)
3321                    .set_body_json(json!({"message": "Resource not accessible by integration"})),
3322            )
3323            .mount(&server)
3324            .await;
3325
3326        let client = client(&server, Arc::new(TestClock::default()));
3327        let err = client
3328            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3329            .await
3330            .expect_err("403");
3331
3332        assert!(matches!(err, GithubError::Forbidden { .. }), "{err:?}");
3333        assert!(!err.is_lockout());
3334        assert!(!err.is_authentication());
3335        assert!(!client.is_locked_out(), "a permissions 403 must not latch");
3336    }
3337
3338    #[tokio::test]
3339    async fn a_locked_out_client_issues_no_further_http_until_the_backoff_elapses() {
3340        let server = MockServer::start().await;
3341        Mock::given(method("GET"))
3342            .and(path("/orgs/acme/actions/runners"))
3343            .respond_with(Script::new(vec![
3344                ResponseTemplate::new(401),
3345                ResponseTemplate::new(403).insert_header("retry-after", "60"),
3346                ResponseTemplate::new(200).set_body_json(json!({"total_count": 0})),
3347            ]))
3348            .mount(&server)
3349            .await;
3350        Mock::given(method("GET"))
3351            .and(path("/user/installations"))
3352            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3353            .mount(&server)
3354            .await;
3355
3356        let clock = Arc::new(TestClock::default());
3357        let client = client(&server, Arc::clone(&clock));
3358        let request = ApiRequest::get("/orgs/acme/actions/runners");
3359
3360        let err = client.send(&request).await.expect_err("locks out");
3361        assert!(err.is_lockout(), "{err:?}");
3362
3363        let after_lockout = server.received_requests().await.unwrap().len();
3364
3365        for _ in 0..3 {
3366            let err = client.send(&request).await.expect_err("still locked out");
3367            assert!(err.is_lockout(), "{err:?}");
3368        }
3369        assert_eq!(
3370            server.received_requests().await.unwrap().len(),
3371            after_lockout,
3372            "a backed-off client must open no sockets at all"
3373        );
3374
3375        clock.advance_secs(61);
3376        assert!(!client.is_locked_out(), "the back-off expires on the clock");
3377        let response = client.send(&request).await.expect("traffic resumes");
3378        assert_eq!(response.status(), StatusCode::OK);
3379        assert_eq!(
3380            server.received_requests().await.unwrap().len(),
3381            after_lockout + 1
3382        );
3383    }
3384
3385    /// `consecutive_unauthorized` is reset only by a successful *caller*
3386    /// response, so a request ending in `404`, `422` or `5xx` leaves it set —
3387    /// and in the agent's long-lived reconciliation loop it stays set for as
3388    /// long as nothing succeeds. Before the fix, the next genuine permissions
3389    /// `403` was therefore reported as `AuthenticationLockout`: sixty seconds of
3390    /// client silence, plus an operator message asserting "the credential itself
3391    /// is not the problem" about a credential that was missing
3392    /// `Administration: write` — the failure `04-subsystem-contracts.md` names
3393    /// as the *expected* one for `generate-jitconfig`.
3394    ///
3395    /// The lockout's real signature is narrower: a `403` on the one retry this
3396    /// client issues after this request's own `401`, or a `403` whose own
3397    /// headers and body say GitHub is continuing a lockout. Neither is "the
3398    /// count is non-zero", which is what a stale `401` leaves behind — so the
3399    /// permissions `403` below is a permissions answer whatever happened minutes
3400    /// ago, and it is the *response*, not the history, that decides.
3401    #[tokio::test]
3402    async fn a_stale_401_does_not_turn_a_later_permissions_403_into_a_lockout() {
3403        let server = MockServer::start().await;
3404        // The first request ends in a 404, which leaves the 401 count set
3405        // because only a 2xx clears it.
3406        Mock::given(method("GET"))
3407            .and(path("/orgs/acme/actions/runners"))
3408            .respond_with(Script::new(vec![
3409                ResponseTemplate::new(401),
3410                ResponseTemplate::new(404).set_body_json(json!({"message": "Not Found"})),
3411            ]))
3412            .mount(&server)
3413            .await;
3414        Mock::given(method("GET"))
3415            .and(path("/user/installations"))
3416            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3417            .mount(&server)
3418            .await;
3419        // Minutes later, a different call is denied for a missing permission.
3420        Mock::given(method("POST"))
3421            .and(path("/orgs/acme/actions/runners/generate-jitconfig"))
3422            .respond_with(
3423                ResponseTemplate::new(403)
3424                    .set_body_json(json!({"message": "Resource not accessible by integration"})),
3425            )
3426            .mount(&server)
3427            .await;
3428
3429        let client = client(&server, Arc::new(TestClock::default()));
3430        let err = client
3431            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3432            .await
3433            .expect_err("404");
3434        assert!(
3435            matches!(err, GithubError::Status { status: 404, .. }),
3436            "{err:?}"
3437        );
3438
3439        let err = client
3440            .send(&ApiRequest::new(
3441                Method::POST,
3442                "/orgs/acme/actions/runners/generate-jitconfig",
3443            ))
3444            .await
3445            .expect_err("403");
3446
3447        assert!(
3448            matches!(err, GithubError::Forbidden { .. }),
3449            "a fresh first-attempt 403 is a permissions answer, not a lockout: {err:?}"
3450        );
3451        assert!(!err.is_lockout());
3452        assert!(
3453            !client.is_locked_out(),
3454            "a stale 401 must not be able to silence the client for a minute"
3455        );
3456    }
3457
3458    /// GitHub's own rate limit is not an answer about the credential, and must
3459    /// not be reported as one. `classify` reached the `403` branch before
3460    /// anything looked at the rate-limit headers, so a primary rate limit
3461    /// arriving during a `401` storm was announced as an authentication lockout
3462    /// with the message "the credential itself is not the problem" — about a
3463    /// response that never mentioned the credential.
3464    #[tokio::test]
3465    async fn a_rate_limited_403_is_not_reported_as_an_authentication_lockout() {
3466        let server = MockServer::start().await;
3467        Mock::given(method("GET"))
3468            .and(path("/orgs/acme/actions/runners"))
3469            .respond_with(Script::new(vec![
3470                ResponseTemplate::new(401),
3471                ResponseTemplate::new(403)
3472                    .insert_header("x-ratelimit-remaining", "0")
3473                    .insert_header("x-ratelimit-reset", "1787270460")
3474                    .insert_header("retry-after", "30")
3475                    .set_body_json(json!({"message": "API rate limit exceeded"})),
3476            ]))
3477            .mount(&server)
3478            .await;
3479        Mock::given(method("GET"))
3480            .and(path("/user/installations"))
3481            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3482            .mount(&server)
3483            .await;
3484
3485        let client = client(&server, Arc::new(TestClock::default()));
3486        let err = client
3487            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3488            .await
3489            .expect_err("rate limited");
3490
3491        assert!(
3492            matches!(err, GithubError::Forbidden { .. }),
3493            "a rate limit is not an authentication outcome: {err:?}"
3494        );
3495        assert!(!err.is_lockout());
3496        assert!(!err.is_authentication());
3497        assert!(
3498            !client.is_locked_out(),
3499            "a rate limit must not latch this crate's authentication back-off"
3500        );
3501
3502        // And `c3` gets the evidence it needs to apply the policy that is its
3503        // own, without editing this file.
3504        let evidence = err
3505            .rate_limit()
3506            .expect("the headers survived classification");
3507        assert_eq!(evidence.remaining, Some(0));
3508        assert_eq!(evidence.reset_unix_secs, Some(1_787_270_460));
3509        assert_eq!(evidence.retry_after, Some(Duration::from_secs(30)));
3510    }
3511
3512    /// The same claim for the variant `429` lands in.
3513    #[tokio::test]
3514    async fn a_429_carries_its_retry_after_across_the_c2_c3_seam() {
3515        let server = MockServer::start().await;
3516        Mock::given(method("GET"))
3517            .and(path("/orgs/acme/actions/runners"))
3518            .respond_with(
3519                ResponseTemplate::new(429)
3520                    .insert_header("retry-after", "17")
3521                    .insert_header("x-ratelimit-remaining", "0")
3522                    .set_body_json(json!({"message": "You have exceeded a secondary rate limit"})),
3523            )
3524            .mount(&server)
3525            .await;
3526
3527        let client = client(&server, Arc::new(TestClock::default()));
3528        let err = client
3529            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3530            .await
3531            .expect_err("429");
3532
3533        assert!(
3534            matches!(err, GithubError::Status { status: 429, .. }),
3535            "{err:?}"
3536        );
3537        assert_eq!(
3538            err.retry_after(),
3539            Some(Duration::from_secs(17)),
3540            "destroying this header is what made `c3`'s Definition of Done unmeetable"
3541        );
3542        assert_eq!(
3543            err.headers().and_then(|h| h.get("x-ratelimit-remaining")),
3544            Some(&reqwest::header::HeaderValue::from_static("0"))
3545        );
3546    }
3547
3548    /// A back-off is a safety mechanism, and this one had both failure modes at
3549    /// once: no ceiling, so `Retry-After: 86400` latched a silent twenty-four
3550    /// hour outage; and `TimeDelta::from_std(...).ok()` on a value too large to
3551    /// convert, which yielded `until = None` — *not locked out at all*, the
3552    /// exact inverse of the requirement, reachable by a header alone.
3553    #[tokio::test]
3554    async fn an_extreme_retry_after_is_clamped_and_never_fails_open() {
3555        async fn lockout_for(header: &str) -> (GithubError, bool, Option<Duration>) {
3556            let server = MockServer::start().await;
3557            Mock::given(method("GET"))
3558                .and(path("/orgs/acme/actions/runners"))
3559                .respond_with(Script::new(vec![
3560                    ResponseTemplate::new(401),
3561                    ResponseTemplate::new(403).insert_header("retry-after", header),
3562                ]))
3563                .mount(&server)
3564                .await;
3565            Mock::given(method("GET"))
3566                .and(path("/user/installations"))
3567                .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3568                .mount(&server)
3569                .await;
3570
3571            let client = AuthenticatedClient::new(
3572                Endpoints::for_test_server(&server.uri()).unwrap(),
3573                UserAccessToken::new(SecretString::from(FIXTURE_TOKEN)),
3574                Arc::new(TestClock::default()),
3575            )
3576            .unwrap();
3577            let err = client
3578                .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3579                .await
3580                .expect_err("403 after a 401");
3581            let locked = client.is_locked_out();
3582            let remaining = client.lockout_remaining();
3583            (err, locked, remaining)
3584        }
3585
3586        // A day-long back-off is clamped to the ceiling.
3587        let (err, locked, remaining) = lockout_for("86400").await;
3588        let GithubError::AuthenticationLockout { retry_after } = &err else {
3589            panic!("expected a lockout, got {err:?}");
3590        };
3591        assert_eq!(
3592            *retry_after, MAX_LOCKOUT_BACKOFF,
3593            "an unclamped Retry-After lets a remote party decide how long this product \
3594             stays down"
3595        );
3596        assert!(locked);
3597        assert!(remaining.is_some_and(|r| r <= MAX_LOCKOUT_BACKOFF));
3598
3599        // A value too large for `chrono` must still lock out. Before the fix
3600        // this produced `until = None`: the more extreme the header, the less
3601        // protection it bought.
3602        let (err, locked, remaining) = lockout_for(&u64::MAX.to_string()).await;
3603        assert!(err.is_lockout(), "{err:?}");
3604        assert!(
3605            locked,
3606            "an absurd Retry-After must not mean `not locked out at all` — that fails open"
3607        );
3608        assert!(remaining.is_some_and(|r| r <= MAX_LOCKOUT_BACKOFF));
3609    }
3610
3611    /// The lockout's own contract is "this client issues no HTTP at all", and
3612    /// `revalidate` is HTTP. It documented an `AuthenticationLockout` it could
3613    /// never return, which made the one direct entry point into the probe the
3614    /// single exception to the rule.
3615    #[tokio::test]
3616    async fn a_direct_revalidation_is_refused_while_the_lockout_is_backing_off() {
3617        let server = MockServer::start().await;
3618        Mock::given(method("GET"))
3619            .and(path("/orgs/acme/actions/runners"))
3620            .respond_with(Script::new(vec![
3621                ResponseTemplate::new(401),
3622                ResponseTemplate::new(403).insert_header("retry-after", "60"),
3623            ]))
3624            .mount(&server)
3625            .await;
3626        Mock::given(method("GET"))
3627            .and(path("/user/installations"))
3628            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3629            .mount(&server)
3630            .await;
3631
3632        let client = client(&server, Arc::new(TestClock::default()));
3633        client
3634            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3635            .await
3636            .expect_err("locks out");
3637        assert!(client.is_locked_out());
3638
3639        let before = server.received_requests().await.unwrap().len();
3640        let err = client
3641            .revalidate()
3642            .await
3643            .expect_err("the documented lockout error is now reachable");
3644        assert!(err.is_lockout(), "{err:?}");
3645        assert_eq!(
3646            server.received_requests().await.unwrap().len(),
3647            before,
3648            "a locked-out client opens no socket, and the probe is not an exception"
3649        );
3650    }
3651
3652    /// The position rule fixed `classify` and left the same defect one function
3653    /// over, behind a comment asserting it could not happen: "the probe only
3654    /// ever runs after a `401`, so it is always in the retry position". Making
3655    /// [`AuthenticatedClient::revalidate`] public — the previous round's own
3656    /// change — is exactly what made that untrue.
3657    ///
3658    /// The sequence is the agent's, not a contrivance. A request 401s, the probe
3659    /// says the credential is fine, the retry answers `404` — which does *not*
3660    /// reset the counter, by design. Minutes later `f1` renders `auth status`,
3661    /// which probes directly, and the probe meets an ordinary permissions `403`.
3662    /// A stale `401` then latched a sixty-second client-wide lockout and told
3663    /// the operator to wait, when the real answer was a missing grant.
3664    #[tokio::test]
3665    async fn a_directly_requested_probe_does_not_latch_a_lockout_from_a_stale_401() {
3666        let server = MockServer::start().await;
3667        Mock::given(method("GET"))
3668            .and(path("/orgs/acme/actions/runners"))
3669            .respond_with(Script::new(vec![
3670                ResponseTemplate::new(401),
3671                // The retry misses. A `404` leaves `consecutive_unauthorized`
3672                // set, which is the whole premise of the position rule.
3673                ResponseTemplate::new(404).set_body_json(json!({"message": "Not Found"})),
3674            ]))
3675            .mount(&server)
3676            .await;
3677        Mock::given(method("GET"))
3678            .and(path("/user/installations"))
3679            .respond_with(Script::new(vec![
3680                // The probe that accompanies the 401 above.
3681                ResponseTemplate::new(200).set_body_json(installations_body(&[])),
3682                // The direct probe, minutes later: a plain permissions answer,
3683                // with no `retry-after` and a message that names a grant.
3684                ResponseTemplate::new(403)
3685                    .set_body_json(json!({"message": "Resource not accessible by integration"})),
3686            ]))
3687            .mount(&server)
3688            .await;
3689
3690        let clock = Arc::new(TestClock::default());
3691        let client = client(&server, clock.clone());
3692        client
3693            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3694            .await
3695            .expect_err("the retry 404s");
3696        assert!(
3697            !client.is_locked_out(),
3698            "a 404 on the retry is not a lockout"
3699        );
3700
3701        clock.advance_secs(300);
3702        let outcome = client
3703            .revalidate()
3704            .await
3705            .expect("a direct probe is not a lockout error");
3706
3707        assert_eq!(
3708            outcome,
3709            Revalidation::Unavailable,
3710            "a 403 on the probe teaches this client nothing about the credential"
3711        );
3712        assert!(
3713            !client.is_locked_out(),
3714            "a caller-initiated probe is a *first* attempt, not the retry that follows a 401: \
3715             latching here converts a stale 401 into a 60-second client-wide outage and \
3716             reports a missing permission as `the credential is fine, please wait`"
3717        );
3718        assert_eq!(client.lockout_remaining(), None);
3719    }
3720
3721    /// The square the other three leave empty, and the one where a defect in the
3722    /// composition would hide.
3723    ///
3724    /// Covered elsewhere: a first-attempt continuation through `send`, a
3725    /// first-attempt permissions `403` through `send`, and a direct probe
3726    /// meeting a permissions `403` (immediately above). A direct probe meeting a
3727    /// *continuation-shaped* `403` is the fourth square, and it is the
3728    /// composition point of the two rules that pull in opposite directions —
3729    /// the narrowing to `Attempt::First` that fixed the stale-`401` lockout, and
3730    /// the continuation rule that re-widens `First` on GitHub's own evidence.
3731    ///
3732    /// If the narrowing swallowed the continuation here, every other test in
3733    /// this file would still pass, and `f1`'s `auth status` would poll a
3734    /// credential GitHub had asked it to leave alone — reporting each refusal as
3735    /// a missing grant.
3736    #[tokio::test]
3737    async fn a_directly_requested_probe_latches_a_continuation_shaped_lockout() {
3738        let server = MockServer::start().await;
3739        Mock::given(method("GET"))
3740            .and(path("/user/installations"))
3741            // The continuation's signature: `retry-after`, and a body with no
3742            // message for `error_message` to find.
3743            .respond_with(ResponseTemplate::new(403).insert_header("retry-after", "60"))
3744            .mount(&server)
3745            .await;
3746
3747        let client = client(&server, Arc::new(TestClock::default()));
3748
3749        // No preceding traffic whatsoever: a first attempt in the strongest
3750        // sense, which is exactly the position the narrowed rule refused to
3751        // latch in.
3752        let err = client
3753            .revalidate()
3754            .await
3755            .expect_err("a probe that latches a lockout reports it rather than `Unavailable`");
3756        assert!(
3757            err.is_lockout(),
3758            "`revalidate` latched a client-wide lockout and must say so; answering \
3759             `Ok(Unavailable)` leaves `f1` to discover a 15-minute outage through a separate \
3760             `is_locked_out()` call it has no reason to make: {err:?}"
3761        );
3762        assert!(
3763            client.is_locked_out(),
3764            "a 403 carrying `retry-after` with no message is GitHub continuing a lockout, \
3765             whoever asked for the request that met it"
3766        );
3767        assert_eq!(client.lockout_remaining(), Some(Duration::from_secs(60)));
3768
3769        // And the back-off is real, not just a renamed error.
3770        let before = server.received_requests().await.unwrap().len();
3771        let err = client.revalidate().await.expect_err("still locked out");
3772        assert!(err.is_lockout(), "{err:?}");
3773        assert_eq!(
3774            server.received_requests().await.unwrap().len(),
3775            before,
3776            "latching must actually stop traffic"
3777        );
3778    }
3779
3780    /// [`retry_after`] parses integer seconds only; RFC 9110 §10.2.3 also
3781    /// permits an HTTP-date. Detection used to gate on that parse succeeding, so
3782    /// a date-form `Retry-After` was not recognised as a continuation at all and
3783    /// the hole the continuation rule exists to close reopened for that shape —
3784    /// silently, because the response leaves as an ordinary `Forbidden`.
3785    ///
3786    /// GitHub sends integer seconds in practice. This pins the crate to not
3787    /// depending on that, and records where the two halves part company:
3788    /// presence decides *whether* it is a lockout, the integer parse decides
3789    /// only *how long*, and `latch_lockout` already had a default for the header
3790    /// it could not read.
3791    #[tokio::test]
3792    async fn a_date_form_retry_after_is_still_recognised_as_a_continuation() {
3793        let server = MockServer::start().await;
3794        Mock::given(method("GET"))
3795            .and(path("/user/installations"))
3796            .respond_with(
3797                ResponseTemplate::new(403)
3798                    .insert_header("retry-after", "Wed, 21 Oct 2026 07:28:00 GMT"),
3799            )
3800            .mount(&server)
3801            .await;
3802
3803        let client = client(&server, Arc::new(TestClock::default()));
3804        let err = client
3805            .revalidate()
3806            .await
3807            .expect_err("a date-form `retry-after` is still GitHub asking to be left alone");
3808        assert!(
3809            err.is_lockout(),
3810            "gating detection on an integer parse hands the continuation bug back for every \
3811             lockout GitHub chose to date-stamp: {err:?}"
3812        );
3813        assert_eq!(
3814            client.lockout_remaining(),
3815            Some(DEFAULT_LOCKOUT_BACKOFF),
3816            "the date form is recognised for detection; the duration falls back to the \
3817             default, which is what `latch_lockout` already did with a header it could not \
3818             parse as seconds"
3819        );
3820    }
3821
3822    /// The narrowing that fixed the stale-`401` lockout opened a hole at the
3823    /// other end of the same back-off.
3824    ///
3825    /// While GitHub is still locking the credential out after the back-off
3826    /// elapses, the next request is a *first* attempt by construction — this
3827    /// client's own retry never happened, because the request never reached the
3828    /// wire. So the position rule declined to call it a lockout and `classify`
3829    /// fell through to [`GithubError::Forbidden`], whose documented reading is
3830    /// "the App installation does not grant it". The client then stopped backing
3831    /// off entirely and hammered a credential GitHub had asked it to leave
3832    /// alone, which is the exact inverse of "backs off without retrying".
3833    ///
3834    /// A continuation is distinguishable from a permissions answer without any
3835    /// counter: GitHub sends `retry-after` and no message body for the lockout,
3836    /// and a message and no `retry-after` for a permissions refusal.
3837    #[tokio::test]
3838    async fn a_lockout_outliving_its_backoff_re_latches_instead_of_reporting_a_permissions_answer()
3839    {
3840        let server = MockServer::start().await;
3841        Mock::given(method("GET"))
3842            .and(path("/orgs/acme/actions/runners"))
3843            .respond_with(Script::new(vec![
3844                ResponseTemplate::new(401),
3845                // The retry: the lockout latches here, in the retry position.
3846                ResponseTemplate::new(403).insert_header("retry-after", "60"),
3847                // The continuation, once the back-off has elapsed. Same shape,
3848                // first position.
3849                ResponseTemplate::new(403).insert_header("retry-after", "60"),
3850            ]))
3851            .mount(&server)
3852            .await;
3853        Mock::given(method("GET"))
3854            .and(path("/user/installations"))
3855            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
3856            .mount(&server)
3857            .await;
3858
3859        let clock = Arc::new(TestClock::default());
3860        let client = client(&server, clock.clone());
3861        let err = client
3862            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3863            .await
3864            .expect_err("403 on the retry");
3865        assert!(err.is_lockout(), "{err:?}");
3866        assert!(client.is_locked_out());
3867
3868        // The back-off elapses with GitHub unchanged.
3869        clock.advance_secs(61);
3870        assert!(!client.is_locked_out(), "the back-off has run out");
3871
3872        let err = client
3873            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3874            .await
3875            .expect_err("GitHub is still locking the credential out");
3876
3877        assert!(
3878            err.is_lockout(),
3879            "a 403 carrying `retry-after` with no message is GitHub continuing the lockout, \
3880             not the App installation refusing a permission; reporting `Forbidden` here \
3881             tells the operator to fix a grant that is not missing: {err:?}"
3882        );
3883        assert!(
3884            client.is_locked_out(),
3885            "`backs off without retrying` fails for any lockout that outlives one back-off \
3886             if the continuation does not re-latch"
3887        );
3888        let GithubError::AuthenticationLockout { retry_after } = err else {
3889            unreachable!("asserted above")
3890        };
3891        assert_eq!(
3892            retry_after,
3893            Duration::from_secs(60),
3894            "the continuation's own `retry-after` sets the new back-off"
3895        );
3896
3897        // And the next request is suppressed before a socket is opened, which is
3898        // the property the whole back-off exists for.
3899        let before = server.received_requests().await.unwrap().len();
3900        let err = client
3901            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3902            .await
3903            .expect_err("still locked out");
3904        assert!(err.is_lockout(), "{err:?}");
3905        assert_eq!(
3906            server.received_requests().await.unwrap().len(),
3907            before,
3908            "re-latching must actually stop traffic, not merely rename the error"
3909        );
3910    }
3911
3912    /// A permissions `403` on a first attempt is still a permissions answer, and
3913    /// the continuation rule above must not swallow it. This is the test that
3914    /// keeps that rule from becoming "every 403 is a lockout".
3915    #[tokio::test]
3916    async fn a_first_attempt_permissions_403_is_still_reported_as_forbidden() {
3917        let server = MockServer::start().await;
3918        Mock::given(method("GET"))
3919            .and(path("/orgs/acme/actions/runners"))
3920            .respond_with(
3921                ResponseTemplate::new(403)
3922                    .set_body_json(json!({"message": "Resource not accessible by integration"})),
3923            )
3924            .mount(&server)
3925            .await;
3926
3927        let client = client(&server, Arc::new(TestClock::default()));
3928        let err = client
3929            .send(&ApiRequest::get("/orgs/acme/actions/runners"))
3930            .await
3931            .expect_err("403");
3932
3933        assert!(
3934            matches!(err, GithubError::Forbidden { .. }),
3935            "a message and no `retry-after` is GitHub naming a missing grant: {err:?}"
3936        );
3937        assert!(!client.is_locked_out());
3938    }
3939
3940    /// The `consecutive_unauthorized > 0` conjunct that used to sit alongside
3941    /// the position rule added no signal — `Attempt::Retry` already implies this
3942    /// request's own `401` incremented the counter — and added a fail-open race:
3943    /// any concurrent success `store(0)`s the counter between the `401` and the
3944    /// retry, and a real lockout is then reported as a permissions answer.
3945    ///
3946    /// The race is driven directly rather than by scheduling two requests and
3947    /// hoping: `store(0)` is the *only* thing the concurrent success contributes,
3948    /// so performing it between the `401` and the classification reproduces the
3949    /// race deterministically and on every run.
3950    #[tokio::test]
3951    async fn a_concurrent_success_cannot_downgrade_a_lockout_to_a_permissions_answer() {
3952        let server = MockServer::start().await;
3953        let client = client(&server, Arc::new(TestClock::default()));
3954
3955        // This request's own 401 has landed: the retry position is established.
3956        client
3957            .consecutive_unauthorized
3958            .fetch_add(1, Ordering::SeqCst);
3959        // ... and a request on another task succeeds in the same instant.
3960        client.consecutive_unauthorized.store(0, Ordering::SeqCst);
3961
3962        let mut headers = HeaderMap::new();
3963        headers.insert("retry-after", "60".parse().unwrap());
3964        let lockout = ApiResponse {
3965            status: StatusCode::FORBIDDEN,
3966            headers,
3967            body: Vec::new(),
3968        };
3969
3970        assert!(
3971            client.is_lockout_403(&lockout, Attempt::Retry),
3972            "`Attempt::Retry` already means this request's own 401 incremented the counter, so \
3973             reading the counter again adds no signal and only lets an unrelated success \
3974             downgrade a real lockout to `Forbidden`"
3975        );
3976
3977        // The counter must stay irrelevant in the other direction too: a
3978        // permissions `403` on a first attempt is not a lockout however many
3979        // `401`s are on the count.
3980        client.consecutive_unauthorized.store(7, Ordering::SeqCst);
3981        let permissions = ApiResponse {
3982            status: StatusCode::FORBIDDEN,
3983            headers: HeaderMap::new(),
3984            body: br#"{"message":"Resource not accessible by integration"}"#.to_vec(),
3985        };
3986        assert!(!client.is_lockout_403(&permissions, Attempt::First));
3987    }
3988
3989    // -- installation discovery ---------------------------------------------
3990
3991    #[tokio::test]
3992    async fn discovery_returns_the_reachable_repository_and_organization_set() {
3993        let server = MockServer::start().await;
3994        Mock::given(method("GET"))
3995            .and(path("/user/installations"))
3996            .respond_with(
3997                ResponseTemplate::new(200).set_body_json(installations_body(&[
3998                    (11, "IvanMurzak", "User", "selected"),
3999                    (22, "Tap-Top-Fun", "Organization", "all"),
4000                ])),
4001            )
4002            .mount(&server)
4003            .await;
4004        Mock::given(method("GET"))
4005            .and(path("/user/installations/11/repositories"))
4006            .respond_with(
4007                ResponseTemplate::new(200)
4008                    .set_body_json(repositories_body(&["IvanMurzak/GitHub-Runner-Scaler-UI"])),
4009            )
4010            .mount(&server)
4011            .await;
4012        Mock::given(method("GET"))
4013            .and(path("/user/installations/22/repositories"))
4014            .respond_with(
4015                ResponseTemplate::new(200)
4016                    .set_body_json(repositories_body(&["Tap-Top-Fun/game", "Tap-Top-Fun/site"])),
4017            )
4018            .mount(&server)
4019            .await;
4020
4021        let client = client(&server, Arc::new(TestClock::default()));
4022        let discovery = client.discover_installations(&app()).await.unwrap();
4023
4024        let targets = discovery.targets().expect("installed");
4025        assert_eq!(
4026            targets
4027                .repositories()
4028                .iter()
4029                .map(ToString::to_string)
4030                .collect::<Vec<_>>(),
4031            [
4032                "IvanMurzak/GitHub-Runner-Scaler-UI",
4033                "Tap-Top-Fun/game",
4034                "Tap-Top-Fun/site"
4035            ]
4036        );
4037        assert_eq!(
4038            targets
4039                .organizations()
4040                .iter()
4041                .map(ToString::to_string)
4042                .collect::<Vec<_>>(),
4043            ["Tap-Top-Fun"],
4044            "a User account is not an organization target"
4045        );
4046        assert!(discovery.install_url().is_none());
4047    }
4048
4049    #[tokio::test]
4050    async fn an_over_broad_installation_is_visible_rather_than_assumed() {
4051        let server = MockServer::start().await;
4052        Mock::given(method("GET"))
4053            .and(path("/user/installations"))
4054            .respond_with(
4055                ResponseTemplate::new(200).set_body_json(installations_body(&[
4056                    (11, "IvanMurzak", "User", "selected"),
4057                    (22, "Tap-Top-Fun", "Organization", "all"),
4058                ])),
4059            )
4060            .mount(&server)
4061            .await;
4062        Mock::given(method("GET"))
4063            .and(path("/user/installations/11/repositories"))
4064            .respond_with(ResponseTemplate::new(200).set_body_json(repositories_body(&["a/b"])))
4065            .mount(&server)
4066            .await;
4067        Mock::given(method("GET"))
4068            .and(path("/user/installations/22/repositories"))
4069            .respond_with(ResponseTemplate::new(200).set_body_json(repositories_body(&["c/d"])))
4070            .mount(&server)
4071            .await;
4072
4073        let client = client(&server, Arc::new(TestClock::default()));
4074        let targets = client
4075            .discover_installations(&app())
4076            .await
4077            .unwrap()
4078            .targets()
4079            .cloned()
4080            .expect("installed");
4081
4082        let over_broad = targets.over_broad();
4083        assert_eq!(over_broad.len(), 1);
4084        assert_eq!(over_broad[0].account.login(), "Tap-Top-Fun");
4085        assert!(over_broad[0].is_over_broad());
4086        assert_eq!(
4087            over_broad[0].repository_selection,
4088            RepositorySelection::All,
4089            "`repository_selection: all` reaches repositories created later too"
4090        );
4091        assert!(
4092            targets.installations().iter().any(|i| i
4093                .permissions
4094                .iter()
4095                .any(|(k, v)| k == "administration" && v == "write")),
4096            "the grant GitHub reports is surfaced verbatim, not assumed from the design"
4097        );
4098    }
4099
4100    #[tokio::test]
4101    async fn discovery_returns_the_installation_url_when_the_set_is_empty() {
4102        let server = MockServer::start().await;
4103        Mock::given(method("GET"))
4104            .and(path("/user/installations"))
4105            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
4106            .mount(&server)
4107            .await;
4108
4109        let client = client(&server, Arc::new(TestClock::default()));
4110        let discovery = client.discover_installations(&app()).await.unwrap();
4111
4112        let url = discovery
4113            .install_url()
4114            .expect("an empty set must yield the installation URL");
4115        assert_eq!(url.path(), "/apps/runner-manager/installations/new");
4116        assert!(discovery.targets().is_none());
4117    }
4118
4119    #[tokio::test]
4120    async fn an_installation_that_reaches_no_repository_is_still_not_installed() {
4121        let server = MockServer::start().await;
4122        Mock::given(method("GET"))
4123            .and(path("/user/installations"))
4124            .respond_with(
4125                ResponseTemplate::new(200).set_body_json(installations_body(&[(
4126                    11,
4127                    "IvanMurzak",
4128                    "User",
4129                    "selected",
4130                )])),
4131            )
4132            .mount(&server)
4133            .await;
4134        Mock::given(method("GET"))
4135            .and(path("/user/installations/11/repositories"))
4136            .respond_with(ResponseTemplate::new(200).set_body_json(repositories_body(&[])))
4137            .mount(&server)
4138            .await;
4139
4140        let client = client(&server, Arc::new(TestClock::default()));
4141        let discovery = client.discover_installations(&app()).await.unwrap();
4142        assert!(
4143            discovery.install_url().is_some(),
4144            "a user installation that selected no repository reaches nothing"
4145        );
4146    }
4147
4148    #[tokio::test]
4149    async fn discovery_follows_every_page_rather_than_trusting_the_first() {
4150        let server = MockServer::start().await;
4151        let next = format!("<{}/user/installations?page=2>; rel=\"next\"", server.uri());
4152        Mock::given(method("GET"))
4153            .and(path("/user/installations"))
4154            .respond_with(Script::new(vec![
4155                ResponseTemplate::new(200)
4156                    .set_body_json(installations_body(&[(
4157                        11,
4158                        "one",
4159                        "Organization",
4160                        "selected",
4161                    )]))
4162                    .insert_header("link", next.as_str()),
4163                ResponseTemplate::new(200).set_body_json(installations_body(&[(
4164                    22,
4165                    "two",
4166                    "Organization",
4167                    "selected",
4168                )])),
4169            ]))
4170            .mount(&server)
4171            .await;
4172        Mock::given(method("GET"))
4173            .and(path("/user/installations/11/repositories"))
4174            .respond_with(ResponseTemplate::new(200).set_body_json(repositories_body(&["one/a"])))
4175            .mount(&server)
4176            .await;
4177        Mock::given(method("GET"))
4178            .and(path("/user/installations/22/repositories"))
4179            .respond_with(ResponseTemplate::new(200).set_body_json(repositories_body(&["two/b"])))
4180            .mount(&server)
4181            .await;
4182
4183        let client = client(&server, Arc::new(TestClock::default()));
4184        let targets = client
4185            .discover_installations(&app())
4186            .await
4187            .unwrap()
4188            .targets()
4189            .cloned()
4190            .expect("installed");
4191        assert_eq!(
4192            targets
4193                .organizations()
4194                .iter()
4195                .map(ToString::to_string)
4196                .collect::<Vec<_>>(),
4197            ["one", "two"],
4198            "the second page must not be dropped"
4199        );
4200    }
4201
4202    /// GitHub's published `installation` schema types `account` as **nullable**,
4203    /// and as either a simple-user *or* an enterprise — which carries
4204    /// `slug`/`name` where a user carries `login`. A required `RawAccount` with
4205    /// a required `login` made either shape a hard `response.json()` failure,
4206    /// which takes down all of `discover_installations`, which is all of
4207    /// `auth status`. One unusual installation must not blind the command that
4208    /// exists to show the user what their credential can reach.
4209    #[tokio::test]
4210    async fn an_installation_with_a_null_or_enterprise_account_does_not_fail_the_whole_decode() {
4211        let server = MockServer::start().await;
4212        Mock::given(method("GET"))
4213            .and(path("/user/installations"))
4214            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
4215                "total_count": 3,
4216                "installations": [
4217                    // Nullable, per the published schema.
4218                    { "id": 10, "account": null, "repository_selection": "selected" },
4219                    // An enterprise: no `login` at all.
4220                    {
4221                        "id": 20,
4222                        "account": { "slug": "acme-enterprise", "name": "Acme Inc" },
4223                        "repository_selection": "selected"
4224                    },
4225                    // And an ordinary user alongside them.
4226                    {
4227                        "id": 30,
4228                        "account": { "login": "IvanMurzak", "type": "User" },
4229                        "repository_selection": "selected"
4230                    }
4231                ]
4232            })))
4233            .mount(&server)
4234            .await;
4235        for (id, repo) in [(20_u64, "acme-enterprise/tools"), (30, "IvanMurzak/app")] {
4236            Mock::given(method("GET"))
4237                .and(path(format!("/user/installations/{id}/repositories")))
4238                .respond_with(ResponseTemplate::new(200).set_body_json(repositories_body(&[repo])))
4239                .mount(&server)
4240                .await;
4241        }
4242
4243        let client = client(&server, Arc::new(TestClock::default()));
4244        let targets = client
4245            .discover_installations(&app())
4246            .await
4247            .expect("one odd account must not fail the whole discovery")
4248            .targets()
4249            .cloned()
4250            .expect("installed");
4251
4252        // Membership rather than order: what matters here is that neither
4253        // installation was lost, not how `OwnerRepo` collates.
4254        let reached = targets
4255            .repositories()
4256            .iter()
4257            .map(ToString::to_string)
4258            .collect::<Vec<_>>();
4259        assert!(
4260            reached.contains(&"acme-enterprise/tools".to_string()),
4261            "the enterprise installation is named from `slug` rather than dropped: {reached:?}"
4262        );
4263        assert!(
4264            reached.contains(&"IvanMurzak/app".to_string()),
4265            "the ordinary installation alongside it survives too: {reached:?}"
4266        );
4267        assert_eq!(reached.len(), 2);
4268        assert_eq!(
4269            targets.installations().len(),
4270            2,
4271            "the null account is skipped, and only it"
4272        );
4273        assert_eq!(
4274            targets.skipped(),
4275            1,
4276            "the skip is the right trade, but it must travel with the answer: everything the \
4277             skipped installation reaches is missing from the lists above, and a short list \
4278             reads exactly like a complete one"
4279        );
4280
4281        // The enterprise is labelled an enterprise. It used to fall through to
4282        // `User`, so `auth status` told the operator their enterprise was a
4283        // personal account.
4284        let enterprise = targets
4285            .installations()
4286            .iter()
4287            .find(|i| i.id == 20)
4288            .expect("the enterprise installation survived");
4289        assert_eq!(
4290            enterprise.account,
4291            InstallationAccount::Enterprise("acme-enterprise".to_string()),
4292            "an account with no `login` that names itself through `slug` is an enterprise, \
4293             and calling it a user is a wrong statement about the operator's own account"
4294        );
4295        assert_eq!(enterprise.account.kind(), "enterprise");
4296        assert!(
4297            enterprise.account.organization().is_none(),
4298            "an enterprise is not an organization target: `GET /orgs/{{org}}/actions/runners` \
4299             does not accept one, so contributing nothing to `organizations()` is correct"
4300        );
4301        assert!(
4302            !targets
4303                .organizations()
4304                .iter()
4305                .any(|o| o.as_str() == "acme-enterprise"),
4306            "and it must not be smuggled in as one either"
4307        );
4308    }
4309
4310    /// The skip is right; the verdict flip was not.
4311    ///
4312    /// A null-account installation that is the *only* installation used to
4313    /// collapse to `NotInstalled`, so `auth status` handed an operator who **is**
4314    /// installed the "install the App" URL — a wrong remediation on the only
4315    /// authentication path there is, contradicted by nothing but a `warn!`.
4316    #[tokio::test]
4317    async fn a_credential_whose_only_installation_was_skipped_is_not_reported_as_not_installed() {
4318        let server = MockServer::start().await;
4319        Mock::given(method("GET"))
4320            .and(path("/user/installations"))
4321            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
4322                "total_count": 1,
4323                "installations": [
4324                    { "id": 10, "account": null, "repository_selection": "selected" }
4325                ]
4326            })))
4327            .mount(&server)
4328            .await;
4329
4330        let client = client(&server, Arc::new(TestClock::default()));
4331        let discovery = client.discover_installations(&app()).await.unwrap();
4332
4333        assert_eq!(
4334            discovery,
4335            InstallationDiscovery::Indeterminate { skipped: 1 },
4336            "GitHub reported an installation; this client could not describe it. That is not \
4337             the same answer as `not installed`, and only one of the two is fixed by \
4338             installing the App"
4339        );
4340        assert_eq!(
4341            discovery.install_url(),
4342            None,
4343            "offering the install URL here is the wrong remediation, and putting it one field \
4344             over from the right verdict would just relocate the defect"
4345        );
4346        assert_eq!(discovery.skipped(), 1);
4347        assert!(discovery.targets().is_none());
4348    }
4349
4350    /// The other side of the same rule: with nothing skipped, an empty reach is
4351    /// still an empty reach, and the install URL is still the remediation.
4352    #[tokio::test]
4353    async fn an_empty_reach_with_nothing_skipped_is_still_not_installed() {
4354        let server = MockServer::start().await;
4355        Mock::given(method("GET"))
4356            .and(path("/user/installations"))
4357            .respond_with(ResponseTemplate::new(200).set_body_json(installations_body(&[])))
4358            .mount(&server)
4359            .await;
4360
4361        let client = client(&server, Arc::new(TestClock::default()));
4362        let discovery = client.discover_installations(&app()).await.unwrap();
4363
4364        assert!(discovery.install_url().is_some(), "{discovery:?}");
4365        assert_eq!(discovery.skipped(), 0);
4366    }
4367
4368    /// A `Link: rel="next"` that points back at the page it arrived on is an
4369    /// infinite loop inside the agent's reconciliation loop — the one place in
4370    /// this product that must not be able to wedge. The ceiling is what makes
4371    /// this test terminate at all.
4372    #[tokio::test]
4373    async fn a_self_referential_link_header_stops_at_the_page_ceiling() {
4374        let server = MockServer::start().await;
4375        let self_link = format!("<{}/user/installations?page=2>; rel=\"next\"", server.uri());
4376        Mock::given(method("GET"))
4377            .and(path("/user/installations"))
4378            .respond_with(
4379                ResponseTemplate::new(200)
4380                    .set_body_json(installations_body(&[]))
4381                    .insert_header("link", self_link.as_str()),
4382            )
4383            .mount(&server)
4384            .await;
4385
4386        let client = client(&server, Arc::new(TestClock::default()));
4387        let discovery = client
4388            .discover_installations(&app())
4389            .await
4390            .expect("the ceiling is what makes this return at all");
4391
4392        assert!(
4393            discovery.install_url().is_some(),
4394            "no installation was found"
4395        );
4396        assert_eq!(
4397            server.received_requests().await.unwrap().len(),
4398            MAX_PAGES,
4399            "pagination must stop at the ceiling rather than follow the loop forever"
4400        );
4401    }
4402
4403    #[test]
4404    fn a_link_header_yields_only_the_next_relation() {
4405        let header = "<https://api.github.com/user/installations?page=3>; rel=\"next\", \
4406                      <https://api.github.com/user/installations?page=9>; rel=\"last\"";
4407        assert_eq!(
4408            parse_link_next(header).map(|u| u.to_string()),
4409            Some("https://api.github.com/user/installations?page=3".to_string())
4410        );
4411        assert!(parse_link_next("<https://x/>; rel=\"last\"").is_none());
4412        assert!(parse_link_next("nonsense").is_none());
4413    }
4414
4415    /// A comma is legal inside a URL and GitHub sends such URLs routinely — a
4416    /// runner query carries `labels=self-hosted,windows`. Splitting the header
4417    /// on `,` before recognising `<...>` tore that URL in half, found no
4418    /// relation, and stopped paginating at page 1 while reporting success. That
4419    /// is precisely what `04-subsystem-contracts.md` forbids ("the dashboard
4420    /// must not treat a first page as a complete inventory"), in the one shared
4421    /// reader `c3`'s inventory also goes through.
4422    #[test]
4423    fn a_next_url_containing_a_comma_still_paginates() {
4424        let header = "<https://api.github.com/repos/o/r/actions/runners\
4425                      ?labels=self-hosted,windows&page=2>; rel=\"next\"";
4426        assert_eq!(
4427            parse_link_next(header).map(|u| u.to_string()),
4428            Some(
4429                "https://api.github.com/repos/o/r/actions/runners\
4430                 ?labels=self-hosted,windows&page=2"
4431                    .to_string()
4432            ),
4433            "a comma inside the URL must not end the link-value"
4434        );
4435
4436        // The same URL as the second link-value, so the scan has to walk past a
4437        // comma-bearing target to reach the relation it wants.
4438        let header = "<https://api.github.com/x?a=1,2&page=1>; rel=\"prev\", \
4439                      <https://api.github.com/x?a=1,2&page=3>; rel=\"next\"";
4440        assert_eq!(
4441            parse_link_next(header).map(|u| u.to_string()),
4442            Some("https://api.github.com/x?a=1,2&page=3".to_string())
4443        );
4444    }
4445
4446    /// `rel="next"` is not always the first link-value, and both quoted and
4447    /// unquoted forms are legal.
4448    #[test]
4449    fn the_next_relation_is_found_wherever_it_sits_in_the_header() {
4450        let not_first = "<https://api.github.com/u?page=1>; rel=\"first\", \
4451                         <https://api.github.com/u?page=9>; rel=\"last\", \
4452                         <https://api.github.com/u?page=4>; rel=\"next\"";
4453        assert_eq!(
4454            parse_link_next(not_first).map(|u| u.to_string()),
4455            Some("https://api.github.com/u?page=4".to_string())
4456        );
4457
4458        let unquoted = "<https://api.github.com/u?page=1>; rel=prev, \
4459                        <https://api.github.com/u?page=3>; rel=next";
4460        assert_eq!(
4461            parse_link_next(unquoted).map(|u| u.to_string()),
4462            Some("https://api.github.com/u?page=3".to_string())
4463        );
4464
4465        assert!(
4466            parse_link_next("<https://api.github.com/u?page=2; rel=\"next\"").is_none(),
4467            "an unterminated target is not a link-value"
4468        );
4469    }
4470
4471    /// The free cross-check that would have caught the comma bug on its own.
4472    #[test]
4473    fn a_short_collection_is_measured_against_the_count_github_reported() {
4474        assert_eq!(under_collected(1, Some(2)), Some(2), "page 2 was dropped");
4475        assert_eq!(under_collected(2, Some(2)), None, "complete");
4476        assert_eq!(
4477            under_collected(3, Some(2)),
4478            None,
4479            "a collection that grew between pages is not an under-collection"
4480        );
4481        assert_eq!(under_collected(0, None), None, "no count, no claim");
4482    }
4483
4484    // -- redaction ----------------------------------------------------------
4485
4486    #[test]
4487    fn no_type_in_this_crate_renders_a_secret_through_debug() {
4488        let token = UserAccessToken::new(SecretString::from(FIXTURE_TOKEN));
4489        let rendered = format!("{token:?}");
4490        assert!(!rendered.contains(FIXTURE_TOKEN), "{rendered}");
4491        assert!(rendered.contains("[REDACTED]"));
4492        assert!(
4493            rendered.contains("ghu_"),
4494            "the family prefix is diagnostic and is not the secret"
4495        );
4496
4497        let request = ApiRequest::post_json("/x", &json!({"encoded_jit_config": "SECRETBLOB"}))
4498            .expect("serializes");
4499        let rendered = format!("{request:?}");
4500        assert!(!rendered.contains("SECRETBLOB"), "{rendered}");
4501
4502        let response = ApiResponse {
4503            status: StatusCode::OK,
4504            headers: HeaderMap::new(),
4505            body: b"{\"encoded_jit_config\":\"SECRETBLOB\"}".to_vec(),
4506        };
4507        let rendered = format!("{response:?}");
4508        assert!(!rendered.contains("SECRETBLOB"), "{rendered}");
4509    }
4510
4511    // The Definition of Done's log scan is `tests/no_secret_reaches_the_logs.rs`
4512    // and not a unit test here. See the note at the end of `mod testing` for the
4513    // `tracing` callsite-cache reason it cannot be one.
4514
4515    // -- the crate-shape scans ----------------------------------------------
4516    //
4517    // The three gates below share these helpers on purpose. The previous round
4518    // defined `normalise` twice — once in the scan and once in the meta-test
4519    // that checks it — which left the meta-test structurally unable to notice a
4520    // change to the real one. One definition, used by both, is the only shape
4521    // in which a meta-test proves anything.
4522
4523    /// Spelled in halves so that this file's own source does not trip the scan
4524    /// it runs: normalising `concat!("refresh", "token")` leaves the
4525    /// quote-comma-quote between the halves, so no needle ever appears whole.
4526    // The renewal guard that used to live here is gone, and its absence is the
4527    // point. It forbade this crate from naming a refresh token at all, on the
4528    // reasoning that the published App opts out of user-token expiration "so
4529    // GitHub issues nothing to renew". That reasoning rested on a second claim
4530    // -- that renewing needs a confidential client credential -- which GitHub's
4531    // own documentation contradicts for the device flow, and which was then
4532    // disproved against live GitHub: a refresh exchange with `client_id` alone
4533    // answers `200`.
4534    //
4535    // What the guard below still forbids is the part that was always true and
4536    // is the reason renewal is safe here: no confidential credential in this
4537    // crate. Renewal was added *without* one, so the remaining half of this
4538    // scan is now evidence for the design rather than against it.
4539    const CONFIDENTIAL: &[&str] = &[concat!("client", "secret"), concat!("app", "secret")];
4540
4541    const MANIFEST: (&str, &str) = ("Cargo.toml", include_str!("../Cargo.toml"));
4542
4543    /// Every `.rs` file at or below `src/`, named by its `/`-joined path
4544    /// relative to `src/` — so a nested module is `("rest/runners.rs",
4545    /// include_str!("rest/runners.rs"))`, not just its file name.
4546    ///
4547    /// This list used to *be* the claim "every source file in the crate", and a
4548    /// hard-coded list is not that claim — it is a snapshot of it. `c3` and `c4`
4549    /// are the tasks that will add files to this directory, so the list was
4550    /// guaranteed to go stale on exactly the work that most needed scanning: a
4551    /// new `pagination.rs` holding a confidential credential passed silently.
4552    /// [`the_confidential_credential_scan_covers_every_source_file`] pins this
4553    /// by walking the directory tree, so adding a file — at the top level or in
4554    /// a subdirectory — and not adding it here fails.
4555    const CRATE_SOURCES: &[(&str, &str)] = &[
4556        ("demand.rs", include_str!("demand.rs")),
4557        ("device_flow.rs", include_str!("device_flow.rs")),
4558        ("jit.rs", include_str!("jit.rs")),
4559        ("lib.rs", include_str!("lib.rs")),
4560        ("rest.rs", include_str!("rest.rs")),
4561    ];
4562
4563    /// The two source files `c2` owns, plus the manifest. The renewal half of
4564    /// the scan stays inside this boundary; see the scan's own documentation.
4565    const SOURCES_OWNED_BY_C2: &[(&str, &str)] = &[
4566        ("device_flow.rs", include_str!("device_flow.rs")),
4567        ("lib.rs", include_str!("lib.rs")),
4568        MANIFEST,
4569    ];
4570
4571    /// Lower-cased with `_` removed, so that one needle catches the snake,
4572    /// camel, Pascal and screaming-snake spellings of an identifier at once.
4573    /// (Those four spellings cannot be written out here: they are exactly what
4574    /// the gate forbids, which is the constraint on documentation this scan
4575    /// imposes and defends below.)
4576    ///
4577    /// # Why `-` is *not* stripped from Rust source
4578    ///
4579    /// It used to be, and that rejected ordinary English. `c3`'s own file opens
4580    /// with a line stating that the gateway holds no such credential, written
4581    /// with the compound adjective English requires — and stripping `-` turned
4582    /// that sentence into the needle, so the gate accused `c3` of naming a
4583    /// confidential credential in the very line that says it holds none. A
4584    /// compound adjective is not an evasion; it is how the language works, and
4585    /// this brief, this crate's documentation and that line all use one.
4586    ///
4587    /// Nothing is lost, because **a Rust identifier cannot contain `-`**.
4588    /// Stripping it never bought identifier coverage: every casing an identifier
4589    /// can actually take is `_`-separated or unseparated, and all of those still
4590    /// collapse onto the needle. What it bought was coverage of a *kebab-case
4591    /// string literal*, and the residual gap is stated plainly rather than
4592    /// papered over: a `.rs` file that wrote this credential's name as a
4593    /// hyphenated string would not be caught here. That gap is narrow on
4594    /// purpose — OAuth 2.0 and GitHub both spell the field `_`-separated, which
4595    /// this catches — and it is the price of a gate that ordinary prose can
4596    /// coexist with. A gate that fires on correct English is not a stricter
4597    /// gate; it is a gate that gets deleted.
4598    ///
4599    /// The alternatives were weighed. Requiring identifier context needs a Rust
4600    /// lexer to tell `a client-secret-free design` from a TOML key, and gets the
4601    /// wrong answer for both string literals and comments. Excluding comment
4602    /// text needs the same lexer to avoid mangling `//` inside a string, and
4603    /// would stop the gate catching a `TODO` comment proposing to read the
4604    /// credential from the environment — which is precisely the drift worth
4605    /// catching early, while it is still a comment. Stripping one character
4606    /// fewer needs neither, which is why it wins.
4607    ///
4608    /// A space is not stripped either, and for the same reason: it is what lets
4609    /// this crate's prose discuss a "client secret" as two words.
4610    fn normalise_source(source: &str) -> String {
4611        source.to_ascii_lowercase().replace('_', "")
4612    }
4613
4614    /// The manifest keeps `-` stripped: TOML keys and crate names are kebab-case
4615    /// by convention, so `-` there is a word separator rather than a hyphen, and
4616    /// a manifest carries no hyphenated English for it to break.
4617    fn normalise_manifest(manifest: &str) -> String {
4618        manifest.to_ascii_lowercase().replace(['_', '-'], "")
4619    }
4620
4621    /// Which normaliser a scanned file gets. The manifest is the only file whose
4622    /// `-` is a separator rather than punctuation.
4623    fn normalise(name: &str, contents: &str) -> String {
4624        if name == MANIFEST.0 {
4625            normalise_manifest(contents)
4626        } else {
4627            normalise_source(contents)
4628        }
4629    }
4630
4631    /// The part of a source file that is not test code.
4632    ///
4633    /// The boundary is the first line that is **exactly** `#[cfg(test)]`, and
4634    /// the word "exactly" is the fix. Splitting on that literal wherever it
4635    /// appeared also split on it in *prose*, and `lib.rs` has carried such a
4636    /// mention since the `testing` module was documented — so the scan below
4637    /// already stopped nine lines early, today, with nothing to say so. A file
4638    /// whose module documentation happened to mention an inline test module
4639    /// would have had its scanned region truncated to a few dozen lines, after
4640    /// which a real `std::fs::write` in non-test code passed silently. That is
4641    /// the same class of defect as the log scan that captured only its own
4642    /// events and the credential scan that claimed a scope it did not have: a
4643    /// gate whose description outran what it did.
4644    fn non_test_prefix(source: &str) -> &str {
4645        let mut offset = 0;
4646        for line in source.split_inclusive('\n') {
4647            if line.trim() == "#[cfg(test)]" {
4648                return &source[..offset];
4649            }
4650            offset += line.len();
4651        }
4652        source
4653    }
4654
4655    /// The Definition of Done's second item, made checkable rather than
4656    /// reviewed: "no renewal token code path exists, and no client secret
4657    /// appears anywhere in the crate **or its configuration**".
4658    ///
4659    /// # Normalised, because a literal scan is evaded by naming
4660    ///
4661    /// This used to be a case-sensitive `contains` over two snake-case
4662    /// spellings, which is a gate that any ordinary Rust or JSON identifier
4663    /// walks straight through: the camel-cased, Pascal-cased and
4664    /// screaming-snake spellings of the very same two identifiers were all
4665    /// invisible to it. None of those is exotic — several are what the
4666    /// surrounding ecosystem actually calls these fields — so evading this gate
4667    /// never had to be deliberate. See [`normalise_source`] for what is
4668    /// collapsed, what is deliberately not, and why.
4669    ///
4670    /// The consequence is that this crate's *prose* may not write those
4671    /// identifiers either, in any casing: it says "renewal token" and "client
4672    /// secret" as separate words, which normalisation preserves and the scan
4673    /// therefore ignores. That is a real constraint on the documentation, and it
4674    /// is the right way round — a gate loosened until the comments compile is
4675    /// not a gate. It is a constraint on *identifier spellings*, though, and
4676    /// never on English: hyphenating a compound adjective is not writing an
4677    /// identifier, and a gate that could not tell those apart is what this round
4678    /// fixed.
4679    ///
4680    /// # Two different scopes, for two different reasons
4681    ///
4682    /// The **renewal** half stays scoped to the two files `c2` owns plus the
4683    /// manifest. A renewal path in `c3`'s or `c4`'s file would be their finding;
4684    /// failing here on their work would be this task reaching across an
4685    /// ownership boundary.
4686    ///
4687    /// The **client secret** half covers every source file in the crate. That is
4688    /// not a boundary crossing but the opposite: a public client cannot hold a
4689    /// client secret at all (D3, `07-security.md`), so one appearing *anywhere*
4690    /// in this crate is a product defect rather than a matter of whose file it
4691    /// is, and `c2` is the designated owner of that clause. "Every source file"
4692    /// is a claim about the directory, so it is checked against the directory —
4693    /// see [`the_confidential_credential_scan_covers_every_source_file`].
4694    #[test]
4695    fn no_confidential_credential_in_this_crate() {
4696        for &(name, source) in CRATE_SOURCES.iter().chain(std::iter::once(&MANIFEST)) {
4697            let haystack = normalise(name, source);
4698            for forbidden in CONFIDENTIAL {
4699                assert!(
4700                    !haystack.contains(forbidden),
4701                    "{name} names {forbidden:?} in some spelling: a public client cannot \
4702                     secure a confidential credential, and this design never tries to (D3)"
4703                );
4704            }
4705        }
4706    }
4707
4708    /// "Every source file in the crate" is a claim about a directory, and the
4709    /// scan above states it as a hard-coded list. A list is a snapshot: the
4710    /// moment `c3` or `c4` adds a file to `src/`, the claim is false and nothing
4711    /// says so. A `src/pagination.rs` holding a confidential credential passed
4712    /// the gate that exists to catch exactly that.
4713    ///
4714    /// Reading the directory here is what turns the claim back into a claim. It
4715    /// cannot be done in the scan itself — `include_str!` needs a literal path
4716    /// at compile time — so the list stays, and this pins it.
4717    ///
4718    /// # Why it walks the tree instead of listing one directory
4719    ///
4720    /// It used to call `read_dir("src")` once and keep the entries ending in
4721    /// `.rs`. That reads like a directory scan and is not one: a subdirectory
4722    /// module — `src/rest/mod.rs`, `src/rest/runners.rs` — arrives as the single
4723    /// entry `rest`, which does not end in `.rs`, so the filter dropped it and
4724    /// took the files underneath with it. The pin went on passing while those
4725    /// files were scanned by nothing at all.
4726    ///
4727    /// That defeated the pin in exactly the case it was written for. `c3` is the
4728    /// REST inventory gateway, a module directory is the ordinary Rust shape for
4729    /// it, and the failure is silent on both sides: the credential scan does not
4730    /// read the file, and the test whose whole job is to notice that reports
4731    /// success.
4732    ///
4733    /// Recursing is the fix, rather than asserting that `src/` holds no
4734    /// subdirectories. The claim being pinned is about *files*, not about
4735    /// layout; banning the directory would fail `c3` for choosing a normal
4736    /// module shape, and a gate that fails correct work is a gate the next round
4737    /// loosens to get its own work compiling — which is how the normalisation
4738    /// half of this same scan was weakened once already.
4739    ///
4740    /// Names are `/`-joined paths relative to `src/`, which is what
4741    /// `include_str!` takes on every platform, so a nested file is listed as
4742    /// `("rest/runners.rs", include_str!("rest/runners.rs"))` and the two sides
4743    /// compare directly.
4744    #[test]
4745    fn the_confidential_credential_scan_covers_every_source_file() {
4746        // Every `.rs` file at or below `dir`, named by its `/`-joined path
4747        // relative to `src/`.
4748        //
4749        // `file_type()` is deliberately not followed through symlinks: a link
4750        // cannot walk this into a cycle, and a symlinked `.rs` file still lands
4751        // in the list through the extension test. A directory is recursed into
4752        // before the extension is considered, so a directory named `foo.rs`
4753        // is walked rather than mistaken for a file.
4754        fn collect(dir: &std::path::Path, prefix: &str, found: &mut Vec<String>) {
4755            for entry in std::fs::read_dir(dir).expect("the source directory is readable") {
4756                let entry = entry.expect("a readable directory entry");
4757                let name = entry.file_name().to_string_lossy().into_owned();
4758                let relative = if prefix.is_empty() {
4759                    name.clone()
4760                } else {
4761                    format!("{prefix}/{name}")
4762                };
4763                if entry.file_type().expect("a readable entry type").is_dir() {
4764                    collect(&entry.path(), &relative, found);
4765                } else if name.ends_with(".rs") {
4766                    found.push(relative);
4767                }
4768            }
4769        }
4770
4771        let mut on_disk = Vec::new();
4772        collect(
4773            std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/src")),
4774            "",
4775            &mut on_disk,
4776        );
4777        on_disk.sort();
4778
4779        // Sorted, rather than taken in declaration order. Comparing a sorted
4780        // `on_disk` against an unsorted `scanned` made this assertion depend on
4781        // `CRATE_SOURCES` happening to be declared alphabetically. It is — but
4782        // nothing said so, and the failure that would follow from reordering the
4783        // list is a diff of two lists holding the same names, which reads as a
4784        // coverage gap rather than as the ordering nit it would actually be.
4785        let mut scanned: Vec<String> = CRATE_SOURCES
4786            .iter()
4787            .map(|(name, _)| (*name).to_string())
4788            .collect();
4789        scanned.sort();
4790
4791        assert_eq!(
4792            scanned, on_disk,
4793            "`src/` and the scanned list have diverged. Add the new file to `CRATE_SOURCES` \
4794             with an `include_str!`, naming it by its `/`-joined path relative to `src/`; \
4795             leaving it out means the confidential-credential scan silently stops covering \
4796             `every source file in the crate`, which is the claim it makes."
4797        );
4798    }
4799
4800    /// The scan above, shown to actually catch the spellings it claims to — and
4801    /// to leave alone the ones it claims to leave alone.
4802    ///
4803    /// Without this, "the gate is case-insensitive now" is a comment rather than
4804    /// a fact, and the finding that produced it was precisely a gate whose
4805    /// description outran what it did. It calls [`normalise`], the same function
4806    /// the scan calls, because a meta-test with its own private copy of the
4807    /// thing under test cannot detect a change to it.
4808    #[test]
4809    fn the_confidential_credential_scan_is_not_evaded_by_naming() {
4810        // Assembled at run time rather than written out, for the same reason the
4811        // needles are spelled in halves: a test that contained these spellings
4812        // literally would fail the scan it is checking.
4813        let source_evasions = [
4814            format!("let {}Token = fetch()", "refresh"),
4815            format!("struct {}Token;", "Refresh"),
4816            format!("{}_TOKEN", "REFRESH"),
4817            format!("{}Secret", "client"),
4818            format!("{}_SECRET", "CLIENT"),
4819            format!("{}_secret", "app"),
4820        ];
4821        for evasion in &source_evasions {
4822            let normalised = normalise("lib.rs", evasion);
4823            assert!(
4824                normalised.contains(concat!("refresh", "token"))
4825                    || normalised.contains(concat!("client", "secret"))
4826                    || normalised.contains(concat!("app", "secret")),
4827                "{evasion:?} would walk straight through the scan"
4828            );
4829        }
4830
4831        // The manifest is where kebab-case is a word separator rather than a
4832        // hyphen, so that is where it is still collapsed.
4833        let manifest_evasion = format!("{}-secret = \"...\"", "client");
4834        assert!(
4835            normalise(MANIFEST.0, &manifest_evasion).contains(concat!("client", "secret")),
4836            "a kebab-case TOML key is an identifier, and the manifest normaliser must \
4837             still collapse it"
4838        );
4839
4840        // And the prose the crate legitimately writes must still pass, or the
4841        // gate would be unusable and would be weakened again to make it usable.
4842        for allowed in [
4843            "a public client cannot hold a client secret",
4844            "the published App issues no renewal token",
4845            // The line that fails the old normalisation, quoted from `c3`'s own
4846            // file. It says the *opposite* of what the gate accused it of.
4847            "//! This gateway is deliberately client-secret-free, as D3 requires.",
4848            // The same shape, for the renewal half.
4849            "a refresh-free credential model",
4850        ] {
4851            let normalised = normalise("lib.rs", allowed);
4852            assert!(
4853                !normalised.contains(concat!("client", "secret"))
4854                    && !normalised.contains(concat!("refresh", "token")),
4855                "{allowed:?} is English, not an identifier, and must not trip the scan"
4856            );
4857        }
4858    }
4859
4860    /// The storage boundary, made checkable the same way. `c2` returns the token
4861    /// and never persists it; the machine-scoped store is `d2` and the wiring is
4862    /// `f1`. A dependency on `runner-manager-platform`, or a filesystem write,
4863    /// would silently move that boundary.
4864    #[test]
4865    fn this_crate_persists_nothing_and_does_not_depend_on_the_platform_crate() {
4866        assert!(
4867            !MANIFEST.1.contains("runner-manager-platform"),
4868            "the gateway must be testable with no platform dependency at all"
4869        );
4870
4871        for &(name, source) in SOURCES_OWNED_BY_C2 {
4872            if name == MANIFEST.0 {
4873                continue;
4874            }
4875            // Everything below `#[cfg(test)]` is test code; the boundary is about
4876            // non-test code, and the tests above legitimately read this file.
4877            let non_test = non_test_prefix(source);
4878            // `OpenOptions`, `File::options` and `std::io::Write` are on this
4879            // list because the original four named only the *obvious* ways to
4880            // write a file. A store built with `OpenOptions::new().create(true)`
4881            // would have moved the persistence boundary silently, which is the
4882            // one thing this scan exists to prevent.
4883            for forbidden in [
4884                "std::fs",
4885                "fs::write",
4886                "File::create",
4887                "File::options",
4888                "OpenOptions",
4889                "std::io::Write",
4890                "tokio::fs",
4891            ] {
4892                assert!(
4893                    !non_test.contains(forbidden),
4894                    "{name} performs a filesystem operation ({forbidden:?}) outside its tests"
4895                );
4896            }
4897        }
4898    }
4899
4900    /// The scan above, shown to be looking at what it says it is looking at.
4901    ///
4902    /// `split("#[cfg(test)]")` matched that literal **anywhere**, prose
4903    /// included. One ordinary sentence in a module's documentation truncated the
4904    /// scanned region to whatever preceded it, and every filesystem call after
4905    /// that point became invisible — with the scan still reporting `ok`. This is
4906    /// the third gate in this crate found describing more than it did, so it
4907    /// gets the same treatment as the other two: a synthetic file where the
4908    /// difference is decisive, and an assertion about the real ones.
4909    #[test]
4910    fn the_non_test_boundary_is_a_line_and_not_a_mention() {
4911        // A file shaped like this crate's own: prose that names the attribute,
4912        // then real non-test code, then the actual module.
4913        let file = "//! Test helpers live in an inline #[cfg(test)] module near the bottom.\n\
4914                    \n\
4915                    fn persist() { std::fs::write(\"x\", b\"y\").unwrap(); }\n\
4916                    \n\
4917                    #[cfg(test)]\n\
4918                    mod tests {\n\
4919                        fn helper() { std::fs::write(\"ok-in-tests\", b\"\").unwrap(); }\n\
4920                    }\n";
4921
4922        let non_test = non_test_prefix(file);
4923        assert!(
4924            non_test.contains("fn persist"),
4925            "a prose mention of the attribute truncated the scanned region, and every \
4926             filesystem call below it stopped being scanned — silently:\n{non_test}"
4927        );
4928        assert!(
4929            !non_test.contains("ok-in-tests"),
4930            "the boundary must still exclude the real test module:\n{non_test}"
4931        );
4932
4933        // And on the real files, whose module documentation contains such a
4934        // mention today. `lib.rs` has carried one since `mod testing` was
4935        // written, so this crate was shipping the truncated scan.
4936        for &(name, source) in SOURCES_OWNED_BY_C2 {
4937            if name == MANIFEST.0 {
4938                continue;
4939            }
4940            let expected = source
4941                .lines()
4942                .position(|line| line.trim() == "#[cfg(test)]")
4943                .expect("each source file has an inline test module");
4944            let scanned = non_test_prefix(source).lines().count();
4945            assert_eq!(
4946                scanned, expected,
4947                "{name}: the scanned region ends at line {scanned} but the test module starts \
4948                 at line {expected}. The gap is code that claims to be scanned and is not."
4949            );
4950        }
4951    }
4952
4953    #[derive(Debug)]
4954    struct SpyRenewal {
4955        invocations: std::sync::atomic::AtomicUsize,
4956    }
4957    #[async_trait::async_trait]
4958    impl CredentialRenewal for SpyRenewal {
4959        async fn renew(&self, _refresh_token: &SecretString) -> Result<UserAccessToken, String> {
4960            self.invocations
4961                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
4962            Ok(UserAccessToken::new(SecretString::from("ghu_renewed")))
4963        }
4964    }
4965
4966    #[tokio::test]
4967    async fn reload_happens_before_renew_to_prevent_cross_process_races() {
4968        let server = MockServer::start().await;
4969        Mock::given(method("GET"))
4970            .and(path("/repos/acme/app"))
4971            .and(header("authorization", "Bearer ghu_initial"))
4972            .respond_with(ResponseTemplate::new(401))
4973            .expect(1)
4974            .mount(&server)
4975            .await;
4976        Mock::given(method("GET"))
4977            .and(path("/repos/acme/app"))
4978            .and(header("authorization", "Bearer ghu_reloaded"))
4979            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"id": 1})))
4980            .expect(1)
4981            .mount(&server)
4982            .await;
4983
4984        let renewal = Arc::new(SpyRenewal {
4985            invocations: std::sync::atomic::AtomicUsize::new(0),
4986        });
4987
4988        let document = serde_json::json!({
4989            "access_token": "ghu_initial",
4990            "refresh_token": "ghr_initial",
4991        });
4992        let initial_token =
4993            UserAccessToken::from_stored_document(&SecretString::from(document.to_string()));
4994
4995        let client = AuthenticatedClient::new(
4996            Endpoints::for_test_server(&server.uri()).unwrap(),
4997            initial_token,
4998            Arc::new(TestClock::default()),
4999        )
5000        .unwrap()
5001        .with_credential_source(Arc::new(StoreHolding(Some("ghu_reloaded"))))
5002        .with_renewal(renewal.clone());
5003
5004        let response = client
5005            .get_json::<serde_json::Value>("/repos/acme/app")
5006            .await
5007            .expect("the reloaded token should succeed");
5008        assert_eq!(response["id"], 1);
5009        assert_eq!(
5010            renewal
5011                .invocations
5012                .load(std::sync::atomic::Ordering::SeqCst),
5013            0,
5014            "renew should not be called because reload succeeded"
5015        );
5016    }
5017}