//! The client link (phase 7): staff make a link for a person, and the //! client fills in their details through it without a login. The table //! keeps the SHA-256 of the link's token, never the token, as `sessions` //! does; the token is shown once, when the link is made. A link is open //! for `LIFETIME`, until the client presses Send, or until staff close it; //! a new link closes the person's earlier one. Everything the client does //! through it is in the audit log with the actor `link `. use std::time::Duration; use anyhow::Result; use chrono::{DateTime, Utc}; use serde::Serialize; use sqlx::{PgConnection, PgPool}; use crate::dates; use crate::oidc::random_token; /// How long a link stays open. pub const LIFETIME: Duration = Duration::from_secs(14 * 24 * 3600); #[derive(Clone, Debug, sqlx::FromRow)] pub struct Link { pub id: i64, pub person_id: i64, pub csrf: String, pub created_by: String, pub created_at: DateTime, pub expires_at: DateTime, pub first_used_at: Option>, pub last_used_at: Option>, pub sent_at: Option>, pub closed_at: Option>, pub closed_by: String, } /// Where a link stands. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] #[serde(rename_all = "lowercase")] pub enum State { /// Made, not opened yet. Open, /// Opened by the client at least once. Used, /// The client pressed Send; closed. Sent, /// Closed by staff, or by a newer link. Closed, Expired, } impl State { pub fn label(self) -> &'static str { match self { State::Open => "open", State::Used => "opened", State::Sent => "sent", State::Closed => "closed", State::Expired => "expired", } } /// The chip's color. pub fn level(self) -> &'static str { match self { State::Open | State::Used => "warn", State::Sent => "ok", State::Closed | State::Expired => "plain", } } } impl Link { pub fn state(&self, now: DateTime) -> State { match (self.sent_at, self.closed_at) { (Some(_), _) => State::Sent, (None, Some(_)) => State::Closed, _ if self.expires_at <= now => State::Expired, _ if self.first_used_at.is_some() => State::Used, _ => State::Open, } } /// The client may still use it. pub fn usable(&self, now: DateTime) -> bool { matches!(self.state(now), State::Open | State::Used) } /// The audit log's actor for what the client does through it. pub fn actor(&self) -> String { actor(self.id) } } pub fn actor(id: i64) -> String { format!("link {id}") } fn hash(token: &str) -> Vec { ring::digest::digest(&ring::digest::SHA256, token.as_bytes()) .as_ref() .to_vec() } /// Makes a link for the person and closes their earlier open ones (by /// `by`, a staff login). Returns the link and its token, which nothing /// keeps: the page that made it shows it once. pub async fn create(conn: &mut PgConnection, person: i64, by: &str) -> Result<(Link, String)> { sqlx::query( "UPDATE client_links SET closed_at = now(), closed_by = $2 \ WHERE person_id = $1 AND closed_at IS NULL AND expires_at > now()", ) .bind(person) .bind(by) .execute(&mut *conn) .await?; let token = random_token(); let ttl = chrono::TimeDelta::seconds(LIFETIME.as_secs() as i64); let link: Link = sqlx::query_as( "INSERT INTO client_links (person_id, token_hash, csrf, created_by, expires_at) \ VALUES ($1, $2, $3, $4, now() + $5) \ RETURNING id, person_id, csrf, created_by, created_at, expires_at, first_used_at, \ last_used_at, sent_at, closed_at, closed_by", ) .bind(person) .bind(hash(&token)) .bind(random_token()) .bind(by) .bind(ttl) .fetch_one(&mut *conn) .await?; Ok((link, token)) } const COLUMNS: &str = "id, person_id, csrf, created_by, created_at, expires_at, first_used_at, \ last_used_at, sent_at, closed_at, closed_by"; /// The link with this token, whatever its state. pub async fn by_token(db: &PgPool, token: &str) -> Result> { // a token is 43 characters of base64url; anything else is no token if token.len() != 43 || !token .bytes() .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') { return Ok(None); } Ok(sqlx::query_as(&format!( "SELECT {COLUMNS} FROM client_links WHERE token_hash = $1" )) .bind(hash(token)) .fetch_optional(db) .await?) } pub async fn get(db: &PgPool, person: i64, id: i64) -> Result> { Ok(sqlx::query_as(&format!( "SELECT {COLUMNS} FROM client_links WHERE person_id = $1 AND id = $2" )) .bind(person) .bind(id) .fetch_optional(db) .await?) } /// The person's links, newest first. pub async fn for_person(db: &PgPool, person: i64) -> Result> { Ok(sqlx::query_as(&format!( "SELECT {COLUMNS} FROM client_links WHERE person_id = $1 ORDER BY id DESC" )) .bind(person) .fetch_all(db) .await?) } /// Notes that the client opened a page of the link. pub async fn touch(db: &PgPool, id: i64) -> Result<()> { sqlx::query( "UPDATE client_links SET first_used_at = COALESCE(first_used_at, now()), \ last_used_at = now() WHERE id = $1", ) .bind(id) .execute(db) .await?; Ok(()) } /// Closes an open link; `sent`: the client sent it. False when it was no /// longer open. pub async fn close(conn: &mut PgConnection, id: i64, by: &str, sent: bool) -> Result { let done = sqlx::query( "UPDATE client_links SET closed_at = now(), closed_by = $2, \ sent_at = CASE WHEN $3 THEN now() END \ WHERE id = $1 AND closed_at IS NULL AND expires_at > now()", ) .bind(id) .bind(by) .bind(sent) .execute(conn) .await?; Ok(done.rows_affected() == 1) } /// What the client changed through a link, from the audit log: one entry /// per record, with the names of the fields (never their values). #[derive(Clone, Debug, Serialize)] pub struct Change { pub entity: String, pub entity_id: Option, pub action: String, pub fields: Vec, } pub async fn changes(db: &PgPool, id: i64) -> Result> { let rows: Vec<(String, Option, String, Vec)> = sqlx::query_as( "SELECT entity, entity_id, action, fields FROM audit_log \ WHERE actor = $1 AND action IN ('create', 'update') ORDER BY id", ) .bind(actor(id)) .fetch_all(db) .await?; let mut out: Vec = Vec::new(); for (entity, entity_id, action, fields) in rows { match out .iter_mut() .find(|c| c.entity == entity && c.entity_id == entity_id) { Some(c) => { for f in fields { if !c.fields.contains(&f) { c.fields.push(f); } } } None => out.push(Change { entity, entity_id, action, fields, }), } } Ok(out) } /// The record of `entity` the link made last, if any: the client's own /// address or passport, which a second save changes instead of adding /// another. pub async fn made(db: &PgPool, id: i64, entity: &str) -> Result> { Ok(sqlx::query_scalar( "SELECT entity_id FROM audit_log WHERE actor = $1 AND action = 'create' \ AND entity = $2 ORDER BY id DESC LIMIT 1", ) .bind(actor(id)) .bind(entity) .fetch_optional(db) .await? .flatten()) } /// "Dec 4, 2026" in Chiang Mai time. pub fn day(t: DateTime) -> String { dates::fmt_date(t.with_timezone(&dates::bangkok()).date_naive()) } #[cfg(test)] mod tests { use super::*; fn link(now: DateTime) -> Link { Link { id: 7, person_id: 1, csrf: String::new(), created_by: "grabowski".into(), created_at: now, expires_at: now + chrono::TimeDelta::days(14), first_used_at: None, last_used_at: None, sent_at: None, closed_at: None, closed_by: String::new(), } } #[test] fn states() { let now = Utc::now(); let mut l = link(now); assert_eq!(l.state(now), State::Open); l.first_used_at = Some(now); assert_eq!(l.state(now), State::Used); assert!(l.usable(now)); assert_eq!(l.state(now + chrono::TimeDelta::days(15)), State::Expired); l.closed_at = Some(now); assert_eq!(l.state(now), State::Closed); assert!(!l.usable(now)); l.sent_at = Some(now); assert_eq!(l.state(now), State::Sent); assert_eq!(l.actor(), "link 7"); } #[test] fn only_tokens_are_looked_up() { assert_eq!(random_token().len(), 43); assert_eq!(hash("x").len(), 32); } }