From 5374899e60860ac5581abb56ceccd624ca583ceb Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 02:07:30 +1300 Subject: [PATCH 1/4] Auth review follow-ups (sc-8900): /auth/session as today (name, avatar, the one organization) with CORS for the site's exact origin alone and no-store; /auth/providers lists the configured forges; tokens' last_used_at written at most once a minute; a project token stays a member of its own project (can review, as today), documented and tested --- app/src/auth/mod.rs | 20 +++++++++++++- app/src/auth/sign_in.rs | 60 ++++++++++++++++++++++++++++++++++++++--- app/tests/auth.rs | 5 ++++ app/tests/sign_in.rs | 22 +++++++++++++++ 4 files changed, 102 insertions(+), 5 deletions(-) diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 614ff811..ae775820 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -132,7 +132,8 @@ impl Principal { } /// Their role in the project's organization, or `None` when they have none. A project token is a member of its - /// own project and nothing else. + /// own project and nothing else, as on today's server: CI uploads and finalizes, and an agent holding the token + /// may review (`review` needs a member). /// /// # Errors /// On a database error. @@ -183,12 +184,28 @@ impl Principal { /// On a database error. pub async fn from_token(token: &str) -> laravel::Result> { let hash = token_hash(token); + // When a token was last used, for the tokens pages: written at most once a minute per token, so a busy CI job + // doesn't write on every request if token.starts_with("vci_") { let Some(t) = ProjectToken::first_where(ProjectToken::token_hash.eq(&hash)).await? else { return Ok(None) }; + let id = t.id; + db::query!( + "UPDATE project_tokens SET last_used_at = now() WHERE id = {id} \ + AND (last_used_at IS NULL OR last_used_at < now() - interval '1 minute')" + ) + .update() + .await?; return Ok(Some(Self::Project { project_id: t.project_id, token_id: t.id, token_name: t.name })); } if token.starts_with("vcu_") { let Some(t) = UserToken::first_where(UserToken::token_hash.eq(&hash)).await? else { return Ok(None) }; + let id = t.id; + db::query!( + "UPDATE user_tokens SET last_used_at = now() WHERE id = {id} \ + AND (last_used_at IS NULL OR last_used_at < now() - interval '1 minute')" + ) + .update() + .await?; let Some(user) = User::find(t.user_id).await? else { return Ok(None) }; return Ok(Some(Self::User { user: Box::new(user), via: Via::Token { token_id: t.id, name: t.name } })); } @@ -245,5 +262,6 @@ pub fn routes(route: &mut laravel::prelude::Router) { route.post("/auth/{forge}/link", sign_in::link); route.get("/auth/{forge}/callback", sign_in::callback); route.get("/auth/session", sign_in::session); + route.get("/auth/providers", sign_in::providers); route.post("/auth/logout", sign_in::logout); } diff --git a/app/src/auth/sign_in.rs b/app/src/auth/sign_in.rs index 6df25cc8..f90317f5 100644 --- a/app/src/auth/sign_in.rs +++ b/app/src/auth/sign_in.rs @@ -162,10 +162,62 @@ pub async fn callback( } /// `GET /auth/session`: whether this browser is signed in, for visualci.com's static pages ("Open app" instead of -/// "Sign in"). Only what that button needs: no email, no IDs. -pub async fn session(auth: Auth) -> laravel::Result> { - let user = auth.user().await?; - Ok(Json(serde_json::json!({ "signed_in": user.is_some(), "name": user.map(|u| u.name) }))) +/// "Sign in"): the name and avatar for the button, and the organization when there's just one, so the button goes +/// straight to it. The site reads it with credentials, so it answers CORS for the site's own origin alone +/// (`VISUALCI_SITE_URL`, exactly), never a reflected one, and is never cached. +pub async fn session( + auth: Auth, + hosts: laravel::config::Section, + headers: axum::http::HeaderMap, +) -> laravel::Result { + let body = match auth.user().await? { + Some(user) => { + let user_id = user.id; + let orgs = db::query!( + "SELECT o.slug FROM organizations o JOIN memberships m ON m.organization_id = o.id \ + WHERE m.user_id = {user_id} ORDER BY o.slug LIMIT 2" + ) + .select_as::() + .await + .unwrap_or_default(); + let org = (orgs.len() == 1).then(|| orgs[0].clone()); + serde_json::json!({ "signed_in": true, "name": user.name, "avatar_url": user.avatar_url, "org": org }) + } + None => serde_json::json!({ "signed_in": false }), + }; + let mut response = laravel::http::Response::new(Json(body)) + .with_header("cache-control", "no-store") + .with_header("vary", "Origin, Cookie"); + let site = hosts.site.as_deref().map(|s| s.trim_end_matches('/').to_string()); + if let (Some(origin), Some(site)) = (headers.get(axum::http::header::ORIGIN).and_then(|o| o.to_str().ok()), site) + && origin == site + { + response = response + .with_header("access-control-allow-origin", origin.to_string()) + .with_header("access-control-allow-credentials", "true"); + } + Ok(response) +} + +/// The forges a person can sign in with here: those whose OAuth application is configured. +#[derive(Clone, laravel::config::Section)] +pub struct ForgeApps { + #[env("GITHUB_CLIENT_ID")] + pub github: Option, + #[env("GITLAB_CLIENT_ID")] + pub gitlab: Option, +} + +/// `GET /auth/providers`: the sign-in buttons the web app shows. +pub async fn providers(apps: laravel::config::Section) -> Json { + let mut forges = Vec::new(); + if apps.github.as_deref().is_some_and(|s| !s.is_empty()) { + forges.push("github"); + } + if apps.gitlab.as_deref().is_some_and(|s| !s.is_empty()) { + forges.push("gitlab"); + } + Json(serde_json::json!({ "forges": forges, "dev_login": false })) } /// `POST /auth/logout`. diff --git a/app/tests/auth.rs b/app/tests/auth.rs index f6981ee0..b27e2d16 100644 --- a/app/tests/auth.rs +++ b/app/tests/auth.rs @@ -57,6 +57,9 @@ async fn tokens_name_their_user_or_project(app: Application) -> laravel::Result< .assert_ok() .assert_json_path("principal.project_id", docs_id) .assert_json_path("client.source", "project_token"); + let used: Option = + db::query!("SELECT last_used_at IS NOT NULL FROM project_tokens WHERE token_hash = {jh}").scalar().await?; + assert_eq!(used, Some(true), "a token's use is recorded"); app.get("/api/v1/whoami").header("authorization", "Bearer vci_nope").await.assert_status(401); app.get("/api/v1/whoami").await.assert_status(401); Ok(()) @@ -77,6 +80,8 @@ async fn roles_come_from_memberships_and_a_project_token_is_a_member_of_its_proj assert!(!ada.can(Role::Admin, &mine).await?); assert!(!ada.can(Role::Read, &theirs).await?); + // As on today's server: a project token is a member of its own project, so CI (or an agent with the token) can + // upload, finalize and review, but not change settings let ci = Principal::Project { project_id: mine.id, token_id: 1, token_name: "CI".into() }; assert!(ci.can(Role::Member, &mine).await? && !ci.can(Role::Admin, &mine).await?); let sibling = ProjectRef { id: mine.id + 1000, organization_id: acme.id }; diff --git a/app/tests/sign_in.rs b/app/tests/sign_in.rs index 1886db3b..a25f08f9 100644 --- a/app/tests/sign_in.rs +++ b/app/tests/sign_in.rs @@ -220,3 +220,25 @@ async fn an_mcp_client_finds_the_oauth_server_and_its_consent_page_asks_for_sign page.assert_redirect_to("/login"); app.get("/login").with_cookies_from(&page).await.assert_ok().assert_see("Sign in with GitHub"); } + +fn with_site() -> Application { + app::testing::configure().with_env("VISUALCI_SITE_URL", "https://visualci.test").create() +} + +#[laravel::test(app = with_site)] +async fn the_session_answers_cors_for_the_site_alone(app: Application) { + let site = app.get("/auth/session").header("origin", "https://visualci.test").await; + site.assert_ok().assert_header("access-control-allow-origin", "https://visualci.test"); + site.assert_header("access-control-allow-credentials", "true"); + let outside = app.get("/auth/session").header("origin", "https://evil.example").await; + outside.assert_ok().assert_header_missing("access-control-allow-origin"); +} + +fn with_github() -> Application { + app::testing::configure().with_envs([("GITHUB_CLIENT_ID", "id"), ("GITHUB_CLIENT_SECRET", "secret")]).create() +} + +#[laravel::test(app = with_github)] +async fn providers_are_the_configured_forges(app: Application) { + app.get("/auth/providers").await.assert_ok().assert_json(json!({ "forges": ["github"], "dev_login": false })); +} From 32c7a78320da3042915d78916420b97a5f841715 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:23:57 +1300 Subject: [PATCH 2/4] Sign-in, review fixes: the site's signed-in hint (vci_signed_in, plain and readable by its script, on the site's domain) is set at sign-in, renewed or cleared by /auth/session and cleared at logout, as today's; /auth/providers and /login offer a forge only when its OAuth application has its ID and its secret --- app/src/auth/sign_in.rs | 103 +++++++++++++++++++++++++++++++++------- app/src/lib.rs | 2 + app/tests/sign_in.rs | 43 +++++++++++++++++ 3 files changed, 131 insertions(+), 17 deletions(-) diff --git a/app/src/auth/sign_in.rs b/app/src/auth/sign_in.rs index f90317f5..44edbfd1 100644 --- a/app/src/auth/sign_in.rs +++ b/app/src/auth/sign_in.rs @@ -66,13 +66,16 @@ fn safe_return(to: &str) -> Option { /// `GET /login`: where a page that needs a signed-in person (an MCP client's consent page) sends someone who isn't, /// and where they come back from afterwards (sign-in returns to the page they were sent from). One line per forge. #[laravel::auth::page(login)] -pub async fn login_page() -> laravel::http::Response { - let page = ") -> laravel::http::Response { + let forges = apps.forges(); + let gitlab = + if forges.contains(&"gitlab") { "

