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..4bcab92a --- /dev/null +++ b/app/database/migrations/2026_12_03_000600_create_device_logins_table.rs @@ -0,0 +1,30 @@ +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, + -- 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, + -- When the CLI collected its token. + 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?; + Ok(()) +} diff --git a/app/src/auth/device.rs b/app/src/auth/device.rs new file mode 100644 index 00000000..b914b479 --- /dev/null +++ b/app/src/auth/device.rs @@ -0,0 +1,317 @@ +//! `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. +//! +//! 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}; +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.middleware(limit_codes).group(|route| { + 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; +/// 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"; + +/// 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, + 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; + 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, requester_ip, expires_at) \ + VALUES ({hash}, {user}, {client}, {requester}, 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), `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); + // 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" + ) + .scalar() + .await?; + 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, 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()); + 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 }))) +} + +/// 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 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" + ) + .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] +#[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..843d2983 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -8,6 +8,7 @@ //! //! Nobody found: `401`. +pub mod device; pub mod invitations; pub mod me; pub mod memberships; @@ -15,6 +16,7 @@ pub mod oauth; pub mod orgs; pub mod setup; pub mod sign_in; +pub mod staff; pub mod tokens; use axum::extract::FromRequestParts; @@ -269,6 +271,8 @@ pub fn routes(route: &mut laravel::prelude::Router) { invitations::routes(route); orgs::routes(route); me::routes(route); + device::routes(route); + staff::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/staff.rs b/app/src/auth/staff.rs new file mode 100644 index 00000000..18b56f6a --- /dev/null +++ b/app/src/auth/staff.rs @@ -0,0 +1,130 @@ +//! Staff pages on the auth and emails side (sc-8900), ported from today's server: the latest sign-ups, every email +//! VisualCI sends rendered with sample data, and failed emails to retry or dismiss. Anyone who isn't staff gets a 404. + +use laravel::auth::Authenticated; +use laravel::db; +use laravel::prelude::*; +use serde_json::{Value, json}; + +use super::me::summary; +use crate::models::User; +use crate::notify::outbox::AppUrl; +use crate::notify::{About, DeliverEmails, render, render::samples}; + +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); +} + +fn staff_only(user: &User) -> laravel::Result<()> { + if user.staff { Ok(()) } else { Err(laravel::abort(404)) } +} + +const TIME: &str = "YYYY-MM-DD\"T\"HH24:MI:SS\"Z\""; + +/// `GET /api/ui/staff/signups`: the latest 100 people, newest first, with how they heard about VisualCI. +pub async fn signups(Authenticated(user): Authenticated) -> laravel::Result> { + staff_only(&user)?; + let rows = db::query!( + "SELECT name, email, heard_about_source, heard_about_detail, \ + to_char(created_at AT TIME ZONE 'UTC', {TIME}) AS created_at, \ + (SELECT login FROM identities WHERE user_id = users.id ORDER BY id LIMIT 1) AS login \ + FROM users ORDER BY id DESC LIMIT 100" + ) + .select() + .await?; + let mut list = Vec::new(); + for r in rows { + let (source, detail): (Option, Option) = + (r.try_get("heard_about_source")?, r.try_get("heard_about_detail")?); + list.push(json!({ + "name": r.try_get::("name")?, "email": r.try_get::("email")?, + "login": r.try_get::>("login")?, "created_at": r.try_get::("created_at")?, + "heard_about": summary(source.as_deref(), detail.as_deref()), + })); + } + Ok(Json(json!({ "signups": list }))) +} + +/// `GET /api/ui/staff/emails`: every email rendered with sample data (for Acme), and the failed ones nobody has +/// retried or dismissed yet, newest first. +pub async fn emails( + Authenticated(user): Authenticated, + app: laravel::config::Section, +) -> laravel::Result> { + staff_only(&user)?; + let about = About { org_name: "Acme", org_slug: "acme", app_url: app.url.trim_end_matches('/') }; + let list: Vec = samples() + .into_iter() + .map(|(label, kind)| { + let r = render(&kind, &about); + json!({ + "label": label, "kind": kind.name(), "subject": r.subject, "text": r.text, "html": r.html, + "can_turn_off": kind.preference().is_some(), + }) + }) + .collect(); + let rows = db::query!( + "SELECT e.id, e.kind, e.recipient, e.attempts, e.last_error, o.slug AS org, \ + to_char(e.created_at AT TIME ZONE 'UTC', {TIME}) AS created_at, \ + to_char(e.updated_at AT TIME ZONE 'UTC', {TIME}) AS failed_at \ + FROM emails e LEFT JOIN organizations o ON o.id = e.organization_id \ + WHERE e.state = 'failed' AND e.dismissed_at IS NULL ORDER BY e.id DESC LIMIT 100" + ) + .select() + .await?; + let mut failed = Vec::new(); + for r in rows { + failed.push(json!({ + "id": r.try_get::("id")?, "kind": r.try_get::("kind")?, + "recipient": r.try_get::("recipient")?, "org": r.try_get::>("org")?, + "attempts": r.try_get::("attempts")?, "last_error": r.try_get::>("last_error")?, + "created_at": r.try_get::("created_at")?, "failed_at": r.try_get::("failed_at")?, + })); + } + Ok(Json(json!({ "emails": list, "failed": failed }))) +} + +#[laravel::input] +#[validate(authenticated)] +pub struct ResolveInput { + /// `retry` or `dismiss`. + #[validate(required)] + action: String, +} + +/// `POST /api/ui/staff/emails/{id}/resolve`: retry a failed email (sent again from scratch) or dismiss it. Either way +/// it stops counting in `/status`'s `emails_failed_unresolved`. 404 when there's no such failed, undismissed email. +pub async fn resolve( + Authenticated(user): Authenticated, + Params(id): Params, + Valid(p): Valid, +) -> laravel::Result> { + staff_only(&user)?; + let done: Option = match p.action.as_str() { + "retry" => { + db::query!( + "UPDATE emails SET state = 'pending', attempts = 0, claimed_at = NULL, updated_at = now() \ + WHERE id = {id} AND state = 'failed' AND dismissed_at IS NULL RETURNING id" + ) + .scalar() + .await? + } + "dismiss" => { + db::query!( + "UPDATE emails SET dismissed_at = now(), updated_at = now() \ + WHERE id = {id} AND state = 'failed' AND dismissed_at IS NULL RETURNING id" + ) + .scalar() + .await? + } + _ => return Err(laravel::abort_with(422, "action is retry or dismiss")), + }; + done.ok_or_else(|| laravel::abort(404))?; + tracing::info!(email_id = id, action = %p.action, staff = user.id, "staff resolved a failed email"); + if p.action == "retry" { + DeliverEmails.dispatch().await?; + } + Ok(Json(json!({ "id": id }))) +} diff --git a/app/src/auth/tokens.rs b/app/src/auth/tokens.rs index 73ed7125..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) @@ -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/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)); } diff --git a/app/tests/device.rs b/app/tests/device.rs new file mode 100644 index 00000000..97ccf645 --- /dev/null +++ b/app/tests/device.rs @@ -0,0 +1,99 @@ +//! `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}"))); + + // 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('-', ""); + app.get(format!("/api/ui/device/{typed}")) + .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) + .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}")).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") + .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(()) +} + +#[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(()) +} diff --git a/app/tests/staff.rs b/app/tests/staff.rs new file mode 100644 index 00000000..11ee277b --- /dev/null +++ b/app/tests/staff.rs @@ -0,0 +1,49 @@ +//! Staff pages: the latest sign-ups, every email rendered, failed emails retried or dismissed; a 404 for anyone else. + +use app::models::User; +use laravel::db; +use laravel::model::create; +use laravel::testing::prelude::*; + +#[laravel::test] +async fn staff_see_sign_ups_and_emails_and_resolve_failures(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 ada_id = ada.id; + db::query!( + "UPDATE users SET heard_about_source = 'ai_assistant', heard_about_detail = 'Claude' WHERE id = {ada_id}" + ) + .update() + .await?; + for path in ["/api/ui/staff/signups", "/api/ui/staff/emails"] { + app.get(path).acting_as(&ada).await.assert_status(404); + } + app.get("/api/ui/staff/signups") + .acting_as(&grace) + .await + .assert_ok() + .assert_json_path("signups.0.name", "Ada") + .assert_json_path("signups.0.heard_about", "AI assistant: Claude"); + + let failed: i64 = db::query!( + "INSERT INTO emails (kind, dedupe_key, recipient, data, state, attempts, last_error) \ + VALUES ('welcome', 'w:1', 'ada@example.com', '[]', 'failed', 5, 'Postmark: HTTP 422') RETURNING id" + ) + .scalar() + .await? + .unwrap(); + let page = app.get("/api/ui/staff/emails").acting_as(&grace).await; + page.assert_ok().assert_json_path("failed.0.id", failed).assert_json_path("emails.0.kind", "credits_low"); + let resolve = |who: &User, action: &str| { + app.post(format!("/api/ui/staff/emails/{failed}/resolve")) + .acting_as(who) + .header("sec-fetch-site", "same-origin") + .json(json!({ "action": action })) + }; + resolve(&ada, "dismiss").await.assert_status(404); + resolve(&grace, "dismiss").await.assert_ok(); + resolve(&grace, "dismiss").await.assert_status(404); + app.get("/api/ui/staff/emails").acting_as(&grace).await.assert_json_path("failed", json!([])); + Ok(()) +}