Asked for on November 19, 2026: the uploaded files land in an S3 bucket of the fleet's Garage instead of a directory on cnx01, as the fleet's other apps keep theirs. The app encrypts each file exactly as before (AES-256-GCM under a key from HKDF, the document's id authenticated), so the bucket holds the same VISADOC1 files and Garage never sees a key or a document in the clear. Garage's SSE-C stays off: its key would come from the same secret. src/s3.rs is a small S3 client on reqwest and ring, as in proplan: SigV4 (checked against AWS's two published examples), path-style PUT, GET, HEAD, DELETE and ListObjectsV2 page by page, three attempts when the server is away or busy. It asks before it writes, so no object is replaced; it sends If-None-Match: * as well, which Garage 2.5 ignores (seen in tests/garage.rs). The store (src/files.rs) keeps the files as documents/<id>.vdoc in the bucket, or as <id>.vdoc in a directory for development and the tests. Its calls are async now. VISA_S3_BUCKET, _ENDPOINT, _REGION and _ACCESS_KEY_ID name the bucket, the secret comes from VISA_S3_SECRET_ACCESS_KEY_FILE or the credential s3-secret; the bucket and a directory together are refused. At the start the app checks the bucket in the background and only warns. New commands: `visa files-migrate --from DIR` copies the files of a directory into the store, each opened and compared with its upload before and after, and may run again; `visa files-mirror --to DIR` makes a directory hold exactly the bucket's files, still encrypted, for the backups, and a restore is files-migrate from it. Tests: an S3 server inside the test process that checks every request's signature and pages its listings (tests/common/fake_s3.rs); uploads, views, downloads and deletions through it, the check finding swapped, missing and stray objects, the move from a directory (again, missing, other bytes, damaged), the mirror and a restore from it, a busy server and a wrong key. tests/garage.rs runs the store against Garage 2.5.0, the version cnx01 runs, which scripts/dev-garage.sh starts in Docker; VISA_DEV_S3=1 scripts/dev.sh runs the dev server on it. The 14 demo documents moved into it with files-migrate and a browser upload landed there.
322 lines
8.6 KiB
Rust
322 lines
8.6 KiB
Rust
#![allow(dead_code)]
|
|
|
|
pub mod fake_s3;
|
|
|
|
use std::path::PathBuf;
|
|
use std::sync::Arc;
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
|
|
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, FilesConfig, FilesPlace, OidcConfig};
|
|
use visa::files::FileKey;
|
|
use visa::web::{self, AppState};
|
|
|
|
/// A files directory of its own for each app, under the target directory.
|
|
pub fn files_dir() -> PathBuf {
|
|
static N: AtomicUsize = AtomicUsize::new(0);
|
|
PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!(
|
|
"files-{}-{}",
|
|
std::process::id(),
|
|
N.fetch_add(1, Ordering::Relaxed)
|
|
))
|
|
}
|
|
|
|
/// Documents on, in a fresh directory with a fresh key.
|
|
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,
|
|
files: Some(FilesConfig {
|
|
place: FilesPlace::Dir(files_dir()),
|
|
key: FileKey::random(),
|
|
}),
|
|
}
|
|
}
|
|
|
|
/// Documents on, in the test server's bucket, with a fresh key.
|
|
pub fn bucket_config(auth: Auth, s3: &fake_s3::FakeS3) -> Config {
|
|
Config {
|
|
files: Some(FilesConfig {
|
|
place: FilesPlace::Bucket(s3.config()),
|
|
key: FileKey::random(),
|
|
}),
|
|
..config(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,
|
|
}
|
|
|
|
// The test's files go with it.
|
|
impl Drop for App {
|
|
fn drop(&mut self) {
|
|
if let Some(FilesConfig {
|
|
place: FilesPlace::Dir(dir),
|
|
..
|
|
}) = &self.st.cfg.files
|
|
{
|
|
std::fs::remove_dir_all(dir).ok();
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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 {
|
|
with_config(pool, config(auth))
|
|
}
|
|
|
|
pub fn with_config(pool: PgPool, cfg: Config) -> App {
|
|
let st = AppState::new(cfg, pool.clone()).unwrap();
|
|
App {
|
|
router: web::router(st.clone()),
|
|
st,
|
|
pool,
|
|
}
|
|
}
|
|
|
|
pub struct Resp {
|
|
pub status: StatusCode,
|
|
pub headers: HeaderMap,
|
|
pub body: String,
|
|
/// The body as it came, for files.
|
|
pub bytes: Vec<u8>,
|
|
}
|
|
|
|
impl Resp {
|
|
pub fn location(&self) -> &str {
|
|
self.header("location")
|
|
}
|
|
|
|
pub fn header(&self, name: &str) -> &str {
|
|
self.headers
|
|
.get(name)
|
|
.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("'", "'")
|
|
.replace("'", "'")
|
|
.replace(""", "\"")
|
|
.replace("/", "/")
|
|
.replace("&", "&")
|
|
}
|
|
}
|
|
|
|
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(),
|
|
bytes: bytes.to_vec(),
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
/// An upload as the page sends it: the form token first, then the
|
|
/// fields, then the files.
|
|
pub async fn upload(
|
|
&self,
|
|
uri: &str,
|
|
fields: &[(&str, &str)],
|
|
files: &[(&str, &[u8])],
|
|
) -> Resp {
|
|
let csrf = self.st.local_csrf().to_string();
|
|
let mut parts = vec![Part::field("csrf", csrf.as_bytes())];
|
|
for (k, v) in fields {
|
|
parts.push(Part::field(k, v.as_bytes()));
|
|
}
|
|
for (name, data) in files {
|
|
parts.push(Part::file(name, data));
|
|
}
|
|
self.upload_raw(uri, &parts, &[("sec-fetch-site", "same-origin")])
|
|
.await
|
|
}
|
|
|
|
pub async fn upload_raw(
|
|
&self,
|
|
uri: &str,
|
|
parts: &[Part<'_>],
|
|
headers: &[(&str, &str)],
|
|
) -> Resp {
|
|
let mut req = Request::post(uri).header(
|
|
"content-type",
|
|
format!("multipart/form-data; boundary={BOUNDARY}"),
|
|
);
|
|
for (k, v) in headers {
|
|
req = req.header(*k, *v);
|
|
}
|
|
self.call(req.body(Body::from(multipart_body(parts))).unwrap())
|
|
.await
|
|
}
|
|
}
|
|
|
|
const BOUNDARY: &str = "----visa-test-7d1f0c";
|
|
|
|
/// One part of a multipart form.
|
|
pub struct Part<'a> {
|
|
pub name: &'a str,
|
|
pub file_name: Option<&'a str>,
|
|
pub data: &'a [u8],
|
|
}
|
|
|
|
impl<'a> Part<'a> {
|
|
pub fn field(name: &'a str, data: &'a [u8]) -> Part<'a> {
|
|
Part {
|
|
name,
|
|
file_name: None,
|
|
data,
|
|
}
|
|
}
|
|
|
|
pub fn file(file_name: &'a str, data: &'a [u8]) -> Part<'a> {
|
|
Part {
|
|
name: "file",
|
|
file_name: Some(file_name),
|
|
data,
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn multipart_body(parts: &[Part<'_>]) -> Vec<u8> {
|
|
let mut body = Vec::new();
|
|
for p in parts {
|
|
body.extend_from_slice(format!("--{BOUNDARY}\r\n").as_bytes());
|
|
let head = match p.file_name {
|
|
Some(f) => format!(
|
|
"Content-Disposition: form-data; name=\"{}\"; filename=\"{f}\"\r\n\
|
|
Content-Type: application/octet-stream\r\n\r\n",
|
|
p.name
|
|
),
|
|
None => format!(
|
|
"Content-Disposition: form-data; name=\"{}\"\r\n\r\n",
|
|
p.name
|
|
),
|
|
};
|
|
body.extend_from_slice(head.as_bytes());
|
|
body.extend_from_slice(p.data);
|
|
body.extend_from_slice(b"\r\n");
|
|
}
|
|
body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes());
|
|
body
|
|
}
|
|
|
|
/// A small PDF that says what it is.
|
|
pub fn pdf(text: &str) -> Vec<u8> {
|
|
format!("%PDF-1.4\n% {text}\n%%EOF\n").into_bytes()
|
|
}
|
|
|
|
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"
|
|
);
|
|
}
|
|
}
|