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.
452 lines
18 KiB
Rust
452 lines
18 KiB
Rust
//! Settings from the environment. The NixOS module sets them; secrets come as
|
|
//! files or systemd credentials, never as values in the environment.
|
|
//!
|
|
//! | Variable | Meaning |
|
|
//! | -------------------------------- | ------------------------------------------------ |
|
|
//! | `VISA_LISTEN` | address to listen on, default 127.0.0.1:8040 |
|
|
//! | `VISA_PUBLIC_URL` | https://visa.buildfor.life (login redirects) |
|
|
//! | `VISA_DATABASE_URL` | postgres://user@host/db |
|
|
//! | `VISA_DATABASE_PASSWORD_FILE` | the role's password (else credential `db-password`) |
|
|
//! | `VISA_OIDC_ISSUER` | https://id.cnx.network/oauth2/openid/visa-web |
|
|
//! | `VISA_OIDC_CLIENT_ID` | default `visa-web` |
|
|
//! | `VISA_OIDC_CLIENT_SECRET_FILE` | else credential `oidc-client-secret` |
|
|
//! | `VISA_OIDC_GROUP` | default `visa` |
|
|
//! | `VISA_INSECURE_NO_LOGIN` | `1`: no login, loopback addresses only |
|
|
//! | `VISA_S3_BUCKET` | the bucket the encrypted documents lie in |
|
|
//! | `VISA_S3_ENDPOINT` | the S3 server, `http://127.0.0.1:3900` (Garage) |
|
|
//! | `VISA_S3_REGION` | default `garage` |
|
|
//! | `VISA_S3_ACCESS_KEY_ID` | the bucket key's id |
|
|
//! | `VISA_S3_SECRET_ACCESS_KEY_FILE` | its secret (else credential `s3-secret`) |
|
|
//! | `VISA_FILES_DIR` | a directory for them instead (development) |
|
|
//! | `VISA_FILES_KEY_FILE` | the file key (else credential `files-key`) |
|
|
//!
|
|
//! With the login on, documents are required: a place for them (the bucket,
|
|
//! or a directory) and the file key. Local development may go without them;
|
|
//! uploads are then off.
|
|
|
|
use std::net::SocketAddr;
|
|
use std::path::PathBuf;
|
|
|
|
use anyhow::{Context, Result, bail, ensure};
|
|
|
|
use crate::files::FileKey;
|
|
use crate::s3::S3Config;
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct Config {
|
|
pub listen: SocketAddr,
|
|
/// Without a trailing slash.
|
|
pub public_url: String,
|
|
pub database_url: String,
|
|
pub database_password: Option<String>,
|
|
pub auth: Auth,
|
|
/// Documents: off in local development without a place for them.
|
|
pub files: Option<FilesConfig>,
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct FilesConfig {
|
|
pub place: FilesPlace,
|
|
pub key: FileKey,
|
|
}
|
|
|
|
/// Where the encrypted files lie.
|
|
#[derive(Clone, Debug)]
|
|
pub enum FilesPlace {
|
|
/// A bucket of an S3 store: the fleet's Garage.
|
|
Bucket(S3Config),
|
|
/// A directory: local development and the tests.
|
|
Dir(PathBuf),
|
|
}
|
|
|
|
/// The S3 settings that only mean something with `VISA_S3_BUCKET`.
|
|
const S3_VARS: [&str; 4] = [
|
|
"VISA_S3_ENDPOINT",
|
|
"VISA_S3_REGION",
|
|
"VISA_S3_ACCESS_KEY_ID",
|
|
"VISA_S3_SECRET_ACCESS_KEY_FILE",
|
|
];
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub enum Auth {
|
|
Oidc(OidcConfig),
|
|
/// Local development: everyone is "local"; loopback addresses only.
|
|
Disabled,
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct OidcConfig {
|
|
pub issuer: String,
|
|
pub client_id: String,
|
|
pub client_secret: String,
|
|
pub group: String,
|
|
}
|
|
|
|
// The secret stays out of logs and panics.
|
|
impl std::fmt::Debug for OidcConfig {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
f.debug_struct("OidcConfig")
|
|
.field("issuer", &self.issuer)
|
|
.field("client_id", &self.client_id)
|
|
.field(
|
|
"client_secret",
|
|
&format_args!("<{} bytes>", self.client_secret.len()),
|
|
)
|
|
.field("group", &self.group)
|
|
.finish()
|
|
}
|
|
}
|
|
|
|
impl Config {
|
|
pub fn from_env() -> Result<Config> {
|
|
Self::from_lookup(&|k| std::env::var(k).ok().filter(|v| !v.is_empty()))
|
|
}
|
|
|
|
pub fn from_lookup(var: &dyn Fn(&str) -> Option<String>) -> Result<Config> {
|
|
let listen: SocketAddr = var("VISA_LISTEN")
|
|
.unwrap_or_else(|| "127.0.0.1:8040".into())
|
|
.parse()
|
|
.context("VISA_LISTEN is not an address:port")?;
|
|
let public_url = var("VISA_PUBLIC_URL")
|
|
.unwrap_or_else(|| format!("http://{listen}"))
|
|
.trim_end_matches('/')
|
|
.to_string();
|
|
let database_url = var("VISA_DATABASE_URL").context("VISA_DATABASE_URL is not set")?;
|
|
let database_password = match var("VISA_DATABASE_PASSWORD_FILE") {
|
|
Some(path) => Some(read_file(&PathBuf::from(path), "the database password")?),
|
|
None => credential(var, "db-password")?,
|
|
};
|
|
let auth = match var("VISA_OIDC_ISSUER") {
|
|
Some(issuer) => {
|
|
ensure!(
|
|
public_url.starts_with("https://"),
|
|
"VISA_PUBLIC_URL must be https:// when the login is on (the session cookie is Secure)"
|
|
);
|
|
let client_secret = match var("VISA_OIDC_CLIENT_SECRET_FILE") {
|
|
Some(path) => read_file(&PathBuf::from(path), "the OIDC client secret")?,
|
|
None => credential(var, "oidc-client-secret")?.context(
|
|
"no OIDC client secret: set VISA_OIDC_CLIENT_SECRET_FILE or pass the \
|
|
credential oidc-client-secret",
|
|
)?,
|
|
};
|
|
Auth::Oidc(OidcConfig {
|
|
issuer: issuer.trim_end_matches('/').to_string(),
|
|
client_id: var("VISA_OIDC_CLIENT_ID").unwrap_or_else(|| "visa-web".into()),
|
|
client_secret,
|
|
group: var("VISA_OIDC_GROUP").unwrap_or_else(|| "visa".into()),
|
|
})
|
|
}
|
|
None if var("VISA_INSECURE_NO_LOGIN").as_deref() == Some("1") => {
|
|
if !listen.ip().is_loopback() {
|
|
bail!("VISA_INSECURE_NO_LOGIN=1 works only with a loopback VISA_LISTEN");
|
|
}
|
|
Auth::Disabled
|
|
}
|
|
None => bail!(
|
|
"no login configured: set VISA_OIDC_ISSUER and the client settings, or \
|
|
VISA_INSECURE_NO_LOGIN=1 for local development on a loopback address"
|
|
),
|
|
};
|
|
let key = match var("VISA_FILES_KEY_FILE") {
|
|
Some(path) => Some(read_file(&PathBuf::from(path), "the file key")?),
|
|
None => credential(var, "files-key")?,
|
|
};
|
|
let place = match (var("VISA_S3_BUCKET"), var("VISA_FILES_DIR")) {
|
|
(Some(_), Some(_)) => bail!(
|
|
"VISA_S3_BUCKET and VISA_FILES_DIR are both set: the documents lie in one place, \
|
|
the bucket or the directory"
|
|
),
|
|
(Some(bucket), None) => Some(FilesPlace::Bucket(s3_config(var, bucket)?)),
|
|
(None, dir) => {
|
|
if let Some(v) = S3_VARS.iter().find(|v| var(v).is_some()) {
|
|
bail!("{v} is set but VISA_S3_BUCKET is not");
|
|
}
|
|
dir.map(|d| FilesPlace::Dir(PathBuf::from(d)))
|
|
}
|
|
};
|
|
let files = match (place, key) {
|
|
(Some(place), Some(key)) => Some(FilesConfig {
|
|
place,
|
|
key: FileKey::from_hex(&key).context("reading the file key")?,
|
|
}),
|
|
(None, None) => None,
|
|
(Some(_), None) => bail!(
|
|
"the documents have a place but there is no file key: set VISA_FILES_KEY_FILE or \
|
|
pass the credential files-key"
|
|
),
|
|
(None, Some(_)) => bail!(
|
|
"there is a file key but no place for the documents: set VISA_S3_BUCKET with the \
|
|
S3 settings, or VISA_FILES_DIR"
|
|
),
|
|
};
|
|
if matches!(auth, Auth::Oidc(_)) && files.is_none() {
|
|
bail!(
|
|
"documents are not set up: with the login on, set VISA_S3_BUCKET with the S3 \
|
|
settings (or VISA_FILES_DIR) and the file key (VISA_FILES_KEY_FILE or the \
|
|
credential files-key)"
|
|
);
|
|
}
|
|
Ok(Config {
|
|
listen,
|
|
public_url,
|
|
database_url,
|
|
database_password,
|
|
auth,
|
|
files,
|
|
})
|
|
}
|
|
|
|
pub fn redirect_uri(&self) -> String {
|
|
format!("{}/auth/callback", self.public_url)
|
|
}
|
|
|
|
pub fn login_enabled(&self) -> bool {
|
|
matches!(self.auth, Auth::Oidc(_))
|
|
}
|
|
}
|
|
|
|
/// The bucket's settings; the secret from its file or the credential
|
|
/// `s3-secret`.
|
|
fn s3_config(var: &dyn Fn(&str) -> Option<String>, bucket: String) -> Result<S3Config> {
|
|
let need =
|
|
|name: &str| var(name).with_context(|| format!("VISA_S3_BUCKET is set but {name} is not"));
|
|
let secret_access_key = match var("VISA_S3_SECRET_ACCESS_KEY_FILE") {
|
|
Some(path) => read_file(&PathBuf::from(path), "the S3 secret key")?,
|
|
None => credential(var, "s3-secret")?.context(
|
|
"VISA_S3_BUCKET is set but there is no S3 secret key: set \
|
|
VISA_S3_SECRET_ACCESS_KEY_FILE or pass the credential s3-secret",
|
|
)?,
|
|
};
|
|
let cfg = S3Config {
|
|
endpoint: need("VISA_S3_ENDPOINT")?,
|
|
bucket,
|
|
region: var("VISA_S3_REGION").unwrap_or_else(|| "garage".into()),
|
|
access_key_id: need("VISA_S3_ACCESS_KEY_ID")?,
|
|
secret_access_key,
|
|
};
|
|
// the endpoint and the name are checked now, not at the first upload
|
|
crate::s3::Bucket::new(&cfg)?;
|
|
Ok(cfg)
|
|
}
|
|
|
|
/// A systemd credential (`LoadCredential=`), when the unit passes one.
|
|
fn credential(var: &dyn Fn(&str) -> Option<String>, name: &str) -> Result<Option<String>> {
|
|
let Some(dir) = var("CREDENTIALS_DIRECTORY") else {
|
|
return Ok(None);
|
|
};
|
|
let path = PathBuf::from(dir).join(name);
|
|
if !path.exists() {
|
|
return Ok(None);
|
|
}
|
|
read_file(&path, name).map(Some)
|
|
}
|
|
|
|
fn read_file(path: &PathBuf, what: &str) -> Result<String> {
|
|
let text = std::fs::read_to_string(path)
|
|
.with_context(|| format!("reading {what} from {}", path.display()))?;
|
|
let value = text.trim().to_string();
|
|
ensure!(!value.is_empty(), "{} is empty", path.display());
|
|
Ok(value)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::collections::HashMap;
|
|
|
|
fn cfg(pairs: &[(&str, &str)]) -> Result<Config> {
|
|
let m: HashMap<String, String> = pairs
|
|
.iter()
|
|
.map(|(k, v)| (k.to_string(), v.to_string()))
|
|
.collect();
|
|
Config::from_lookup(&|k| m.get(k).cloned())
|
|
}
|
|
|
|
#[test]
|
|
fn refuses_to_start_without_a_login() {
|
|
let e = cfg(&[("VISA_DATABASE_URL", "postgres://x/y")]).unwrap_err();
|
|
assert!(e.to_string().contains("no login configured"), "{e}");
|
|
}
|
|
|
|
#[test]
|
|
fn no_login_only_on_loopback() {
|
|
let ok = cfg(&[
|
|
("VISA_DATABASE_URL", "postgres://x/y"),
|
|
("VISA_INSECURE_NO_LOGIN", "1"),
|
|
])
|
|
.unwrap();
|
|
assert!(matches!(ok.auth, Auth::Disabled));
|
|
assert_eq!(ok.public_url, "http://127.0.0.1:8040");
|
|
let e = cfg(&[
|
|
("VISA_DATABASE_URL", "postgres://x/y"),
|
|
("VISA_INSECURE_NO_LOGIN", "1"),
|
|
("VISA_LISTEN", "0.0.0.0:8040"),
|
|
])
|
|
.unwrap_err();
|
|
assert!(e.to_string().contains("loopback"), "{e}");
|
|
}
|
|
|
|
#[test]
|
|
fn oidc_reads_the_secret_from_a_file() {
|
|
let dir = std::env::temp_dir().join(format!("visa-cfg-{}", std::process::id()));
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
let f = dir.join("secret");
|
|
std::fs::write(&f, "s3cret\n").unwrap();
|
|
let key = dir.join("files.key");
|
|
std::fs::write(&key, format!("{}\n", "ab".repeat(32))).unwrap();
|
|
let files_dir = dir.join("files");
|
|
let c = cfg(&[
|
|
("VISA_DATABASE_URL", "postgres://x/y"),
|
|
("VISA_PUBLIC_URL", "https://visa.example/"),
|
|
(
|
|
"VISA_OIDC_ISSUER",
|
|
"https://id.example/oauth2/openid/visa-web/",
|
|
),
|
|
("VISA_OIDC_CLIENT_SECRET_FILE", f.to_str().unwrap()),
|
|
("VISA_FILES_DIR", files_dir.to_str().unwrap()),
|
|
("VISA_FILES_KEY_FILE", key.to_str().unwrap()),
|
|
])
|
|
.unwrap();
|
|
let Auth::Oidc(o) = &c.auth else {
|
|
panic!("login expected")
|
|
};
|
|
assert_eq!(o.client_secret, "s3cret");
|
|
assert_eq!(o.client_id, "visa-web");
|
|
assert_eq!(o.group, "visa");
|
|
assert_eq!(o.issuer, "https://id.example/oauth2/openid/visa-web");
|
|
assert_eq!(c.redirect_uri(), "https://visa.example/auth/callback");
|
|
assert!(!format!("{o:?}").contains("s3cret"));
|
|
// a plain-http public URL cannot carry the Secure cookie
|
|
let e = cfg(&[
|
|
("VISA_DATABASE_URL", "postgres://x/y"),
|
|
("VISA_PUBLIC_URL", "http://visa.example"),
|
|
(
|
|
"VISA_OIDC_ISSUER",
|
|
"https://id.example/oauth2/openid/visa-web",
|
|
),
|
|
("VISA_OIDC_CLIENT_SECRET_FILE", f.to_str().unwrap()),
|
|
])
|
|
.unwrap_err();
|
|
assert!(e.to_string().contains("https"), "{e}");
|
|
// with the login on, documents must be set up
|
|
let e = cfg(&[
|
|
("VISA_DATABASE_URL", "postgres://x/y"),
|
|
("VISA_PUBLIC_URL", "https://visa.example"),
|
|
(
|
|
"VISA_OIDC_ISSUER",
|
|
"https://id.example/oauth2/openid/visa-web",
|
|
),
|
|
("VISA_OIDC_CLIENT_SECRET_FILE", f.to_str().unwrap()),
|
|
])
|
|
.unwrap_err();
|
|
assert!(e.to_string().contains("documents are not set up"), "{e}");
|
|
let files = c.files.unwrap();
|
|
assert!(matches!(&files.place, FilesPlace::Dir(d) if *d == files_dir));
|
|
assert!(!format!("{files:?}").contains("abab"));
|
|
std::fs::remove_dir_all(&dir).ok();
|
|
}
|
|
|
|
#[test]
|
|
fn documents_need_both_the_directory_and_the_key() {
|
|
let dir = std::env::temp_dir().join(format!("visa-cfg-files-{}", std::process::id()));
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
let key = dir.join("files.key");
|
|
let base = [
|
|
("VISA_DATABASE_URL", "postgres://x/y"),
|
|
("VISA_INSECURE_NO_LOGIN", "1"),
|
|
];
|
|
// local development may go without documents
|
|
assert!(cfg(&base).unwrap().files.is_none());
|
|
let with = |extra: &[(&str, &str)]| {
|
|
let mut all = base.to_vec();
|
|
all.extend_from_slice(extra);
|
|
cfg(&all)
|
|
};
|
|
let e = with(&[("VISA_FILES_DIR", "/srv/files")]).unwrap_err();
|
|
assert!(e.to_string().contains("no file key"), "{e}");
|
|
std::fs::write(&key, "not hex").unwrap();
|
|
let e = with(&[
|
|
("VISA_FILES_DIR", "/srv/files"),
|
|
("VISA_FILES_KEY_FILE", key.to_str().unwrap()),
|
|
])
|
|
.unwrap_err();
|
|
assert!(format!("{e:#}").contains("64 hex digits"), "{e:#}");
|
|
// the systemd credential
|
|
std::fs::write(dir.join("files-key"), "cd".repeat(32)).unwrap();
|
|
let c = with(&[
|
|
("VISA_FILES_DIR", "/srv/files"),
|
|
("CREDENTIALS_DIRECTORY", dir.to_str().unwrap()),
|
|
])
|
|
.unwrap();
|
|
assert!(c.files.is_some());
|
|
let e = with(&[("CREDENTIALS_DIRECTORY", dir.to_str().unwrap())]).unwrap_err();
|
|
assert!(e.to_string().contains("no place for the documents"), "{e}");
|
|
std::fs::remove_dir_all(&dir).ok();
|
|
}
|
|
|
|
#[test]
|
|
fn documents_in_a_bucket_take_its_settings_and_the_secret_from_a_credential() {
|
|
let dir = std::env::temp_dir().join(format!("visa-cfg-s3-{}", std::process::id()));
|
|
std::fs::create_dir_all(&dir).unwrap();
|
|
std::fs::write(dir.join("files-key"), "cd".repeat(32)).unwrap();
|
|
std::fs::write(dir.join("s3-secret"), "s3-secret-value\n").unwrap();
|
|
let creds = dir.to_str().unwrap();
|
|
let base = [
|
|
("VISA_DATABASE_URL", "postgres://x/y"),
|
|
("VISA_INSECURE_NO_LOGIN", "1"),
|
|
("CREDENTIALS_DIRECTORY", creds),
|
|
];
|
|
let with = |extra: &[(&str, &str)]| {
|
|
let mut all = base.to_vec();
|
|
all.extend_from_slice(extra);
|
|
cfg(&all)
|
|
};
|
|
let bucket = [
|
|
("VISA_S3_BUCKET", "visa-documents"),
|
|
("VISA_S3_ENDPOINT", "http://127.0.0.1:3900"),
|
|
("VISA_S3_ACCESS_KEY_ID", "GK00112233"),
|
|
];
|
|
let c = with(&bucket).unwrap();
|
|
let Some(FilesConfig {
|
|
place: FilesPlace::Bucket(b),
|
|
..
|
|
}) = &c.files
|
|
else {
|
|
panic!("a bucket expected: {:?}", c.files)
|
|
};
|
|
assert_eq!(b.bucket, "visa-documents");
|
|
assert_eq!(b.region, "garage");
|
|
assert_eq!(b.secret_access_key, "s3-secret-value");
|
|
assert!(!format!("{c:?}").contains("s3-secret-value"));
|
|
// every part is needed, and one place only
|
|
for missing in ["VISA_S3_ENDPOINT", "VISA_S3_ACCESS_KEY_ID"] {
|
|
let some: Vec<_> = bucket
|
|
.iter()
|
|
.copied()
|
|
.filter(|(k, _)| *k != missing)
|
|
.collect();
|
|
let e = with(&some).unwrap_err();
|
|
assert!(e.to_string().contains(missing), "{e}");
|
|
}
|
|
let mut both = bucket.to_vec();
|
|
both.push(("VISA_FILES_DIR", "/srv/files"));
|
|
let e = with(&both).unwrap_err();
|
|
assert!(e.to_string().contains("both set"), "{e}");
|
|
let e = with(&[("VISA_S3_ENDPOINT", "http://127.0.0.1:3900")]).unwrap_err();
|
|
assert!(e.to_string().contains("VISA_S3_BUCKET is not"), "{e}");
|
|
let mut bad = bucket.to_vec();
|
|
bad[1] = ("VISA_S3_ENDPOINT", "127.0.0.1:3900");
|
|
assert!(with(&bad).is_err());
|
|
// without the credential, the secret's file must be named
|
|
std::fs::remove_file(dir.join("s3-secret")).unwrap();
|
|
let e = with(&bucket).unwrap_err();
|
|
assert!(e.to_string().contains("no S3 secret key"), "{e}");
|
|
let f = dir.join("secret-file");
|
|
std::fs::write(&f, "from-a-file").unwrap();
|
|
let mut named = bucket.to_vec();
|
|
named.push(("VISA_S3_SECRET_ACCESS_KEY_FILE", f.to_str().unwrap()));
|
|
assert!(with(&named).is_ok());
|
|
std::fs::remove_dir_all(&dir).ok();
|
|
}
|
|
}
|