Skip to content
Original file line number Diff line number Diff line change
@@ -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(())
}
317 changes: 317 additions & 0 deletions app/src/auth/device.rs
Original file line number Diff line number Diff line change
@@ -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<Option<i64>> = 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<String>,
}

/// `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<AppUrl>,
requester: Option<axum::Extension<Requester>>,
Valid(p): Valid<CodeInput>,
) -> laravel::Result<Json<Value>> {
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<i64> = 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<TokenInput>) -> laravel::Result<Json<Value>> {
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<i64> = 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<i64> =
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<String> = 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::<bool>("denied")? => "denied",
Some(r) if r.try_get::<bool>("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<User>,
Params(code): Params<String>,
) -> laravel::Result<Json<Value>> {
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::<Option<String>>("requester_ip")?,
"requested_at": row.try_get::<String>("requested_at")?,
"client": row.try_get::<String>("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<u64> {
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<User>,
Params(code): Params<String>,
Valid(p): Valid<DecideInput>,
) -> laravel::Result<Json<Value>> {
let (code, user_id) = (normalize_user_code(&code), user.id);
let decided: Option<i64> = 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))));
}
}
4 changes: 4 additions & 0 deletions app/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@
//!
//! Nobody found: `401`.

pub mod device;
pub mod invitations;
pub mod me;
pub mod memberships;
pub mod oauth;
pub mod orgs;
pub mod setup;
pub mod sign_in;
pub mod staff;
pub mod tokens;

use axum::extract::FromRequestParts;
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading