Phase 7: the client link
CI / secret scan (push) Successful in 6s
CI / fmt, clippy, tests (push) Successful in 59s
CI / release (push) Skipped

Staff make a link for a person (or "+ New client": a record with only the
name they know, and its link); the client fills in their own record from
their phone without a login, and presses Send.

- Links (src/links.rs, migrations/0006): the table keeps the SHA-256 of
  the token only, as sessions do; the link is shown once, to copy, to email
  (mailto with the person's address) or as a QR code (qrcode crate, inline
  SVG). It is open 14 days, until Send, or until staff close it; a new
  link closes the earlier one. States open, opened, sent, closed, expired.
- The client's pages at /c/<token> (src/web/client.rs, client_*.html in a
  frame of their own, phone first): About you, Passport (the photo reader;
  a zone fills in the personal details still empty), Address in Thailand,
  Contact, Documents, Send. Each part is saved on its own, straight into
  the record. Forms carry the link's own token plus the same-site check.
  A passport with the same number is changed; an address unlike the
  current one is added beside it, so the current one and its TM.30 receipt
  stay; a second save changes what the link added. Uploads (passport page,
  photo, visa, arrival stamp, TDAC, work permit, other) go through the
  same checks and encrypted store as staff uploads, tied to the person's
  newest record of their kind.
- Audit: the client's views and changes carry the actor `link <id>`;
  actions send and close and entity link are new. The person's page shows
  the newest links, when they were opened and sent, and each record the
  client changed, with the fields, to check.
- Demo data: Erika sent her link an hour ago (phone and email changed),
  Jane opened hers.
- documents::read_upload returns why it refused, so the client's pages
  answer in their own words.

Checks: fmt, clippy; 101 unit and 54 integration tests (tests/client.rs:
the link shown once and kept as a hash, a new client, the whole client
flow with the login on, forged, closed, expired and made-up links);
layout check light/dark desk/phone on the client pages, the person page
and the new client form: no problems; the camera reader on the client's
passport page with a fake camera filled the form and Send closed the link.
This commit is contained in:
grabowski committed 2026-11-20 19:48:34 +07:00
1 parent a6ebdfc89c
commit 43ed75d81b
32 files changed
+2706 -40

No files matched your search

