From 4a8db345d47674289de50a998e5ae1456906abb8 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 02:56:28 +1300 Subject: [PATCH 1/6] app/: visualci login's device-code sign-in (sc-8900): POST /api/v1/device/code and /device/token for the CLI (device code stored hashed, ten minutes, one token once, claimed in one statement), GET/POST /api/ui/device/{code} for the person to approve or deny (codes read as typed); a security notice when the CLI signs in --- ...12_03_000600_create_device_logins_table.rs | 25 +++ app/src/auth/device.rs | 194 ++++++++++++++++++ app/src/auth/mod.rs | 3 + app/src/auth/tokens.rs | 26 ++- app/src/http/api.rs | 13 ++ app/tests/device.rs | 68 ++++++ 6 files changed, 321 insertions(+), 8 deletions(-) create mode 100644 app/database/migrations/2026_12_03_000600_create_device_logins_table.rs create mode 100644 app/src/auth/device.rs create mode 100644 app/src/http/api.rs create mode 100644 app/tests/device.rs diff --git a/app/database/migrations/2026_12_03_000600_create_device_logins_table.rs b/app/database/migrations/2026_12_03_000600_create_device_logins_table.rs new file mode 100644 index 00000000..9f5b38cd --- /dev/null +++ b/app/database/migrations/2026_12_03_000600_create_device_logins_table.rs @@ -0,0 +1,25 @@ +use laravel::db::AnyTransaction; + +/// `visualci login`'s device-code sign-in (ported as today's): the device code is stored hashed; a code gives one +/// token, once. +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query( + "CREATE TABLE device_logins ( + id BIGSERIAL PRIMARY KEY, + device_code_hash TEXT NOT NULL UNIQUE, + user_code TEXT NOT NULL UNIQUE, + -- What's asking, shown on the approval page: \"visualci CLI on ada-laptop\". + client_name TEXT NOT NULL, + user_id BIGINT REFERENCES users(id) ON DELETE CASCADE, + approved_at TIMESTAMPTZ, + denied_at TIMESTAMPTZ, + -- When the CLI collected its token. + consumed_at TIMESTAMPTZ, + expires_at TIMESTAMPTZ NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() + );", + ) + .unprepared() + .await?; + Ok(()) +} diff --git a/app/src/auth/device.rs b/app/src/auth/device.rs new file mode 100644 index 00000000..e3257d6a --- /dev/null +++ b/app/src/auth/device.rs @@ -0,0 +1,194 @@ +//! `visualci login`'s device-code sign-in (in the style of RFC 8628; sc-8900, the auth side, ported from today's +//! server). The CLI asks for a code pair: a secret device code it polls with, and a short user code the person types +//! or follows on the app's /device page. Once they approve it, the next poll gets a new personal token, once, and the +//! person gets a security notice. Codes last ten minutes. + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use serde_json::{Value, json}; + +use crate::models::{User, token_hash}; +use crate::notify::outbox::AppUrl; +use crate::notify::{self, Kind, To}; + +/// The CLI's side, on the `api` group: no session, no CSRF. +pub fn api_routes(route: &mut Router) { + route.post("/v1/device/code", code); + route.post("/v1/device/token", token); +} + +/// The person's side, on the `web` group. +pub fn routes(route: &mut Router) { + route.get("/api/ui/device/{code}", show); + route.post("/api/ui/device/{code}", decide); +} + +/// How long a code pair can be approved and collected. +pub const LIFETIME_SECONDS: i64 = 600; +/// How often the CLI may ask. +pub const INTERVAL_SECONDS: i64 = 3; + +/// Letters that can't be mistaken for each other or for digits. +const USER_CODE_ALPHABET: &[u8] = b"BCDFGHJKLMNPQRSTVWXZ"; + +/// A user code such as `KQHT-WMRP`. +fn new_user_code() -> String { + let mut letters = Vec::new(); + while letters.len() < 8 { + letters.extend(laravel::str::random(64).bytes().filter(|b| USER_CODE_ALPHABET.contains(b))); + } + let code: String = letters[..8].iter().map(|&b| char::from(b)).collect(); + format!("{}-{}", &code[..4], &code[4..]) +} + +/// A user code as people type it: upper case, with the dash where it belongs. +#[must_use] +pub fn normalize_user_code(code: &str) -> String { + let letters: String = code.chars().filter(char::is_ascii_alphabetic).map(|c| c.to_ascii_uppercase()).collect(); + if letters.len() == 8 { format!("{}-{}", &letters[..4], &letters[4..]) } else { letters } +} + +#[laravel::input] +#[validate(anyone)] +pub struct CodeInput { + /// What's asking, shown when the person approves: "visualci CLI on ada-laptop". + name: Option, +} + +/// `POST /api/v1/device/code`: a code pair. The person opens `verification_uri_complete` (or `verification_uri` and +/// types `user_code`) and approves; the CLI polls `/api/v1/device/token` with `device_code` every `interval` seconds. +pub async fn code(app: laravel::config::Section, Valid(p): Valid) -> laravel::Result> { + let client: String = p.name.unwrap_or_default().chars().filter(|c| !c.is_control()).take(100).collect(); + let client = if client.trim().is_empty() { "visualci CLI".to_string() } else { client }; + let lifetime = LIFETIME_SECONDS; + for _ in 0..5 { + let device = laravel::str::random(40); + let user = new_user_code(); + let hash = token_hash(&device); + let inserted: Option = db::query!( + "INSERT INTO device_logins (device_code_hash, user_code, client_name, expires_at) \ + VALUES ({hash}, {user}, {client}, now() + make_interval(secs => {lifetime}::int)) \ + ON CONFLICT DO NOTHING RETURNING id" + ) + .scalar() + .await?; + if inserted.is_some() { + let uri = format!("{}/device", app.url.trim_end_matches('/')); + return Ok(Json(json!({ + "device_code": device, + "user_code": user, + "verification_uri": uri, + "verification_uri_complete": format!("{uri}?code={user}"), + "expires_in": LIFETIME_SECONDS, + "interval": INTERVAL_SECONDS, + }))); + } + } + Err(laravel::abort_with(503, "couldn't make a code; try again")) +} + +#[laravel::input] +#[validate(anyone)] +pub struct TokenInput { + #[validate(required, max_length(200))] + device_code: String, +} + +/// `POST /api/v1/device/token`, polled: `status` is `pending` (ask again), `denied`, `expired`, or `approved` with a +/// new personal token (`token`), given once. +pub async fn token(Valid(p): Valid) -> laravel::Result> { + let hash = token_hash(&p.device_code); + // Claim an approved, uncollected code in one statement, so two polls never both get a token. + let claimed = db::query!( + "UPDATE device_logins SET consumed_at = now() WHERE device_code_hash = {hash} AND approved_at IS NOT NULL \ + AND consumed_at IS NULL AND expires_at > now() RETURNING user_id, client_name" + ) + .select_one() + .await?; + if let Some(row) = claimed { + let user_id: i64 = row.try_get("user_id")?; + let client: String = row.try_get("client_name")?; + let (token, _) = super::tokens::make_user_token(user_id, &client).await?; + let at = laravel::now().timestamp().strftime("%-d %B %Y, %H:%M UTC").to_string(); + let kind = Kind::DeviceSignIn { client, at }; + let key = format!("device_sign_in:{user_id}:{}", laravel::now().timestamp().as_millisecond()); + notify::queue(&kind, To::User(user_id), None, &key).await?; + let name: Option = db::query!("SELECT name FROM users WHERE id = {user_id}").scalar().await?; + return Ok(Json(json!({ "status": "approved", "token": token, "user": name }))); + } + let row = db::query!( + "SELECT (denied_at IS NOT NULL) AS denied, (expires_at > now() AND consumed_at IS NULL) AS live \ + FROM device_logins WHERE device_code_hash = {hash}" + ) + .select_one() + .await?; + let status = match row { + Some(r) if r.try_get::("denied")? => "denied", + Some(r) if r.try_get::("live")? => "pending", + _ => "expired", + }; + Ok(Json(json!({ "status": status }))) +} + +/// `GET /api/ui/device/{code}`: what's asking to sign in with this user code; 404 when there's no such pending code. +pub async fn show( + Authenticated(_user): Authenticated, + Params(code): Params, +) -> laravel::Result> { + let code = normalize_user_code(&code); + let client: Option = db::query!( + "SELECT client_name FROM device_logins WHERE user_code = {code} AND expires_at > now() \ + AND approved_at IS NULL AND denied_at IS NULL" + ) + .scalar() + .await?; + let client = client.ok_or_else(|| laravel::abort(404))?; + Ok(Json(json!({ "client": client }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct DecideInput { + approve: bool, +} + +/// `POST /api/ui/device/{code}`: approve or deny. Approving gives the waiting CLI a personal token for this person. +pub async fn decide( + Authenticated(user): Authenticated, + Params(code): Params, + Valid(p): Valid, +) -> laravel::Result> { + let (code, user_id) = (normalize_user_code(&code), user.id); + let decided: Option = if p.approve { + db::query!( + "UPDATE device_logins SET approved_at = now(), user_id = {user_id} WHERE user_code = {code} \ + AND expires_at > now() AND approved_at IS NULL AND denied_at IS NULL RETURNING id" + ) + .scalar() + .await? + } else { + db::query!( + "UPDATE device_logins SET denied_at = now(), user_id = {user_id} WHERE user_code = {code} \ + AND expires_at > now() AND approved_at IS NULL AND denied_at IS NULL RETURNING id" + ) + .scalar() + .await? + }; + decided.ok_or_else(|| laravel::abort(404))?; + Ok(Json(json!({ "ok": true }))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn user_codes_read_as_typed() { + assert_eq!(normalize_user_code("kqht wmrp"), "KQHT-WMRP"); + assert_eq!(normalize_user_code("KQHT-WMRP"), "KQHT-WMRP"); + let code = new_user_code(); + assert_eq!(code.len(), 9); + assert!(code.chars().all(|c| c == '-' || USER_CODE_ALPHABET.contains(&(c as u8)))); + } +} diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 5a04ea03..a15aa4cf 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -8,6 +8,8 @@ //! //! Nobody found: `401`. +pub mod oauth; +pub mod device; pub mod invitations; pub mod me; pub mod memberships; @@ -269,6 +271,7 @@ pub fn routes(route: &mut laravel::prelude::Router) { invitations::routes(route); orgs::routes(route); me::routes(route); + device::routes(route); route.get("/auth/{forge}", sign_in::start); route.post("/auth/{forge}/link", sign_in::link); route.get("/auth/{forge}/callback", sign_in::callback); diff --git a/app/src/auth/tokens.rs b/app/src/auth/tokens.rs index 73ed7125..42686bcc 100644 --- a/app/src/auth/tokens.rs +++ b/app/src/auth/tokens.rs @@ -66,6 +66,23 @@ pub async fn list_user_tokens(Authenticated(user): Authenticated) -> larav Ok(Json(json!({ "tokens": tokens }))) } +/// A new personal token for `user_id`, named `name`, and its id. Only its hash is stored, so this is the one time +/// it's seen. +/// +/// # Errors +/// On a database error. +pub async fn make_user_token(user_id: i64, name: &str) -> laravel::Result<(String, i64)> { + let (token, hash, shown) = generate("vcu_"); + let id: i64 = db::query!( + "INSERT INTO user_tokens (user_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({user_id}, {name}, {hash}, {shown}, now(), now()) RETURNING id" + ) + .scalar() + .await? + .ok_or_else(|| laravel::Error::msg("no token id"))?; + Ok((token, id)) +} + /// Make a personal token. It's shown once. pub async fn create_user_token( Authenticated(user): Authenticated, @@ -75,15 +92,8 @@ pub async fn create_user_token( if name.is_empty() { return Err(laravel::abort_with(422, "give the token a name")); } - let (token, hash, shown) = generate("vcu_"); let user_id = user.id; - let id: i64 = db::query!( - "INSERT INTO user_tokens (user_id, name, token_hash, token_prefix, created_at, updated_at) \ - VALUES ({user_id}, {name}, {hash}, {shown}, now(), now()) RETURNING id" - ) - .scalar() - .await? - .ok_or_else(|| laravel::Error::msg("no token id"))?; + let (token, id) = make_user_token(user_id, &name).await?; let kind = Kind::TokenCreated { name: name.clone(), project: None }; notice(&kind, user_id, None, &format!("token_created:user:{id}")).await; Ok(Json(json!({ "token": token }))) diff --git a/app/src/http/api.rs b/app/src/http/api.rs new file mode 100644 index 00000000..f256a62d --- /dev/null +++ b/app/src/http/api.rs @@ -0,0 +1,13 @@ +//! The REST API, under `/api` (`/api/v1/...`). + +use laravel::prelude::*; +use serde_json::json; + +pub fn routes(route: &mut Router) { + route.get("/v1/version", async || { + Json(json!({ "visualci": env!("CARGO_PKG_VERSION"), "laravel": laravel::VERSION })) + }); + route.get("/v1/whoami", crate::auth::whoami); + crate::auth::device::api_routes(route); + route.fallback(async || laravel::abort(404)); +} diff --git a/app/tests/device.rs b/app/tests/device.rs new file mode 100644 index 00000000..722f53f0 --- /dev/null +++ b/app/tests/device.rs @@ -0,0 +1,68 @@ +//! `visualci login`: the CLI gets a code pair, the person approves the user code, and the next poll gets a working +//! personal token, once, with a security notice; a denied code says so. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +#[laravel::test] +async fn an_approved_code_gives_the_cli_one_token(app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let pair = app.post("/api/v1/device/code").json(json!({ "name": "visualci CLI on ada-laptop" })).await; + pair.assert_ok().assert_json_path("interval", 3); + let device = pair.json()["device_code"].as_str().unwrap().to_string(); + let user_code = pair.json()["user_code"].as_str().unwrap().to_string(); + assert!(pair.json()["verification_uri_complete"].as_str().unwrap().ends_with(&format!("/device?code={user_code}"))); + + let poll = || app.post("/api/v1/device/token").json(json!({ "device_code": device.clone() })); + poll().await.assert_ok().assert_json_path("status", "pending"); + + let typed = user_code.to_lowercase().replace('-', ""); + app.get(format!("/api/ui/device/{typed}")) + .acting_as(&ada) + .await + .assert_ok() + .assert_json_path("client", "visualci CLI on ada-laptop"); + app.post(format!("/api/ui/device/{user_code}")) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "approve": true })) + .await + .assert_ok(); + app.get(format!("/api/ui/device/{user_code}")).acting_as(&ada).await.assert_status(404); + + let approved = poll().await; + approved.assert_ok().assert_json_path("status", "approved").assert_json_path("user", "Ada"); + let token = approved.json()["token"].as_str().unwrap().to_string(); + app.get("/api/v1/whoami") + .header("authorization", format!("Bearer {token}")) + .await + .assert_ok() + .assert_json_path("client.token_name", "visualci CLI on ada-laptop"); + poll().await.assert_json_path("status", "expired"); + let notices: Option = db::query!("SELECT count(*) FROM emails WHERE kind = 'device_sign_in'").scalar().await?; + assert_eq!(notices, Some(1)); + Ok(()) +} + +#[laravel::test] +async fn a_denied_code_says_so(app: Application) -> laravel::Result<()> { + let ada = create!(User { pid: laravel::str::uuid7(), name: "Ada", email: "ada@example.com", staff: false }).await?; + let pair = app.post("/api/v1/device/code").json(json!({})).await; + let device = pair.json()["device_code"].as_str().unwrap().to_string(); + let user_code = pair.json()["user_code"].as_str().unwrap().to_string(); + app.get(format!("/api/ui/device/{user_code}")).await.assert_status(401); + app.post(format!("/api/ui/device/{user_code}")) + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "approve": false })) + .await + .assert_ok(); + app.post("/api/v1/device/token").json(json!({ "device_code": device })).await.assert_json_path("status", "denied"); + app.post("/api/v1/device/token") + .json(json!({ "device_code": "nothing-like-it" })) + .await + .assert_json_path("status", "expired"); + Ok(()) +} From 2fa0c793e393f583ed3e1753c62760ea3918f16b Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:32:47 +1300 Subject: [PATCH 2/6] Device sign-in, review fixes: the approval page leads with a fixed 'VisualCI command-line sign-in' label, where and when it was asked for and 'only approve this if you just ran visualci login', with the name the CLI sent as a detail; at most ten codes per address in ten minutes (429); expired codes deleted daily (VISUALCI_DEVICE_PRUNE_HEARTBEAT); a poll within the interval gets slow_down; the code is claimed and its token made in one transaction; the client's address comes through TRUSTED_PROXIES --- ...12_03_000600_create_device_logins_table.rs | 7 +- app/src/auth/device.rs | 163 +++++++++++++++--- app/src/auth/tokens.rs | 2 +- app/src/lib.rs | 7 + app/tests/device.rs | 33 +++- 5 files changed, 189 insertions(+), 23 deletions(-) diff --git a/app/database/migrations/2026_12_03_000600_create_device_logins_table.rs b/app/database/migrations/2026_12_03_000600_create_device_logins_table.rs index 9f5b38cd..4bcab92a 100644 --- a/app/database/migrations/2026_12_03_000600_create_device_logins_table.rs +++ b/app/database/migrations/2026_12_03_000600_create_device_logins_table.rs @@ -10,6 +10,10 @@ pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { user_code TEXT NOT NULL UNIQUE, -- What's asking, shown on the approval page: \"visualci CLI on ada-laptop\". client_name TEXT NOT NULL, + -- Who asked for it (behind the trusted proxies, the address they report), shown on the approval page and + -- counted for the per-address limit. + requester_ip TEXT, + last_polled_at TIMESTAMPTZ, user_id BIGINT REFERENCES users(id) ON DELETE CASCADE, approved_at TIMESTAMPTZ, denied_at TIMESTAMPTZ, @@ -17,7 +21,8 @@ pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { consumed_at TIMESTAMPTZ, expires_at TIMESTAMPTZ NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() - );", + ); + CREATE INDEX device_logins_requester ON device_logins (requester_ip, created_at);", ) .unprepared() .await?; diff --git a/app/src/auth/device.rs b/app/src/auth/device.rs index e3257d6a..b914b479 100644 --- a/app/src/auth/device.rs +++ b/app/src/auth/device.rs @@ -2,10 +2,20 @@ //! server). The CLI asks for a code pair: a secret device code it polls with, and a short user code the person types //! or follows on the app's /device page. Once they approve it, the next poll gets a new personal token, once, and the //! person gets a security notice. Codes last ten minutes. +//! +//! A code pair can be asked for by anyone, so the approval page is built against phishing: it names the request as a +//! VisualCI command-line sign-in, with where and when it was asked for, and says to approve it only right after running +//! `visualci login`; the name the CLI sent is a detail below that. Each address may ask for a few codes in ten minutes, +//! and expired codes are deleted daily. + +use std::net::IpAddr; use laravel::auth::Authenticated; use laravel::db; +use laravel::http::{Next, Request, Response, middleware}; use laravel::prelude::*; +use laravel::queue::{Queueable, job}; +use laravel::schedule::{self, Schedule}; use serde_json::{Value, json}; use crate::models::{User, token_hash}; @@ -14,7 +24,9 @@ use crate::notify::{self, Kind, To}; /// The CLI's side, on the `api` group: no session, no CSRF. pub fn api_routes(route: &mut Router) { - route.post("/v1/device/code", code); + route.middleware(limit_codes).group(|route| { + route.post("/v1/device/code", code); + }); route.post("/v1/device/token", token); } @@ -28,6 +40,39 @@ pub fn routes(route: &mut Router) { pub const LIFETIME_SECONDS: i64 = 600; /// How often the CLI may ask. pub const INTERVAL_SECONDS: i64 = 3; +/// Code pairs one address may ask for in ten minutes. +pub const CODES_PER_ADDRESS: i64 = 10; + +/// The address that asked for a code pair (behind the trusted proxies, the one they report). +#[derive(Clone, Copy, Debug)] +pub struct Requester(pub IpAddr); + +/// Route middleware for `/api/v1/device/code`: at most [`CODES_PER_ADDRESS`] code pairs per address in ten minutes +/// (429 after that), and the address passed on for the approval page. +#[middleware] +pub async fn limit_codes(request: Request, next: Next) -> Response { + let ip = request.ip(); + let address = ip.to_string(); + let recent: laravel::Result> = db::query!( + "SELECT count(*) FROM device_logins WHERE requester_ip = {address} AND created_at > now() - interval '10 minutes'" + ) + .scalar() + .await; + match recent { + Ok(Some(n)) if n >= CODES_PER_ADDRESS => { + return Response::new(Json( + json!({ "error": "too many sign-in codes from this address; try again in ten minutes" }), + )) + .with_status(429) + .with_header("retry-after", "600"); + } + Err(e) => tracing::warn!(error = %e, "device code limit"), + _ => {} + } + let mut http = request.into_http(); + http.extensions_mut().insert(Requester(ip)); + next.run(Request::from_http(http)).await +} /// Letters that can't be mistaken for each other or for digits. const USER_CODE_ALPHABET: &[u8] = b"BCDFGHJKLMNPQRSTVWXZ"; @@ -58,7 +103,12 @@ pub struct CodeInput { /// `POST /api/v1/device/code`: a code pair. The person opens `verification_uri_complete` (or `verification_uri` and /// types `user_code`) and approves; the CLI polls `/api/v1/device/token` with `device_code` every `interval` seconds. -pub async fn code(app: laravel::config::Section, Valid(p): Valid) -> laravel::Result> { +pub async fn code( + app: laravel::config::Section, + requester: Option>, + Valid(p): Valid, +) -> laravel::Result> { + let requester = requester.map(|r| r.0.0.to_string()); let client: String = p.name.unwrap_or_default().chars().filter(|c| !c.is_control()).take(100).collect(); let client = if client.trim().is_empty() { "visualci CLI".to_string() } else { client }; let lifetime = LIFETIME_SECONDS; @@ -67,8 +117,8 @@ pub async fn code(app: laravel::config::Section, Valid(p): Valid = db::query!( - "INSERT INTO device_logins (device_code_hash, user_code, client_name, expires_at) \ - VALUES ({hash}, {user}, {client}, now() + make_interval(secs => {lifetime}::int)) \ + "INSERT INTO device_logins (device_code_hash, user_code, client_name, requester_ip, expires_at) \ + VALUES ({hash}, {user}, {client}, {requester}, now() + make_interval(secs => {lifetime}::int)) \ ON CONFLICT DO NOTHING RETURNING id" ) .scalar() @@ -95,21 +145,52 @@ pub struct TokenInput { device_code: String, } -/// `POST /api/v1/device/token`, polled: `status` is `pending` (ask again), `denied`, `expired`, or `approved` with a -/// new personal token (`token`), given once. +/// `POST /api/v1/device/token`, polled: `status` is `pending` (ask again), `slow_down` (asked again within the +/// interval: wait longer), `denied`, `expired`, or `approved` with a new personal token (`token`), given once. pub async fn token(Valid(p): Valid) -> laravel::Result> { let hash = token_hash(&p.device_code); - // Claim an approved, uncollected code in one statement, so two polls never both get a token. - let claimed = db::query!( - "UPDATE device_logins SET consumed_at = now() WHERE device_code_hash = {hash} AND approved_at IS NOT NULL \ - AND consumed_at IS NULL AND expires_at > now() RETURNING user_id, client_name" + // A second's grace for clocks and networks, as RFC 8628 asks clients to keep the interval. + let pace = INTERVAL_SECONDS - 1; + let paced: Option = db::query!( + "UPDATE device_logins SET last_polled_at = now() WHERE device_code_hash = {hash} \ + AND (last_polled_at IS NULL OR last_polled_at <= now() - make_interval(secs => {pace}::int)) RETURNING id" ) - .select_one() + .scalar() .await?; - if let Some(row) = claimed { + if paced.is_none() { + let known: Option = + db::query!("SELECT id FROM device_logins WHERE device_code_hash = {hash}").scalar().await?; + if known.is_some() { + return Ok(Json(json!({ "status": "slow_down" }))); + } + } + // Claim an approved, uncollected code and make its token in one transaction: two polls never both get a token, + // and a failure leaves the code to collect again. + let claimed = db::transaction(async |tx| { + let Some(row) = db::query!( + tx, + "UPDATE device_logins SET consumed_at = now() WHERE device_code_hash = {hash} AND approved_at IS NOT NULL \ + AND consumed_at IS NULL AND expires_at > now() RETURNING user_id, client_name" + ) + .select_one() + .await? + else { + return Ok(None); + }; let user_id: i64 = row.try_get("user_id")?; let client: String = row.try_get("client_name")?; - let (token, _) = super::tokens::make_user_token(user_id, &client).await?; + let (token, token_hash_, shown) = super::tokens::generate("vcu_"); + db::query!( + tx, + "INSERT INTO user_tokens (user_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({user_id}, {client}, {token_hash_}, {shown}, now(), now())" + ) + .insert() + .await?; + Ok(Some((user_id, client, token))) + }) + .await?; + if let Some((user_id, client, token)) = claimed { let at = laravel::now().timestamp().strftime("%-d %B %Y, %H:%M UTC").to_string(); let kind = Kind::DeviceSignIn { client, at }; let key = format!("device_sign_in:{user_id}:{}", laravel::now().timestamp().as_millisecond()); @@ -131,20 +212,62 @@ pub async fn token(Valid(p): Valid) -> laravel::Result> Ok(Json(json!({ "status": status }))) } -/// `GET /api/ui/device/{code}`: what's asking to sign in with this user code; 404 when there's no such pending code. +/// What the approval page says, before anything the request itself sent. +pub const LABEL: &str = "VisualCI command-line sign-in"; +pub const WARNING: &str = "Only approve this if you just ran visualci login yourself. Approving gives whoever asked a \ + token that acts as you."; + +/// `GET /api/ui/device/{code}`: the sign-in a user code asks for, to approve or deny: a fixed label and warning, where +/// and when it was asked for, and the name the CLI sent as a detail (`client`), since anyone can choose that. 404 when +/// there's no such pending code. pub async fn show( Authenticated(_user): Authenticated, Params(code): Params, ) -> laravel::Result> { let code = normalize_user_code(&code); - let client: Option = db::query!( - "SELECT client_name FROM device_logins WHERE user_code = {code} AND expires_at > now() \ + let row = db::query!( + "SELECT client_name, requester_ip, \ + to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') AS requested_at \ + FROM device_logins WHERE user_code = {code} AND expires_at > now() \ AND approved_at IS NULL AND denied_at IS NULL" ) - .scalar() - .await?; - let client = client.ok_or_else(|| laravel::abort(404))?; - Ok(Json(json!({ "client": client }))) + .select_one() + .await? + .ok_or_else(|| laravel::abort(404))?; + Ok(Json(json!({ + "label": LABEL, + "warning": WARNING, + "requested_from": row.try_get::>("requester_ip")?, + "requested_at": row.try_get::("requested_at")?, + "client": row.try_get::("client_name")?, + }))) +} + +/// Delete codes that expired more than a day ago, daily; pushes `VISUALCI_DEVICE_PRUNE_HEARTBEAT`. +#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct PruneDeviceLogins; + +#[job] +impl PruneDeviceLogins { + async fn handle(self) -> laravel::Result<()> { + let pruned = prune().await; + let health = pruned.as_ref().map(|_| ()).map_err(ToString::to_string); + crate::heartbeat::push("VISUALCI_DEVICE_PRUNE_HEARTBEAT", health).await; + pruned.map(|_| ()) + } +} + +/// Delete codes that expired more than a day ago. Returns how many. +/// +/// # Errors +/// On a database error. +pub async fn prune() -> laravel::Result { + db::query!("DELETE FROM device_logins WHERE expires_at < now() - interval '1 day'").delete().await +} + +#[schedule::tasks] +fn schedule(schedule: &mut Schedule) { + schedule.job(PruneDeviceLogins).daily().without_overlapping(); } #[laravel::input] diff --git a/app/src/auth/tokens.rs b/app/src/auth/tokens.rs index 42686bcc..9448fa02 100644 --- a/app/src/auth/tokens.rs +++ b/app/src/auth/tokens.rs @@ -28,7 +28,7 @@ async fn notice(kind: &Kind, user_id: i64, org_id: Option, key: &str) { } /// A new token: the prefix and 40 letters and digits. Returns it, its hash and what's shown of it. -fn generate(prefix: &str) -> (String, String, String) { +pub(crate) fn generate(prefix: &str) -> (String, String, String) { let token = format!("{prefix}{}", laravel::str::random(40)); let shown = token[..prefix.len() + 6].to_string(); (token.clone(), token_hash(&token), shown) diff --git a/app/src/lib.rs b/app/src/lib.rs index 95033310..d935a401 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -51,6 +51,13 @@ pub fn configure() -> ApplicationBuilder { .with_middleware(|middleware, _| { if let Err(e) = middleware.try_trust_proxies(config::trusted_proxies()) { tracing::error!(error = %e, "TRUSTED_PROXIES: trusting no proxies"); + // The load balancers in front (TRUSTED_PROXIES, comma-separated addresses or networks): the client's + // address comes from their X-Forwarded-For, for the device sign-in's page and its per-address limit + if let Ok(proxies) = std::env::var("TRUSTED_PROXIES") + && let Err(e) = + middleware.try_trust_proxies(proxies.split(',').map(str::trim).filter(|p| !p.is_empty())) + { + tracing::warn!("TRUSTED_PROXIES: {e}; trusting no proxies"); } middleware.prepend(http::hosts::route_by_host); // The site's signed-in hint is read by its script: plain, not encrypted diff --git a/app/tests/device.rs b/app/tests/device.rs index 722f53f0..d2f40360 100644 --- a/app/tests/device.rs +++ b/app/tests/device.rs @@ -15,7 +15,11 @@ async fn an_approved_code_gives_the_cli_one_token(app: Application) -> laravel:: let user_code = pair.json()["user_code"].as_str().unwrap().to_string(); assert!(pair.json()["verification_uri_complete"].as_str().unwrap().ends_with(&format!("/device?code={user_code}"))); - let poll = || app.post("/api/v1/device/token").json(json!({ "device_code": device.clone() })); + // Each poll as if the interval had passed (a quicker one gets slow_down, tested below) + let poll = || async { + db::query!("UPDATE device_logins SET last_polled_at = NULL").update().await.unwrap(); + app.post("/api/v1/device/token").json(json!({ "device_code": device.clone() })).await + }; poll().await.assert_ok().assert_json_path("status", "pending"); let typed = user_code.to_lowercase().replace('-', ""); @@ -23,6 +27,7 @@ async fn an_approved_code_gives_the_cli_one_token(app: Application) -> laravel:: .acting_as(&ada) .await .assert_ok() + .assert_json_path("label", "VisualCI command-line sign-in") .assert_json_path("client", "visualci CLI on ada-laptop"); app.post(format!("/api/ui/device/{user_code}")) .acting_as(&ada) @@ -66,3 +71,29 @@ async fn a_denied_code_says_so(app: Application) -> laravel::Result<()> { .assert_json_path("status", "expired"); Ok(()) } + +#[laravel::test] +async fn a_quick_poll_is_told_to_slow_down(app: Application) -> laravel::Result<()> { + let pair = app.post("/api/v1/device/code").json(json!({})).await; + let device = pair.json()["device_code"].as_str().unwrap().to_string(); + let poll = || app.post("/api/v1/device/token").json(json!({ "device_code": device.clone() })); + poll().await.assert_json_path("status", "pending"); + poll().await.assert_json_path("status", "slow_down"); + Ok(()) +} + +#[laravel::test] +async fn one_address_gets_a_few_codes_and_old_ones_are_pruned(app: Application) -> laravel::Result<()> { + for _ in 0..app::auth::device::CODES_PER_ADDRESS { + app.post("/api/v1/device/code").json(json!({})).await.assert_ok(); + } + app.post("/api/v1/device/code").json(json!({})).await.assert_status(429); + db::query!( + "UPDATE device_logins SET expires_at = now() - interval '2 days', created_at = now() - interval '2 days'" + ) + .update() + .await?; + assert_eq!(app::auth::device::prune().await?, app::auth::device::CODES_PER_ADDRESS as u64); + app.post("/api/v1/device/code").json(json!({})).await.assert_ok(); + Ok(()) +} From bf506882a47ff1652c56eb6e8b0940f640a10506 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 04:56:50 +1300 Subject: [PATCH 3/6] Test: a signed-out device page request asks for JSON, as the React app does --- app/tests/device.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/tests/device.rs b/app/tests/device.rs index d2f40360..97ccf645 100644 --- a/app/tests/device.rs +++ b/app/tests/device.rs @@ -57,7 +57,7 @@ async fn a_denied_code_says_so(app: Application) -> laravel::Result<()> { let pair = app.post("/api/v1/device/code").json(json!({})).await; let device = pair.json()["device_code"].as_str().unwrap().to_string(); let user_code = pair.json()["user_code"].as_str().unwrap().to_string(); - app.get(format!("/api/ui/device/{user_code}")).await.assert_status(401); + app.get(format!("/api/ui/device/{user_code}")).header("accept", "application/json").await.assert_status(401); app.post(format!("/api/ui/device/{user_code}")) .acting_as(&ada) .header("sec-fetch-site", "same-origin") From 2d66f5aa4e34967cbe32082cdccee4b21cdefca2 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 04:57:41 +1300 Subject: [PATCH 4/6] Device sign-in: its CLI routes in http/api/mod.rs, where main's API routes now live --- app/src/http/api.rs | 13 ------------- app/src/http/api/mod.rs | 1 + 2 files changed, 1 insertion(+), 13 deletions(-) delete mode 100644 app/src/http/api.rs diff --git a/app/src/http/api.rs b/app/src/http/api.rs deleted file mode 100644 index f256a62d..00000000 --- a/app/src/http/api.rs +++ /dev/null @@ -1,13 +0,0 @@ -//! The REST API, under `/api` (`/api/v1/...`). - -use laravel::prelude::*; -use serde_json::json; - -pub fn routes(route: &mut Router) { - route.get("/v1/version", async || { - Json(json!({ "visualci": env!("CARGO_PKG_VERSION"), "laravel": laravel::VERSION })) - }); - route.get("/v1/whoami", crate::auth::whoami); - crate::auth::device::api_routes(route); - route.fallback(async || laravel::abort(404)); -} diff --git a/app/src/http/api/mod.rs b/app/src/http/api/mod.rs index 7d0c1efb..13f1edb5 100644 --- a/app/src/http/api/mod.rs +++ b/app/src/http/api/mod.rs @@ -23,6 +23,7 @@ pub fn routes(route: &mut Router) { builds::routes(route); route.post("/v1/support/feedback", support::feedback); downloads::routes(route); + crate::auth::device::api_routes(route); route.fallback(async || laravel::abort(404)); } From 34ba83077b8ef63e3352559c0367798ae4fc8f1b Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 04:58:08 +1300 Subject: [PATCH 5/6] Rebased on main: Cargo.lock resolved from main's, and the boot checks and dependencies merged --- app/src/auth/mod.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index a15aa4cf..1f7ffc81 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -8,7 +8,6 @@ //! //! Nobody found: `401`. -pub mod oauth; pub mod device; pub mod invitations; pub mod me; From 0fe3cf4b36cb32eef9d90b13a34075cadf6eee50 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 10:42:51 +1300 Subject: [PATCH 6/6] Rebased on main: Cargo.lock resolved from main's, and the boot checks and dependencies merged --- app/src/lib.rs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/app/src/lib.rs b/app/src/lib.rs index d935a401..95033310 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -51,13 +51,6 @@ pub fn configure() -> ApplicationBuilder { .with_middleware(|middleware, _| { if let Err(e) = middleware.try_trust_proxies(config::trusted_proxies()) { tracing::error!(error = %e, "TRUSTED_PROXIES: trusting no proxies"); - // The load balancers in front (TRUSTED_PROXIES, comma-separated addresses or networks): the client's - // address comes from their X-Forwarded-For, for the device sign-in's page and its per-address limit - if let Ok(proxies) = std::env::var("TRUSTED_PROXIES") - && let Err(e) = - middleware.try_trust_proxies(proxies.split(',').map(str::trim).filter(|p| !p.is_empty())) - { - tracing::warn!("TRUSTED_PROXIES: {e}; trusting no proxies"); } middleware.prepend(http::hosts::route_by_host); // The site's signed-in hint is read by its script: plain, not encrypted