Sign in with GitLab

" } else { "" }; + let head = "Sign in · VisualCI

Sign in with GitHub

\ -

Sign in with GitLab

"; + p{margin:0 0 8px}

Sign in with GitHub

"; + let page = format!("{head}{gitlab}
"); laravel::http::Response::new(laravel::view::Html::raw(page)) } @@ -113,6 +116,7 @@ pub async fn callback( auth: Auth, sign_ups: laravel::config::Section, gitlab: laravel::config::Section, + hosts: laravel::config::Section, session: Session, ) -> laravel::Result { let provider = provider(&forge)?; @@ -158,7 +162,7 @@ pub async fn callback( // needs a route for its fallback) None => Redirect::to(session.pull::("url.intended").unwrap_or_else(|| "/".to_string())), }; - Ok(laravel::http::Response::new(back)) + Ok(laravel::http::Response::new(back).with_cookie(signed_in_hint(&hosts, true))) } /// `GET /auth/session`: whether this browser is signed in, for visualci.com's static pages ("Open app" instead of @@ -170,7 +174,20 @@ pub async fn session( hosts: laravel::config::Section, headers: axum::http::HeaderMap, ) -> laravel::Result { - let body = match auth.user().await? { + let user = auth.user().await?; + // The site's hint follows the answer: renewed while signed in, cleared once the session has gone. + let hinted = headers + .get_all(axum::http::header::COOKIE) + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|v| v.split(';')) + .any(|c| c.trim() == format!("{SIGNED_IN_HINT}=1")); + let hint = match (&user, hinted) { + (Some(_), _) => Some(signed_in_hint(&hosts, true)), + (None, true) => Some(signed_in_hint(&hosts, false)), + (None, false) => None, + }; + let body = match user { Some(user) => { let user_id = user.id; let orgs = db::query!( @@ -188,6 +205,9 @@ pub async fn session( let mut response = laravel::http::Response::new(Json(body)) .with_header("cache-control", "no-store") .with_header("vary", "Origin, Cookie"); + if let Some(hint) = hint { + response = response.with_cookie(hint); + } let site = hosts.site.as_deref().map(|s| s.trim_end_matches('/').to_string()); if let (Some(origin), Some(site)) = (headers.get(axum::http::header::ORIGIN).and_then(|o| o.to_str().ok()), site) && origin == site @@ -204,26 +224,75 @@ pub async fn session( pub struct ForgeApps { #[env("GITHUB_CLIENT_ID")] pub github: Option, + #[env("GITHUB_CLIENT_SECRET")] + pub github_secret: Option, #[env("GITLAB_CLIENT_ID")] pub gitlab: Option, + #[env("GITLAB_CLIENT_SECRET")] + pub gitlab_secret: Option, +} + +impl ForgeApps { + /// The forges whose OAuth application has both its ID and its secret. + #[must_use] + pub fn forges(&self) -> Vec<&'static str> { + let set = |v: &Option| v.as_deref().is_some_and(|s| !s.trim().is_empty()); + let mut forges = Vec::new(); + if set(&self.github) && set(&self.github_secret) { + forges.push("github"); + } + if set(&self.gitlab) && set(&self.gitlab_secret) { + forges.push("gitlab"); + } + forges + } } /// `GET /auth/providers`: the sign-in buttons the web app shows. pub async fn providers(apps: laravel::config::Section) -> Json { - let mut forges = Vec::new(); - if apps.github.as_deref().is_some_and(|s| !s.is_empty()) { - forges.push("github"); - } - if apps.gitlab.as_deref().is_some_and(|s| !s.is_empty()) { - forges.push("gitlab"); - } - Json(serde_json::json!({ "forges": forges, "dev_login": false })) + Json(serde_json::json!({ "forges": apps.forges(), "dev_login": false })) } -/// `POST /auth/logout`. -pub async fn logout(auth: Auth) -> laravel::Result> { +/// `POST /auth/logout`: the session ends, and so does the site's hint. +pub async fn logout( + auth: Auth, + hosts: laravel::config::Section, +) -> laravel::Result { auth.logout().await?; - Ok(Json(serde_json::json!({ "ok": true }))) + Ok(laravel::http::Response::new(Json(serde_json::json!({ "ok": true }))).with_cookie(signed_in_hint(&hosts, false))) +} + +/// The cookie visualci.com's static pages read to show "Open app" instead of "Sign in": `1` while signed in. It says +/// nothing else, so it's readable by the site's script (not `HttpOnly`) and not encrypted (`EncryptCookies` passes it +/// through). On the site's domain when the app is one of its subdomains (`Domain=visualci.com`), host-only otherwise. +pub const SIGNED_IN_HINT: &str = "vci_signed_in"; +/// How long the hint lasts: today's session's 30 days, renewed by every `/auth/session`. +const HINT_DAYS: i64 = 30; + +/// The hint, set (`on`) or cleared. +pub fn signed_in_hint(hosts: &crate::http::hosts::HostUrls, on: bool) -> laravel::cookie::Cookie { + use laravel::time::ToSpan; + let host = |url: &Option| { + let url = url.as_deref()?.trim(); + let rest = url.split_once("://").map_or(url, |(_, r)| r); + let host = rest.split(['/', ':']).next()?.to_ascii_lowercase(); + (!host.is_empty()).then_some(host) + }; + let domain = match (host(&hosts.site), host(&hosts.app)) { + (Some(site), Some(app)) if app.ends_with(&format!(".{site}")) => Some(site), + _ => None, + }; + let production = laravel::config().app.env.is_production(); + let mut cookie = laravel::cookie::Cookie::new(SIGNED_IN_HINT, if on { "1" } else { "" }) + .path("/") + .http_only(false) + .secure(production) + .same_site(laravel::cookie::SameSite::Lax) + .max_age(if on { HINT_DAYS.days() } else { 0.seconds() }); + if let Some(domain) = domain { + cookie = cookie.domain(domain); + } + cookie } /// The MCP client an authorization's return address names (`/oauth/authorize?client_id=…`). diff --git a/app/src/lib.rs b/app/src/lib.rs index 835b8494..a2fb8294 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -40,6 +40,8 @@ pub fn configure() -> ApplicationBuilder { }) .with_middleware(|middleware, _| { middleware.prepend(http::hosts::route_by_host); + // The site's signed-in hint is read by its script: plain, not encrypted + middleware.replace(laravel::cookie::EncryptCookies::except([auth::sign_in::SIGNED_IN_HINT])); }) .with_routing(|routing, _| { routing.web(auth::routes).api(http::api::routes).health("/up"); diff --git a/app/tests/sign_in.rs b/app/tests/sign_in.rs index a25f08f9..dc4ff232 100644 --- a/app/tests/sign_in.rs +++ b/app/tests/sign_in.rs @@ -45,6 +45,8 @@ async fn a_new_person_gets_an_account_and_returns_where_they_started(app: Applic start.assert_redirect(); let done = app.get("/auth/github/callback").with_cookies_from(&start).await; done.assert_redirect_to("/acme/web/builds/3"); + // The site's hint: plain, so its script can read it + done.assert_cookie("vci_signed_in", "1"); let user = User::first_where(User::email.eq("ada@example.com")).await?.expect("an account"); assert_eq!(user.name, "Ada Lovelace"); @@ -242,3 +244,44 @@ fn with_github() -> Application { async fn providers_are_the_configured_forges(app: Application) { app.get("/auth/providers").await.assert_ok().assert_json(json!({ "forges": ["github"], "dev_login": false })); } + +fn with_site_and_app() -> Application { + app::testing::configure() + .with_envs([("VISUALCI_SITE_URL", "https://visualci.test"), ("VISUALCI_APP_URL", "https://app.visualci.test")]) + .create() +} + +#[laravel::test(app = with_site_and_app)] +async fn the_sites_hint_follows_the_session(app: Application) -> laravel::Result<()> { + // A hint left over from a session that has gone is cleared; no hint and no session sends none. + app.get("/auth/session").cookie("vci_signed_in", "1").await.assert_ok().assert_cookie_expired("vci_signed_in"); + app.get("/auth/session").await.assert_ok().assert_cookie_missing("vci_signed_in"); + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let renewed = app.get("/auth/session").acting_as(&ada).await; + renewed.assert_ok().assert_cookie("vci_signed_in", "1"); + assert!( + renewed + .headers() + .get_all("set-cookie") + .iter() + .any(|v| v.to_str().unwrap_or("").contains("Domain=visualci.test")), + "shared with the site's domain" + ); + app.post("/auth/logout") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .await + .assert_ok() + .assert_cookie_expired("vci_signed_in"); + Ok(()) +} + +fn with_github_id_only() -> Application { + app::testing::configure().with_envs([("GITHUB_CLIENT_ID", "id"), ("GITLAB_CLIENT_ID", "id")]).create() +} + +#[laravel::test(app = with_github_id_only)] +async fn a_forge_without_its_secret_is_not_offered(app: Application) { + app.get("/auth/providers").await.assert_ok().assert_json(json!({ "forges": [], "dev_login": false })); + app.get("/login").await.assert_ok().assert_dont_see("GitLab"); +} From 911deb6a41b7be2dfae5b8e8731d26f35247efd8 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 04:22:39 +1300 Subject: [PATCH 3/4] Test: OAuth discovery expects the tests' APP_URL (https://app.visualci.test, since #59) --- app/tests/sign_in.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/tests/sign_in.rs b/app/tests/sign_in.rs index dc4ff232..471d2244 100644 --- a/app/tests/sign_in.rs +++ b/app/tests/sign_in.rs @@ -217,7 +217,7 @@ async fn an_mcp_client_finds_the_oauth_server_and_its_consent_page_asks_for_sign app.get("/.well-known/oauth-authorization-server") .await .assert_ok() - .assert_json_path("authorization_endpoint", "http://localhost/oauth/authorize"); + .assert_json_path("authorization_endpoint", "https://app.visualci.test/oauth/authorize"); let page = app.get("/oauth/authorize?client_id=x&response_type=code").header("accept", "text/html").await; page.assert_redirect_to("/login"); app.get("/login").with_cookies_from(&page).await.assert_ok().assert_see("Sign in with GitHub"); From 407ee0d69ab2525b8aa97f657c9077be36dd0832 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 04:30:32 +1300 Subject: [PATCH 4/4] app/Cargo.toml: one tracing entry (#57's merge listed it twice, so cargo couldn't read the manifest and main's app job failed) --- app/Cargo.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/app/Cargo.toml b/app/Cargo.toml index 6aad54ab..4c410008 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -41,7 +41,6 @@ tracing = "0.1" # VisualCI's own crates, shared with the CLI. visualci-core = { path = "../crates/visualci-core" } snapshot-diff = { path = "../crates/snapshot-diff" } -tracing = "0.1" [dev-dependencies] regex = "1"