+466
View File
@@ -0,0 +1,466 @@
//! The client link (phase 7): a link shown once and kept as a hash, the
//! client's pages open without a login and only through an open link, each
//! part saved straight into the record and logged as the link's, uploads
//! tied to their record, Send, and links that are closed, expired or made
//! up.
use axum::http::StatusCode;
use sqlx::PgPool;
use visa::config::Auth;
use crate::common::{App, Part, assert_unique_ids, erika_mrz, local, oidc_config, pdf, with_auth};
/// The token in the page that shows a new link.
fn token_in(html: &str) -> String {
let i = html.find("/c/").expect("no link on the page");
html[i + 3..]
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
.collect()
}
/// A form of the client's page: the link's own token, from this site.
async fn send_form(app: &App, uri: &str, csrf: &str, form: &[(&str, &str)]) -> crate::common::Resp {
let mut pairs = form.to_vec();
pairs.push(("csrf", csrf));
app.post_raw(uri, &pairs, &[("sec-fetch-site", "same-origin")])
.await
}
async fn csrf_of(pool: &PgPool, link: i64) -> String {
sqlx::query_scalar("SELECT csrf FROM client_links WHERE id = $1")
.bind(link)
.fetch_one(pool)
.await
.unwrap()
}
/// A person with only a name, and a link for them made as staff make it.
async fn person_with_link(pool: &PgPool) -> (i64, i64, String) {
let mut conn = pool.acquire().await.unwrap();
let person: i64 = sqlx::query_scalar(
"INSERT INTO people (surname, first_name) VALUES ('Becker', 'Hans') RETURNING id",
)
.fetch_one(&mut *conn)
.await
.unwrap();
let (link, token) = visa::links::create(&mut conn, person, "grabowski")
.await
.unwrap();
(person, link.id, token)
}
async fn audit_rows(pool: &PgPool, actor: &str) -> Vec<(String, String, Vec<String>)> {
sqlx::query_as("SELECT action, entity, fields FROM audit_log WHERE actor = $1 ORDER BY id")
.bind(actor)
.fetch_all(pool)
.await
.unwrap()
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn a_link_is_shown_once_and_kept_as_a_hash(pool: PgPool) {
let app = local(pool.clone());
let r = app
.post(
"/people",
&[
("surname", "Becker"),
("first_name", "Hans"),
("email", "hans@example.com"),
],
)
.await;
let person = crate::common::id_from(r.location());
let r = app.post(&format!("/people/{person}/links"), &[]).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
let t = r.text();
assert!(t.contains("The link is shown only now"), "{t}");
assert!(t.contains("<svg"), "no QR code: {t}");
assert!(t.contains("mailto:hans@example.com?subject="), "{t}");
assert_unique_ids(&r.body, "link made");
let token = token_in(&t);
assert_eq!(token.len(), 43);
// the table holds the token's SHA-256 only
let (hash, by): (Vec<u8>, String) =
sqlx::query_as("SELECT token_hash, created_by FROM client_links WHERE person_id = $1")
.bind(person)
.fetch_one(&pool)
.await
.unwrap();
let want = ring::digest::digest(&ring::digest::SHA256, token.as_bytes());
assert_eq!(hash, want.as_ref());
assert_eq!(by, "local");
let dump: String = sqlx::query_scalar("SELECT string_agg(t::text, ' ') FROM client_links t")
.fetch_one(&pool)
.await
.unwrap();
assert!(!dump.contains(&token));
// the person's page lists it; the client opens it
let page = app.get(&format!("/people/{person}")).await.text();
assert!(page.contains("id=\"client-link\""), "{page}");
assert!(page.contains(">open</span>"), "{page}");
assert_eq!(app.get(&format!("/c/{token}")).await.status, StatusCode::OK);
let page = app.get(&format!("/people/{person}")).await.text();
assert!(page.contains(">opened</span>"), "{page}");
// a new link closes the old one
let r = app.post(&format!("/people/{person}/links"), &[]).await;
let newer = token_in(&r.text());
let old = app.get(&format!("/c/{token}")).await;
assert_eq!(old.status, StatusCode::GONE);
assert!(old.text().contains("This link is closed"));
assert_eq!(app.get(&format!("/c/{newer}")).await.status, StatusCode::OK);
// staff close it
let lid: i64 = sqlx::query_scalar(
"SELECT id FROM client_links WHERE person_id = $1 ORDER BY id DESC LIMIT 1",
)
.bind(person)
.fetch_one(&pool)
.await
.unwrap();
let r = app
.post(&format!("/people/{person}/links/{lid}/close"), &[])
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
assert_eq!(
app.get(&format!("/c/{newer}")).await.status,
StatusCode::GONE
);
let made: Vec<String> = sqlx::query_scalar(
"SELECT action FROM audit_log WHERE entity = 'link' AND actor = 'local' ORDER BY id",
)
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(made, ["create", "create", "close"]);
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn a_new_client_is_a_name_and_a_link(pool: PgPool) {
let app = local(pool.clone());
let form = app.get("/people/new-client").await;
assert_eq!(form.status, StatusCode::OK);
let r = app.post("/people/new-client", &[]).await;
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
assert!(r.text().contains("Enter a name to find the record by"));
let r = app
.post("/people/new-client", &[("first_name", "Mai")])
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
let token = token_in(&r.text());
let name: String = sqlx::query_scalar("SELECT first_name FROM people")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(name, "Mai");
let c = app.get(&format!("/c/{token}")).await.text();
assert!(c.contains("Hello Mai"), "{c}");
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn the_client_fills_in_everything_without_a_login(pool: PgPool) {
// with the login on: the staff's pages need it, the client's do not
let app = with_auth(pool.clone(), Auth::Oidc(oidc_config("https://idp.test")));
let (person, link, token) = person_with_link(&pool).await;
let csrf = csrf_of(&pool, link).await;
let base = format!("/c/{token}");
assert!(
app.get(&format!("/people/{person}"))
.await
.location()
.starts_with("/login")
);
let r = app.get(&base).await;
assert_eq!(r.status, StatusCode::OK);
let t = r.text();
assert!(t.contains("Hello Hans"), "{t}");
assert!(
!t.contains("Sign out") && !t.contains("/activity"),
"staff frame on {t}"
);
assert_eq!(r.header("referrer-policy"), "same-origin");
for part in ["about", "contact", "passport", "address", "documents"] {
let r = app.get(&format!("{base}/{part}")).await;
assert_eq!(r.status, StatusCode::OK, "{part}: {}", r.body);
assert_unique_ids(&r.body, part);
}
// the photo reader's page allows the camera and WebAssembly
let r = app.get(&format!("{base}/passport")).await;
assert!(r.header("permissions-policy").contains("camera=(self)"));
assert!(r.text().contains("data-mrz-camera"));
// about you: straight into the record, logged as the link's
let r = send_form(
&app,
&format!("{base}/about"),
&csrf,
&[
("surname", "Becker"),
("first_name", "Hans"),
("middle_name", "Peter"),
("sex", "M"),
("date_of_birth", "1990-02-03"),
("nationality", "DEU"),
("occupation", "Engineer"),
// not a field of the part: ignored
("notes", "from the client"),
],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
assert_eq!(r.location(), format!("{base}?saved=about"));
let (middle, notes): (String, String) =
sqlx::query_as("SELECT middle_name, notes FROM people WHERE id = $1")
.bind(person)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!((middle.as_str(), notes.as_str()), ("Peter", ""));
assert!(
app.get(&format!("{base}?saved=about"))
.await
.text()
.contains("Saved: About you.")
);
// a wrong date is marked, nothing saved
let r = send_form(
&app,
&format!("{base}/about"),
&csrf,
&[
("surname", "Becker"),
("first_name", "Hans"),
("date_of_birth", "2090-01-01"),
],
)
.await;
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
// contact
let r = send_form(
&app,
&format!("{base}/contact"),
&csrf,
&[("phone", "+66 81 000 0000"), ("email", "hans@example.com")],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
// the passport from its zone; Read first fills the form in
let zone = erika_mrz();
let r = send_form(
&app,
&format!("{base}/passport"),
&csrf,
&[("mrz", &zone), ("action", "read-mrz")],
)
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert!(r.text().contains("value=\"C01X00T47\""));
let r = send_form(
&app,
&format!("{base}/passport"),
&csrf,
&[("mrz", &zone), ("action", "save")],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
// the same passport again changes it, adds none
let r = send_form(
&app,
&format!("{base}/passport"),
&csrf,
&[
("mrz", &zone),
("issued_at", "Stadt Köln"),
("action", "save"),
],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
let passports: Vec<(i64, String)> =
sqlx::query_as("SELECT id, issued_at FROM passports WHERE person_id = $1")
.bind(person)
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(passports.len(), 1);
assert_eq!(passports[0].1, "Stadt Köln");
// the address: added once, then changed in place
let addr = [
("house_no", "12/3"),
("district", "Mueang Chiang Mai"),
("province", "Chiang Mai"),
("postal_code", "50200"),
("house_master", "Khun Somchai"),
// staff's fields: ignored
("tm30_receipt_no", "FAKE"),
];
let r = send_form(&app, &format!("{base}/address"), &csrf, &addr).await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
let mut moved = addr.to_vec();
moved[0] = ("house_no", "12/4");
send_form(&app, &format!("{base}/address"), &csrf, &moved).await;
let addresses: Vec<(String, String)> =
sqlx::query_as("SELECT house_no, tm30_receipt_no FROM addresses WHERE person_id = $1")
.bind(person)
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(addresses, [("12/4".to_string(), String::new())]);
// a scan of the photo page belongs to the passport
let scan = pdf("photo page");
let parts = [
Part::field("csrf", csrf.as_bytes()),
Part::field("kind", b"passport-photo-page"),
Part::file("page.pdf", &scan),
];
let r = app
.upload_raw(
&format!("{base}/documents"),
&parts,
&[("sec-fetch-site", "same-origin")],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
let (by, pp): (String, Option<i64>) =
sqlx::query_as("SELECT uploaded_by, passport_id FROM documents WHERE person_id = $1")
.bind(person)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(by, format!("link {link}"));
assert_eq!(pp, Some(passports[0].0));
let docs = app.get(&format!("{base}/documents")).await.text();
assert!(
docs.contains("Passport photo page") && docs.contains("page.pdf"),
"{docs}"
);
// a kind staff keep to themselves is refused
let parts = [
Part::field("csrf", csrf.as_bytes()),
Part::field("kind", b"tm30-receipt"),
Part::file("x.pdf", &scan),
];
let r = app
.upload_raw(
&format!("{base}/documents"),
&parts,
&[("sec-fetch-site", "same-origin")],
)
.await;
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
// every change carries the link as the actor, with field names only
let rows = audit_rows(&pool, &format!("link {link}")).await;
let changes: Vec<(String, String)> = rows
.iter()
.filter(|r| r.0 != "view")
.map(|r| (r.0.clone(), r.1.clone()))
.collect();
let want: Vec<(String, String)> = [
("update", "person"),
("update", "person"),
("create", "passport"),
("update", "passport"),
("create", "address"),
("update", "address"),
("create", "document"),
]
.iter()
.map(|(a, e)| (a.to_string(), e.to_string()))
.collect();
assert_eq!(changes, want);
assert!(rows.iter().any(|r| r.0 == "view"));
let first = rows.iter().find(|r| r.0 == "update").unwrap();
assert!(first.2.contains(&"middle_name".to_string()), "{rows:?}");
assert!(!first.2.contains(&"notes".to_string()), "{rows:?}");
let changes = visa::links::changes(&pool, link).await.unwrap();
assert_eq!(changes.len(), 4, "{changes:?}");
// Send closes the link and thanks
let r = send_form(&app, &format!("{base}/send"), &csrf, &[]).await;
assert_eq!(r.status, StatusCode::OK);
assert!(r.text().contains("Thank you"));
let after = app.get(&base).await;
assert_eq!(after.status, StatusCode::GONE);
assert!(after.text().contains("You sent your details on"));
let (sent, by): (bool, String) =
sqlx::query_as("SELECT sent_at IS NOT NULL, closed_by FROM client_links WHERE id = $1")
.bind(link)
.fetch_one(&pool)
.await
.unwrap();
assert!(sent);
assert_eq!(by, "client");
// and takes nothing more
let r = send_form(&app, &format!("{base}/contact"), &csrf, &[("phone", "1")]).await;
assert_eq!(r.status, StatusCode::GONE);
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn forged_closed_and_made_up_links_are_refused(pool: PgPool) {
let app = local(pool.clone());
let (_, link, token) = person_with_link(&pool).await;
let base = format!("/c/{token}");
// without the link's token, or with the local session's
let r = app
.post_raw(
&format!("{base}/contact"),
&[("phone", "1")],
&[("sec-fetch-site", "same-origin")],
)
.await;
assert_eq!(r.status, StatusCode::FORBIDDEN);
let r = app
.post(&format!("{base}/contact"), &[("phone", "1")])
.await;
assert_eq!(r.status, StatusCode::FORBIDDEN);
// from another site
let csrf = csrf_of(&pool, link).await;
let r = app
.post_raw(
&format!("{base}/contact"),
&[("phone", "1"), ("csrf", &csrf)],
&[("sec-fetch-site", "cross-site")],
)
.await;
assert_eq!(r.status, StatusCode::FORBIDDEN);
let phone: String = sqlx::query_scalar("SELECT phone FROM people")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(phone, "");
// made up, malformed
for bad in ["/c/xyz", "/c/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"] {
let r = app.get(bad).await;
assert_eq!(r.status, StatusCode::NOT_FOUND, "{bad}");
assert!(r.text().contains("This link does not work"));
}
// expired
sqlx::query(
"UPDATE client_links SET created_at = now() - interval '15 days', \
expires_at = now() - interval '1 day' WHERE id = $1",
)
.bind(link)
.execute(&pool)
.await
.unwrap();
let r = app.get(&base).await;
assert_eq!(r.status, StatusCode::GONE);
assert!(r.text().contains("This link has expired"));
let page = app.get("/people/1").await.text();
assert!(page.contains(">expired</span>"), "{page}");
}