From 8fdef5f65098914b6938cbbc5bf8c3b16a829790 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 16:20:39 +0000 Subject: [PATCH] Service accounts: "Last used" counts only the requests that run as the account The trusted-header realm recorded a use of the account its headers name when the middleware resolved the principal, before the handler read a credential of the request's own in its place: a Bearer API token on /repository, a registry token on /v2. The middleware now records the use after the handler has answered, unless the handler says another credential replaced the principal (or was refused). Fixes #586 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_012e6DJacez28ygnEtA1z3mF --- crates/db/src/user_dao.rs | 8 +- crates/server/src/auth/trusted_header.rs | 23 ++-- crates/server/src/formats.rs | 9 +- crates/server/src/images/dispatch.rs | 10 +- crates/server/src/middleware/principal.rs | 139 ++++++++++++++++++++-- crates/server/tests/trusted_header.rs | 132 ++++++++++++++++++++ docs/changes/2.2.0/586.fixed.md | 7 ++ 7 files changed, 304 insertions(+), 24 deletions(-) create mode 100644 docs/changes/2.2.0/586.fixed.md diff --git a/crates/db/src/user_dao.rs b/crates/db/src/user_dao.rs index b52ad49f..59a4835f 100644 --- a/crates/db/src/user_dao.rs +++ b/crates/db/src/user_dao.rs @@ -326,8 +326,8 @@ pub struct AccountDetails { pub realm_id: Option, pub realm: Option, /// When the account last authenticated: the latest use of one of its - /// API tokens, or the last request a trusted-header realm named it in - /// ([`touch_last_authenticated`]). + /// API tokens, or the last request that ran as the account a + /// trusted-header realm named ([`touch_last_authenticated`]). pub last_used_at: Option>, } @@ -352,8 +352,8 @@ pub async fn account_details( .await } -/// Record that a trusted-header realm just authenticated `user_id` -/// (`app_user.last_auth_source_at`): written only when the last write is +/// Record that a request ran as `user_id`, the account a trusted-header +/// realm named (`app_user.last_auth_source_at`): written only when the last write is /// older than `min_age_secs`, so the requests of a busy account do not all /// write its row. pub async fn touch_last_authenticated( diff --git a/crates/server/src/auth/trusted_header.rs b/crates/server/src/auth/trusted_header.rs index 981034ef..4313594e 100644 --- a/crates/server/src/auth/trusted_header.rs +++ b/crates/server/src/auth/trusted_header.rs @@ -77,6 +77,7 @@ use subtle::ConstantTimeEq; use super::realms::NewAccountAccess; use super::RealmAuth; +use crate::middleware::principal::TrustedHeaders; /// Shortest accepted `secret`, in bytes. pub const MIN_SECRET_BYTES: usize = 16; @@ -373,22 +374,30 @@ impl TrustedHeaderSource { ); return SourceOutcome::Invalid; } + // Not yet a use of the account ([`TrustedHeaders::record_use`]): the + // request may carry a credential of its own that its handler reads. + SourceOutcome::Authenticated(Principal::User { + user_id: user.id, + token_id: None, + method: AuthMethod::TrustedHeader, + }) + } +} + +#[async_trait::async_trait] +impl TrustedHeaders for TrustedHeaderSource { + async fn record_use(&self, user_id: i64) { // Best effort: when the account was last used is for the admin // screens, and never fails the request. if let Err(e) = user_dao::touch_last_authenticated( &self.pool, - user.id, + user_id, LAST_AUTHENTICATED_INTERVAL_SECS, ) .await { - tracing::debug!(error = %e, user_id = user.id, "touch_last_authenticated failed"); + tracing::debug!(error = %e, user_id, "touch_last_authenticated failed"); } - SourceOutcome::Authenticated(Principal::User { - user_id: user.id, - token_id: None, - method: AuthMethod::TrustedHeader, - }) } } diff --git a/crates/server/src/formats.rs b/crates/server/src/formats.rs index 7b472134..7f8f9e69 100644 --- a/crates/server/src/formats.rs +++ b/crates/server/src/formats.rs @@ -253,7 +253,14 @@ async fn with_bearer( async fn dispatch_request(state: AppState, req: Request) -> Response { let uri = req.uri().clone(); - let principal = match with_bearer(&state, req.headers(), principal_of(&req)).await { + let named = principal_of(&req); + let principal = with_bearer(&state, req.headers(), named.clone()).await; + // A Bearer token in the place of the account the proxy's headers named, + // or refused: the request is no use of that account (#586). + if principal.as_ref().ok() != Some(&named) { + crate::middleware::principal::NamedAccountUse::replaced_in(&req); + } + let principal = match principal { Ok(principal) => principal, Err(response) => return response, }; diff --git a/crates/server/src/images/dispatch.rs b/crates/server/src/images/dispatch.rs index 2afc72dc..ce78d51c 100644 --- a/crates/server/src/images/dispatch.rs +++ b/crates/server/src/images/dispatch.rs @@ -109,7 +109,15 @@ impl Registry { _ => Some(self.spec().image_path(req.method().as_str(), &rest)?), }; let site = self.site(request_host(&req)).await?; - let caller = self.caller(principal, req.headers(), &site).await?; + let caller = self.caller(principal.clone(), req.headers(), &site).await; + // A registry token's principal in the place of the account the + // proxy's headers named, or a token refused: the request is no use + // of that account. A token that names nobody leaves the request to + // run as it. + if !matches!(&caller, Ok(caller) if caller.principal == principal) { + crate::middleware::principal::NamedAccountUse::replaced_in(&req); + } + let caller = caller?; match (rest.as_str(), path) { (_, Some(path)) => self.repository_request(caller, site, path, req).await, ("/token", None) => { diff --git a/crates/server/src/middleware/principal.rs b/crates/server/src/middleware/principal.rs index 06c1fbd1..24d99c31 100644 --- a/crates/server/src/middleware/principal.rs +++ b/crates/server/src/middleware/principal.rs @@ -17,6 +17,13 @@ //! anonymous, so a credential its handler reads (a Bearer API token on a //! feed, a registry token) still counts, and its sender can sign in (#573). //! +//! Such a credential also wins over the account the headers do name, in the +//! handler that reads it, after this middleware. So the account's use ("Last +//! used", [`TrustedHeaders::record_use`]) is recorded once the handler has +//! answered, and only when the request ran as that account: the handler says +//! so on the request's [`NamedAccountUse`] when another credential replaced +//! the principal (#586). +//! //! Security rules (enforced by [`forge_core::auth::token::resolve_principal`]): //! * The first source that authenticates wins. //! * If any source reports credentials were **present but invalid**, the request @@ -71,6 +78,7 @@ //! session never locks the browser out of the login page or the SPA. use std::net::{IpAddr, SocketAddr}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use axum::extract::{ConnectInfo, State}; @@ -99,6 +107,45 @@ pub const CSRF_HEADER: &str = "x-csrf-token"; #[derive(Debug, Clone, Copy)] pub struct NamedByTrustedHeaders; +/// The trusted-header realms, as the middleware asks them: who the proxy's +/// headers name ([`PrincipalSource`]), and the record that the account was +/// used. +#[async_trait::async_trait] +pub trait TrustedHeaders: PrincipalSource { + /// Record that a request ran as account `user_id`, which the headers + /// named (its "Last used"). Best effort: it never fails the request. + async fn record_use(&self, user_id: i64); +} + +/// Request extension beside a [`Principal`] the headers of a trusted-header +/// realm's proxy named: whether the request ran as that account. A handler +/// that reads a credential of the request's own in the principal's place (a +/// Bearer API token on a feed, a registry token) calls +/// [`replaced`](Self::replaced), and the request is then no use of the +/// account the headers name. +#[derive(Debug, Clone, Default)] +pub struct NamedAccountUse(Arc); + +impl NamedAccountUse { + /// The request does not run as the account the headers name: a + /// credential of its own took the principal's place, or was refused. + pub fn replaced(&self) { + self.0.store(true, Ordering::Relaxed); + } + + /// [`replaced`](Self::replaced) on the extension of `req`, when the + /// headers named its principal. + pub fn replaced_in(req: &Request) { + if let Some(named) = req.extensions().get::() { + named.replaced(); + } + } + + fn is_replaced(&self) -> bool { + self.0.load(Ordering::Relaxed) + } +} + /// Pre-session endpoints exempt from the CSRF layer: they authenticate a *new* /// login from the request body and never act on the presented session, so a /// stale cookie in the browser must not block signing in again. (Both require @@ -119,7 +166,7 @@ pub struct PrincipalLayer { pub sources: Arc>>, /// The trusted-header realms, asked after `sources` found no credentials /// and only for a request from a trusted proxy that names this server. - pub trusted_header: Option>, + pub trusted_header: Option>, /// Trusted proxy CIDRs for `X-Forwarded-For` resolution. pub trusted_proxies: Arc>, /// Anonymous-access policy. @@ -308,10 +355,11 @@ pub async fn attach_principal( let trusted_header = layer.trusted_header.as_deref().filter(|_| { is_trusted_peer(peer, &layer.trusted_proxies) && host_is_allowed(&req, &layer.allowed_hosts) }); + let fallback = trusted_header.map(|source| source as &dyn PrincipalSource); let resolved = match resolve_principal_with_fallback( &layer.sources, - trusted_header, + fallback, req.headers(), client_ip, &anon, @@ -334,17 +382,28 @@ pub async fn attach_principal( } } - let named_by_headers = matches!( - resolved.principal, + // The account the headers named, and whether the request runs as it: + // its handler may read a credential of the request's own instead. + let named = match resolved.principal { Principal::User { + user_id, method: AuthMethod::TrustedHeader, .. - } - ); + } => Some((user_id, NamedAccountUse::default())), + _ => None, + }; + if let Some((_, account_use)) = &named { + req.extensions_mut().insert(account_use.clone()); + } req.extensions_mut().insert(resolved.principal); let mut resp = next.run(req).await; - if named_by_headers { + if let Some((user_id, account_use)) = named { resp.extensions_mut().insert(NamedByTrustedHeaders); + if !account_use.is_replaced() { + if let Some(source) = trusted_header { + source.record_use(user_id).await; + } + } } // A dead session cookie continues as anonymous/unauthenticated; drop it // from the browser so it stops riding along — unless the handler set the @@ -799,8 +858,19 @@ mod tests { } /// A stub trusted-header source: names user 7 whenever `x-test-user` is - /// present. - struct HeaderStub; + /// present, and counts the uses recorded. + #[derive(Default)] + struct HeaderStub { + uses: std::sync::atomic::AtomicUsize, + } + + #[async_trait::async_trait] + impl TrustedHeaders for HeaderStub { + async fn record_use(&self, user_id: i64) { + assert_eq!(user_id, 7); + self.uses.fetch_add(1, Ordering::Relaxed); + } + } #[async_trait::async_trait] impl PrincipalSource for HeaderStub { @@ -826,7 +896,7 @@ mod tests { require_header: true, }; let mut l = layer(vec![Box::new(basic)], AnonPolicy::All); - l.trusted_header = Some(Arc::new(HeaderStub)); + l.trusted_header = Some(Arc::new(HeaderStub::default())); let send = |l: PrincipalLayer, req: http::request::Builder| async move { let resp = app(l) .oneshot(req.body(Body::empty()).unwrap()) @@ -888,10 +958,57 @@ mod tests { ); } + /// The account the headers name is used by the requests that run as it, + /// not by one whose handler read a credential of its own instead (#586). + #[tokio::test] + async fn a_use_of_the_named_account_is_recorded_unless_the_handler_replaced_it() { + async fn handler(req: Request) -> Response { + if req.headers().contains_key(AUTHORIZATION) { + NamedAccountUse::replaced_in(&req); + } + StatusCode::OK.into_response() + } + let stub = Arc::new(HeaderStub::default()); + let mut l = layer(vec![], AnonPolicy::All); + l.trusted_header = Some(stub.clone()); + l.trusted_proxies = Arc::new(vec!["127.0.0.0/8".parse().unwrap()]); + let app = Router::new() + .route("/", get(handler)) + .layer(axum::middleware::from_fn_with_state(l, attach_principal)); + let send = |headers: &[(&'static str, &'static str)]| { + let mut req = Request::builder() + .uri("/") + .header(header::HOST, "forge.example"); + for (name, value) in headers { + req = req.header(*name, *value); + } + app.clone().oneshot(req.body(Body::empty()).unwrap()) + }; + let uses = || stub.uses.load(Ordering::Relaxed); + + // A credential only the handler reads took the principal's place. + let named = ("x-test-user", "alice@example.com"); + let resp = send(&[named, ("authorization", "Bearer own")]) + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + assert_eq!(uses(), 0); + // The response is still one to a request with credentials. + assert!(resp.extensions().get::().is_some()); + // The headers alone: the request ran as the account. + send(&[named]).await.unwrap(); + assert_eq!(uses(), 1); + // Headers that name nobody, or none: no account to record. + send(&[("x-test-user", "refused")]).await.unwrap(); + send(&[("authorization", "Bearer own")]).await.unwrap(); + send(&[]).await.unwrap(); + assert_eq!(uses(), 1); + } + #[tokio::test] async fn a_cross_site_mutation_is_refused_before_the_trusted_headers() { let mut l = layer(vec![], AnonPolicy::Off); - l.trusted_header = Some(Arc::new(HeaderStub)); + l.trusted_header = Some(Arc::new(HeaderStub::default())); l.trusted_proxies = Arc::new(vec!["127.0.0.0/8".parse().unwrap()]); let post = |site: &'static str| { Request::builder() diff --git a/crates/server/tests/trusted_header.rs b/crates/server/tests/trusted_header.rs index 4d189e45..e9683996 100644 --- a/crates/server/tests/trusted_header.rs +++ b/crates/server/tests/trusted_header.rs @@ -853,3 +853,135 @@ async fn basic_in_another_case_is_the_requests_own_credential() { assert_eq!(body["is_admin"], json!(true), "{scheme}: {body}"); } } + +/// Whether a trusted-header realm has recorded a use of account `id` +/// (`app_user.last_auth_source_at`, the "Last used" of an account without +/// tokens). +async fn used(srv: &TestServer, id: i64) -> bool { + sqlx::query_scalar("SELECT last_auth_source_at IS NOT NULL FROM app_user WHERE id = $1") + .bind(id) + .fetch_one(&srv.pool) + .await + .unwrap() +} + +/// Forget the recorded use of account `id`. +async fn forget_use(srv: &TestServer, id: i64) { + sqlx::query("UPDATE app_user SET last_auth_source_at = NULL WHERE id = $1") + .bind(id) + .execute(&srv.pool) + .await + .unwrap(); +} + +/// "Last used" of the account the headers name moves only when the request +/// runs as that account (#586): a request with a credential of its own that +/// its handler reads — npm's Bearer token on a feed, a registry token — +/// is a use of that credential's account, not of the network's. +#[tokio::test] +async fn a_request_with_its_own_credential_is_no_use_of_the_account_the_headers_name() { + let srv = proxied().await; + let realm = create_realm(&srv, false).await; + let n = common::unique(); + let office = format!("office{n}@example.com"); + let office_id = create_account(&srv, &realm, &office, "roles_only").await; + let ci = format!("ci{n}@example.com"); + let ci_id = create_account(&srv, &realm, &ci, "roles_only").await; + let (u, p) = srv.admin_basic(); + let repo = format!("npm{n}"); + let resp = srv + .client() + .post(format!("{}/admin/repositories", srv.base_url)) + .basic_auth(&u, Some(&p)) + .json(&json!({"name": repo, "kind": "hosted", "format": "npm"})) + .send() + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::CREATED); + let token: Value = srv + .client() + .post(format!("{}/admin/users/{ci_id}/tokens", srv.base_url)) + .basic_auth(&u, Some(&p)) + .json(&json!({"name": "ci"})) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + let token = token["token"].as_str().unwrap(); + let office_says = |rb: RequestBuilder| realm.named(rb, &office); + let whoami = format!("{}/repository/{repo}/-/whoami", srv.base_url); + let v2 = format!("{}/v2/", srv.base_url); + let registry_token = |rb: RequestBuilder| async move { + let resp = rb.query(&[("service", "test.local")]).send().await.unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + let body: Value = resp.json().await.unwrap(); + body["token"].as_str().unwrap().to_string() + }; + assert!(!used(&srv, office_id).await); + + // npm's own token on a feed: the request runs as its account… + let (status, body) = me(office_says(srv.client().get(&whoami)).bearer_auth(token)).await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert_eq!(body["username"], json!(ci)); + assert!(!used(&srv, office_id).await, "a feed's Bearer token"); + // …and one that is refused runs as nobody. + let (status, _) = me(office_says(srv.client().get(&whoami)).bearer_auth("not-a-token")).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert!(!used(&srv, office_id).await, "a refused Bearer token"); + + // `docker login` with a token, then the registry token it got. + let token_url = format!("{}/v2/token", srv.base_url); + let registry = + registry_token(office_says(srv.client().get(&token_url)).basic_auth(&ci, Some(token))) + .await; + assert!(!used(&srv, office_id).await, "docker login"); + let resp = office_says(srv.client().get(&v2)) + .bearer_auth(®istry) + .send() + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + assert!(!used(&srv, office_id).await, "a registry token"); + // A registry token that is refused runs as nobody either. + let resp = office_says(srv.client().get(&v2)) + .bearer_auth(format!("{registry}x")) + .send() + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); + assert!(!used(&srv, office_id).await, "a refused registry token"); + + // The headers alone: the request runs as the account they name, on a + // feed… + let (status, body) = me(office_says(srv.client().get(&whoami))).await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert_eq!(body["username"], json!(office)); + assert!(used(&srv, office_id).await, "the headers on a feed"); + // …on the registry, which challenges it for a token like anyone + // without a credential of their own… + forget_use(&srv, office_id).await; + let resp = office_says(srv.client().get(&v2)).send().await.unwrap(); + assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); + assert!(used(&srv, office_id).await, "the headers on the registry"); + // …and with the registry token the headers alone got, which names + // nobody: the request still runs as the account the headers name. + forget_use(&srv, office_id).await; + let anonymous = registry_token(office_says(srv.client().get(&token_url))).await; + assert!( + used(&srv, office_id).await, + "the headers at the token service" + ); + forget_use(&srv, office_id).await; + let resp = office_says(srv.client().get(&v2)) + .bearer_auth(&anonymous) + .send() + .await + .unwrap(); + assert_eq!(resp.status(), StatusCode::OK); + assert!( + used(&srv, office_id).await, + "the headers beside their own registry token" + ); +} diff --git a/docs/changes/2.2.0/586.fixed.md b/docs/changes/2.2.0/586.fixed.md new file mode 100644 index 00000000..7b4c3994 --- /dev/null +++ b/docs/changes/2.2.0/586.fixed.md @@ -0,0 +1,7 @@ +**Admin → Service accounts** showed an account a trusted-header realm names +as just used ("Last used") for every request the proxy's headers named it +in, also the ones that ran as someone else: an npm request with its own +Bearer token, or a docker request with a registry token. From a network the +load balancer admits as a service account, the account so looked in use +while nobody relied on it. A use is now recorded only for a request that +runs as the account.