From e98b70f25460172b7d42e3d8ad8bb4ff3edbb988 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 13:50:10 +1300 Subject: [PATCH 1/5] app/: the last web routes from ui.rs (sc-8900): GET /api/ui/orgs/{org} (the organization's page: projects with their newest build, usage and usage by project, the last 50 charges, members, and for admins the billing email and invitations; GitLab instances empty until sc-8634), GET /api/ui/org-exists/{slug}, POST /api/ui/requests (feedback of kind request, emailed to the team), GET /api/ui/staff/feedback; and POST /auth/dev-login for development and CI's screenshots (DEV_LOGIN=true, never in production, reported by /auth/providers) --- app/src/auth/invitations.rs | 2 +- app/src/auth/me.rs | 43 +++++++++++++++++ app/src/auth/mod.rs | 1 + app/src/auth/orgs.rs | 96 ++++++++++++++++++++++++++++++++++++- app/src/auth/sign_in.rs | 64 ++++++++++++++++++++++++- app/src/auth/staff.rs | 39 +++++++++++++++ app/src/lib.rs | 3 ++ app/tests/hosts.rs | 24 ++++++++++ app/tests/orgs.rs | 36 ++++++++++++++ app/tests/sign_in.rs | 25 ++++++++++ app/tests/staff.rs | 34 +++++++++++++ 11 files changed, 363 insertions(+), 4 deletions(-) diff --git a/app/src/auth/invitations.rs b/app/src/auth/invitations.rs index 3ca34dec..b4635535 100644 --- a/app/src/auth/invitations.rs +++ b/app/src/auth/invitations.rs @@ -136,7 +136,7 @@ pub async fn may_send(org_id: i64, address: Option<&str>) -> laravel::Result laravel::Result<(i64, String, Role)> { +pub(crate) async fn org_role(user: &User, slug: &str) -> laravel::Result<(i64, String, Role)> { let user_id = user.id; let row = db::query!( "SELECT o.id, o.name, m.role FROM organizations o \ diff --git a/app/src/auth/me.rs b/app/src/auth/me.rs index 30dd4c56..72f95b4e 100644 --- a/app/src/auth/me.rs +++ b/app/src/auth/me.rs @@ -20,6 +20,7 @@ pub fn routes(route: &mut Router) { route.get("/api/ui/me", me); route.patch("/api/ui/me/notifications", update_notifications); route.post("/api/ui/me/heard-about", heard_about); + route.post("/api/ui/requests", create_request); route.put("/api/ui/orgs/{org}/billing-email", update_billing_email); } @@ -457,3 +458,45 @@ mod tests { assert!(text.contains("Buildkite with Cypress")); } } + +#[laravel::input] +#[validate(authenticated)] +pub struct RequestInput { + text: Option, +} + +/// `POST /api/ui/requests`, "What do you need from VisualCI?": kept as feedback of kind `request`, which emails the +/// team; they reply by email, to the address it returns. +pub async fn create_request( + Authenticated(user): Authenticated, + Valid(p): Valid, +) -> laravel::Result> { + use crate::domain::feedback::{self, FeedbackError, Report, Sender}; + let text = p.text.as_deref().unwrap_or_default().trim(); + if text.is_empty() { + return Err(laravel::abort_with(422, "write what you need")); + } + let mut title: String = text.lines().next().unwrap_or(text).chars().take(120).collect(); + if title.chars().count() < 3 { + title = format!("Request: {title}"); + } + let report = Report { + title: Some(title), + kind: Some("request".into()), + description: Some(text.chars().take(4000).collect()), + source: Some("user".into()), + ..Default::default() + }; + let sender = Sender { + user_id: Some(user.id), + project_id: None, + account: format!("user:{}", user.id), + channel: "web", + client: None, + }; + match feedback::record(sender, report).await { + Ok(_) => Ok(Json(json!({ "ok": true, "email": user.email }))), + Err(FeedbackError::Invalid(m) | FeedbackError::RateLimited(m)) => Err(laravel::abort_with(422, m)), + Err(FeedbackError::Server(e)) => Err(e), + } +} diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 592a33d6..3d3642ea 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -279,6 +279,7 @@ pub fn routes(route: &mut laravel::prelude::Router) { route.get("/auth/session", sign_in::session); route.get("/auth/providers", sign_in::providers); route.post("/auth/logout", sign_in::logout); + route.post("/auth/dev-login", sign_in::dev_login); setup::routes(route); // Anything else on the web group is a page of the React app route.fallback(crate::http::app_shell::app_shell); diff --git a/app/src/auth/orgs.rs b/app/src/auth/orgs.rs index fb1c2f02..2297f70f 100644 --- a/app/src/auth/orgs.rs +++ b/app/src/auth/orgs.rs @@ -6,11 +6,14 @@ use laravel::db; use laravel::prelude::*; use serde_json::{Value, json}; -use crate::models::User; +use super::Role; use crate::models::valid_slug; +use crate::models::{Build, Organization, User}; pub fn routes(route: &mut Router) { route.post("/api/ui/orgs", create); + route.get("/api/ui/orgs/{org}", show); + route.get("/api/ui/org-exists/{slug}", exists); } /// Organizations someone may create in a day. @@ -112,3 +115,94 @@ pub async fn create_org(user: &User, slug: &str, name: &str) -> laravel::Result< } Ok(slug) } + +/// `GET /api/ui/org-exists/{slug}`: whether an organization has the slug, for the new-organization form. +pub async fn exists(Params(slug): Params) -> laravel::Result> { + let found: Option = db::query!("SELECT id FROM organizations WHERE slug = {slug}").scalar().await?; + Ok(Json(json!({ "exists": found.is_some() }))) +} + +/// A build as the organization's page lists it: its project's newest. +fn build_summary(b: &Build) -> Value { + json!({ + "number": b.number, "name": b.name, "branch": b.branch, "commit_sha": b.commit_sha, "pr_number": b.pr_number, + "mode": b.mode, "environment": b.environment, + "environment_info": crate::domain::builds::environment_info_for(b, true), + "state": b.state, "review_state": b.review_state, "conclusion": b.conclusion, + "stats": crate::domain::builds::stats(b), "created_at": b.created_at.to_string(), + }) +} + +/// This month's credits per project, with how much came from the open source pool, for the Usage tab. +async fn usage_by_project(org_id: i64) -> laravel::Result> { + let since = crate::domain::credits::month_start(); + let rows = db::query!( + "SELECT p.slug, p.name, (p.open_source AND p.public AND NOT p.open_source_withdrawn) AS open_source, \ + COALESCE(-SUM(t.amount), 0)::bigint AS credits, COALESCE(SUM(t.open_source_credits), 0)::bigint AS pool \ + FROM projects p LEFT JOIN credit_transactions t ON t.project_id = p.id AND t.created_at >= {since} \ + AND t.kind IN ('build', 'render', 'gallery') \ + WHERE p.organization_id = {org_id} GROUP BY p.id ORDER BY credits DESC, p.slug" + ) + .select() + .await?; + rows.iter() + .map(|r| { + Ok(json!({ + "project": r.try_get::("slug")?, "name": r.try_get::("name")?, + "open_source": r.try_get::("open_source")?, "credits": r.try_get::("credits")?, + "open_source_credits": r.try_get::("pool")?, + })) + }) + .collect() +} + +/// `GET /api/ui/orgs/{org}`: the organization's page for a member: its projects with their newest build, the last 50 +/// charges, this month's usage (in all and by project), its members, and for admins its billing email and pending +/// invitations. Self-managed GitLab is off until sc-8634, so its section is empty and hidden. +pub async fn show( + Authenticated(user): Authenticated, + Params(org): Params, +) -> laravel::Result> { + let (org_id, _, role) = super::invitations::org_role(&user, &org).await?; + let org = Organization::find_or_fail(org_id).await?; + let admin = role == Role::Admin; + let projects: Vec<(i64, String, String)> = + db::query!("SELECT id, slug, name FROM projects WHERE organization_id = {org_id} ORDER BY slug") + .select() + .await? + .iter() + .map(|r| Ok((r.try_get("id")?, r.try_get("slug")?, r.try_get("name")?))) + .collect::>()?; + let mut list = Vec::new(); + for (id, slug, name) in projects { + let last = crate::domain::builds::recent(id, None, false, 1).await?; + list.push(json!({ "slug": slug, "name": name, "last_build": last.first().map(build_summary) })); + } + let history: Vec = db::query!( + "SELECT -amount AS credits, kind, reference, \ + to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') AS created_at FROM credit_transactions \ + WHERE organization_id = {org_id} AND kind IN ('build', 'render', 'gallery') ORDER BY id DESC LIMIT 50" + ) + .select() + .await? + .iter() + .map(|r| { + Ok(json!({ + "credits": r.try_get::("credits")?, "kind": r.try_get::("kind")?, + "reference": r.try_get::>("reference")?, + "created_at": r.try_get::("created_at")?, + })) + }) + .collect::>()?; + let invitations = if admin { super::invitations::pending(org_id).await? } else { Vec::new() }; + Ok(Json(json!({ + "slug": org.slug, "name": org.name, "role": role.as_str(), + "usage": crate::domain::credits::usage(&org).await?, + "subscribed": org.stripe_subscription_id.is_some(), + "billing_email": if admin { org.billing_email.clone() } else { None }, + "projects": list, "history": history, "usage_by_project": usage_by_project(org_id).await?, + "members": super::invitations::members_json(org_id, admin).await?, "invitations": invitations, + "setup": super::setup::state(org_id, Some(user.pid)).await?, + "gitlab_instances": [], "gitlab_instances_enabled": false, + }))) +} diff --git a/app/src/auth/sign_in.rs b/app/src/auth/sign_in.rs index 5eed8d59..973ff886 100644 --- a/app/src/auth/sign_in.rs +++ b/app/src/auth/sign_in.rs @@ -249,8 +249,68 @@ impl ForgeApps { } /// `GET /auth/providers`: the sign-in buttons the web app shows. -pub async fn providers(apps: laravel::config::Section) -> Json { - Json(serde_json::json!({ "forges": apps.forges(), "dev_login": false })) +pub async fn providers( + apps: laravel::config::Section, + dev: laravel::config::Section, +) -> Json { + Json(serde_json::json!({ "forges": apps.forges(), "dev_login": dev.allowed() })) +} + +/// Development and tests only: sign in as anyone by email (`DEV_LOGIN=true`), for local work and CI's screenshots. +/// Never in production, whatever the flag says. +#[derive(Clone, Debug, laravel::config::Section)] +pub struct DevLogin { + #[env("DEV_LOGIN", default = false)] + pub enabled: bool, +} + +impl DevLogin { + /// Whether the development sign-in is on here: the flag, outside production. + #[must_use] + pub fn allowed(&self) -> bool { + self.enabled && !laravel::config().app.env.is_production() + } +} + +#[laravel::input] +#[validate(anyone)] +pub struct DevLoginInput { + #[validate(required, email)] + email: String, +} + +/// `POST /auth/dev-login` (development and tests only): signs in as the user with this email, made if there's none +/// (verified, and asked how they heard about VisualCI like any new account). A 404 unless [`DevLogin::allowed`]. +pub async fn dev_login( + dev: laravel::config::Section, + auth: Auth, + hosts: laravel::config::Section, + Valid(p): Valid, +) -> laravel::Result { + if !dev.allowed() { + return Err(laravel::abort(404)); + } + let email = p.email.trim().to_lowercase(); + let user = match User::query().filter(User::email.eq(&email)).first().await? { + Some(user) => user, + None => { + let name = email.split('@').next().unwrap_or("dev").to_string(); + let user = create!(User { + pid: laravel::str::uuid7(), + name: name, + email: email.clone(), + email_verified_at: Some(laravel::now()), + staff: false, + }) + .await?; + let user_id = user.id; + db::query!("UPDATE users SET heard_about_pending = true WHERE id = {user_id}").update().await?; + SignedUp { user_id, via: "dev".to_string() }.dispatch().await?; + user + } + }; + auth.login(&user).await?; + Ok(laravel::http::Response::new(Json(serde_json::json!({ "ok": true }))).with_cookie(signed_in_hint(&hosts, true))) } /// `POST /auth/logout`: the session ends, and so does the site's hint. diff --git a/app/src/auth/staff.rs b/app/src/auth/staff.rs index 18b56f6a..f226a220 100644 --- a/app/src/auth/staff.rs +++ b/app/src/auth/staff.rs @@ -15,6 +15,7 @@ pub fn routes(route: &mut Router) { route.get("/api/ui/staff/signups", signups); route.get("/api/ui/staff/emails", emails); route.post("/api/ui/staff/emails/{id}/resolve", resolve); + route.get("/api/ui/staff/feedback", feedback); } fn staff_only(user: &User) -> laravel::Result<()> { @@ -128,3 +129,41 @@ pub async fn resolve( } Ok(Json(json!({ "id": id }))) } + +#[laravel::query] +pub struct FeedbackQuery { + /// The next page: feedback older than this ID. + before: Option, +} + +/// `GET /api/ui/staff/feedback`: customers' feedback, newest first, 100 at a time (`?before=` for the next +/// page), with who sent it and whether someone handled it. +pub async fn feedback( + Authenticated(user): Authenticated, + Query(q): Query, +) -> laravel::Result> { + staff_only(&user)?; + let before = q.before; + let rows = db::query!( + "SELECT json_build_object('id', f.id, 'pid', f.pid::text, 'title', f.title, 'kind', f.kind, \ + 'description', f.description, 'impact', f.impact, 'task', f.task, 'tool', f.tool, 'error', f.error, \ + 'suggestion', f.suggestion, 'session', f.session, 'channel', f.channel, 'client', f.client, \ + 'request_ids', f.request_ids, 'agent', f.agent, \ + 'user', CASE WHEN u.id IS NULL THEN NULL ELSE json_build_object('email', u.email, 'name', u.name) END, \ + 'project', CASE WHEN p.id IS NULL THEN NULL ELSE o.slug || '/' || p.slug END, \ + 'created_at', to_char(f.created_at AT TIME ZONE 'UTC', {TIME}), \ + 'notified_at', to_char(f.notified_at AT TIME ZONE 'UTC', {TIME}), \ + 'handled_at', to_char(f.handled_at AT TIME ZONE 'UTC', {TIME}), \ + 'handled_by', h.email, 'handled_note', f.handled_note)::text AS j \ + FROM feedback f LEFT JOIN users u ON u.id = f.user_id LEFT JOIN users h ON h.id = f.handled_by \ + LEFT JOIN projects p ON p.id = f.project_id LEFT JOIN organizations o ON o.id = p.organization_id \ + WHERE ({before}::bigint IS NULL OR f.id < {before}) ORDER BY f.id DESC LIMIT 100" + ) + .select() + .await?; + let items = rows + .iter() + .map(|r| Ok(serde_json::from_str::(&r.try_get::("j")?)?)) + .collect::>>()?; + Ok(Json(json!({ "feedback": items }))) +} diff --git a/app/src/lib.rs b/app/src/lib.rs index 043bd950..51daecf3 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -61,6 +61,9 @@ pub fn configure() -> ApplicationBuilder { // addresses (probes). `route_by_host` is the host check instead: each configured host reaches only its // own paths, and in production any other host only `/up` and the renderers' paths. middleware.trust_hosts(["*"]); + // The development sign-in (refused in production and unless DEV_LOGIN is on) is posted by CI's screenshot + // scripts, which send no Sec-Fetch-Site and hold no CSRF token yet + middleware.replace(laravel::http::middleware::PreventRequestForgery::new().except(["auth/dev-login"])); // Outermost, so every response gets the security headers, the host check's 404s included middleware.prepend(http::security::security_headers); }) diff --git a/app/tests/hosts.rs b/app/tests/hosts.rs index a09a626a..79836357 100644 --- a/app/tests/hosts.rs +++ b/app/tests/hosts.rs @@ -157,3 +157,27 @@ async fn every_response_carries_the_security_headers(app: Application) { .assert_status(404) .assert_header("x-frame-options", "DENY"); } + +/// The development sign-in never works in production, even with its flag set. +#[tokio::test(flavor = "multi_thread")] +async fn production_refuses_the_development_sign_in() { + let app = in_production() + .with_envs([ + ("DEV_LOGIN", "true"), + ("VISUALCI_SITE_URL", "https://visualci.test"), + ("VISUALCI_APP_URL", "https://app.visualci.test"), + ("VISUALCI_API_URL", "https://api.visualci.test"), + ("VISUALCI_MCP_URL", "https://mcp.visualci.test"), + ("OAUTH_ISSUER", "https://mcp.visualci.test"), + ("OAUTH_AUTHORIZATION_ENDPOINT", "https://app.visualci.test/oauth/authorize"), + ]) + .create(); + app.boot().await.expect("it boots"); + let host = "app.visualci.test"; + app.get("/auth/providers").header("host", host).await.assert_ok().assert_json_path("dev_login", false); + app.post("/auth/dev-login") + .header("host", host) + .json(json!({ "email": "owner@visualci.test" })) + .await + .assert_status(404); +} diff --git a/app/tests/orgs.rs b/app/tests/orgs.rs index cd40bce4..a8e0ab4c 100644 --- a/app/tests/orgs.rs +++ b/app/tests/orgs.rs @@ -34,3 +34,39 @@ async fn the_creator_is_the_admin_and_creations_are_limited(app: Application) -> make("acme-7", "Acme").await.assert_status(422); Ok(()) } + +/// An organization's page: its projects with their newest build, usage, members, and for admins the billing email and +/// invitations; a 404 for anyone outside it. `org-exists` says whether a slug is taken. +#[laravel::test] +async fn members_see_the_organizations_page(app: Application) -> laravel::Result<()> { + use app::testing::fixtures; + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let bob = create!(User { pid: laravel::str::uuid7(), name: "Bob", email: "bob@example.com", staff: false }).await?; + let eve = create!(User { pid: laravel::str::uuid7(), name: "Eve", email: "eve@example.com", staff: false }).await?; + let org = fixtures::organization("acme").await?; + fixtures::member(&org, &ada, "admin").await?; + fixtures::member(&org, &bob, "member").await?; + fixtures::project(&org, "web").await?; + let org_id = org.id; + db::query!("UPDATE organizations SET billing_email = 'billing@acme.test' WHERE id = {org_id}").update().await?; + + let page = app.get("/api/ui/orgs/acme").acting_as(&ada).await; + page.assert_ok() + .assert_json_path("slug", "acme") + .assert_json_path("role", "admin") + .assert_json_path("billing_email", "billing@acme.test") + .assert_json_path("projects.0.slug", "web") + .assert_json_path("projects.0.last_build", json!(null)) + .assert_json_path("usage_by_project.0.project", "web") + .assert_json_path("gitlab_instances_enabled", false); + assert_eq!(page.json()["members"].as_array().map(Vec::len), Some(2)); + assert!(page.json()["usage"]["plan"]["name"].is_string(), "{}", page.json()["usage"]); + + let as_member = app.get("/api/ui/orgs/acme").acting_as(&bob).await; + as_member.assert_ok().assert_json_path("role", "member").assert_json_path("billing_email", json!(null)); + app.get("/api/ui/orgs/acme").acting_as(&eve).await.assert_status(404); + + app.get("/api/ui/org-exists/acme").acting_as(&eve).await.assert_ok().assert_json_path("exists", true); + app.get("/api/ui/org-exists/nobody").acting_as(&eve).await.assert_ok().assert_json_path("exists", false); + Ok(()) +} diff --git a/app/tests/sign_in.rs b/app/tests/sign_in.rs index 65f49b08..d2fededc 100644 --- a/app/tests/sign_in.rs +++ b/app/tests/sign_in.rs @@ -289,3 +289,28 @@ 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"); } + +fn dev_login() -> Application { + app::testing::configure().with_env("DEV_LOGIN", "true").create() +} + +/// The development sign-in, for local work and CI's screenshots: signs in by email (making the account), posted +/// without a browser's same-origin header; the providers say it's there. Off unless DEV_LOGIN is set. +#[laravel::test(app = dev_login)] +async fn the_development_sign_in_signs_in_by_email(app: Application) -> laravel::Result<()> { + app.get("/auth/providers").await.assert_ok().assert_json_path("dev_login", true); + let signed_in = app.post("/auth/dev-login").json(json!({ "email": "Owner@VisualCI.test" })).await; + signed_in.assert_ok().assert_json_path("ok", true); + let user = User::first_where(User::email.eq("owner@visualci.test")).await?.expect("the account made"); + assert!(user.email_verified_at.is_some()); + app.get("/api/ui/me").acting_as(&user).await.assert_ok(); + app.post("/auth/dev-login").json(json!({ "email": "not an email" })).await.assert_status(422); + Ok(()) +} + +#[laravel::test] +async fn the_development_sign_in_is_off_without_its_flag(app: Application) -> laravel::Result<()> { + app.get("/auth/providers").await.assert_ok().assert_json_path("dev_login", false); + app.post("/auth/dev-login").json(json!({ "email": "owner@visualci.test" })).await.assert_status(404); + Ok(()) +} diff --git a/app/tests/staff.rs b/app/tests/staff.rs index 11ee277b..f616c5bd 100644 --- a/app/tests/staff.rs +++ b/app/tests/staff.rs @@ -47,3 +47,37 @@ async fn staff_see_sign_ups_and_emails_and_resolve_failures(app: Application) -> app.get("/api/ui/staff/emails").acting_as(&grace).await.assert_json_path("failed", json!([])); Ok(()) } + +/// "What do you need from VisualCI?" becomes feedback of kind `request`, which staff read with the rest. +#[laravel::test] +async fn requests_reach_staffs_feedback_list(app: Application) -> laravel::Result<()> { + let grace = + create!(User { pid: laravel::str::uuid7(), name: "Grace", email: "grace@example.com", staff: true }).await?; + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let ask = |text: &str| { + app.post("/api/ui/requests") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "text": text })) + }; + ask(" ").await.assert_status(422); + ask("Bitbucket support\nWe use Bitbucket Pipelines.") + .await + .assert_ok() + .assert_json_path("email", "ada@example.com"); + + app.get("/api/ui/staff/feedback").acting_as(&ada).await.assert_status(404); + let list = app.get("/api/ui/staff/feedback").acting_as(&grace).await; + list.assert_ok() + .assert_json_path("feedback.0.kind", "request") + .assert_json_path("feedback.0.title", "Bitbucket support") + .assert_json_path("feedback.0.channel", "web") + .assert_json_path("feedback.0.user.email", "ada@example.com"); + let id = list.json()["feedback"][0]["id"].as_i64().unwrap(); + app.get(format!("/api/ui/staff/feedback?before={id}")) + .acting_as(&grace) + .await + .assert_ok() + .assert_json_path("feedback", json!([])); + Ok(()) +} From 2104e69bd5ff78c384919a5691bc10719fd82584 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 15:02:47 +1300 Subject: [PATCH 2/5] app/: the development sign-in exists only outside production: a production boot with DEV_LOGIN refuses to start, and its route isn't registered there (sc-8900) --- app/src/auth/mod.rs | 1 - app/src/auth/sign_in.rs | 25 +++++++++++++++++++++++-- app/src/lib.rs | 9 ++++++++- app/tests/hosts.rs | 30 +++++++++++++++++------------- 4 files changed, 48 insertions(+), 17 deletions(-) diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 3d3642ea..592a33d6 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -279,7 +279,6 @@ pub fn routes(route: &mut laravel::prelude::Router) { route.get("/auth/session", sign_in::session); route.get("/auth/providers", sign_in::providers); route.post("/auth/logout", sign_in::logout); - route.post("/auth/dev-login", sign_in::dev_login); setup::routes(route); // Anything else on the web group is a page of the React app route.fallback(crate::http::app_shell::app_shell); diff --git a/app/src/auth/sign_in.rs b/app/src/auth/sign_in.rs index 973ff886..8fad7a62 100644 --- a/app/src/auth/sign_in.rs +++ b/app/src/auth/sign_in.rs @@ -270,6 +270,26 @@ impl DevLogin { pub fn allowed(&self) -> bool { self.enabled && !laravel::config().app.env.is_production() } + + /// Whether to register `POST /auth/dev-login` at all: only outside production, with the flag on. In production + /// the route doesn't exist. + #[must_use] + pub fn routable(config: &laravel::config::Config) -> bool { + config.section::().enabled && !config.app.env.is_production() + } + + /// Production refuses to boot with `DEV_LOGIN` on: it would let anyone sign in as anyone. + /// + /// # Errors + /// That. + pub fn check(&self, production: bool) -> laravel::Result<()> { + if production && self.enabled { + return Err(laravel::Error::msg( + "DEV_LOGIN is on in production: it lets anyone sign in as anyone. Remove it from the environment.", + )); + } + Ok(()) + } } #[laravel::input] @@ -279,8 +299,9 @@ pub struct DevLoginInput { email: String, } -/// `POST /auth/dev-login` (development and tests only): signs in as the user with this email, made if there's none -/// (verified, and asked how they heard about VisualCI like any new account). A 404 unless [`DevLogin::allowed`]. +/// `POST /auth/dev-login` (development and tests only, registered only when [`DevLogin::routable`]): signs in as the +/// user with this email, made if there's none (verified, and asked how they heard about VisualCI like any new +/// account). It checks [`DevLogin::allowed`] again itself. pub async fn dev_login( dev: laravel::config::Section, auth: Auth, diff --git a/app/src/lib.rs b/app/src/lib.rs index 51daecf3..ed77218a 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -48,6 +48,7 @@ pub fn configure() -> ApplicationBuilder { http::hosts::check(config.section::(), config.app.env.is_production())?; billing::check(config.section::(), config.app.env.is_production())?; http::security::check(config, config.app.env.is_production())?; + config.section::().check(config.app.env.is_production())?; Ok(()) }) .with_middleware(|middleware, _| { @@ -67,7 +68,13 @@ pub fn configure() -> ApplicationBuilder { // Outermost, so every response gets the security headers, the host check's 404s included middleware.prepend(http::security::security_headers); }) - .with_routing(|routing, _| { + .with_routing(|routing, config| { + // The development sign-in exists only outside production, with DEV_LOGIN on + if auth::sign_in::DevLogin::routable(config) { + routing.web(|route| { + route.post("/auth/dev-login", auth::sign_in::dev_login); + }); + } routing .web(auth::routes) .api(http::api::routes) diff --git a/app/tests/hosts.rs b/app/tests/hosts.rs index 79836357..093431ba 100644 --- a/app/tests/hosts.rs +++ b/app/tests/hosts.rs @@ -158,25 +158,29 @@ async fn every_response_carries_the_security_headers(app: Application) { .assert_header("x-frame-options", "DENY"); } -/// The development sign-in never works in production, even with its flag set. +/// The development sign-in can't exist in production: production won't boot with DEV_LOGIN on, and without it the +/// route isn't there (a 404, not a refusal) and the providers don't offer it. #[tokio::test(flavor = "multi_thread")] -async fn production_refuses_the_development_sign_in() { - let app = in_production() - .with_envs([ - ("DEV_LOGIN", "true"), - ("VISUALCI_SITE_URL", "https://visualci.test"), - ("VISUALCI_APP_URL", "https://app.visualci.test"), - ("VISUALCI_API_URL", "https://api.visualci.test"), - ("VISUALCI_MCP_URL", "https://mcp.visualci.test"), - ("OAUTH_ISSUER", "https://mcp.visualci.test"), - ("OAUTH_AUTHORIZATION_ENDPOINT", "https://app.visualci.test/oauth/authorize"), - ]) - .create(); +async fn production_has_no_development_sign_in() { + let hosts = [ + ("VISUALCI_SITE_URL", "https://visualci.test"), + ("VISUALCI_APP_URL", "https://app.visualci.test"), + ("VISUALCI_API_URL", "https://api.visualci.test"), + ("VISUALCI_MCP_URL", "https://mcp.visualci.test"), + ("OAUTH_ISSUER", "https://mcp.visualci.test"), + ("OAUTH_AUTHORIZATION_ENDPOINT", "https://app.visualci.test/oauth/authorize"), + ]; + let flagged = in_production().with_envs(hosts).with_env("DEV_LOGIN", "true").create(); + let refused = flagged.boot().await.expect_err("production doesn't boot with DEV_LOGIN on"); + assert!(format!("{refused:?}").contains("DEV_LOGIN"), "{refused:?}"); + + let app = in_production().with_envs(hosts).create(); app.boot().await.expect("it boots"); let host = "app.visualci.test"; app.get("/auth/providers").header("host", host).await.assert_ok().assert_json_path("dev_login", false); app.post("/auth/dev-login") .header("host", host) + .header("sec-fetch-site", "same-origin") .json(json!({ "email": "owner@visualci.test" })) .await .assert_status(404); From b6ada6d6f390528d09b8d874212c51b2f0dd78ae Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 15:05:16 +1300 Subject: [PATCH 3/5] app/: the development sign-in runs only where APP_ENV is local or testing; a misspelt environment counts as production (sc-8900) --- app/src/auth/sign_in.rs | 32 ++++++++++++++++++++------------ app/src/lib.rs | 4 ++-- app/tests/hosts.rs | 4 ++++ 3 files changed, 26 insertions(+), 14 deletions(-) diff --git a/app/src/auth/sign_in.rs b/app/src/auth/sign_in.rs index 8fad7a62..135ff20d 100644 --- a/app/src/auth/sign_in.rs +++ b/app/src/auth/sign_in.rs @@ -10,6 +10,7 @@ use laravel::auth::Auth; use laravel::auth::social::{self, Provider}; +use laravel::config::app::Environment; use laravel::db; use laravel::model::create; use laravel::prelude::*; @@ -257,36 +258,43 @@ pub async fn providers( } /// Development and tests only: sign in as anyone by email (`DEV_LOGIN=true`), for local work and CI's screenshots. -/// Never in production, whatever the flag says. +/// Only where `APP_ENV` is `local` or `testing`: an unset `APP_ENV` is production, and so is a misspelt one here. #[derive(Clone, Debug, laravel::config::Section)] pub struct DevLogin { #[env("DEV_LOGIN", default = false)] pub enabled: bool, } +/// Whether `env` is a development one (`local` or `testing`), where the development sign-in may run. +fn development(env: &Environment) -> bool { + matches!(env, Environment::Local | Environment::Testing) +} + impl DevLogin { - /// Whether the development sign-in is on here: the flag, outside production. + /// Whether the development sign-in is on here: the flag, in development. #[must_use] pub fn allowed(&self) -> bool { - self.enabled && !laravel::config().app.env.is_production() + self.enabled && development(&laravel::config().app.env) } - /// Whether to register `POST /auth/dev-login` at all: only outside production, with the flag on. In production - /// the route doesn't exist. + /// Whether to register `POST /auth/dev-login` at all: only in development, with the flag on. Anywhere else the + /// route doesn't exist. #[must_use] pub fn routable(config: &laravel::config::Config) -> bool { - config.section::().enabled && !config.app.env.is_production() + config.section::().enabled && development(&config.app.env) } - /// Production refuses to boot with `DEV_LOGIN` on: it would let anyone sign in as anyone. + /// Anything but development refuses to boot with `DEV_LOGIN` on: it would let anyone sign in as anyone. /// /// # Errors /// That. - pub fn check(&self, production: bool) -> laravel::Result<()> { - if production && self.enabled { - return Err(laravel::Error::msg( - "DEV_LOGIN is on in production: it lets anyone sign in as anyone. Remove it from the environment.", - )); + pub fn check(&self, env: &Environment) -> laravel::Result<()> { + if self.enabled && !development(env) { + return Err(laravel::Error::msg(format!( + "DEV_LOGIN is on with APP_ENV={}: it lets anyone sign in as anyone, so it runs only in local or \ + testing. Remove it from the environment.", + env.as_str() + ))); } Ok(()) } diff --git a/app/src/lib.rs b/app/src/lib.rs index ed77218a..a26eba39 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -48,7 +48,7 @@ pub fn configure() -> ApplicationBuilder { http::hosts::check(config.section::(), config.app.env.is_production())?; billing::check(config.section::(), config.app.env.is_production())?; http::security::check(config, config.app.env.is_production())?; - config.section::().check(config.app.env.is_production())?; + config.section::().check(&config.app.env)?; Ok(()) }) .with_middleware(|middleware, _| { @@ -69,7 +69,7 @@ pub fn configure() -> ApplicationBuilder { middleware.prepend(http::security::security_headers); }) .with_routing(|routing, config| { - // The development sign-in exists only outside production, with DEV_LOGIN on + // The development sign-in exists only in local and testing, with DEV_LOGIN on if auth::sign_in::DevLogin::routable(config) { routing.web(|route| { route.post("/auth/dev-login", auth::sign_in::dev_login); diff --git a/app/tests/hosts.rs b/app/tests/hosts.rs index 093431ba..c1fed7ce 100644 --- a/app/tests/hosts.rs +++ b/app/tests/hosts.rs @@ -173,6 +173,10 @@ async fn production_has_no_development_sign_in() { let flagged = in_production().with_envs(hosts).with_env("DEV_LOGIN", "true").create(); let refused = flagged.boot().await.expect_err("production doesn't boot with DEV_LOGIN on"); assert!(format!("{refused:?}").contains("DEV_LOGIN"), "{refused:?}"); + // A misspelt environment counts as production: the development sign-in runs only in local and testing + let misspelt = in_production().with_envs(hosts).with_env("APP_ENV", "prod").with_env("DEV_LOGIN", "true").create(); + let refused = misspelt.boot().await.expect_err("APP_ENV=prod doesn't boot with DEV_LOGIN on"); + assert!(format!("{refused:?}").contains("APP_ENV=prod"), "{refused:?}"); let app = in_production().with_envs(hosts).create(); app.boot().await.expect("it boots"); From 210a1d3288aca96bba56962042fa7bd01277a8c4 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 15:17:31 +1300 Subject: [PATCH 4/5] app/tests/hosts.rs: in production, POST /auth/dev-login is a 405: only GET /auth/{forge} matches the path --- app/tests/hosts.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/tests/hosts.rs b/app/tests/hosts.rs index c1fed7ce..bd662433 100644 --- a/app/tests/hosts.rs +++ b/app/tests/hosts.rs @@ -187,5 +187,6 @@ async fn production_has_no_development_sign_in() { .header("sec-fetch-site", "same-origin") .json(json!({ "email": "owner@visualci.test" })) .await - .assert_status(404); + // No such route: only the sign-in start, GET /auth/{forge}, matches the path + .assert_status(405); } From 80e84112ea6c04bff703938332cf816527df2fc8 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 15:35:27 +1300 Subject: [PATCH 5/5] app/tests/sign_in.rs: without DEV_LOGIN, POST /auth/dev-login is a 405 and signs nobody up --- app/tests/sign_in.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/tests/sign_in.rs b/app/tests/sign_in.rs index d2fededc..27464ab2 100644 --- a/app/tests/sign_in.rs +++ b/app/tests/sign_in.rs @@ -311,6 +311,8 @@ async fn the_development_sign_in_signs_in_by_email(app: Application) -> laravel: #[laravel::test] async fn the_development_sign_in_is_off_without_its_flag(app: Application) -> laravel::Result<()> { app.get("/auth/providers").await.assert_ok().assert_json_path("dev_login", false); - app.post("/auth/dev-login").json(json!({ "email": "owner@visualci.test" })).await.assert_status(404); + // No such route: only the sign-in start, GET /auth/{forge}, matches the path + app.post("/auth/dev-login").json(json!({ "email": "owner@visualci.test" })).await.assert_status(405); + assert_eq!(User::query().count().await?, 0); Ok(()) }