Files
visa/tests/agreements.rs
grabowski b7c9818dd6
CI / secret scan (push) Successful in 8s
CI / fmt, clippy, tests (push) Successful in 1m28s
CI / release (push) Skipped
Pictures: refuse a header that claims too many pixels, before decoding
The first fuzz run on cnx01 found it: a drawn signature of 798 bytes
whose PNG header says 300 x 738,197,594 pixels made krilla ask for
885 GB. A failed allocation aborts the process, so one such signature
on any client link (or such an upload in a pack) would have ended the
app for everyone; reproduced on a normal build, with a valid IHDR
checksum.

krilla decodes a picture as soon as it makes it, so papers::pixels
reads the size from the header first, with the decoder krilla uses
(png, zune-jpeg, image-webp; already in Cargo.lock, now direct
dependencies), and papers::picture refuses more than MAX_PIXELS (50
megapixels, about 200 MB decoded) before krilla sees the file. The pack
and the Documents tab print a note for such a file, the signed copy
refuses it, and the client page refuses the signature (422, "did not
arrive whole") before anything is stored.

tests/fuzz_cases/signed_copy/png-claims-885-gigabytes is the finding,
replayed on every push; unit tests for the header sizes and the limit,
and the agreements test sends the forged signature.
2026-11-23 10:24:15 +07:00

427 lines
13 KiB
Rust

//! Agreements (task 7.6): staff publish texts in versions that never
//! change; the client link asks for every active one, the client signs with
//! their name and a drawing, the signed copy is a PDF among the person's
//! documents, and a new version is signed again.
use axum::http::StatusCode;
use sqlx::PgPool;
use crate::common::{App, Resp, assert_unique_ids, local};
/// A 1 x 1 PNG, as the signature pad would send it.
const DRAWING: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";
const TEXT: &str = "# 1. What Lanna Desk keeps\nYour name and passport.\n\n- name\n- passport";
async fn client_post(
app: &App,
uri: &str,
csrf: &str,
form: &[(&str, &str)],
headers: &[(&str, &str)],
) -> Resp {
let mut pairs = form.to_vec();
pairs.push(("csrf", csrf));
let mut h = vec![("sec-fetch-site", "same-origin")];
h.extend_from_slice(headers);
app.post_raw(uri, &pairs, &h).await
}
/// A person, an open link for them, and the link's form token.
async fn client(pool: &PgPool) -> (i64, i64, String, String) {
let mut conn = pool.acquire().await.unwrap();
let person: i64 = sqlx::query_scalar(
"INSERT INTO people (surname, first_name, date_of_birth) \
VALUES ('Becker', 'Hans', '1990-02-03') RETURNING id",
)
.fetch_one(&mut *conn)
.await
.unwrap();
let (link, token) = visa::links::create(&mut conn, person, "grabowski")
.await
.unwrap();
(person, link.id, token, link.csrf)
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn staff_publish_versions_that_never_change(pool: PgPool) {
let app = local(pool.clone());
let r = app.get("/agreements").await;
assert_eq!(r.status, StatusCode::OK);
assert!(r.text().contains("No agreement yet"));
// a preview publishes nothing
let r = app
.post(
"/agreements",
&[
("title", "Your data"),
("body", TEXT),
("action", "preview"),
],
)
.await;
assert_eq!(r.status, StatusCode::OK);
assert!(
r.text().contains("<h3>1. What Lanna Desk keeps</h3>"),
"{}",
r.body
);
assert!(r.text().contains("<li>passport</li>"));
let n: i64 = sqlx::query_scalar("SELECT count(*) FROM agreements")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(n, 0);
let r = app
.post("/agreements", &[("title", ""), ("body", "")])
.await;
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
let r = app
.post(
"/agreements",
&[
("title", "Your data"),
("body", TEXT),
("action", "publish"),
],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
let page = r.location().to_string();
let r = app.get(&page).await;
assert_eq!(r.status, StatusCode::OK);
assert_unique_ids(&r.body, &page);
assert!(r.text().contains("Publish version 2"));
// the same text again is no new version; a changed one is
let r = app
.post(
&format!("{page}/versions"),
&[("body", TEXT), ("action", "publish")],
)
.await;
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
let r = app
.post(
&format!("{page}/versions"),
&[
("body", &format!("{TEXT}\n- address")),
("action", "publish"),
],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
let r = app.get(&format!("{page}/versions/1")).await;
assert_eq!(r.status, StatusCode::OK);
assert!(!r.text().contains("<li>address</li>"));
assert_eq!(
app.get(&format!("{page}/versions/9")).await.status,
StatusCode::NOT_FOUND
);
// the database refuses to change a published text
let changed = sqlx::query("UPDATE agreement_versions SET body = 'other'")
.execute(&pool)
.await;
assert!(changed.is_err());
let deleted = sqlx::query("DELETE FROM agreement_versions")
.execute(&pool)
.await;
assert!(deleted.is_err());
let list = app.get("/agreements").await.text();
assert!(
list.contains("Your data") && list.contains("asked for"),
"{list}"
);
let r = app
.post(&format!("{page}/active"), &[("active", "0")])
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
assert!(app.get("/agreements").await.text().contains("switched off"));
let actions: Vec<(String, String)> = sqlx::query_as(
"SELECT action, entity FROM audit_log WHERE entity = 'agreement' ORDER BY id",
)
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(actions.len(), 3, "{actions:?}");
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn the_client_signs_and_signs_again_after_a_change(pool: PgPool) {
let app = local(pool.clone());
app.post(
"/agreements",
&[
("title", "Your data"),
("body", TEXT),
("action", "publish"),
],
)
.await;
let agreement: i64 = sqlx::query_scalar("SELECT id FROM agreements")
.fetch_one(&pool)
.await
.unwrap();
let v1: i64 = sqlx::query_scalar("SELECT id FROM agreement_versions")
.fetch_one(&pool)
.await
.unwrap();
let (person, link, token, csrf) = client(&pool).await;
let base = format!("/c/{token}");
let uri = format!("{base}/agree/{agreement}");
// the link asks for it first
let o = app.get(&base).await.text();
let first = o.find("Your data").unwrap();
assert!(first < o.find("About you").unwrap(), "{o}");
assert!(o.contains("To sign"));
let r = app.get(&uri).await;
assert_eq!(r.status, StatusCode::OK);
assert_unique_ids(&r.body, &uri);
let t = r.text();
assert!(t.contains("<h3>1. What Lanna Desk keeps</h3>"));
assert!(t.contains("value=\"Hans Becker\""), "{t}");
assert!(t.contains("/static/signature.js"));
// nothing else opens before the agreement is signed, and nothing is
// taken: every part leads to it, Send included
assert!(o.contains("First read and sign"), "{o}");
assert!(
o.contains("After signing") && !o.contains("send-btn"),
"{o}"
);
for part in ["about", "contact", "passport", "address", "documents"] {
let r = app.get(&format!("{base}/{part}")).await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{part}");
assert_eq!(r.location(), uri, "{part}");
}
let r = client_post(
&app,
&format!("{base}/contact"),
&csrf,
&[("phone", "123")],
&[],
)
.await;
assert_eq!(r.location(), uri);
let r = client_post(&app, &format!("{base}/send"), &csrf, &[], &[]).await;
assert_eq!(r.location(), uri);
let (phone, open): (String, bool) = sqlx::query_as(
"SELECT p.phone, l.closed_at IS NULL FROM people p JOIN client_links l ON l.person_id = p.id \
WHERE p.id = $1",
)
.bind(person)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!((phone.as_str(), open), ("", true));
// without the box ticked, or with a broken drawing
let r = client_post(
&app,
&uri,
&csrf,
&[("name", "Hans Becker"), ("version", &v1.to_string())],
&[],
)
.await;
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
assert!(r.text().contains("Tick the box"));
let r = client_post(
&app,
&uri,
&csrf,
&[
("name", "Hans Becker"),
("accept", "yes"),
("version", &v1.to_string()),
("drawing", "data:image/png;base64,AAAA"),
],
&[],
)
.await;
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
// a whole PNG whose header claims 300 x 738,197,594 pixels (found by the
// nightly fuzzing): refused before it is decoded, and the app lives on
let forged = {
use base64::Engine;
let png = include_bytes!("fuzz_cases/signed_copy/png-claims-885-gigabytes");
format!(
"data:image/png;base64,{}",
base64::engine::general_purpose::STANDARD.encode(png)
)
};
let r = client_post(
&app,
&uri,
&csrf,
&[
("name", "Hans Becker"),
("accept", "yes"),
("version", &v1.to_string()),
("drawing", &forged),
],
&[],
)
.await;
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
assert!(r.text().contains("did not arrive whole"));
// without the link's token
let r = client_post(
&app,
&uri,
"wrong",
&[("name", "x"), ("accept", "yes")],
&[],
)
.await;
assert_eq!(r.status, StatusCode::FORBIDDEN);
let r = client_post(
&app,
&uri,
&csrf,
&[
("name", "Hans Peter Becker"),
("accept", "yes"),
("version", &v1.to_string()),
("drawing", DRAWING),
],
&[
("x-forwarded-for", "203.0.113.7, 10.0.0.1"),
("user-agent", "TestPhone/1.0"),
],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
assert_eq!(r.location(), format!("{base}?saved=agree/{agreement}"));
let (name, drawn, ip, ua, doc): (String, bool, String, String, Option<i64>) = sqlx::query_as(
"SELECT signed_name, drawn, ip, user_agent, document_id FROM signatures \
WHERE person_id = $1",
)
.bind(person)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(name, "Hans Peter Becker");
assert!(drawn);
assert_eq!(ip, "203.0.113.7");
assert_eq!(ua, "TestPhone/1.0");
let doc = doc.expect("a signed copy");
let (kind, by, note): (String, String, String) =
sqlx::query_as("SELECT kind, uploaded_by, note FROM documents WHERE id = $1")
.bind(doc)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(kind, "agreement");
assert_eq!(by, format!("link {link}"));
assert_eq!(note, "Your data, version 1");
let file = app
.get(&format!("/people/{person}/documents/{doc}/file"))
.await;
assert_eq!(file.status, StatusCode::OK);
assert!(file.bytes.starts_with(b"%PDF-"));
// signed: the other parts open
assert_eq!(
app.get(&format!("{base}/about")).await.status,
StatusCode::OK
);
assert!(app.get(&base).await.text().contains("send-btn"));
// signed: the page says so, a second post changes nothing
assert!(
app.get(&uri)
.await
.text()
.contains("You signed this version on")
);
assert!(app.get(&base).await.text().contains(">Signed</span>"));
let again = client_post(
&app,
&uri,
&csrf,
&[
("name", "X"),
("accept", "yes"),
("version", &v1.to_string()),
],
&[],
)
.await;
assert_eq!(again.status, StatusCode::SEE_OTHER);
let n: i64 = sqlx::query_scalar("SELECT count(*) FROM signatures")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(n, 1);
let person_page = app.get(&format!("/people/{person}")).await.text();
assert!(
person_page.contains("signed as <b>Hans Peter Becker</b>"),
"{person_page}"
);
let logged: Vec<(String, String)> = sqlx::query_as(
"SELECT action, entity FROM audit_log WHERE actor = $1 AND action = 'create' ORDER BY id",
)
.bind(format!("link {link}"))
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(
logged,
[
("create".to_string(), "signature".to_string()),
("create".to_string(), "document".to_string())
]
);
// a new version: signed again, and a post of the old one is refused
app.post(
&format!("/agreements/{agreement}/versions"),
&[("body", "Changed text."), ("action", "publish")],
)
.await;
let o = app.get(&base).await.text();
assert!(
o.contains("Its text has changed since you signed it"),
"{o}"
);
assert!(
app.get(&format!("/people/{person}"))
.await
.text()
.contains("to sign again")
);
let r = client_post(
&app,
&uri,
&csrf,
&[
("name", "Hans Becker"),
("accept", "yes"),
("version", &v1.to_string()),
],
&[],
)
.await;
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
assert!(r.text().contains("changed the text while you read it"));
// and the parts close again until it is signed
assert_eq!(app.get(&format!("{base}/about")).await.location(), uri);
// switched off: no longer asked for
app.post(
&format!("/agreements/{agreement}/active"),
&[("active", "0")],
)
.await;
assert!(!app.get(&base).await.text().contains("Your data"));
assert_eq!(app.get(&uri).await.status, StatusCode::NOT_FOUND);
}