From 63140595ff8ff2ac45176dc6310177eadd320e9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 20:04:53 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=9B=A1=EF=B8=8F=20ops:=20loopback-only=20?= =?UTF-8?q?http,=20private=20files=20from=20creation,=20secret=20file=20mo?= =?UTF-8?q?des,=20redacted=20Debug,=20bounded=20IdP=20answers,=20pinned=20?= =?UTF-8?q?argon2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 1 + Cargo.toml | 1 + README.md | 9 ++-- config/in.example.toml | 12 +++-- crates/in-core/Cargo.toml | 1 + crates/in-core/src/backup.rs | 18 ++++++- crates/in-core/src/config.rs | 71 +++++++++++++++++++++++-- crates/in-core/src/export.rs | 12 +++-- crates/in-core/src/password.rs | 24 ++++++--- crates/in-core/src/secret.rs | 26 +++++++-- crates/in-core/src/store/links.rs | 43 ++++++++++++++- crates/in-core/src/store/mod.rs | 29 ++++++++++ crates/in-core/src/store/sessions.rs | 40 +++++++++++++- crates/in-core/src/store/snapshot.rs | 7 ++- crates/in-web/src/boot.rs | 48 +++++++++++++++-- crates/in-web/src/directory.rs | 8 +-- crates/in-web/src/family.rs | 15 +++--- crates/in-web/src/oidc.rs | 30 +++++++---- crates/in-web/src/pages/backchannel.rs | 12 ++++- crates/in-web/src/pages/links.rs | 17 +++++- crates/in-web/src/pages/photo.rs | 20 +++++-- crates/in-web/src/pages/public_share.rs | 15 +++++- crates/in-web/src/pages/sign_in.rs | 37 +++++++++++-- crates/in-web/src/serve_bytes.rs | 3 +- docs/architecture.md | 7 +-- 25 files changed, 433 insertions(+), 73 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5e71863..8a1129c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1739,6 +1739,7 @@ dependencies = [ "turso", "ulid", "unicode-normalization", + "url", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index bfa3da6..b183eed 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -79,4 +79,5 @@ tracing-subscriber = "0.3.23" turso = { version = "0.8.3", default-features = false, features = ["mimalloc"] } ulid = "3.0.0" unicode-normalization = "0.1.26" +url = "2.5.8" diff --git a/README.md b/README.md index a070f24..e838fc8 100644 --- a/README.md +++ b/README.md @@ -38,19 +38,22 @@ Do not enable the unit until the configuration and the `im` client below are in `config/in.example.toml` on first run. Unknown keys are an error, so a typo fails at start-up. The file holds no secrets. The OIDC client secret and the S3 keys are read from files that only the service -user can read: +user can read; `in` refuses a secret file that group or world can read: | Key | Meaning | |---|---| -| `database`, `data_dir` | Database file and data directory (blobs, staging, `in.key`, `in.lock`). The data directory is created with mode 0700. | +| `database`, `data_dir` | Database file and data directory (blobs, staging, `in.key`, `in.lock`). The data directory is created with mode 0700, and the database file and its `-wal` and `-shm` files with mode 0600. | | `listen` | Address to bind. Keep it on loopback and put the reverse proxy in front. | -| `base_url` | Public origin with no trailing slash. An `https` origin turns on `Secure` cookies and HSTS. | +| `base_url` | Public origin with no trailing slash. An `https` origin turns on `Secure` cookies and HSTS. Plain `http` is accepted only for a loopback host (`localhost`, `127.0.0.0/8`, `::1`), and never with userinfo. | | `trusted_proxies` | Proxies whose `X-Forwarded-For` is believed. Behind Ferron on the same host, `["127.0.0.1/32"]`; left empty there, every visitor counts as the proxy. | | `[oidc]` | `issuer` (the `im` origin), `client_id` (the id `im` printed for this client), `client_secret_file`. | | `[storage]` | `backend = "local"` (default) or `"s3"` with `[storage.s3]`. | | `[backup]` | Optional. `dir`, `interval_hours`, `keep`, `healthcheck_url`. See *Backups*. | | `[limits]` | Optional defaults the admin page may override: quotas, purge days, upload size, link length. | +At start-up `in` logs a warning when `listen` is a loopback address with no `trusted_proxies`, when `[backup]` or +`[oidc]` is not configured, and when `database` is outside `data_dir`. None of them stops the server. + The admin page at `/admin` shows, next to each runtime value, whether it was set there, comes from the file, or is the built-in default. A blank field on that page removes the page's value again. diff --git a/config/in.example.toml b/config/in.example.toml index fbe363f..011b234 100644 --- a/config/in.example.toml +++ b/config/in.example.toml @@ -2,20 +2,23 @@ # Secrets are never written here. The OIDC client secret and the S3 keys are read from files or # entered in the admin UI. -# Database file (Turso). Relative paths are relative to the working directory. +# Database file (Turso). Relative paths are relative to the working directory. Created with mode 0600, and +# outside data_dir the data-directory lock and restore do not cover it. database = "data/in.db" # Directory for blobs, staging files, the instance key (in.key) and caches. Created with mode 0700. data_dir = "data" # Address the HTTP server binds to. Put a TLS reverse proxy in front of it for public use. listen = "127.0.0.1:7655" -# Public URL of this instance, with no trailing slash. An https URL turns on Secure cookies and HSTS. +# Public URL of this instance, with no trailing slash. An https URL turns on Secure cookies and HSTS. Plain +# http is accepted only for a loopback host (localhost, 127.0.0.0/8, ::1). base_url = "http://127.0.0.1:7655" # Proxies whose X-Forwarded-For header is believed for client addresses. CIDR ranges or bare addresses. # Behind Ferron on the same host, set ["127.0.0.1/32"]; left empty there, every visitor counts as 127.0.0.1. trusted_proxies = [] # Sign-in through im (OpenID Connect). Point issuer at the im instance you run (its origin, no -# trailing slash). The client secret is read from client_secret_file at boot; it is never in this file. +# trailing slash; http only for a loopback host). The client secret is read from client_secret_file at +# boot; it is never in this file, and the file must not be readable by group or world (mode 0600). [oidc] issuer = "http://127.0.0.1:7650" client_id = "in" @@ -24,7 +27,8 @@ client_secret_file = "data/oidc_client_secret" [storage] backend = "local" -# To store blobs in an S3-compatible bucket instead, use backend = "s3" and this table: +# To store blobs in an S3-compatible bucket instead, use backend = "s3" and this table. The credential files +# must not be readable by group or world (mode 0600); the endpoint follows the same rules as base_url. # [storage.s3] # endpoint = "https://.r2.cloudflarestorage.com" # omit for AWS # region = "auto" diff --git a/crates/in-core/Cargo.toml b/crates/in-core/Cargo.toml index 5b54387..e543aec 100644 --- a/crates/in-core/Cargo.toml +++ b/crates/in-core/Cargo.toml @@ -31,6 +31,7 @@ tracing.workspace = true turso.workspace = true ulid.workspace = true unicode-normalization.workspace = true +url.workspace = true [dev-dependencies] tempfile.workspace = true diff --git a/crates/in-core/src/backup.rs b/crates/in-core/src/backup.rs index 92bb31d..e25dc83 100644 --- a/crates/in-core/src/backup.rs +++ b/crates/in-core/src/backup.rs @@ -192,6 +192,19 @@ fn write_private(path: &Path, bytes: &[u8]) -> Result<()> { Ok(()) } +/// Copies `from` to `to`, which must not exist, with mode 0600. A restored database is never readable by +/// others, scratch copies included. +fn copy_private(from: &Path, to: &Path) -> Result<()> { + let mut out = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(to)?; + std::io::copy(&mut std::fs::File::open(from)?, &mut out)?; + out.sync_all()?; + Ok(()) +} + /// Size and SHA-256 of a file, read in chunks. fn file_digest(path: &Path) -> Result<(u64, String)> { let mut file = std::fs::File::open(path)?; @@ -297,7 +310,8 @@ pub async fn restore( let scratch_dir = data_dir.join(crate::staging::TMP_DIR); std::fs::create_dir_all(&scratch_dir)?; let scratch = scratch_dir.join(format!("restore-{stamp}.db")); - std::fs::copy(&source, &scratch)?; + copy_private(&source, &scratch)?; + crate::store::create_private_files(&scratch)?; let check = integrity_of(&scratch).await; remove_sidecars(&scratch)?; std::fs::remove_file(&scratch)?; @@ -324,7 +338,7 @@ pub async fn restore( None }; let staged = scratch_dir.join(format!("restore-{stamp}-final.db")); - std::fs::copy(&source, &staged)?; + copy_private(&source, &staged)?; std::fs::rename(&staged, database)?; std::fs::File::open(&parent)?.sync_all()?; diff --git a/crates/in-core/src/config.rs b/crates/in-core/src/config.rs index 7a6c62a..28772fb 100644 --- a/crates/in-core/src/config.rs +++ b/crates/in-core/src/config.rs @@ -2,14 +2,17 @@ //! S3 keys are read from files or entered in the admin UI. Every struct rejects unknown keys, so a //! typo fails at boot instead of being silently ignored. +use std::fmt; use std::net::{IpAddr, SocketAddr}; use std::path::{Path, PathBuf}; use std::str::FromStr; use ipnet::IpNet; use serde::{Deserialize, Deserializer}; +use url::{Host, Url}; use crate::error::{Error, Result}; +use crate::secret::Redacted; /// The example file. It is committed, and it is written to `config/in.toml` when that file is missing. pub const EXAMPLE: &str = include_str!("../../../config/in.example.toml"); @@ -123,7 +126,7 @@ pub struct S3 { } /// The `[backup]` table. -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[derive(Clone, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields)] pub struct Backup { /// Directory that receives one snapshot set per run. @@ -139,6 +142,20 @@ pub struct Backup { pub healthcheck_url: Option, } +impl fmt::Debug for Backup { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Backup") + .field("dir", &self.dir) + .field("interval_hours", &self.interval_hours) + .field("keep", &self.keep) + .field( + "healthcheck_url", + &self.healthcheck_url.as_ref().map(|_| Redacted), + ) + .finish() + } +} + fn default_interval_hours() -> u32 { 24 } @@ -257,12 +274,34 @@ fn config_err(message: &str) -> Error { Error::Config(message.to_string()) } -/// An http or https URL with no trailing slash. Scheme checks only: the rest is left to the -/// component that uses the URL, which reports its own error. +/// Parses `url` and returns it only when `in` may connect to it: `https` always, and `http` only for a +/// loopback host with no userinfo, so plain text never leaves the machine. Every URL `in` is given +/// goes through here, the configuration and the family switcher alike. +pub fn parse_endpoint(url: &str) -> Option { + let parsed = Url::parse(url).ok()?; + let plain_ok = parsed.scheme() == "http" + && parsed.username().is_empty() + && parsed.password().is_none() + && is_loopback(&parsed); + (parsed.scheme() == "https" || plain_ok).then_some(parsed) +} + +/// Whether the host of `url` is `localhost`, an IPv4 address in 127.0.0.0/8, or `::1`. +fn is_loopback(url: &Url) -> bool { + match url.host() { + Some(Host::Domain(name)) => name == "localhost", + Some(Host::Ipv4(ip)) => ip.is_loopback(), + Some(Host::Ipv6(ip)) => ip.is_loopback(), + None => false, + } +} + +/// A URL that [`parse_endpoint`] accepts, with no trailing slash and no whitespace. The rest is left to +/// the component that uses the URL, which reports its own error. fn validate_base_url(field: &str, url: &str) -> Result<()> { - if !(url.starts_with("https://") || url.starts_with("http://")) { + if parse_endpoint(url).is_none() { return Err(config_err(&format!( - "{field} must start with http:// or https://" + "{field} must be an https:// URL, or an http:// URL for a loopback host" ))); } if url.ends_with('/') || url.chars().any(char::is_whitespace) { @@ -300,6 +339,28 @@ pub fn parse_proxy(text: &str) -> std::result::Result { mod tests { use super::*; + #[test] + fn plain_http_is_allowed_only_for_loopback_hosts() { + for url in [ + "http://127.0.0.1:7655", + "http://127.4.5.6", + "http://localhost:7650", + "http://[::1]:7650", + "https://im.example.com", + ] { + assert!(parse_endpoint(url).is_some(), "{url}"); + } + for url in [ + "http://localhost.evil.example", + "http://localhost@evil.example", + "http://192.168.1.5", + "http://evil.example", + "ftp://127.0.0.1", + ] { + assert!(parse_endpoint(url).is_none(), "{url}"); + } + } + #[test] fn example_is_valid_and_bare_proxy_addresses_are_accepted() { let config: Config = toml::from_str(EXAMPLE).unwrap(); diff --git a/crates/in-core/src/export.rs b/crates/in-core/src/export.rs index f29e8d4..e8b7aea 100644 --- a/crates/in-core/src/export.rs +++ b/crates/in-core/src/export.rs @@ -5,9 +5,11 @@ //! output directory: a separator or control character becomes `_`, and `.` and `..` are never used as //! a name. Each file is created with `create_new`, so an existing file or a planted symlink is never //! written through. Bytes are hashed while they are copied and checked against the database row; a -//! mismatch removes the partial file and is reported. Trashed items are not exported. +//! mismatch removes the partial file and is reported. Trashed items are not exported. Folders are made +//! with mode 0700 and files with mode 0600, so the copy is private whatever the umask says. use std::io::Write; +use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; use std::path::{Path, PathBuf}; use futures_util::StreamExt; @@ -83,7 +85,10 @@ pub async fn export_member( sub: &str, out: &Path, ) -> Result { - std::fs::create_dir_all(out)?; + std::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(out)?; let root = std::fs::canonicalize(out)?; let mut report = ExportReport::default(); // Work list of (folder id, the directory it goes into). @@ -92,7 +97,7 @@ pub async fn export_member( let listing = store.list_children(sub, folder.as_deref()).await?; for Folder { id, name, .. } in listing.folders { let path = free_path(&dir, &safe_component(&name), false)?; - std::fs::create_dir(&path)?; + std::fs::DirBuilder::new().mode(0o700).create(&path)?; ensure_inside(&root, &path)?; report.folders += 1; pending.push((Some(id), path)); @@ -149,6 +154,7 @@ async fn copy_file( let mut file = std::fs::OpenOptions::new() .write(true) .create_new(true) + .mode(0o600) .open(path) .map_err(|e| e.to_string())?; let outcome = write_verified(blobs, key, size, sha256, &mut file).await; diff --git a/crates/in-core/src/password.rs b/crates/in-core/src/password.rs index b4f725d..67ff2fd 100644 --- a/crates/in-core/src/password.rs +++ b/crates/in-core/src/password.rs @@ -2,16 +2,30 @@ //! blocking versions are slow by design, so async callers use the `_async` functions, which run them //! on tokio's blocking pool. -use argon2::Argon2; use argon2::password_hash::phc::PasswordHash; use argon2::password_hash::{PasswordHasher, PasswordVerifier}; +use argon2::{Algorithm, Argon2, Params, Version}; use crate::error::{Error, Result}; -/// Hashes `pw` with argon2id (default parameters) and a random salt. Returns a PHC string. +/// Memory cost of a hash, in KiB (19 MiB), time cost and lanes. They are written out here, not left to the +/// crate's defaults, so a crate upgrade cannot change new hashes silently. A stored hash carries its own +/// parameters, so every hash made before still verifies. +const M_COST_KIB: u32 = 19 * 1024; +const T_COST: u32 = 2; +const P_COST: u32 = 1; + +/// The argon2id hasher with the pinned parameters. +fn hasher() -> Argon2<'static> { + let params = Params::new(M_COST_KIB, T_COST, P_COST, None) + .expect("the pinned argon2 parameters are valid"); + Argon2::new(Algorithm::Argon2id, Version::V0x13, params) +} + +/// Hashes `pw` with argon2id (pinned parameters) and a random salt. Returns a PHC string. pub fn hash_password(pw: &str) -> Result { // The trait method draws a fresh salt from the OS RNG. - Argon2::default() + hasher() .hash_password(pw.as_bytes()) .map(|h| h.to_string()) .map_err(|e| Error::Crypto(format!("argon2: {e}"))) @@ -23,9 +37,7 @@ pub fn verify_password(pw: &str, hash: &str) -> bool { let Ok(parsed) = PasswordHash::new(hash) else { return false; }; - Argon2::default() - .verify_password(pw.as_bytes(), &parsed) - .is_ok() + hasher().verify_password(pw.as_bytes(), &parsed).is_ok() } /// [`hash_password`] on the blocking pool, so the async runtime is not held for the hashing time. diff --git a/crates/in-core/src/secret.rs b/crates/in-core/src/secret.rs index bc06361..4266d83 100644 --- a/crates/in-core/src/secret.rs +++ b/crates/in-core/src/secret.rs @@ -5,6 +5,7 @@ //! (see [`derive_subkey`]), and every seal is bound to a [`purpose`] that is checked as associated data, //! so a value sealed for one purpose does not open as another. +use std::fmt; use std::path::Path; use base64::prelude::{BASE64_STANDARD, Engine as _}; @@ -37,6 +38,16 @@ pub mod purpose { pub const SHARE_LINK_TOKEN: &str = "share-link-token"; } +/// Stands in for a secret in a hand-written `Debug`. It prints as ``, so a struct that holds a +/// secret can be logged without leaking it. +pub struct Redacted; + +impl fmt::Debug for Redacted { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("") + } +} + /// Loads the 32-byte instance key at `path`, creating it when missing. A new key is created with /// mode 0600 and `O_EXCL`, so an existing key is never overwritten. An existing key with group or /// world access is refused. @@ -79,21 +90,28 @@ fn create_key(path: &Path) -> std::io::Result<[u8; 32]> { Ok(key) } -/// Reads an existing instance key without creating one. A key with group or world access, or of the wrong -/// length, is refused. -pub fn read_key(path: &Path) -> Result<[u8; 32]> { +/// Refuses a secret file that group or world can read or write. The instance key and every credential +/// file `in` reads at boot must pass this, so a secret is never used from a file others can open. +pub fn check_private(path: &Path) -> Result<()> { #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let mode = std::fs::metadata(path)?.permissions().mode(); if mode & 0o077 != 0 { return Err(Error::Crypto(format!( - "instance key {} is group/world accessible (mode {:o}); expected 0600", + "{} is group/world accessible (mode {:o}); expected 0600", path.display(), mode & 0o777 ))); } } + Ok(()) +} + +/// Reads an existing instance key without creating one. A key with group or world access, or of the wrong +/// length, is refused. +pub fn read_key(path: &Path) -> Result<[u8; 32]> { + check_private(path)?; let bytes = std::fs::read(path)?; <[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| { Error::Crypto(format!( diff --git a/crates/in-core/src/store/links.rs b/crates/in-core/src/store/links.rs index 4fdcff9..cb595fd 100644 --- a/crates/in-core/src/store/links.rs +++ b/crates/in-core/src/store/links.rs @@ -5,9 +5,12 @@ //! This module stores and finds links. Whether a visitor may see something through a link is decided by //! the web layer with `authz` (the link actor) and the store's `is_within` and `item_trashed`. +use std::fmt; + use turso::{Connection, Row}; use crate::error::{Error, Result}; +use crate::secret::Redacted; use crate::store::files::live_file; use crate::store::folders::live_folder; use crate::store::shares::{kind_from_word, kind_word}; @@ -23,7 +26,7 @@ pub const LINK_COLS: &str = "id, token_hash, token_sealed, target_kind, target_i password_hash, expires_at, revoked_at, created_at, last_used_at, use_count"; /// One row of the `links` table. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub struct Link { /// Link id (a lower-case ULID). It names the unlock cookie. pub id: String, @@ -53,6 +56,26 @@ pub struct Link { pub use_count: i64, } +impl fmt::Debug for Link { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Link") + .field("id", &self.id) + .field("token_hash", &self.token_hash) + .field("token_sealed", &Redacted) + .field("kind", &self.kind) + .field("target_id", &self.target_id) + .field("owner", &self.owner) + .field("can_download", &self.can_download) + .field("password_hash", &self.password_hash) + .field("expires_at", &self.expires_at) + .field("revoked_at", &self.revoked_at) + .field("created_at", &self.created_at) + .field("last_used_at", &self.last_used_at) + .field("use_count", &self.use_count) + .finish() + } +} + impl Link { /// Whether the link still works at `now` (a stamp of this format): not revoked and not expired. /// The target's own trash state is checked separately. @@ -62,7 +85,7 @@ impl Link { } /// What a new link needs. The token is generated and sealed by the caller. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub struct NewLink { /// Id, made by the caller so it is known before the insert. pub id: String, @@ -84,6 +107,22 @@ pub struct NewLink { pub expires_at: Option, } +impl fmt::Debug for NewLink { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("NewLink") + .field("id", &self.id) + .field("token_hash", &self.token_hash) + .field("token_sealed", &Redacted) + .field("kind", &self.kind) + .field("target_id", &self.target_id) + .field("owner", &self.owner) + .field("can_download", &self.can_download) + .field("password_hash", &self.password_hash) + .field("expires_at", &self.expires_at) + .finish() + } +} + /// Maps a row selected with [`LINK_COLS`]. fn map_link(row: &Row) -> Result { let kind = kind_from_word(&col_text(row, 3)?) diff --git a/crates/in-core/src/store/mod.rs b/crates/in-core/src/store/mod.rs index 38e38ad..4db364d 100644 --- a/crates/in-core/src/store/mod.rs +++ b/crates/in-core/src/store/mod.rs @@ -64,6 +64,7 @@ impl Store { let path_str = path.to_str().ok_or_else(|| { Error::Config(format!("database path is not UTF-8: {}", path.display())) })?; + create_private_files(path)?; let db = Builder::new_local(path_str).build().await.map_err(db_err)?; let conn = db.connect().map_err(db_err)?; apply_pragmas(&conn).await; @@ -102,6 +103,34 @@ impl Store { } } +/// Creates `path` with mode 0600, failing if it exists (a symlink counts). The umask does not decide who +/// can read a database this way. +pub(crate) fn create_private_file(path: &Path) -> std::io::Result<()> { + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + options.open(path).map(drop) +} + +/// Creates the database file and its `-wal` and `-shm` sidecars with mode 0600 when they are missing. A file +/// that exists is left as it is. +pub(crate) fn create_private_files(path: &Path) -> Result<()> { + for suffix in ["", "-wal", "-shm"] { + let mut name = path.as_os_str().to_owned(); + name.push(suffix); + match create_private_file(Path::new(&name)) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(e) => return Err(e.into()), + } + } + Ok(()) +} + /// Sets the pragmas every connection needs. A pragma that fails is logged, not fatal, and the values /// in effect are read back and logged so a silent failure is visible at boot. async fn apply_pragmas(conn: &Connection) { diff --git a/crates/in-core/src/store/sessions.rs b/crates/in-core/src/store/sessions.rs index 4e5ffb3..044f0a6 100644 --- a/crates/in-core/src/store/sessions.rs +++ b/crates/in-core/src/store/sessions.rs @@ -4,7 +4,10 @@ //! sessions of disabled people are never returned by [`Store::session_by_token_hash`], so a session //! stops working the moment it expires, even before the sweeper removes it. +use std::fmt; + use crate::error::Result; +use crate::secret::Redacted; use crate::store::{Store, col_opt_text, col_text, db_err, fetch_opt, new_id}; use crate::time::now_stamp; @@ -13,7 +16,7 @@ pub const SESSION_COLS: &str = "id, sub, token_hash, csrf_token, im_sid, created last_seen_at, ip, user_agent, id_token_sealed"; /// One row of the `sessions` table. The token itself is not in here. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub struct Session { /// Session id (a ULID). pub id: String, @@ -40,8 +43,26 @@ pub struct Session { pub id_token_sealed: Option, } +impl fmt::Debug for Session { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Session") + .field("id", &self.id) + .field("sub", &self.sub) + .field("token_hash", &self.token_hash) + .field("csrf_token", &Redacted) + .field("im_sid", &self.im_sid) + .field("created_at", &self.created_at) + .field("expires_at", &self.expires_at) + .field("last_seen_at", &self.last_seen_at) + .field("ip", &self.ip) + .field("user_agent", &self.user_agent) + .field("id_token_sealed", &self.id_token_sealed) + .finish() + } +} + /// What a new session needs. The id and timestamps are made by the store. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub struct NewSession { /// The person. pub sub: String, @@ -61,6 +82,21 @@ pub struct NewSession { pub id_token_sealed: Option, } +impl fmt::Debug for NewSession { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("NewSession") + .field("sub", &self.sub) + .field("token_hash", &self.token_hash) + .field("csrf_token", &Redacted) + .field("im_sid", &self.im_sid) + .field("expires_at", &self.expires_at) + .field("ip", &self.ip) + .field("user_agent", &self.user_agent) + .field("id_token_sealed", &self.id_token_sealed) + .finish() + } +} + /// Maps a row selected with [`SESSION_COLS`]. pub fn map_session(row: &turso::Row) -> Result { Ok(Session { diff --git a/crates/in-core/src/store/snapshot.rs b/crates/in-core/src/store/snapshot.rs index ec07764..8d0362d 100644 --- a/crates/in-core/src/store/snapshot.rs +++ b/crates/in-core/src/store/snapshot.rs @@ -2,12 +2,13 @@ //! so no write can interleave with it. A WAL-mode copy keeps its rows in a sidecar file, so the copy is //! then checkpointed until it is one self-contained file. +use std::os::unix::fs::PermissionsExt; use std::path::Path; use turso::Builder; use crate::error::{Error, Result}; -use crate::store::{Store, col_int, db_err, fetch_all}; +use crate::store::{Store, col_int, create_private_files, db_err, fetch_all}; impl Store { /// Writes a consistent copy of the database to `dest`, then fsyncs it. `dest` must not exist. @@ -26,6 +27,9 @@ impl Store { let conn = self.inner.conn.lock().await; conn.execute(&sql, ()).await.map_err(db_err)?; } + // VACUUM INTO creates the file with the umask's mode, so it is narrowed to 0600 before anything else + // opens it. The engine refuses an existing target, so the file cannot be made private first. + std::fs::set_permissions(dest, std::fs::Permissions::from_mode(0o600))?; make_self_contained(dest).await?; std::fs::File::open(dest)?.sync_all()?; Ok(()) @@ -48,6 +52,7 @@ async fn make_self_contained(dest: &Path) -> Result<()> { let text = dest .to_str() .ok_or_else(|| Error::Config(format!("snapshot path is not UTF-8: {}", dest.display())))?; + create_private_files(dest)?; let db = Builder::new_local(text).build().await.map_err(db_err)?; let conn = db.connect().map_err(db_err)?; // Columns: busy flag, frames in the log, frames checkpointed. diff --git a/crates/in-web/src/boot.rs b/crates/in-web/src/boot.rs index 1006deb..00e78d8 100644 --- a/crates/in-web/src/boot.rs +++ b/crates/in-web/src/boot.rs @@ -13,7 +13,7 @@ use std::sync::Arc; use in_core::blob::BlobStore; use in_core::blob::local::LocalBlobs; use in_core::blob::s3::{S3Blobs, S3Settings}; -use in_core::config::{Backend, Config, S3}; +use in_core::config::{Backend, Config, S3, parse_endpoint}; use in_core::error::{Error, Result}; use in_core::secret; use in_core::store::Store; @@ -103,6 +103,7 @@ pub async fn open_offline(config_path: &Path) -> Result { pub async fn serve(config_path: &Path) -> Result<()> { let config = Config::load(config_path)?; let listen = config.listen; + warn_about_setup(&config); // Held until the server stops: an operator command started now refuses instead of racing the server. let _lock = lock_data_dir(&config.data_dir)?; let state = open_state(config).await?; @@ -145,6 +146,28 @@ pub async fn serve(config_path: &Path) -> Result<()> { Ok(()) } +/// Logs the settings that are legal but usually a mistake. Each one is a warning, never a refusal, because +/// a local development setup has good reasons to leave them out. +fn warn_about_setup(config: &Config) { + if listen_is_loopback(config) && config.trusted_proxies.is_empty() { + tracing::warn!( + listen = %config.listen, + "listen is a loopback address and trusted_proxies is empty: behind a proxy on this host, every client shares its address for the rate limits" + ); + } + if config.backup.is_none() { + tracing::warn!("[backup] is not configured: there are no scheduled backups"); + } + if config.oidc.is_none() { + tracing::warn!("[oidc] is not configured: sign-in is disabled"); + } +} + +/// Whether the listener is bound to a loopback address only. +fn listen_is_loopback(config: &Config) -> bool { + config.listen.ip().is_loopback() +} + /// Creates the data directory and opens the key, the database and the blob store. Everything the /// router needs that touches the disk is ready when this returns. async fn open_state(config: Config) -> Result { @@ -159,6 +182,19 @@ async fn open_state(config: Config) -> Result { { std::fs::create_dir_all(parent)?; } + let database_dir = std::fs::canonicalize( + config + .database + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")), + )?; + if !database_dir.starts_with(&data_dir) { + tracing::warn!( + database = %config.database.display(), + "database is outside data_dir: restore will not replace it, and the data-directory lock does not cover it" + ); + } let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; let store = Store::open(&config.database).await?; let blobs = open_blobs(&config, &data_dir)?; @@ -205,15 +241,15 @@ pub fn open_blobs(config: &Config, data_dir: &Path) -> Result } /// Turns the `[storage.s3]` table and its credential files into the client settings. Without an -/// endpoint the AWS endpoint of the region is used. Plain http is allowed only when the configured -/// endpoint says so. +/// endpoint the AWS endpoint of the region is used. Plain http is allowed only for a loopback endpoint. fn s3_settings(s3: &S3) -> Result { let endpoint = s3 .endpoint .clone() .unwrap_or_else(|| format!("https://s3.{}.amazonaws.com", s3.region)); + let allow_http = parse_endpoint(&endpoint).is_some_and(|url| url.scheme() == "http"); Ok(S3Settings { - allow_http: endpoint.starts_with("http://"), + allow_http, endpoint, region: s3.region.clone(), bucket: s3.bucket.clone(), @@ -222,10 +258,12 @@ fn s3_settings(s3: &S3) -> Result { }) } -/// Reads a credential file and drops the trailing newline. An empty file is a configuration error. +/// Reads a credential file and drops the trailing newline. An empty file is a configuration error, and so +/// is a file that group or world can read. fn read_secret(path: &Path) -> Result { let text = std::fs::read_to_string(path) .map_err(|e| Error::Config(format!("cannot read {}: {e}", path.display())))?; + secret::check_private(path)?; let value = text.trim().to_owned(); if value.is_empty() { return Err(Error::Config(format!("{} is empty", path.display()))); diff --git a/crates/in-web/src/directory.rs b/crates/in-web/src/directory.rs index 2310f35..fb3d6f2 100644 --- a/crates/in-web/src/directory.rs +++ b/crates/in-web/src/directory.rs @@ -261,13 +261,13 @@ async fn full_sync(state: &AppState, oidc: &OidcClient) -> Result<(), SyncError> .header(ACCEPT, "application/json") .send() .await - .map_err(|e| SyncError::Transport(e.to_string()))?; + .map_err(|e| SyncError::Transport(e.without_url().to_string()))?; if !response.status().is_success() { return Err(SyncError::Status(response.status())); } let bytes = read_limited(response, ROSTER_MAX_BYTES) .await - .map_err(|e| SyncError::Transport(e.to_string()))? + .map_err(|e| SyncError::Transport(e.without_url().to_string()))? .ok_or(SyncError::TooLarge)?; let listing: Listing = serde_json::from_slice(&bytes).map_err(|_| SyncError::Listing)?; @@ -308,7 +308,7 @@ async fn follow( let response = request .send() .await - .map_err(|e| SyncError::Transport(e.to_string()))?; + .map_err(|e| SyncError::Transport(e.without_url().to_string()))?; if !response.status().is_success() { return Err(SyncError::Status(response.status())); } @@ -326,7 +326,7 @@ async fn follow( let Some(chunk) = chunk else { return Ok(closed(opened, applied)); }; - let chunk = chunk.map_err(|e| SyncError::Transport(e.to_string()))?; + let chunk = chunk.map_err(|e| SyncError::Transport(e.without_url().to_string()))?; for event in parser.push(&chunk)? { applied = true; if let Some(ended) = apply_event(state, event).await? { diff --git a/crates/in-web/src/family.rs b/crates/in-web/src/family.rs index 0093f9a..99cd257 100644 --- a/crates/in-web/src/family.rs +++ b/crates/in-web/src/family.rs @@ -3,13 +3,15 @@ //! //! A worker fetches `GET {issuer}/api/v1/family` every five minutes with a client-credentials token for //! `im` (the token is cached by the OIDC client). A failed fetch keeps the last good list, because the list -//! changes rarely and a stale switcher is harmless. Only links a browser may follow are kept: http or https -//! URLs with no whitespace or control characters, and never this service's own key. The shell escapes every -//! field when it renders, so a hostile name cannot break the page. +//! changes rarely and a stale switcher is harmless. Only links a browser may follow are kept: https URLs, or +//! http URLs for a loopback host (see `parse_endpoint`), with no whitespace or control characters, and never +//! this service's own key. The shell escapes every field when it renders, so a hostile name cannot break the +//! page. use std::sync::{PoisonError, RwLock}; use std::time::Duration; +use in_core::config::parse_endpoint; use serde::Deserialize; use tokio::sync::watch; @@ -66,12 +68,11 @@ impl FamilyCache { } } -/// Whether a switcher link may be shown: an absolute http or https URL with no whitespace or control -/// characters, and not this service itself. +/// Whether a switcher link may be shown: an absolute URL that [`parse_endpoint`] accepts, with no whitespace +/// or control characters, and not this service itself. pub fn usable(link: &FamilyLink) -> bool { let url = link.url.as_str(); - let scheme_ok = url.starts_with("https://") || url.starts_with("http://"); - scheme_ok + parse_endpoint(url).is_some() && !url.chars().any(|c| c.is_whitespace() || c.is_control()) && link.key != SELF_KEY && !link.key.is_empty() diff --git a/crates/in-web/src/oidc.rs b/crates/in-web/src/oidc.rs index f94c559..a7db72d 100644 --- a/crates/in-web/src/oidc.rs +++ b/crates/in-web/src/oidc.rs @@ -48,6 +48,9 @@ pub const HTTP_TIMEOUT: Duration = Duration::from_secs(10); /// keep-alive every 30 seconds (contracts section 3.2), so three of them missed means it is dead. const STREAM_READ_TIMEOUT: Duration = Duration::from_secs(90); +/// The largest JSON answer read from `im`: discovery, the key set and token answers are far smaller. +const MAX_DOCUMENT_BYTES: usize = 1024 * 1024; + /// A service token is refreshed this long before its stated end (contracts section 2.6). const SERVICE_TOKEN_MARGIN: Duration = Duration::from_secs(60); @@ -554,6 +557,19 @@ pub async fn read_limited( Ok(Some(body)) } +/// Reads the body of a JSON answer from `im`, at most [`MAX_DOCUMENT_BYTES`]. A larger body is unavailable, +/// and a read error is reported without the URL. +async fn read_document(response: reqwest::Response) -> Result, OidcError> { + read_limited(response, MAX_DOCUMENT_BYTES) + .await + .map_err(|e| OidcError::Unavailable(e.without_url().to_string()))? + .ok_or_else(|| { + OidcError::Unavailable(format!( + "an answer is larger than {MAX_DOCUMENT_BYTES} bytes" + )) + }) +} + /// Percent-encodes one value for a query, a form body or a Basic credential (RFC 6749 section 2.3.1): /// unreserved characters pass, everything else becomes `%XX`. pub fn percent_encode(value: &str) -> String { @@ -744,17 +760,14 @@ impl OidcClient { .get(url) .send() .await - .map_err(|e| OidcError::Unavailable(e.to_string()))?; + .map_err(|e| OidcError::Unavailable(e.without_url().to_string()))?; if !response.status().is_success() { return Err(OidcError::Unavailable(format!( "{url} answered {}", response.status() ))); } - let bytes = response - .bytes() - .await - .map_err(|e| OidcError::Unavailable(e.to_string()))?; + let bytes = read_document(response).await?; serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string())) } @@ -959,7 +972,7 @@ impl OidcClient { .form(form) .send() .await - .map_err(|e| OidcError::Unavailable(e.to_string()))?; + .map_err(|e| OidcError::Unavailable(e.without_url().to_string()))?; let status = response.status(); if status.is_client_error() { tracing::warn!(status = %status, "oidc: the token endpoint refused the request"); @@ -970,10 +983,7 @@ impl OidcClient { "token endpoint answered {status}" ))); } - let bytes = response - .bytes() - .await - .map_err(|e| OidcError::Unavailable(e.to_string()))?; + let bytes = read_document(response).await?; serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string())) } } diff --git a/crates/in-web/src/pages/backchannel.rs b/crates/in-web/src/pages/backchannel.rs index 7d2f4cd..b48b9ae 100644 --- a/crates/in-web/src/pages/backchannel.rs +++ b/crates/in-web/src/pages/backchannel.rs @@ -11,9 +11,11 @@ use http::header::CONTENT_TYPE; use http::{HeaderMap, HeaderValue}; use in_core::error::Result as CoreResult; +use in_core::secret::Redacted; use in_core::store::Store; use in_core::time::stamp_after; use serde::Deserialize; +use std::fmt; use std::time::Duration; use topcoat::Result; use topcoat::context::{Cx, app_context}; @@ -35,12 +37,20 @@ pub const REPLAY_WINDOW: Duration = Duration::from_secs(10 * 60); pub type Answer = (StatusCode, HeaderMap, String); /// The form body of a delivery: the one field `im` sends. -#[derive(Debug, Default, Deserialize)] +#[derive(Default, Deserialize)] #[serde(default)] struct LogoutTokenForm { logout_token: String, } +impl fmt::Debug for LogoutTokenForm { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("LogoutTokenForm") + .field("logout_token", &Redacted) + .finish() + } +} + /// What ending the sessions for one token did. #[derive(Debug, PartialEq, Eq)] pub enum Outcome { diff --git a/crates/in-web/src/pages/links.rs b/crates/in-web/src/pages/links.rs index 4c18d63..51a3eb9 100644 --- a/crates/in-web/src/pages/links.rs +++ b/crates/in-web/src/pages/links.rs @@ -6,6 +6,7 @@ //! argon2id on the blocking pool and is never shown again. Revoking and reminting need the owner; anything //! else is `404`. +use std::fmt; use std::time::Duration; use in_core::error::Error as CoreError; @@ -183,7 +184,7 @@ async fn links_page(cx: &Cx) -> Result { /// The form of link writes: the CSRF token, the return page, and for a creation the item, the expiry in /// days (blank for the maximum), an optional password and the download flag. -#[derive(Debug, Default, Deserialize)] +#[derive(Default, Deserialize)] #[serde(default)] pub struct LinkForm { /// The CSRF token of the session. @@ -202,6 +203,20 @@ pub struct LinkForm { pub download: String, } +impl fmt::Debug for LinkForm { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("LinkForm") + .field("csrf", &self.csrf) + .field("back", &self.back) + .field("kind", &self.kind) + .field("target_id", &self.target_id) + .field("days", &self.days) + .field("password", &secret::Redacted) + .field("download", &self.download) + .finish() + } +} + /// Makes a fresh token and its sealed copy: `(token hash, sealed token, token)`. fn new_token(state: &AppState) -> Result<(String, String, String)> { let token = generate_token(); diff --git a/crates/in-web/src/pages/photo.rs b/crates/in-web/src/pages/photo.rs index 787ac96..d2598cf 100644 --- a/crates/in-web/src/pages/photo.rs +++ b/crates/in-web/src/pages/photo.rs @@ -12,6 +12,7 @@ use std::path::{Path, PathBuf}; use http::header::{CONTENT_TYPE, ETAG, IF_NONE_MATCH}; use http::{HeaderMap, HeaderValue}; +use tokio::io::AsyncWriteExt; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::error::{not_found, service_unavailable}; @@ -80,7 +81,11 @@ async fn write_cache(photo_dir: &Path, sub: &str, version: i64, content_type: &s return; }; let written = async { - tokio::fs::create_dir_all(dir).await?; + tokio::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(dir) + .await?; write_atomically(&type_path, content_type.as_bytes()).await?; write_atomically(&bytes_path, bytes).await } @@ -92,9 +97,16 @@ async fn write_cache(photo_dir: &Path, sub: &str, version: i64, content_type: &s /// Writes `bytes` to `path` through a temporary file and a rename. The temporary name carries a fresh /// ULID, so two writers of the same photo never share one, and a rename never publishes a mix of two. +/// The file is created with mode 0600. async fn write_atomically(path: &Path, bytes: &[u8]) -> std::io::Result<()> { let temporary = PathBuf::from(format!("{}.{}.tmp", path.display(), ulid::Ulid::generate())); - tokio::fs::write(&temporary, bytes).await?; + let mut file = tokio::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&temporary) + .await?; + file.write_all(bytes).await?; tokio::fs::rename(&temporary, path).await } @@ -116,7 +128,7 @@ async fn fetch_photo( let response = match oidc.http().get(url).bearer_auth(token).send().await { Ok(response) => response, Err(error) => { - tracing::warn!(error = %error, "photo: im could not be reached"); + tracing::warn!(error = %error.without_url(), "photo: im could not be reached"); return Err(unavailable()); } }; @@ -150,7 +162,7 @@ async fn fetch_photo( Ok(Some(bytes)) => bytes, Ok(None) => return Ok(None), Err(error) => { - tracing::warn!(error = %error, "photo: the body could not be read"); + tracing::warn!(error = %error.without_url(), "photo: the body could not be read"); return Err(unavailable()); } }; diff --git a/crates/in-web/src/pages/public_share.rs b/crates/in-web/src/pages/public_share.rs index 1c53bd8..0f2abf2 100644 --- a/crates/in-web/src/pages/public_share.rs +++ b/crates/in-web/src/pages/public_share.rs @@ -14,11 +14,13 @@ //! No session is read here and no member's details are shown. The pages send `Referrer-Policy: no-referrer` //! and `X-Robots-Tag: noindex` (set in `security.rs`), and `Cache-Control: no-store`. +use std::fmt; + use http::HeaderValue; use http::header::CACHE_CONTROL; use in_core::authz::{Action, Actor, Grant, Target, authorize}; use in_core::password::verify_password_async; -use in_core::secret::unlock_proof; +use in_core::secret::{Redacted, unlock_proof}; use in_core::store::files::File; use in_core::store::files::thumb_blob_key; use in_core::store::folders::{Folder, Listing}; @@ -165,7 +167,7 @@ pub struct PublicQuery { } /// The form of the password gate. -#[derive(Debug, Default, Deserialize)] +#[derive(Default, Deserialize)] #[serde(default)] pub struct GateForm { /// The CSRF token that the gate cookie must match. @@ -174,6 +176,15 @@ pub struct GateForm { pub password: String, } +impl fmt::Debug for GateForm { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("GateForm") + .field("csrf", &self.csrf) + .field("password", &Redacted) + .finish() + } +} + /// A folder listing inside a folder link: its breadcrumbs, its current folder, and what it holds. pub struct FolderPanel { /// The folders from the link's root down to the current one. diff --git a/crates/in-web/src/pages/sign_in.rs b/crates/in-web/src/pages/sign_in.rs index d18840b..012828c 100644 --- a/crates/in-web/src/pages/sign_in.rs +++ b/crates/in-web/src/pages/sign_in.rs @@ -6,6 +6,7 @@ //! on every outcome, so it is single use. After the callback the local session is created (section 2.4). //! Failures redirect to the problem page with a fixed reason word; no text from the request is reflected. +use std::fmt; use std::sync::Arc; use std::time::Duration; @@ -54,7 +55,7 @@ struct LoginQuery { } /// The query of `/auth/callback`, as `im` sends it. Only the fields `in` reads are named. -#[derive(Debug, Default, Deserialize)] +#[derive(Default, Deserialize)] #[serde(default)] struct CallbackQuery { code: String, @@ -62,15 +63,33 @@ struct CallbackQuery { error: String, } +impl fmt::Debug for CallbackQuery { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("CallbackQuery") + .field("code", &secret::Redacted) + .field("state", &secret::Redacted) + .field("error", &self.error) + .finish() + } +} + /// The form of `/auth/logout`: the CSRF token of the session. -#[derive(Debug, Default, Deserialize)] +#[derive(Default, Deserialize)] #[serde(default)] struct LogoutForm { csrf: String, } +impl fmt::Debug for LogoutForm { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("LogoutForm") + .field("csrf", &secret::Redacted) + .finish() + } +} + /// The sealed content of the flight cookie. -#[derive(Debug, Serialize, Deserialize)] +#[derive(Serialize, Deserialize)] struct Flight { state: String, nonce: String, @@ -80,6 +99,18 @@ struct Flight { expires_at: i64, } +impl fmt::Debug for Flight { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Flight") + .field("state", &secret::Redacted) + .field("nonce", &secret::Redacted) + .field("verifier", &secret::Redacted) + .field("next", &self.next) + .field("expires_at", &self.expires_at) + .finish() + } +} + /// Redirects to the problem page with one of the fixed reason words. fn problem(reason: &str) -> SeeOther { see_other(format!("/sign-in/problem?reason={reason}")) diff --git a/crates/in-web/src/serve_bytes.rs b/crates/in-web/src/serve_bytes.rs index 5b8a4f1..b2e2ab3 100644 --- a/crates/in-web/src/serve_bytes.rs +++ b/crates/in-web/src/serve_bytes.rs @@ -56,7 +56,8 @@ pub struct ByteSource<'a> { /// is checked against it while it streams (see [`check_digest`]). `None` for derived bytes such as /// thumbnails, whose validator is not the hash of what is stored. pub content_sha256: Option<&'a str>, - /// The sniffed MIME type, as stored. It is never the uploader's claim. + /// The MIME type, as stored. For a file uploaded through the drive it is the sniffed type, never the + /// uploader's claim. For the objects API it is the calling service's claim, which is not sniffed. pub mime: &'a str, /// The display name, used for the `Content-Disposition` file name. pub name: &'a str, diff --git a/docs/architecture.md b/docs/architecture.md index 6e9d719..e0428e1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -163,8 +163,9 @@ The sweeper removes unreferenced blobs older than 24 h. Per contracts.md 2: `/auth/login?next=` builds the flight cookie and redirects to `im`; `/auth/callback` validates state, exchanges the code (client_secret_basic), validates the ID token, upserts the member from its claims (so a person can use `in` before the directory stream catches up), creates a local session (12 h), and -redirects to `next`. The client secret is read from `data_dir/oidc_client_secret` (0600) or the -`IN_OIDC_CLIENT_SECRET` environment variable, never from the TOML. A member with `disabled` set cannot sign in +redirects to `next`. The client secret is read from the file named by `client_secret_file` (0600), never +from the TOML. A secret file, and every S3 credential file, +that group or world can read is refused at boot (`secret::check_private`). A member with `disabled` set cannot sign in and has no sessions. --- @@ -270,7 +271,7 @@ credentials (S3 secret sealed) are Restart settings. A bare `in` (or `in serve`) runs the server. Backups are written by the server's backup worker. `in restore --from SET` replaces the database with a verified set (server stopped; needs the same `in.key`). -`in export --member --out DIR` writes a plain tree with real names. `in fsck [--hash] [--quarantine]` +`in export --member --out DIR` writes a plain tree with real names (folders 0700, files 0600). `in fsck [--hash] [--quarantine]` checks that every row has its blob and every blob has a row (sizes, and hashes with `--hash`); it changes nothing, except that `--quarantine` moves orphan blobs over an hour old into `data_dir/quarantine/` (never deletes). `in quota recompute` recomputes used bytes.