Files
visa/tests/common/mod.rs
T
grabowski 2e009700a9
CI / secret scan (push) Successful in 4s
CI / fmt, clippy, tests (push) Successful in 42s
Phase 1: app, Kanidm login, people, passports, addresses, audit log
visa.buildfor.life keeps the immigration records of the foreigners B4L
looks after. This first phase is the base the deadlines and extension
packs build on (docs/PLAN.md, phases 2 to 7).

- One Rust binary (axum 0.8, minijinja, sqlx on PostgreSQL) with its
  templates, static files and migrations compiled in.
- Login through Kanidm (OpenID Connect with PKCE and a nonce, ES256),
  client visa-web, group visa; sessions in PostgreSQL keyed by the
  SHA-256 of the cookie. VISA_INSECURE_NO_LOGIN=1 for loopback
  development only.
- Same-site check and form token on every POST; a CSP without inline
  script or style; security headers.
- People: list with filter, page, create, edit, archive, restore.
- Passports from the machine-readable zone with check digits (ICAO
  9303 TD3); expiry warnings at 12 and 6 months.
- Addresses in Thailand in the order Thai forms use, with the house
  master and the TM.30 receipt.
- Append-only audit log of every view and change, with the names of the
  changed fields but never their values (PDPA); the Activity page.
- Invented demo people (visa seed-demo, refused when login is on).
- 40 tests: unit tests, pages with demo data, the forms, the audit log
  and the whole login against a fake OpenID provider.
- CI: gitleaks over the history, fmt, clippy and the tests against
  PostgreSQL 18; the pre-commit secret scan.
2026-11-17 16:58:48 +07:00

175 lines
4.6 KiB
Rust

#![allow(dead_code)]
use std::sync::Arc;
use axum::Router;
use axum::body::Body;
use axum::http::{HeaderMap, Request, StatusCode};
use chrono::NaiveDate;
use http_body_util::BodyExt;
use sqlx::PgPool;
use tower::ServiceExt;
use visa::config::{Auth, Config, OidcConfig};
use visa::web::{self, AppState};
pub fn config(auth: Auth) -> Config {
Config {
listen: "127.0.0.1:0".parse().unwrap(),
public_url: "https://visa.test".into(),
database_url: "postgres://unused".into(),
database_password: None,
auth,
}
}
pub fn oidc_config(issuer: &str) -> OidcConfig {
OidcConfig {
issuer: issuer.into(),
client_id: "visa-web".into(),
client_secret: "test-secret".into(),
group: "visa".into(),
}
}
pub struct App {
pub st: Arc<AppState>,
pub router: Router,
pub pool: PgPool,
}
/// Local development mode: no login, everyone is "local".
pub fn local(pool: PgPool) -> App {
with_auth(pool, Auth::Disabled)
}
pub fn with_auth(pool: PgPool, auth: Auth) -> App {
let st = AppState::new(config(auth), pool.clone()).unwrap();
App {
router: web::router(st.clone()),
st,
pool,
}
}
pub struct Resp {
pub status: StatusCode,
pub headers: HeaderMap,
pub body: String,
}
impl Resp {
pub fn location(&self) -> &str {
self.headers
.get("location")
.and_then(|v| v.to_str().ok())
.unwrap_or("")
}
/// The decoded page text, for assertions on what people read.
pub fn text(&self) -> String {
self.body
.replace("&#x27;", "'")
.replace("&#39;", "'")
.replace("&quot;", "\"")
.replace("&#x2f;", "/")
.replace("&amp;", "&")
}
}
pub fn form_body(pairs: &[(&str, &str)]) -> String {
form_urlencoded::Serializer::new(String::new())
.extend_pairs(pairs)
.finish()
}
impl App {
pub async fn call(&self, req: Request<Body>) -> Resp {
let resp = self.router.clone().oneshot(req).await.unwrap();
let status = resp.status();
let headers = resp.headers().clone();
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
Resp {
status,
headers,
body: String::from_utf8_lossy(&bytes).into_owned(),
}
}
pub async fn get(&self, uri: &str) -> Resp {
self.get_with(uri, &[]).await
}
pub async fn get_with(&self, uri: &str, headers: &[(&str, &str)]) -> Resp {
let mut req = Request::get(uri);
for (k, v) in headers {
req = req.header(*k, *v);
}
self.call(req.body(Body::empty()).unwrap()).await
}
/// A form as a browser on this site sends it, with the local token.
pub async fn post(&self, uri: &str, form: &[(&str, &str)]) -> Resp {
let csrf = self.st.local_csrf().to_string();
let mut pairs: Vec<(&str, &str)> = form.to_vec();
pairs.push(("csrf", &csrf));
self.post_raw(uri, &pairs, &[("sec-fetch-site", "same-origin")])
.await
}
pub async fn post_raw(
&self,
uri: &str,
form: &[(&str, &str)],
headers: &[(&str, &str)],
) -> Resp {
let mut req =
Request::post(uri).header("content-type", "application/x-www-form-urlencoded");
for (k, v) in headers {
req = req.header(*k, *v);
}
self.call(req.body(Body::from(form_body(form))).unwrap())
.await
}
}
pub fn d(s: &str) -> NaiveDate {
NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap()
}
/// The id at the end of a redirect to /people/<id>.
pub fn id_from(location: &str) -> i64 {
location
.trim_start_matches("/people/")
.split(['#', '/'])
.next()
.unwrap()
.parse()
.unwrap_or_else(|_| panic!("no person id in {location:?}"))
}
/// The two MRZ lines for an invented German passport.
pub fn erika_mrz() -> String {
visa::mrz::compose(&visa::mrz::Compose {
issuing_state: "D",
surname: "MUSTERMANN",
given_names: "ERIKA",
number: "C01X00T47",
nationality: "D",
date_of_birth: d("1984-08-12"),
sex: "F",
expiry_date: d("2031-08-01"),
})
}
/// Duplicate element ids make `getElementById` pick the wrong element.
pub fn assert_unique_ids(html: &str, page: &str) {
let mut seen = std::collections::HashSet::new();
for part in html.split(" id=\"").skip(1) {
let id = part.split('"').next().unwrap();
assert!(
seen.insert(id.to_string()),
"{page}: id {id:?} occurs twice"
);
}
}