🛡️ ops: loopback-only http, private files from creation, secret file modes, redacted Debug, bounded IdP answers, pinned argon2
Browse files at this commit63140595ff8ff2ac45176dc6310177eadd320e9eParent: b5e729025 changed files +433 -73
- Cargo.lock +1 -0
- Cargo.toml +1 -0
- README.md +6 -3
- config/in.example.toml +8 -4
- crates/in-core/Cargo.toml +1 -0
- crates/in-core/src/backup.rs +16 -2
- crates/in-core/src/config.rs +66 -5
- crates/in-core/src/export.rs +9 -3
- crates/in-core/src/password.rs +18 -6
- crates/in-core/src/secret.rs +22 -4
- crates/in-core/src/store/links.rs +41 -2
- crates/in-core/src/store/mod.rs +29 -0
- crates/in-core/src/store/sessions.rs +38 -2
- crates/in-core/src/store/snapshot.rs +6 -1
- crates/in-web/src/boot.rs +43 -5
- crates/in-web/src/directory.rs +4 -4
- crates/in-web/src/family.rs +8 -7
- crates/in-web/src/oidc.rs +20 -10
- crates/in-web/src/pages/backchannel.rs +11 -1
- crates/in-web/src/pages/links.rs +16 -1
- crates/in-web/src/pages/photo.rs +16 -4
- crates/in-web/src/pages/public_share.rs +13 -2
- crates/in-web/src/pages/sign_in.rs +34 -3
- crates/in-web/src/serve_bytes.rs +2 -1
- docs/architecture.md +4 -3
Cargo.lockmodified+1 -0
| @@ -1739,6 +1739,7 @@ dependencies = [ | |||
| 1739 | "turso", | 1739 | "turso", |
| 1740 | "ulid", | 1740 | "ulid", |
| 1741 | "unicode-normalization", | 1741 | "unicode-normalization", |
| 1742 | + "url", | ||
| 1742 | ] | 1743 | ] |
| 1743 | 1744 | ||
| 1744 | [[package]] | 1745 | [[package]] |
Cargo.tomlmodified+1 -0
| @@ -79,4 +79,5 @@ tracing-subscriber = "0.3.23" | |||
| 79 | turso = { version = "0.8.3", default-features = false, features = ["mimalloc"] } | 79 | turso = { version = "0.8.3", default-features = false, features = ["mimalloc"] } |
| 80 | ulid = "3.0.0" | 80 | ulid = "3.0.0" |
| 81 | unicode-normalization = "0.1.26" | 81 | unicode-normalization = "0.1.26" |
| 82 | +url = "2.5.8" | ||
| 82 | 83 | ||
README.mdmodified+6 -3
| @@ -38,19 +38,22 @@ Do not enable the unit until the configuration and the `im` client below are in | |||
| 38 | `config/in.example.toml` on first run. Unknown keys are an error, so a typo fails at start-up. | 38 | `config/in.example.toml` on first run. Unknown keys are an error, so a typo fails at start-up. |
| 39 | 39 | ||
| 40 | The file holds no secrets. The OIDC client secret and the S3 keys are read from files that only the service | 40 | The file holds no secrets. The OIDC client secret and the S3 keys are read from files that only the service |
| 41 | -user can read: | 41 | +user can read; `in` refuses a secret file that group or world can read: |
| 42 | 42 | ||
| 43 | | Key | Meaning | | 43 | | Key | Meaning | |
| 44 | |---|---| | 44 | |---|---| |
| 45 | -| `database`, `data_dir` | Database file and data directory (blobs, staging, `in.key`, `in.lock`). The data directory is created with mode 0700. | | 45 | +| `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. | |
| 46 | | `listen` | Address to bind. Keep it on loopback and put the reverse proxy in front. | | 46 | | `listen` | Address to bind. Keep it on loopback and put the reverse proxy in front. | |
| 47 | -| `base_url` | Public origin with no trailing slash. An `https` origin turns on `Secure` cookies and HSTS. | | 47 | +| `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. | |
| 48 | | `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. | | 48 | | `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. | |
| 49 | | `[oidc]` | `issuer` (the `im` origin), `client_id` (the id `im` printed for this client), `client_secret_file`. | | 49 | | `[oidc]` | `issuer` (the `im` origin), `client_id` (the id `im` printed for this client), `client_secret_file`. | |
| 50 | | `[storage]` | `backend = "local"` (default) or `"s3"` with `[storage.s3]`. | | 50 | | `[storage]` | `backend = "local"` (default) or `"s3"` with `[storage.s3]`. | |
| 51 | | `[backup]` | Optional. `dir`, `interval_hours`, `keep`, `healthcheck_url`. See *Backups*. | | 51 | | `[backup]` | Optional. `dir`, `interval_hours`, `keep`, `healthcheck_url`. See *Backups*. | |
| 52 | | `[limits]` | Optional defaults the admin page may override: quotas, purge days, upload size, link length. | | 52 | | `[limits]` | Optional defaults the admin page may override: quotas, purge days, upload size, link length. | |
| 53 | 53 | ||
| 54 | +At start-up `in` logs a warning when `listen` is a loopback address with no `trusted_proxies`, when `[backup]` or | ||
| 55 | +`[oidc]` is not configured, and when `database` is outside `data_dir`. None of them stops the server. | ||
| 56 | + | ||
| 54 | The admin page at `/admin` shows, next to each runtime value, whether it was set there, comes from the file, or | 57 | The admin page at `/admin` shows, next to each runtime value, whether it was set there, comes from the file, or |
| 55 | is the built-in default. A blank field on that page removes the page's value again. | 58 | is the built-in default. A blank field on that page removes the page's value again. |
| 56 | 59 | ||
config/in.example.tomlmodified+8 -4
| @@ -2,20 +2,23 @@ | |||
| 2 | # Secrets are never written here. The OIDC client secret and the S3 keys are read from files or | 2 | # Secrets are never written here. The OIDC client secret and the S3 keys are read from files or |
| 3 | # entered in the admin UI. | 3 | # entered in the admin UI. |
| 4 | 4 | ||
| 5 | -# Database file (Turso). Relative paths are relative to the working directory. | 5 | +# Database file (Turso). Relative paths are relative to the working directory. Created with mode 0600, and |
| 6 | +# outside data_dir the data-directory lock and restore do not cover it. | ||
| 6 | database = "data/in.db" | 7 | database = "data/in.db" |
| 7 | # Directory for blobs, staging files, the instance key (in.key) and caches. Created with mode 0700. | 8 | # Directory for blobs, staging files, the instance key (in.key) and caches. Created with mode 0700. |
| 8 | data_dir = "data" | 9 | data_dir = "data" |
| 9 | # Address the HTTP server binds to. Put a TLS reverse proxy in front of it for public use. | 10 | # Address the HTTP server binds to. Put a TLS reverse proxy in front of it for public use. |
| 10 | listen = "127.0.0.1:7655" | 11 | listen = "127.0.0.1:7655" |
| 11 | -# Public URL of this instance, with no trailing slash. An https URL turns on Secure cookies and HSTS. | 12 | +# Public URL of this instance, with no trailing slash. An https URL turns on Secure cookies and HSTS. Plain |
| 13 | +# http is accepted only for a loopback host (localhost, 127.0.0.0/8, ::1). | ||
| 12 | base_url = "http://127.0.0.1:7655" | 14 | base_url = "http://127.0.0.1:7655" |
| 13 | # Proxies whose X-Forwarded-For header is believed for client addresses. CIDR ranges or bare addresses. | 15 | # Proxies whose X-Forwarded-For header is believed for client addresses. CIDR ranges or bare addresses. |
| 14 | # Behind Ferron on the same host, set ["127.0.0.1/32"]; left empty there, every visitor counts as 127.0.0.1. | 16 | # Behind Ferron on the same host, set ["127.0.0.1/32"]; left empty there, every visitor counts as 127.0.0.1. |
| 15 | trusted_proxies = [] | 17 | trusted_proxies = [] |
| 16 | 18 | ||
| 17 | # Sign-in through im (OpenID Connect). Point issuer at the im instance you run (its origin, no | 19 | # Sign-in through im (OpenID Connect). Point issuer at the im instance you run (its origin, no |
| 18 | -# trailing slash). The client secret is read from client_secret_file at boot; it is never in this file. | 20 | +# trailing slash; http only for a loopback host). The client secret is read from client_secret_file at |
| 21 | +# boot; it is never in this file, and the file must not be readable by group or world (mode 0600). | ||
| 19 | [oidc] | 22 | [oidc] |
| 20 | issuer = "http://127.0.0.1:7650" | 23 | issuer = "http://127.0.0.1:7650" |
| 21 | client_id = "in" | 24 | client_id = "in" |
| @@ -24,7 +27,8 @@ client_secret_file = "data/oidc_client_secret" | |||
| 24 | [storage] | 27 | [storage] |
| 25 | backend = "local" | 28 | backend = "local" |
| 26 | 29 | ||
| 27 | -# To store blobs in an S3-compatible bucket instead, use backend = "s3" and this table: | 30 | +# To store blobs in an S3-compatible bucket instead, use backend = "s3" and this table. The credential files |
| 31 | +# must not be readable by group or world (mode 0600); the endpoint follows the same rules as base_url. | ||
| 28 | # [storage.s3] | 32 | # [storage.s3] |
| 29 | # endpoint = "https://<account>.r2.cloudflarestorage.com" # omit for AWS | 33 | # endpoint = "https://<account>.r2.cloudflarestorage.com" # omit for AWS |
| 30 | # region = "auto" | 34 | # region = "auto" |
crates/in-core/Cargo.tomlmodified+1 -0
| @@ -31,6 +31,7 @@ tracing.workspace = true | |||
| 31 | turso.workspace = true | 31 | turso.workspace = true |
| 32 | ulid.workspace = true | 32 | ulid.workspace = true |
| 33 | unicode-normalization.workspace = true | 33 | unicode-normalization.workspace = true |
| 34 | +url.workspace = true | ||
| 34 | 35 | ||
| 35 | [dev-dependencies] | 36 | [dev-dependencies] |
| 36 | tempfile.workspace = true | 37 | tempfile.workspace = true |
crates/in-core/src/backup.rsmodified+16 -2
| @@ -192,6 +192,19 @@ fn write_private(path: &Path, bytes: &[u8]) -> Result<()> { | |||
| 192 | Ok(()) | 192 | Ok(()) |
| 193 | } | 193 | } |
| 194 | 194 | ||
| 195 | +/// Copies `from` to `to`, which must not exist, with mode 0600. A restored database is never readable by | ||
| 196 | +/// others, scratch copies included. | ||
| 197 | +fn copy_private(from: &Path, to: &Path) -> Result<()> { | ||
| 198 | + let mut out = OpenOptions::new() | ||
| 199 | + .write(true) | ||
| 200 | + .create_new(true) | ||
| 201 | + .mode(0o600) | ||
| 202 | + .open(to)?; | ||
| 203 | + std::io::copy(&mut std::fs::File::open(from)?, &mut out)?; | ||
| 204 | + out.sync_all()?; | ||
| 205 | + Ok(()) | ||
| 206 | +} | ||
| 207 | + | ||
| 195 | /// Size and SHA-256 of a file, read in chunks. | 208 | /// Size and SHA-256 of a file, read in chunks. |
| 196 | fn file_digest(path: &Path) -> Result<(u64, String)> { | 209 | fn file_digest(path: &Path) -> Result<(u64, String)> { |
| 197 | let mut file = std::fs::File::open(path)?; | 210 | let mut file = std::fs::File::open(path)?; |
| @@ -297,7 +310,8 @@ pub async fn restore( | |||
| 297 | let scratch_dir = data_dir.join(crate::staging::TMP_DIR); | 310 | let scratch_dir = data_dir.join(crate::staging::TMP_DIR); |
| 298 | std::fs::create_dir_all(&scratch_dir)?; | 311 | std::fs::create_dir_all(&scratch_dir)?; |
| 299 | let scratch = scratch_dir.join(format!("restore-{stamp}.db")); | 312 | let scratch = scratch_dir.join(format!("restore-{stamp}.db")); |
| 300 | - std::fs::copy(&source, &scratch)?; | 313 | + copy_private(&source, &scratch)?; |
| 314 | + crate::store::create_private_files(&scratch)?; | ||
| 301 | let check = integrity_of(&scratch).await; | 315 | let check = integrity_of(&scratch).await; |
| 302 | remove_sidecars(&scratch)?; | 316 | remove_sidecars(&scratch)?; |
| 303 | std::fs::remove_file(&scratch)?; | 317 | std::fs::remove_file(&scratch)?; |
| @@ -324,7 +338,7 @@ pub async fn restore( | |||
| 324 | None | 338 | None |
| 325 | }; | 339 | }; |
| 326 | let staged = scratch_dir.join(format!("restore-{stamp}-final.db")); | 340 | let staged = scratch_dir.join(format!("restore-{stamp}-final.db")); |
| 327 | - std::fs::copy(&source, &staged)?; | 341 | + copy_private(&source, &staged)?; |
| 328 | std::fs::rename(&staged, database)?; | 342 | std::fs::rename(&staged, database)?; |
| 329 | std::fs::File::open(&parent)?.sync_all()?; | 343 | std::fs::File::open(&parent)?.sync_all()?; |
| 330 | 344 | ||
crates/in-core/src/config.rsmodified+66 -5
| @@ -2,14 +2,17 @@ | |||
| 2 | //! S3 keys are read from files or entered in the admin UI. Every struct rejects unknown keys, so a | 2 | //! S3 keys are read from files or entered in the admin UI. Every struct rejects unknown keys, so a |
| 3 | //! typo fails at boot instead of being silently ignored. | 3 | //! typo fails at boot instead of being silently ignored. |
| 4 | 4 | ||
| 5 | +use std::fmt; | ||
| 5 | use std::net::{IpAddr, SocketAddr}; | 6 | use std::net::{IpAddr, SocketAddr}; |
| 6 | use std::path::{Path, PathBuf}; | 7 | use std::path::{Path, PathBuf}; |
| 7 | use std::str::FromStr; | 8 | use std::str::FromStr; |
| 8 | 9 | ||
| 9 | use ipnet::IpNet; | 10 | use ipnet::IpNet; |
| 10 | use serde::{Deserialize, Deserializer}; | 11 | use serde::{Deserialize, Deserializer}; |
| 12 | +use url::{Host, Url}; | ||
| 11 | 13 | ||
| 12 | use crate::error::{Error, Result}; | 14 | use crate::error::{Error, Result}; |
| 15 | +use crate::secret::Redacted; | ||
| 13 | 16 | ||
| 14 | /// The example file. It is committed, and it is written to `config/in.toml` when that file is missing. | 17 | /// The example file. It is committed, and it is written to `config/in.toml` when that file is missing. |
| 15 | pub const EXAMPLE: &str = include_str!("../../../config/in.example.toml"); | 18 | pub const EXAMPLE: &str = include_str!("../../../config/in.example.toml"); |
| @@ -123,7 +126,7 @@ pub struct S3 { | |||
| 123 | } | 126 | } |
| 124 | 127 | ||
| 125 | /// The `[backup]` table. | 128 | /// The `[backup]` table. |
| 126 | -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] | 129 | +#[derive(Clone, PartialEq, Eq, Deserialize)] |
| 127 | #[serde(deny_unknown_fields)] | 130 | #[serde(deny_unknown_fields)] |
| 128 | pub struct Backup { | 131 | pub struct Backup { |
| 129 | /// Directory that receives one snapshot set per run. | 132 | /// Directory that receives one snapshot set per run. |
| @@ -139,6 +142,20 @@ pub struct Backup { | |||
| 139 | pub healthcheck_url: Option<String>, | 142 | pub healthcheck_url: Option<String>, |
| 140 | } | 143 | } |
| 141 | 144 | ||
| 145 | +impl fmt::Debug for Backup { | ||
| 146 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 147 | + f.debug_struct("Backup") | ||
| 148 | + .field("dir", &self.dir) | ||
| 149 | + .field("interval_hours", &self.interval_hours) | ||
| 150 | + .field("keep", &self.keep) | ||
| 151 | + .field( | ||
| 152 | + "healthcheck_url", | ||
| 153 | + &self.healthcheck_url.as_ref().map(|_| Redacted), | ||
| 154 | + ) | ||
| 155 | + .finish() | ||
| 156 | + } | ||
| 157 | +} | ||
| 158 | + | ||
| 142 | fn default_interval_hours() -> u32 { | 159 | fn default_interval_hours() -> u32 { |
| 143 | 24 | 160 | 24 |
| 144 | } | 161 | } |
| @@ -257,12 +274,34 @@ fn config_err(message: &str) -> Error { | |||
| 257 | Error::Config(message.to_string()) | 274 | Error::Config(message.to_string()) |
| 258 | } | 275 | } |
| 259 | 276 | ||
| 260 | -/// An http or https URL with no trailing slash. Scheme checks only: the rest is left to the | 277 | +/// Parses `url` and returns it only when `in` may connect to it: `https` always, and `http` only for a |
| 261 | -/// component that uses the URL, which reports its own error. | 278 | +/// loopback host with no userinfo, so plain text never leaves the machine. Every URL `in` is given |
| 279 | +/// goes through here, the configuration and the family switcher alike. | ||
| 280 | +pub fn parse_endpoint(url: &str) -> Option<Url> { | ||
| 281 | + let parsed = Url::parse(url).ok()?; | ||
| 282 | + let plain_ok = parsed.scheme() == "http" | ||
| 283 | + && parsed.username().is_empty() | ||
| 284 | + && parsed.password().is_none() | ||
| 285 | + && is_loopback(&parsed); | ||
| 286 | + (parsed.scheme() == "https" || plain_ok).then_some(parsed) | ||
| 287 | +} | ||
| 288 | + | ||
| 289 | +/// Whether the host of `url` is `localhost`, an IPv4 address in 127.0.0.0/8, or `::1`. | ||
| 290 | +fn is_loopback(url: &Url) -> bool { | ||
| 291 | + match url.host() { | ||
| 292 | + Some(Host::Domain(name)) => name == "localhost", | ||
| 293 | + Some(Host::Ipv4(ip)) => ip.is_loopback(), | ||
| 294 | + Some(Host::Ipv6(ip)) => ip.is_loopback(), | ||
| 295 | + None => false, | ||
| 296 | + } | ||
| 297 | +} | ||
| 298 | + | ||
| 299 | +/// A URL that [`parse_endpoint`] accepts, with no trailing slash and no whitespace. The rest is left to | ||
| 300 | +/// the component that uses the URL, which reports its own error. | ||
| 262 | fn validate_base_url(field: &str, url: &str) -> Result<()> { | 301 | fn validate_base_url(field: &str, url: &str) -> Result<()> { |
| 263 | - if !(url.starts_with("https://") || url.starts_with("http://")) { | 302 | + if parse_endpoint(url).is_none() { |
| 264 | return Err(config_err(&format!( | 303 | return Err(config_err(&format!( |
| 265 | - "{field} must start with http:// or https://" | 304 | + "{field} must be an https:// URL, or an http:// URL for a loopback host" |
| 266 | ))); | 305 | ))); |
| 267 | } | 306 | } |
| 268 | if url.ends_with('/') || url.chars().any(char::is_whitespace) { | 307 | if url.ends_with('/') || url.chars().any(char::is_whitespace) { |
| @@ -300,6 +339,28 @@ pub fn parse_proxy(text: &str) -> std::result::Result<IpNet, String> { | |||
| 300 | mod tests { | 339 | mod tests { |
| 301 | use super::*; | 340 | use super::*; |
| 302 | 341 | ||
| 342 | + #[test] | ||
| 343 | + fn plain_http_is_allowed_only_for_loopback_hosts() { | ||
| 344 | + for url in [ | ||
| 345 | + "http://127.0.0.1:7655", | ||
| 346 | + "http://127.4.5.6", | ||
| 347 | + "http://localhost:7650", | ||
| 348 | + "http://[::1]:7650", | ||
| 349 | + "https://im.example.com", | ||
| 350 | + ] { | ||
| 351 | + assert!(parse_endpoint(url).is_some(), "{url}"); | ||
| 352 | + } | ||
| 353 | + for url in [ | ||
| 354 | + "http://localhost.evil.example", | ||
| 355 | + "http://localhost@evil.example", | ||
| 356 | + "http://192.168.1.5", | ||
| 357 | + "http://evil.example", | ||
| 358 | + "ftp://127.0.0.1", | ||
| 359 | + ] { | ||
| 360 | + assert!(parse_endpoint(url).is_none(), "{url}"); | ||
| 361 | + } | ||
| 362 | + } | ||
| 363 | + | ||
| 303 | #[test] | 364 | #[test] |
| 304 | fn example_is_valid_and_bare_proxy_addresses_are_accepted() { | 365 | fn example_is_valid_and_bare_proxy_addresses_are_accepted() { |
| 305 | let config: Config = toml::from_str(EXAMPLE).unwrap(); | 366 | let config: Config = toml::from_str(EXAMPLE).unwrap(); |
crates/in-core/src/export.rsmodified+9 -3
| @@ -5,9 +5,11 @@ | |||
| 5 | //! output directory: a separator or control character becomes `_`, and `.` and `..` are never used as | 5 | //! output directory: a separator or control character becomes `_`, and `.` and `..` are never used as |
| 6 | //! a name. Each file is created with `create_new`, so an existing file or a planted symlink is never | 6 | //! a name. Each file is created with `create_new`, so an existing file or a planted symlink is never |
| 7 | //! written through. Bytes are hashed while they are copied and checked against the database row; a | 7 | //! written through. Bytes are hashed while they are copied and checked against the database row; a |
| 8 | -//! mismatch removes the partial file and is reported. Trashed items are not exported. | 8 | +//! mismatch removes the partial file and is reported. Trashed items are not exported. Folders are made |
| 9 | +//! with mode 0700 and files with mode 0600, so the copy is private whatever the umask says. | ||
| 9 | 10 | ||
| 10 | use std::io::Write; | 11 | use std::io::Write; |
| 12 | +use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; | ||
| 11 | use std::path::{Path, PathBuf}; | 13 | use std::path::{Path, PathBuf}; |
| 12 | 14 | ||
| 13 | use futures_util::StreamExt; | 15 | use futures_util::StreamExt; |
| @@ -83,7 +85,10 @@ pub async fn export_member( | |||
| 83 | sub: &str, | 85 | sub: &str, |
| 84 | out: &Path, | 86 | out: &Path, |
| 85 | ) -> Result<ExportReport> { | 87 | ) -> Result<ExportReport> { |
| 86 | - std::fs::create_dir_all(out)?; | 88 | + std::fs::DirBuilder::new() |
| 89 | + .recursive(true) | ||
| 90 | + .mode(0o700) | ||
| 91 | + .create(out)?; | ||
| 87 | let root = std::fs::canonicalize(out)?; | 92 | let root = std::fs::canonicalize(out)?; |
| 88 | let mut report = ExportReport::default(); | 93 | let mut report = ExportReport::default(); |
| 89 | // Work list of (folder id, the directory it goes into). | 94 | // Work list of (folder id, the directory it goes into). |
| @@ -92,7 +97,7 @@ pub async fn export_member( | |||
| 92 | let listing = store.list_children(sub, folder.as_deref()).await?; | 97 | let listing = store.list_children(sub, folder.as_deref()).await?; |
| 93 | for Folder { id, name, .. } in listing.folders { | 98 | for Folder { id, name, .. } in listing.folders { |
| 94 | let path = free_path(&dir, &safe_component(&name), false)?; | 99 | let path = free_path(&dir, &safe_component(&name), false)?; |
| 95 | - std::fs::create_dir(&path)?; | 100 | + std::fs::DirBuilder::new().mode(0o700).create(&path)?; |
| 96 | ensure_inside(&root, &path)?; | 101 | ensure_inside(&root, &path)?; |
| 97 | report.folders += 1; | 102 | report.folders += 1; |
| 98 | pending.push((Some(id), path)); | 103 | pending.push((Some(id), path)); |
| @@ -149,6 +154,7 @@ async fn copy_file( | |||
| 149 | let mut file = std::fs::OpenOptions::new() | 154 | let mut file = std::fs::OpenOptions::new() |
| 150 | .write(true) | 155 | .write(true) |
| 151 | .create_new(true) | 156 | .create_new(true) |
| 157 | + .mode(0o600) | ||
| 152 | .open(path) | 158 | .open(path) |
| 153 | .map_err(|e| e.to_string())?; | 159 | .map_err(|e| e.to_string())?; |
| 154 | let outcome = write_verified(blobs, key, size, sha256, &mut file).await; | 160 | let outcome = write_verified(blobs, key, size, sha256, &mut file).await; |
crates/in-core/src/password.rsmodified+18 -6
| @@ -2,16 +2,30 @@ | |||
| 2 | //! blocking versions are slow by design, so async callers use the `_async` functions, which run them | 2 | //! blocking versions are slow by design, so async callers use the `_async` functions, which run them |
| 3 | //! on tokio's blocking pool. | 3 | //! on tokio's blocking pool. |
| 4 | 4 | ||
| 5 | -use argon2::Argon2; | ||
| 6 | use argon2::password_hash::phc::PasswordHash; | 5 | use argon2::password_hash::phc::PasswordHash; |
| 7 | use argon2::password_hash::{PasswordHasher, PasswordVerifier}; | 6 | use argon2::password_hash::{PasswordHasher, PasswordVerifier}; |
| 7 | +use argon2::{Algorithm, Argon2, Params, Version}; | ||
| 8 | 8 | ||
| 9 | use crate::error::{Error, Result}; | 9 | use crate::error::{Error, Result}; |
| 10 | 10 | ||
| 11 | -/// Hashes `pw` with argon2id (default parameters) and a random salt. Returns a PHC string. | 11 | +/// Memory cost of a hash, in KiB (19 MiB), time cost and lanes. They are written out here, not left to the |
| 12 | +/// crate's defaults, so a crate upgrade cannot change new hashes silently. A stored hash carries its own | ||
| 13 | +/// parameters, so every hash made before still verifies. | ||
| 14 | +const M_COST_KIB: u32 = 19 * 1024; | ||
| 15 | +const T_COST: u32 = 2; | ||
| 16 | +const P_COST: u32 = 1; | ||
| 17 | + | ||
| 18 | +/// The argon2id hasher with the pinned parameters. | ||
| 19 | +fn hasher() -> Argon2<'static> { | ||
| 20 | + let params = Params::new(M_COST_KIB, T_COST, P_COST, None) | ||
| 21 | + .expect("the pinned argon2 parameters are valid"); | ||
| 22 | + Argon2::new(Algorithm::Argon2id, Version::V0x13, params) | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +/// Hashes `pw` with argon2id (pinned parameters) and a random salt. Returns a PHC string. | ||
| 12 | pub fn hash_password(pw: &str) -> Result<String> { | 26 | pub fn hash_password(pw: &str) -> Result<String> { |
| 13 | // The trait method draws a fresh salt from the OS RNG. | 27 | // The trait method draws a fresh salt from the OS RNG. |
| 14 | - Argon2::default() | 28 | + hasher() |
| 15 | .hash_password(pw.as_bytes()) | 29 | .hash_password(pw.as_bytes()) |
| 16 | .map(|h| h.to_string()) | 30 | .map(|h| h.to_string()) |
| 17 | .map_err(|e| Error::Crypto(format!("argon2: {e}"))) | 31 | .map_err(|e| Error::Crypto(format!("argon2: {e}"))) |
| @@ -23,9 +37,7 @@ pub fn verify_password(pw: &str, hash: &str) -> bool { | |||
| 23 | let Ok(parsed) = PasswordHash::new(hash) else { | 37 | let Ok(parsed) = PasswordHash::new(hash) else { |
| 24 | return false; | 38 | return false; |
| 25 | }; | 39 | }; |
| 26 | - Argon2::default() | 40 | + hasher().verify_password(pw.as_bytes(), &parsed).is_ok() |
| 27 | - .verify_password(pw.as_bytes(), &parsed) | ||
| 28 | - .is_ok() | ||
| 29 | } | 41 | } |
| 30 | 42 | ||
| 31 | /// [`hash_password`] on the blocking pool, so the async runtime is not held for the hashing time. | 43 | /// [`hash_password`] on the blocking pool, so the async runtime is not held for the hashing time. |
crates/in-core/src/secret.rsmodified+22 -4
| @@ -5,6 +5,7 @@ | |||
| 5 | //! (see [`derive_subkey`]), and every seal is bound to a [`purpose`] that is checked as associated data, | 5 | //! (see [`derive_subkey`]), and every seal is bound to a [`purpose`] that is checked as associated data, |
| 6 | //! so a value sealed for one purpose does not open as another. | 6 | //! so a value sealed for one purpose does not open as another. |
| 7 | 7 | ||
| 8 | +use std::fmt; | ||
| 8 | use std::path::Path; | 9 | use std::path::Path; |
| 9 | 10 | ||
| 10 | use base64::prelude::{BASE64_STANDARD, Engine as _}; | 11 | use base64::prelude::{BASE64_STANDARD, Engine as _}; |
| @@ -37,6 +38,16 @@ pub mod purpose { | |||
| 37 | pub const SHARE_LINK_TOKEN: &str = "share-link-token"; | 38 | pub const SHARE_LINK_TOKEN: &str = "share-link-token"; |
| 38 | } | 39 | } |
| 39 | 40 | ||
| 41 | +/// Stands in for a secret in a hand-written `Debug`. It prints as `<redacted>`, so a struct that holds a | ||
| 42 | +/// secret can be logged without leaking it. | ||
| 43 | +pub struct Redacted; | ||
| 44 | + | ||
| 45 | +impl fmt::Debug for Redacted { | ||
| 46 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 47 | + f.write_str("<redacted>") | ||
| 48 | + } | ||
| 49 | +} | ||
| 50 | + | ||
| 40 | /// Loads the 32-byte instance key at `path`, creating it when missing. A new key is created with | 51 | /// Loads the 32-byte instance key at `path`, creating it when missing. A new key is created with |
| 41 | /// mode 0600 and `O_EXCL`, so an existing key is never overwritten. An existing key with group or | 52 | /// mode 0600 and `O_EXCL`, so an existing key is never overwritten. An existing key with group or |
| 42 | /// world access is refused. | 53 | /// world access is refused. |
| @@ -79,21 +90,28 @@ fn create_key(path: &Path) -> std::io::Result<[u8; 32]> { | |||
| 79 | Ok(key) | 90 | Ok(key) |
| 80 | } | 91 | } |
| 81 | 92 | ||
| 82 | -/// Reads an existing instance key without creating one. A key with group or world access, or of the wrong | 93 | +/// Refuses a secret file that group or world can read or write. The instance key and every credential |
| 83 | -/// length, is refused. | 94 | +/// file `in` reads at boot must pass this, so a secret is never used from a file others can open. |
| 84 | -pub fn read_key(path: &Path) -> Result<[u8; 32]> { | 95 | +pub fn check_private(path: &Path) -> Result<()> { |
| 85 | #[cfg(unix)] | 96 | #[cfg(unix)] |
| 86 | { | 97 | { |
| 87 | use std::os::unix::fs::PermissionsExt; | 98 | use std::os::unix::fs::PermissionsExt; |
| 88 | let mode = std::fs::metadata(path)?.permissions().mode(); | 99 | let mode = std::fs::metadata(path)?.permissions().mode(); |
| 89 | if mode & 0o077 != 0 { | 100 | if mode & 0o077 != 0 { |
| 90 | return Err(Error::Crypto(format!( | 101 | return Err(Error::Crypto(format!( |
| 91 | - "instance key {} is group/world accessible (mode {:o}); expected 0600", | 102 | + "{} is group/world accessible (mode {:o}); expected 0600", |
| 92 | path.display(), | 103 | path.display(), |
| 93 | mode & 0o777 | 104 | mode & 0o777 |
| 94 | ))); | 105 | ))); |
| 95 | } | 106 | } |
| 96 | } | 107 | } |
| 108 | + Ok(()) | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +/// Reads an existing instance key without creating one. A key with group or world access, or of the wrong | ||
| 112 | +/// length, is refused. | ||
| 113 | +pub fn read_key(path: &Path) -> Result<[u8; 32]> { | ||
| 114 | + check_private(path)?; | ||
| 97 | let bytes = std::fs::read(path)?; | 115 | let bytes = std::fs::read(path)?; |
| 98 | <[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| { | 116 | <[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| { |
| 99 | Error::Crypto(format!( | 117 | Error::Crypto(format!( |
crates/in-core/src/store/links.rsmodified+41 -2
| @@ -5,9 +5,12 @@ | |||
| 5 | //! This module stores and finds links. Whether a visitor may see something through a link is decided by | 5 | //! This module stores and finds links. Whether a visitor may see something through a link is decided by |
| 6 | //! the web layer with `authz` (the link actor) and the store's `is_within` and `item_trashed`. | 6 | //! the web layer with `authz` (the link actor) and the store's `is_within` and `item_trashed`. |
| 7 | 7 | ||
| 8 | +use std::fmt; | ||
| 9 | + | ||
| 8 | use turso::{Connection, Row}; | 10 | use turso::{Connection, Row}; |
| 9 | 11 | ||
| 10 | use crate::error::{Error, Result}; | 12 | use crate::error::{Error, Result}; |
| 13 | +use crate::secret::Redacted; | ||
| 11 | use crate::store::files::live_file; | 14 | use crate::store::files::live_file; |
| 12 | use crate::store::folders::live_folder; | 15 | use crate::store::folders::live_folder; |
| 13 | use crate::store::shares::{kind_from_word, kind_word}; | 16 | 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 | |||
| 23 | password_hash, expires_at, revoked_at, created_at, last_used_at, use_count"; | 26 | password_hash, expires_at, revoked_at, created_at, last_used_at, use_count"; |
| 24 | 27 | ||
| 25 | /// One row of the `links` table. | 28 | /// One row of the `links` table. |
| 26 | -#[derive(Debug, Clone, PartialEq, Eq)] | 29 | +#[derive(Clone, PartialEq, Eq)] |
| 27 | pub struct Link { | 30 | pub struct Link { |
| 28 | /// Link id (a lower-case ULID). It names the unlock cookie. | 31 | /// Link id (a lower-case ULID). It names the unlock cookie. |
| 29 | pub id: String, | 32 | pub id: String, |
| @@ -53,6 +56,26 @@ pub struct Link { | |||
| 53 | pub use_count: i64, | 56 | pub use_count: i64, |
| 54 | } | 57 | } |
| 55 | 58 | ||
| 59 | +impl fmt::Debug for Link { | ||
| 60 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 61 | + f.debug_struct("Link") | ||
| 62 | + .field("id", &self.id) | ||
| 63 | + .field("token_hash", &self.token_hash) | ||
| 64 | + .field("token_sealed", &Redacted) | ||
| 65 | + .field("kind", &self.kind) | ||
| 66 | + .field("target_id", &self.target_id) | ||
| 67 | + .field("owner", &self.owner) | ||
| 68 | + .field("can_download", &self.can_download) | ||
| 69 | + .field("password_hash", &self.password_hash) | ||
| 70 | + .field("expires_at", &self.expires_at) | ||
| 71 | + .field("revoked_at", &self.revoked_at) | ||
| 72 | + .field("created_at", &self.created_at) | ||
| 73 | + .field("last_used_at", &self.last_used_at) | ||
| 74 | + .field("use_count", &self.use_count) | ||
| 75 | + .finish() | ||
| 76 | + } | ||
| 77 | +} | ||
| 78 | + | ||
| 56 | impl Link { | 79 | impl Link { |
| 57 | /// Whether the link still works at `now` (a stamp of this format): not revoked and not expired. | 80 | /// Whether the link still works at `now` (a stamp of this format): not revoked and not expired. |
| 58 | /// The target's own trash state is checked separately. | 81 | /// The target's own trash state is checked separately. |
| @@ -62,7 +85,7 @@ impl Link { | |||
| 62 | } | 85 | } |
| 63 | 86 | ||
| 64 | /// What a new link needs. The token is generated and sealed by the caller. | 87 | /// What a new link needs. The token is generated and sealed by the caller. |
| 65 | -#[derive(Debug, Clone, PartialEq, Eq)] | 88 | +#[derive(Clone, PartialEq, Eq)] |
| 66 | pub struct NewLink { | 89 | pub struct NewLink { |
| 67 | /// Id, made by the caller so it is known before the insert. | 90 | /// Id, made by the caller so it is known before the insert. |
| 68 | pub id: String, | 91 | pub id: String, |
| @@ -84,6 +107,22 @@ pub struct NewLink { | |||
| 84 | pub expires_at: Option<String>, | 107 | pub expires_at: Option<String>, |
| 85 | } | 108 | } |
| 86 | 109 | ||
| 110 | +impl fmt::Debug for NewLink { | ||
| 111 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 112 | + f.debug_struct("NewLink") | ||
| 113 | + .field("id", &self.id) | ||
| 114 | + .field("token_hash", &self.token_hash) | ||
| 115 | + .field("token_sealed", &Redacted) | ||
| 116 | + .field("kind", &self.kind) | ||
| 117 | + .field("target_id", &self.target_id) | ||
| 118 | + .field("owner", &self.owner) | ||
| 119 | + .field("can_download", &self.can_download) | ||
| 120 | + .field("password_hash", &self.password_hash) | ||
| 121 | + .field("expires_at", &self.expires_at) | ||
| 122 | + .finish() | ||
| 123 | + } | ||
| 124 | +} | ||
| 125 | + | ||
| 87 | /// Maps a row selected with [`LINK_COLS`]. | 126 | /// Maps a row selected with [`LINK_COLS`]. |
| 88 | fn map_link(row: &Row) -> Result<Link> { | 127 | fn map_link(row: &Row) -> Result<Link> { |
| 89 | let kind = kind_from_word(&col_text(row, 3)?) | 128 | let kind = kind_from_word(&col_text(row, 3)?) |
crates/in-core/src/store/mod.rsmodified+29 -0
| @@ -64,6 +64,7 @@ impl Store { | |||
| 64 | let path_str = path.to_str().ok_or_else(|| { | 64 | let path_str = path.to_str().ok_or_else(|| { |
| 65 | Error::Config(format!("database path is not UTF-8: {}", path.display())) | 65 | Error::Config(format!("database path is not UTF-8: {}", path.display())) |
| 66 | })?; | 66 | })?; |
| 67 | + create_private_files(path)?; | ||
| 67 | let db = Builder::new_local(path_str).build().await.map_err(db_err)?; | 68 | let db = Builder::new_local(path_str).build().await.map_err(db_err)?; |
| 68 | let conn = db.connect().map_err(db_err)?; | 69 | let conn = db.connect().map_err(db_err)?; |
| 69 | apply_pragmas(&conn).await; | 70 | apply_pragmas(&conn).await; |
| @@ -102,6 +103,34 @@ impl Store { | |||
| 102 | } | 103 | } |
| 103 | } | 104 | } |
| 104 | 105 | ||
| 106 | +/// Creates `path` with mode 0600, failing if it exists (a symlink counts). The umask does not decide who | ||
| 107 | +/// can read a database this way. | ||
| 108 | +pub(crate) fn create_private_file(path: &Path) -> std::io::Result<()> { | ||
| 109 | + let mut options = std::fs::OpenOptions::new(); | ||
| 110 | + options.write(true).create_new(true); | ||
| 111 | + #[cfg(unix)] | ||
| 112 | + { | ||
| 113 | + use std::os::unix::fs::OpenOptionsExt; | ||
| 114 | + options.mode(0o600); | ||
| 115 | + } | ||
| 116 | + options.open(path).map(drop) | ||
| 117 | +} | ||
| 118 | + | ||
| 119 | +/// Creates the database file and its `-wal` and `-shm` sidecars with mode 0600 when they are missing. A file | ||
| 120 | +/// that exists is left as it is. | ||
| 121 | +pub(crate) fn create_private_files(path: &Path) -> Result<()> { | ||
| 122 | + for suffix in ["", "-wal", "-shm"] { | ||
| 123 | + let mut name = path.as_os_str().to_owned(); | ||
| 124 | + name.push(suffix); | ||
| 125 | + match create_private_file(Path::new(&name)) { | ||
| 126 | + Ok(()) => {} | ||
| 127 | + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} | ||
| 128 | + Err(e) => return Err(e.into()), | ||
| 129 | + } | ||
| 130 | + } | ||
| 131 | + Ok(()) | ||
| 132 | +} | ||
| 133 | + | ||
| 105 | /// Sets the pragmas every connection needs. A pragma that fails is logged, not fatal, and the values | 134 | /// Sets the pragmas every connection needs. A pragma that fails is logged, not fatal, and the values |
| 106 | /// in effect are read back and logged so a silent failure is visible at boot. | 135 | /// in effect are read back and logged so a silent failure is visible at boot. |
| 107 | async fn apply_pragmas(conn: &Connection) { | 136 | async fn apply_pragmas(conn: &Connection) { |
crates/in-core/src/store/sessions.rsmodified+38 -2
| @@ -4,7 +4,10 @@ | |||
| 4 | //! sessions of disabled people are never returned by [`Store::session_by_token_hash`], so a session | 4 | //! sessions of disabled people are never returned by [`Store::session_by_token_hash`], so a session |
| 5 | //! stops working the moment it expires, even before the sweeper removes it. | 5 | //! stops working the moment it expires, even before the sweeper removes it. |
| 6 | 6 | ||
| 7 | +use std::fmt; | ||
| 8 | + | ||
| 7 | use crate::error::Result; | 9 | use crate::error::Result; |
| 10 | +use crate::secret::Redacted; | ||
| 8 | use crate::store::{Store, col_opt_text, col_text, db_err, fetch_opt, new_id}; | 11 | use crate::store::{Store, col_opt_text, col_text, db_err, fetch_opt, new_id}; |
| 9 | use crate::time::now_stamp; | 12 | use crate::time::now_stamp; |
| 10 | 13 | ||
| @@ -13,7 +16,7 @@ pub const SESSION_COLS: &str = "id, sub, token_hash, csrf_token, im_sid, created | |||
| 13 | last_seen_at, ip, user_agent, id_token_sealed"; | 16 | last_seen_at, ip, user_agent, id_token_sealed"; |
| 14 | 17 | ||
| 15 | /// One row of the `sessions` table. The token itself is not in here. | 18 | /// One row of the `sessions` table. The token itself is not in here. |
| 16 | -#[derive(Debug, Clone, PartialEq, Eq)] | 19 | +#[derive(Clone, PartialEq, Eq)] |
| 17 | pub struct Session { | 20 | pub struct Session { |
| 18 | /// Session id (a ULID). | 21 | /// Session id (a ULID). |
| 19 | pub id: String, | 22 | pub id: String, |
| @@ -40,8 +43,26 @@ pub struct Session { | |||
| 40 | pub id_token_sealed: Option<String>, | 43 | pub id_token_sealed: Option<String>, |
| 41 | } | 44 | } |
| 42 | 45 | ||
| 46 | +impl fmt::Debug for Session { | ||
| 47 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 48 | + f.debug_struct("Session") | ||
| 49 | + .field("id", &self.id) | ||
| 50 | + .field("sub", &self.sub) | ||
| 51 | + .field("token_hash", &self.token_hash) | ||
| 52 | + .field("csrf_token", &Redacted) | ||
| 53 | + .field("im_sid", &self.im_sid) | ||
| 54 | + .field("created_at", &self.created_at) | ||
| 55 | + .field("expires_at", &self.expires_at) | ||
| 56 | + .field("last_seen_at", &self.last_seen_at) | ||
| 57 | + .field("ip", &self.ip) | ||
| 58 | + .field("user_agent", &self.user_agent) | ||
| 59 | + .field("id_token_sealed", &self.id_token_sealed) | ||
| 60 | + .finish() | ||
| 61 | + } | ||
| 62 | +} | ||
| 63 | + | ||
| 43 | /// What a new session needs. The id and timestamps are made by the store. | 64 | /// What a new session needs. The id and timestamps are made by the store. |
| 44 | -#[derive(Debug, Clone, PartialEq, Eq)] | 65 | +#[derive(Clone, PartialEq, Eq)] |
| 45 | pub struct NewSession { | 66 | pub struct NewSession { |
| 46 | /// The person. | 67 | /// The person. |
| 47 | pub sub: String, | 68 | pub sub: String, |
| @@ -61,6 +82,21 @@ pub struct NewSession { | |||
| 61 | pub id_token_sealed: Option<String>, | 82 | pub id_token_sealed: Option<String>, |
| 62 | } | 83 | } |
| 63 | 84 | ||
| 85 | +impl fmt::Debug for NewSession { | ||
| 86 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 87 | + f.debug_struct("NewSession") | ||
| 88 | + .field("sub", &self.sub) | ||
| 89 | + .field("token_hash", &self.token_hash) | ||
| 90 | + .field("csrf_token", &Redacted) | ||
| 91 | + .field("im_sid", &self.im_sid) | ||
| 92 | + .field("expires_at", &self.expires_at) | ||
| 93 | + .field("ip", &self.ip) | ||
| 94 | + .field("user_agent", &self.user_agent) | ||
| 95 | + .field("id_token_sealed", &self.id_token_sealed) | ||
| 96 | + .finish() | ||
| 97 | + } | ||
| 98 | +} | ||
| 99 | + | ||
| 64 | /// Maps a row selected with [`SESSION_COLS`]. | 100 | /// Maps a row selected with [`SESSION_COLS`]. |
| 65 | pub fn map_session(row: &turso::Row) -> Result<Session> { | 101 | pub fn map_session(row: &turso::Row) -> Result<Session> { |
| 66 | Ok(Session { | 102 | Ok(Session { |
crates/in-core/src/store/snapshot.rsmodified+6 -1
| @@ -2,12 +2,13 @@ | |||
| 2 | //! so no write can interleave with it. A WAL-mode copy keeps its rows in a sidecar file, so the copy is | 2 | //! so no write can interleave with it. A WAL-mode copy keeps its rows in a sidecar file, so the copy is |
| 3 | //! then checkpointed until it is one self-contained file. | 3 | //! then checkpointed until it is one self-contained file. |
| 4 | 4 | ||
| 5 | +use std::os::unix::fs::PermissionsExt; | ||
| 5 | use std::path::Path; | 6 | use std::path::Path; |
| 6 | 7 | ||
| 7 | use turso::Builder; | 8 | use turso::Builder; |
| 8 | 9 | ||
| 9 | use crate::error::{Error, Result}; | 10 | use crate::error::{Error, Result}; |
| 10 | -use crate::store::{Store, col_int, db_err, fetch_all}; | 11 | +use crate::store::{Store, col_int, create_private_files, db_err, fetch_all}; |
| 11 | 12 | ||
| 12 | impl Store { | 13 | impl Store { |
| 13 | /// Writes a consistent copy of the database to `dest`, then fsyncs it. `dest` must not exist. | 14 | /// Writes a consistent copy of the database to `dest`, then fsyncs it. `dest` must not exist. |
| @@ -26,6 +27,9 @@ impl Store { | |||
| 26 | let conn = self.inner.conn.lock().await; | 27 | let conn = self.inner.conn.lock().await; |
| 27 | conn.execute(&sql, ()).await.map_err(db_err)?; | 28 | conn.execute(&sql, ()).await.map_err(db_err)?; |
| 28 | } | 29 | } |
| 30 | + // VACUUM INTO creates the file with the umask's mode, so it is narrowed to 0600 before anything else | ||
| 31 | + // opens it. The engine refuses an existing target, so the file cannot be made private first. | ||
| 32 | + std::fs::set_permissions(dest, std::fs::Permissions::from_mode(0o600))?; | ||
| 29 | make_self_contained(dest).await?; | 33 | make_self_contained(dest).await?; |
| 30 | std::fs::File::open(dest)?.sync_all()?; | 34 | std::fs::File::open(dest)?.sync_all()?; |
| 31 | Ok(()) | 35 | Ok(()) |
| @@ -48,6 +52,7 @@ async fn make_self_contained(dest: &Path) -> Result<()> { | |||
| 48 | let text = dest | 52 | let text = dest |
| 49 | .to_str() | 53 | .to_str() |
| 50 | .ok_or_else(|| Error::Config(format!("snapshot path is not UTF-8: {}", dest.display())))?; | 54 | .ok_or_else(|| Error::Config(format!("snapshot path is not UTF-8: {}", dest.display())))?; |
| 55 | + create_private_files(dest)?; | ||
| 51 | let db = Builder::new_local(text).build().await.map_err(db_err)?; | 56 | let db = Builder::new_local(text).build().await.map_err(db_err)?; |
| 52 | let conn = db.connect().map_err(db_err)?; | 57 | let conn = db.connect().map_err(db_err)?; |
| 53 | // Columns: busy flag, frames in the log, frames checkpointed. | 58 | // Columns: busy flag, frames in the log, frames checkpointed. |
crates/in-web/src/boot.rsmodified+43 -5
| @@ -13,7 +13,7 @@ use std::sync::Arc; | |||
| 13 | use in_core::blob::BlobStore; | 13 | use in_core::blob::BlobStore; |
| 14 | use in_core::blob::local::LocalBlobs; | 14 | use in_core::blob::local::LocalBlobs; |
| 15 | use in_core::blob::s3::{S3Blobs, S3Settings}; | 15 | use in_core::blob::s3::{S3Blobs, S3Settings}; |
| 16 | -use in_core::config::{Backend, Config, S3}; | 16 | +use in_core::config::{Backend, Config, S3, parse_endpoint}; |
| 17 | use in_core::error::{Error, Result}; | 17 | use in_core::error::{Error, Result}; |
| 18 | use in_core::secret; | 18 | use in_core::secret; |
| 19 | use in_core::store::Store; | 19 | use in_core::store::Store; |
| @@ -103,6 +103,7 @@ pub async fn open_offline(config_path: &Path) -> Result<Offline> { | |||
| 103 | pub async fn serve(config_path: &Path) -> Result<()> { | 103 | pub async fn serve(config_path: &Path) -> Result<()> { |
| 104 | let config = Config::load(config_path)?; | 104 | let config = Config::load(config_path)?; |
| 105 | let listen = config.listen; | 105 | let listen = config.listen; |
| 106 | + warn_about_setup(&config); | ||
| 106 | // Held until the server stops: an operator command started now refuses instead of racing the server. | 107 | // Held until the server stops: an operator command started now refuses instead of racing the server. |
| 107 | let _lock = lock_data_dir(&config.data_dir)?; | 108 | let _lock = lock_data_dir(&config.data_dir)?; |
| 108 | let state = open_state(config).await?; | 109 | let state = open_state(config).await?; |
| @@ -145,6 +146,28 @@ pub async fn serve(config_path: &Path) -> Result<()> { | |||
| 145 | Ok(()) | 146 | Ok(()) |
| 146 | } | 147 | } |
| 147 | 148 | ||
| 149 | +/// Logs the settings that are legal but usually a mistake. Each one is a warning, never a refusal, because | ||
| 150 | +/// a local development setup has good reasons to leave them out. | ||
| 151 | +fn warn_about_setup(config: &Config) { | ||
| 152 | + if listen_is_loopback(config) && config.trusted_proxies.is_empty() { | ||
| 153 | + tracing::warn!( | ||
| 154 | + listen = %config.listen, | ||
| 155 | + "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" | ||
| 156 | + ); | ||
| 157 | + } | ||
| 158 | + if config.backup.is_none() { | ||
| 159 | + tracing::warn!("[backup] is not configured: there are no scheduled backups"); | ||
| 160 | + } | ||
| 161 | + if config.oidc.is_none() { | ||
| 162 | + tracing::warn!("[oidc] is not configured: sign-in is disabled"); | ||
| 163 | + } | ||
| 164 | +} | ||
| 165 | + | ||
| 166 | +/// Whether the listener is bound to a loopback address only. | ||
| 167 | +fn listen_is_loopback(config: &Config) -> bool { | ||
| 168 | + config.listen.ip().is_loopback() | ||
| 169 | +} | ||
| 170 | + | ||
| 148 | /// Creates the data directory and opens the key, the database and the blob store. Everything the | 171 | /// Creates the data directory and opens the key, the database and the blob store. Everything the |
| 149 | /// router needs that touches the disk is ready when this returns. | 172 | /// router needs that touches the disk is ready when this returns. |
| 150 | async fn open_state(config: Config) -> Result<AppState> { | 173 | async fn open_state(config: Config) -> Result<AppState> { |
| @@ -159,6 +182,19 @@ async fn open_state(config: Config) -> Result<AppState> { | |||
| 159 | { | 182 | { |
| 160 | std::fs::create_dir_all(parent)?; | 183 | std::fs::create_dir_all(parent)?; |
| 161 | } | 184 | } |
| 185 | + let database_dir = std::fs::canonicalize( | ||
| 186 | + config | ||
| 187 | + .database | ||
| 188 | + .parent() | ||
| 189 | + .filter(|p| !p.as_os_str().is_empty()) | ||
| 190 | + .unwrap_or(Path::new(".")), | ||
| 191 | + )?; | ||
| 192 | + if !database_dir.starts_with(&data_dir) { | ||
| 193 | + tracing::warn!( | ||
| 194 | + database = %config.database.display(), | ||
| 195 | + "database is outside data_dir: restore will not replace it, and the data-directory lock does not cover it" | ||
| 196 | + ); | ||
| 197 | + } | ||
| 162 | let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; | 198 | let key = secret::load_or_create_key(&data_dir.join(KEY_FILE))?; |
| 163 | let store = Store::open(&config.database).await?; | 199 | let store = Store::open(&config.database).await?; |
| 164 | let blobs = open_blobs(&config, &data_dir)?; | 200 | let blobs = open_blobs(&config, &data_dir)?; |
| @@ -205,15 +241,15 @@ pub fn open_blobs(config: &Config, data_dir: &Path) -> Result<Arc<dyn BlobStore> | |||
| 205 | } | 241 | } |
| 206 | 242 | ||
| 207 | /// Turns the `[storage.s3]` table and its credential files into the client settings. Without an | 243 | /// Turns the `[storage.s3]` table and its credential files into the client settings. Without an |
| 208 | -/// endpoint the AWS endpoint of the region is used. Plain http is allowed only when the configured | 244 | +/// endpoint the AWS endpoint of the region is used. Plain http is allowed only for a loopback endpoint. |
| 209 | -/// endpoint says so. | ||
| 210 | fn s3_settings(s3: &S3) -> Result<S3Settings> { | 245 | fn s3_settings(s3: &S3) -> Result<S3Settings> { |
| 211 | let endpoint = s3 | 246 | let endpoint = s3 |
| 212 | .endpoint | 247 | .endpoint |
| 213 | .clone() | 248 | .clone() |
| 214 | .unwrap_or_else(|| format!("https://s3.{}.amazonaws.com", s3.region)); | 249 | .unwrap_or_else(|| format!("https://s3.{}.amazonaws.com", s3.region)); |
| 250 | + let allow_http = parse_endpoint(&endpoint).is_some_and(|url| url.scheme() == "http"); | ||
| 215 | Ok(S3Settings { | 251 | Ok(S3Settings { |
| 216 | - allow_http: endpoint.starts_with("http://"), | 252 | + allow_http, |
| 217 | endpoint, | 253 | endpoint, |
| 218 | region: s3.region.clone(), | 254 | region: s3.region.clone(), |
| 219 | bucket: s3.bucket.clone(), | 255 | bucket: s3.bucket.clone(), |
| @@ -222,10 +258,12 @@ fn s3_settings(s3: &S3) -> Result<S3Settings> { | |||
| 222 | }) | 258 | }) |
| 223 | } | 259 | } |
| 224 | 260 | ||
| 225 | -/// Reads a credential file and drops the trailing newline. An empty file is a configuration error. | 261 | +/// Reads a credential file and drops the trailing newline. An empty file is a configuration error, and so |
| 262 | +/// is a file that group or world can read. | ||
| 226 | fn read_secret(path: &Path) -> Result<String> { | 263 | fn read_secret(path: &Path) -> Result<String> { |
| 227 | let text = std::fs::read_to_string(path) | 264 | let text = std::fs::read_to_string(path) |
| 228 | .map_err(|e| Error::Config(format!("cannot read {}: {e}", path.display())))?; | 265 | .map_err(|e| Error::Config(format!("cannot read {}: {e}", path.display())))?; |
| 266 | + secret::check_private(path)?; | ||
| 229 | let value = text.trim().to_owned(); | 267 | let value = text.trim().to_owned(); |
| 230 | if value.is_empty() { | 268 | if value.is_empty() { |
| 231 | return Err(Error::Config(format!("{} is empty", path.display()))); | 269 | return Err(Error::Config(format!("{} is empty", path.display()))); |
crates/in-web/src/directory.rsmodified+4 -4
| @@ -261,13 +261,13 @@ async fn full_sync(state: &AppState, oidc: &OidcClient) -> Result<(), SyncError> | |||
| 261 | .header(ACCEPT, "application/json") | 261 | .header(ACCEPT, "application/json") |
| 262 | .send() | 262 | .send() |
| 263 | .await | 263 | .await |
| 264 | - .map_err(|e| SyncError::Transport(e.to_string()))?; | 264 | + .map_err(|e| SyncError::Transport(e.without_url().to_string()))?; |
| 265 | if !response.status().is_success() { | 265 | if !response.status().is_success() { |
| 266 | return Err(SyncError::Status(response.status())); | 266 | return Err(SyncError::Status(response.status())); |
| 267 | } | 267 | } |
| 268 | let bytes = read_limited(response, ROSTER_MAX_BYTES) | 268 | let bytes = read_limited(response, ROSTER_MAX_BYTES) |
| 269 | .await | 269 | .await |
| 270 | - .map_err(|e| SyncError::Transport(e.to_string()))? | 270 | + .map_err(|e| SyncError::Transport(e.without_url().to_string()))? |
| 271 | .ok_or(SyncError::TooLarge)?; | 271 | .ok_or(SyncError::TooLarge)?; |
| 272 | let listing: Listing = serde_json::from_slice(&bytes).map_err(|_| SyncError::Listing)?; | 272 | let listing: Listing = serde_json::from_slice(&bytes).map_err(|_| SyncError::Listing)?; |
| 273 | 273 | ||
| @@ -308,7 +308,7 @@ async fn follow( | |||
| 308 | let response = request | 308 | let response = request |
| 309 | .send() | 309 | .send() |
| 310 | .await | 310 | .await |
| 311 | - .map_err(|e| SyncError::Transport(e.to_string()))?; | 311 | + .map_err(|e| SyncError::Transport(e.without_url().to_string()))?; |
| 312 | if !response.status().is_success() { | 312 | if !response.status().is_success() { |
| 313 | return Err(SyncError::Status(response.status())); | 313 | return Err(SyncError::Status(response.status())); |
| 314 | } | 314 | } |
| @@ -326,7 +326,7 @@ async fn follow( | |||
| 326 | let Some(chunk) = chunk else { | 326 | let Some(chunk) = chunk else { |
| 327 | return Ok(closed(opened, applied)); | 327 | return Ok(closed(opened, applied)); |
| 328 | }; | 328 | }; |
| 329 | - let chunk = chunk.map_err(|e| SyncError::Transport(e.to_string()))?; | 329 | + let chunk = chunk.map_err(|e| SyncError::Transport(e.without_url().to_string()))?; |
| 330 | for event in parser.push(&chunk)? { | 330 | for event in parser.push(&chunk)? { |
| 331 | applied = true; | 331 | applied = true; |
| 332 | if let Some(ended) = apply_event(state, event).await? { | 332 | if let Some(ended) = apply_event(state, event).await? { |
crates/in-web/src/family.rsmodified+8 -7
| @@ -3,13 +3,15 @@ | |||
| 3 | //! | 3 | //! |
| 4 | //! A worker fetches `GET {issuer}/api/v1/family` every five minutes with a client-credentials token for | 4 | //! A worker fetches `GET {issuer}/api/v1/family` every five minutes with a client-credentials token for |
| 5 | //! `im` (the token is cached by the OIDC client). A failed fetch keeps the last good list, because the list | 5 | //! `im` (the token is cached by the OIDC client). A failed fetch keeps the last good list, because the list |
| 6 | -//! changes rarely and a stale switcher is harmless. Only links a browser may follow are kept: http or https | 6 | +//! changes rarely and a stale switcher is harmless. Only links a browser may follow are kept: https URLs, or |
| 7 | -//! URLs with no whitespace or control characters, and never this service's own key. The shell escapes every | 7 | +//! http URLs for a loopback host (see `parse_endpoint`), with no whitespace or control characters, and never |
| 8 | -//! field when it renders, so a hostile name cannot break the page. | 8 | +//! this service's own key. The shell escapes every field when it renders, so a hostile name cannot break the |
| 9 | +//! page. | ||
| 9 | 10 | ||
| 10 | use std::sync::{PoisonError, RwLock}; | 11 | use std::sync::{PoisonError, RwLock}; |
| 11 | use std::time::Duration; | 12 | use std::time::Duration; |
| 12 | 13 | ||
| 14 | +use in_core::config::parse_endpoint; | ||
| 13 | use serde::Deserialize; | 15 | use serde::Deserialize; |
| 14 | use tokio::sync::watch; | 16 | use tokio::sync::watch; |
| 15 | 17 | ||
| @@ -66,12 +68,11 @@ impl FamilyCache { | |||
| 66 | } | 68 | } |
| 67 | } | 69 | } |
| 68 | 70 | ||
| 69 | -/// Whether a switcher link may be shown: an absolute http or https URL with no whitespace or control | 71 | +/// Whether a switcher link may be shown: an absolute URL that [`parse_endpoint`] accepts, with no whitespace |
| 70 | -/// characters, and not this service itself. | 72 | +/// or control characters, and not this service itself. |
| 71 | pub fn usable(link: &FamilyLink) -> bool { | 73 | pub fn usable(link: &FamilyLink) -> bool { |
| 72 | let url = link.url.as_str(); | 74 | let url = link.url.as_str(); |
| 73 | - let scheme_ok = url.starts_with("https://") || url.starts_with("http://"); | 75 | + parse_endpoint(url).is_some() |
| 74 | - scheme_ok | ||
| 75 | && !url.chars().any(|c| c.is_whitespace() || c.is_control()) | 76 | && !url.chars().any(|c| c.is_whitespace() || c.is_control()) |
| 76 | && link.key != SELF_KEY | 77 | && link.key != SELF_KEY |
| 77 | && !link.key.is_empty() | 78 | && !link.key.is_empty() |
crates/in-web/src/oidc.rsmodified+20 -10
| @@ -48,6 +48,9 @@ pub const HTTP_TIMEOUT: Duration = Duration::from_secs(10); | |||
| 48 | /// keep-alive every 30 seconds (contracts section 3.2), so three of them missed means it is dead. | 48 | /// keep-alive every 30 seconds (contracts section 3.2), so three of them missed means it is dead. |
| 49 | const STREAM_READ_TIMEOUT: Duration = Duration::from_secs(90); | 49 | const STREAM_READ_TIMEOUT: Duration = Duration::from_secs(90); |
| 50 | 50 | ||
| 51 | +/// The largest JSON answer read from `im`: discovery, the key set and token answers are far smaller. | ||
| 52 | +const MAX_DOCUMENT_BYTES: usize = 1024 * 1024; | ||
| 53 | + | ||
| 51 | /// A service token is refreshed this long before its stated end (contracts section 2.6). | 54 | /// A service token is refreshed this long before its stated end (contracts section 2.6). |
| 52 | const SERVICE_TOKEN_MARGIN: Duration = Duration::from_secs(60); | 55 | const SERVICE_TOKEN_MARGIN: Duration = Duration::from_secs(60); |
| 53 | 56 | ||
| @@ -554,6 +557,19 @@ pub async fn read_limited( | |||
| 554 | Ok(Some(body)) | 557 | Ok(Some(body)) |
| 555 | } | 558 | } |
| 556 | 559 | ||
| 560 | +/// Reads the body of a JSON answer from `im`, at most [`MAX_DOCUMENT_BYTES`]. A larger body is unavailable, | ||
| 561 | +/// and a read error is reported without the URL. | ||
| 562 | +async fn read_document(response: reqwest::Response) -> Result<Vec<u8>, OidcError> { | ||
| 563 | + read_limited(response, MAX_DOCUMENT_BYTES) | ||
| 564 | + .await | ||
| 565 | + .map_err(|e| OidcError::Unavailable(e.without_url().to_string()))? | ||
| 566 | + .ok_or_else(|| { | ||
| 567 | + OidcError::Unavailable(format!( | ||
| 568 | + "an answer is larger than {MAX_DOCUMENT_BYTES} bytes" | ||
| 569 | + )) | ||
| 570 | + }) | ||
| 571 | +} | ||
| 572 | + | ||
| 557 | /// Percent-encodes one value for a query, a form body or a Basic credential (RFC 6749 section 2.3.1): | 573 | /// Percent-encodes one value for a query, a form body or a Basic credential (RFC 6749 section 2.3.1): |
| 558 | /// unreserved characters pass, everything else becomes `%XX`. | 574 | /// unreserved characters pass, everything else becomes `%XX`. |
| 559 | pub fn percent_encode(value: &str) -> String { | 575 | pub fn percent_encode(value: &str) -> String { |
| @@ -744,17 +760,14 @@ impl OidcClient { | |||
| 744 | .get(url) | 760 | .get(url) |
| 745 | .send() | 761 | .send() |
| 746 | .await | 762 | .await |
| 747 | - .map_err(|e| OidcError::Unavailable(e.to_string()))?; | 763 | + .map_err(|e| OidcError::Unavailable(e.without_url().to_string()))?; |
| 748 | if !response.status().is_success() { | 764 | if !response.status().is_success() { |
| 749 | return Err(OidcError::Unavailable(format!( | 765 | return Err(OidcError::Unavailable(format!( |
| 750 | "{url} answered {}", | 766 | "{url} answered {}", |
| 751 | response.status() | 767 | response.status() |
| 752 | ))); | 768 | ))); |
| 753 | } | 769 | } |
| 754 | - let bytes = response | 770 | + let bytes = read_document(response).await?; |
| 755 | - .bytes() | ||
| 756 | - .await | ||
| 757 | - .map_err(|e| OidcError::Unavailable(e.to_string()))?; | ||
| 758 | serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string())) | 771 | serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string())) |
| 759 | } | 772 | } |
| 760 | 773 | ||
| @@ -959,7 +972,7 @@ impl OidcClient { | |||
| 959 | .form(form) | 972 | .form(form) |
| 960 | .send() | 973 | .send() |
| 961 | .await | 974 | .await |
| 962 | - .map_err(|e| OidcError::Unavailable(e.to_string()))?; | 975 | + .map_err(|e| OidcError::Unavailable(e.without_url().to_string()))?; |
| 963 | let status = response.status(); | 976 | let status = response.status(); |
| 964 | if status.is_client_error() { | 977 | if status.is_client_error() { |
| 965 | tracing::warn!(status = %status, "oidc: the token endpoint refused the request"); | 978 | tracing::warn!(status = %status, "oidc: the token endpoint refused the request"); |
| @@ -970,10 +983,7 @@ impl OidcClient { | |||
| 970 | "token endpoint answered {status}" | 983 | "token endpoint answered {status}" |
| 971 | ))); | 984 | ))); |
| 972 | } | 985 | } |
| 973 | - let bytes = response | 986 | + let bytes = read_document(response).await?; |
| 974 | - .bytes() | ||
| 975 | - .await | ||
| 976 | - .map_err(|e| OidcError::Unavailable(e.to_string()))?; | ||
| 977 | serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string())) | 987 | serde_json::from_slice(&bytes).map_err(|e| OidcError::Unavailable(e.to_string())) |
| 978 | } | 988 | } |
| 979 | } | 989 | } |
crates/in-web/src/pages/backchannel.rsmodified+11 -1
| @@ -11,9 +11,11 @@ | |||
| 11 | use http::header::CONTENT_TYPE; | 11 | use http::header::CONTENT_TYPE; |
| 12 | use http::{HeaderMap, HeaderValue}; | 12 | use http::{HeaderMap, HeaderValue}; |
| 13 | use in_core::error::Result as CoreResult; | 13 | use in_core::error::Result as CoreResult; |
| 14 | +use in_core::secret::Redacted; | ||
| 14 | use in_core::store::Store; | 15 | use in_core::store::Store; |
| 15 | use in_core::time::stamp_after; | 16 | use in_core::time::stamp_after; |
| 16 | use serde::Deserialize; | 17 | use serde::Deserialize; |
| 18 | +use std::fmt; | ||
| 17 | use std::time::Duration; | 19 | use std::time::Duration; |
| 18 | use topcoat::Result; | 20 | use topcoat::Result; |
| 19 | use topcoat::context::{Cx, app_context}; | 21 | use topcoat::context::{Cx, app_context}; |
| @@ -35,12 +37,20 @@ pub const REPLAY_WINDOW: Duration = Duration::from_secs(10 * 60); | |||
| 35 | pub type Answer = (StatusCode, HeaderMap, String); | 37 | pub type Answer = (StatusCode, HeaderMap, String); |
| 36 | 38 | ||
| 37 | /// The form body of a delivery: the one field `im` sends. | 39 | /// The form body of a delivery: the one field `im` sends. |
| 38 | -#[derive(Debug, Default, Deserialize)] | 40 | +#[derive(Default, Deserialize)] |
| 39 | #[serde(default)] | 41 | #[serde(default)] |
| 40 | struct LogoutTokenForm { | 42 | struct LogoutTokenForm { |
| 41 | logout_token: String, | 43 | logout_token: String, |
| 42 | } | 44 | } |
| 43 | 45 | ||
| 46 | +impl fmt::Debug for LogoutTokenForm { | ||
| 47 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 48 | + f.debug_struct("LogoutTokenForm") | ||
| 49 | + .field("logout_token", &Redacted) | ||
| 50 | + .finish() | ||
| 51 | + } | ||
| 52 | +} | ||
| 53 | + | ||
| 44 | /// What ending the sessions for one token did. | 54 | /// What ending the sessions for one token did. |
| 45 | #[derive(Debug, PartialEq, Eq)] | 55 | #[derive(Debug, PartialEq, Eq)] |
| 46 | pub enum Outcome { | 56 | pub enum Outcome { |
crates/in-web/src/pages/links.rsmodified+16 -1
| @@ -6,6 +6,7 @@ | |||
| 6 | //! argon2id on the blocking pool and is never shown again. Revoking and reminting need the owner; anything | 6 | //! argon2id on the blocking pool and is never shown again. Revoking and reminting need the owner; anything |
| 7 | //! else is `404`. | 7 | //! else is `404`. |
| 8 | 8 | ||
| 9 | +use std::fmt; | ||
| 9 | use std::time::Duration; | 10 | use std::time::Duration; |
| 10 | 11 | ||
| 11 | use in_core::error::Error as CoreError; | 12 | use in_core::error::Error as CoreError; |
| @@ -183,7 +184,7 @@ async fn links_page(cx: &Cx) -> Result<impl View> { | |||
| 183 | 184 | ||
| 184 | /// The form of link writes: the CSRF token, the return page, and for a creation the item, the expiry in | 185 | /// The form of link writes: the CSRF token, the return page, and for a creation the item, the expiry in |
| 185 | /// days (blank for the maximum), an optional password and the download flag. | 186 | /// days (blank for the maximum), an optional password and the download flag. |
| 186 | -#[derive(Debug, Default, Deserialize)] | 187 | +#[derive(Default, Deserialize)] |
| 187 | #[serde(default)] | 188 | #[serde(default)] |
| 188 | pub struct LinkForm { | 189 | pub struct LinkForm { |
| 189 | /// The CSRF token of the session. | 190 | /// The CSRF token of the session. |
| @@ -202,6 +203,20 @@ pub struct LinkForm { | |||
| 202 | pub download: String, | 203 | pub download: String, |
| 203 | } | 204 | } |
| 204 | 205 | ||
| 206 | +impl fmt::Debug for LinkForm { | ||
| 207 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 208 | + f.debug_struct("LinkForm") | ||
| 209 | + .field("csrf", &self.csrf) | ||
| 210 | + .field("back", &self.back) | ||
| 211 | + .field("kind", &self.kind) | ||
| 212 | + .field("target_id", &self.target_id) | ||
| 213 | + .field("days", &self.days) | ||
| 214 | + .field("password", &secret::Redacted) | ||
| 215 | + .field("download", &self.download) | ||
| 216 | + .finish() | ||
| 217 | + } | ||
| 218 | +} | ||
| 219 | + | ||
| 205 | /// Makes a fresh token and its sealed copy: `(token hash, sealed token, token)`. | 220 | /// Makes a fresh token and its sealed copy: `(token hash, sealed token, token)`. |
| 206 | fn new_token(state: &AppState) -> Result<(String, String, String)> { | 221 | fn new_token(state: &AppState) -> Result<(String, String, String)> { |
| 207 | let token = generate_token(); | 222 | let token = generate_token(); |
crates/in-web/src/pages/photo.rsmodified+16 -4
| @@ -12,6 +12,7 @@ use std::path::{Path, PathBuf}; | |||
| 12 | 12 | ||
| 13 | use http::header::{CONTENT_TYPE, ETAG, IF_NONE_MATCH}; | 13 | use http::header::{CONTENT_TYPE, ETAG, IF_NONE_MATCH}; |
| 14 | use http::{HeaderMap, HeaderValue}; | 14 | use http::{HeaderMap, HeaderValue}; |
| 15 | +use tokio::io::AsyncWriteExt; | ||
| 15 | use topcoat::Result; | 16 | use topcoat::Result; |
| 16 | use topcoat::context::{Cx, app_context}; | 17 | use topcoat::context::{Cx, app_context}; |
| 17 | use topcoat::router::error::{not_found, service_unavailable}; | 18 | 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 | |||
| 80 | return; | 81 | return; |
| 81 | }; | 82 | }; |
| 82 | let written = async { | 83 | let written = async { |
| 83 | - tokio::fs::create_dir_all(dir).await?; | 84 | + tokio::fs::DirBuilder::new() |
| 85 | + .recursive(true) | ||
| 86 | + .mode(0o700) | ||
| 87 | + .create(dir) | ||
| 88 | + .await?; | ||
| 84 | write_atomically(&type_path, content_type.as_bytes()).await?; | 89 | write_atomically(&type_path, content_type.as_bytes()).await?; |
| 85 | write_atomically(&bytes_path, bytes).await | 90 | write_atomically(&bytes_path, bytes).await |
| 86 | } | 91 | } |
| @@ -92,9 +97,16 @@ async fn write_cache(photo_dir: &Path, sub: &str, version: i64, content_type: &s | |||
| 92 | 97 | ||
| 93 | /// Writes `bytes` to `path` through a temporary file and a rename. The temporary name carries a fresh | 98 | /// Writes `bytes` to `path` through a temporary file and a rename. The temporary name carries a fresh |
| 94 | /// ULID, so two writers of the same photo never share one, and a rename never publishes a mix of two. | 99 | /// ULID, so two writers of the same photo never share one, and a rename never publishes a mix of two. |
| 100 | +/// The file is created with mode 0600. | ||
| 95 | async fn write_atomically(path: &Path, bytes: &[u8]) -> std::io::Result<()> { | 101 | async fn write_atomically(path: &Path, bytes: &[u8]) -> std::io::Result<()> { |
| 96 | let temporary = PathBuf::from(format!("{}.{}.tmp", path.display(), ulid::Ulid::generate())); | 102 | let temporary = PathBuf::from(format!("{}.{}.tmp", path.display(), ulid::Ulid::generate())); |
| 97 | - tokio::fs::write(&temporary, bytes).await?; | 103 | + let mut file = tokio::fs::OpenOptions::new() |
| 104 | + .write(true) | ||
| 105 | + .create_new(true) | ||
| 106 | + .mode(0o600) | ||
| 107 | + .open(&temporary) | ||
| 108 | + .await?; | ||
| 109 | + file.write_all(bytes).await?; | ||
| 98 | tokio::fs::rename(&temporary, path).await | 110 | tokio::fs::rename(&temporary, path).await |
| 99 | } | 111 | } |
| 100 | 112 | ||
| @@ -116,7 +128,7 @@ async fn fetch_photo( | |||
| 116 | let response = match oidc.http().get(url).bearer_auth(token).send().await { | 128 | let response = match oidc.http().get(url).bearer_auth(token).send().await { |
| 117 | Ok(response) => response, | 129 | Ok(response) => response, |
| 118 | Err(error) => { | 130 | Err(error) => { |
| 119 | - tracing::warn!(error = %error, "photo: im could not be reached"); | 131 | + tracing::warn!(error = %error.without_url(), "photo: im could not be reached"); |
| 120 | return Err(unavailable()); | 132 | return Err(unavailable()); |
| 121 | } | 133 | } |
| 122 | }; | 134 | }; |
| @@ -150,7 +162,7 @@ async fn fetch_photo( | |||
| 150 | Ok(Some(bytes)) => bytes, | 162 | Ok(Some(bytes)) => bytes, |
| 151 | Ok(None) => return Ok(None), | 163 | Ok(None) => return Ok(None), |
| 152 | Err(error) => { | 164 | Err(error) => { |
| 153 | - tracing::warn!(error = %error, "photo: the body could not be read"); | 165 | + tracing::warn!(error = %error.without_url(), "photo: the body could not be read"); |
| 154 | return Err(unavailable()); | 166 | return Err(unavailable()); |
| 155 | } | 167 | } |
| 156 | }; | 168 | }; |
crates/in-web/src/pages/public_share.rsmodified+13 -2
| @@ -14,11 +14,13 @@ | |||
| 14 | //! No session is read here and no member's details are shown. The pages send `Referrer-Policy: no-referrer` | 14 | //! No session is read here and no member's details are shown. The pages send `Referrer-Policy: no-referrer` |
| 15 | //! and `X-Robots-Tag: noindex` (set in `security.rs`), and `Cache-Control: no-store`. | 15 | //! and `X-Robots-Tag: noindex` (set in `security.rs`), and `Cache-Control: no-store`. |
| 16 | 16 | ||
| 17 | +use std::fmt; | ||
| 18 | + | ||
| 17 | use http::HeaderValue; | 19 | use http::HeaderValue; |
| 18 | use http::header::CACHE_CONTROL; | 20 | use http::header::CACHE_CONTROL; |
| 19 | use in_core::authz::{Action, Actor, Grant, Target, authorize}; | 21 | use in_core::authz::{Action, Actor, Grant, Target, authorize}; |
| 20 | use in_core::password::verify_password_async; | 22 | use in_core::password::verify_password_async; |
| 21 | -use in_core::secret::unlock_proof; | 23 | +use in_core::secret::{Redacted, unlock_proof}; |
| 22 | use in_core::store::files::File; | 24 | use in_core::store::files::File; |
| 23 | use in_core::store::files::thumb_blob_key; | 25 | use in_core::store::files::thumb_blob_key; |
| 24 | use in_core::store::folders::{Folder, Listing}; | 26 | use in_core::store::folders::{Folder, Listing}; |
| @@ -165,7 +167,7 @@ pub struct PublicQuery { | |||
| 165 | } | 167 | } |
| 166 | 168 | ||
| 167 | /// The form of the password gate. | 169 | /// The form of the password gate. |
| 168 | -#[derive(Debug, Default, Deserialize)] | 170 | +#[derive(Default, Deserialize)] |
| 169 | #[serde(default)] | 171 | #[serde(default)] |
| 170 | pub struct GateForm { | 172 | pub struct GateForm { |
| 171 | /// The CSRF token that the gate cookie must match. | 173 | /// The CSRF token that the gate cookie must match. |
| @@ -174,6 +176,15 @@ pub struct GateForm { | |||
| 174 | pub password: String, | 176 | pub password: String, |
| 175 | } | 177 | } |
| 176 | 178 | ||
| 179 | +impl fmt::Debug for GateForm { | ||
| 180 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 181 | + f.debug_struct("GateForm") | ||
| 182 | + .field("csrf", &self.csrf) | ||
| 183 | + .field("password", &Redacted) | ||
| 184 | + .finish() | ||
| 185 | + } | ||
| 186 | +} | ||
| 187 | + | ||
| 177 | /// A folder listing inside a folder link: its breadcrumbs, its current folder, and what it holds. | 188 | /// A folder listing inside a folder link: its breadcrumbs, its current folder, and what it holds. |
| 178 | pub struct FolderPanel { | 189 | pub struct FolderPanel { |
| 179 | /// The folders from the link's root down to the current one. | 190 | /// The folders from the link's root down to the current one. |
crates/in-web/src/pages/sign_in.rsmodified+34 -3
| @@ -6,6 +6,7 @@ | |||
| 6 | //! on every outcome, so it is single use. After the callback the local session is created (section 2.4). | 6 | //! on every outcome, so it is single use. After the callback the local session is created (section 2.4). |
| 7 | //! Failures redirect to the problem page with a fixed reason word; no text from the request is reflected. | 7 | //! Failures redirect to the problem page with a fixed reason word; no text from the request is reflected. |
| 8 | 8 | ||
| 9 | +use std::fmt; | ||
| 9 | use std::sync::Arc; | 10 | use std::sync::Arc; |
| 10 | use std::time::Duration; | 11 | use std::time::Duration; |
| 11 | 12 | ||
| @@ -54,7 +55,7 @@ struct LoginQuery { | |||
| 54 | } | 55 | } |
| 55 | 56 | ||
| 56 | /// The query of `/auth/callback`, as `im` sends it. Only the fields `in` reads are named. | 57 | /// The query of `/auth/callback`, as `im` sends it. Only the fields `in` reads are named. |
| 57 | -#[derive(Debug, Default, Deserialize)] | 58 | +#[derive(Default, Deserialize)] |
| 58 | #[serde(default)] | 59 | #[serde(default)] |
| 59 | struct CallbackQuery { | 60 | struct CallbackQuery { |
| 60 | code: String, | 61 | code: String, |
| @@ -62,15 +63,33 @@ struct CallbackQuery { | |||
| 62 | error: String, | 63 | error: String, |
| 63 | } | 64 | } |
| 64 | 65 | ||
| 66 | +impl fmt::Debug for CallbackQuery { | ||
| 67 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 68 | + f.debug_struct("CallbackQuery") | ||
| 69 | + .field("code", &secret::Redacted) | ||
| 70 | + .field("state", &secret::Redacted) | ||
| 71 | + .field("error", &self.error) | ||
| 72 | + .finish() | ||
| 73 | + } | ||
| 74 | +} | ||
| 75 | + | ||
| 65 | /// The form of `/auth/logout`: the CSRF token of the session. | 76 | /// The form of `/auth/logout`: the CSRF token of the session. |
| 66 | -#[derive(Debug, Default, Deserialize)] | 77 | +#[derive(Default, Deserialize)] |
| 67 | #[serde(default)] | 78 | #[serde(default)] |
| 68 | struct LogoutForm { | 79 | struct LogoutForm { |
| 69 | csrf: String, | 80 | csrf: String, |
| 70 | } | 81 | } |
| 71 | 82 | ||
| 83 | +impl fmt::Debug for LogoutForm { | ||
| 84 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 85 | + f.debug_struct("LogoutForm") | ||
| 86 | + .field("csrf", &secret::Redacted) | ||
| 87 | + .finish() | ||
| 88 | + } | ||
| 89 | +} | ||
| 90 | + | ||
| 72 | /// The sealed content of the flight cookie. | 91 | /// The sealed content of the flight cookie. |
| 73 | -#[derive(Debug, Serialize, Deserialize)] | 92 | +#[derive(Serialize, Deserialize)] |
| 74 | struct Flight { | 93 | struct Flight { |
| 75 | state: String, | 94 | state: String, |
| 76 | nonce: String, | 95 | nonce: String, |
| @@ -80,6 +99,18 @@ struct Flight { | |||
| 80 | expires_at: i64, | 99 | expires_at: i64, |
| 81 | } | 100 | } |
| 82 | 101 | ||
| 102 | +impl fmt::Debug for Flight { | ||
| 103 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 104 | + f.debug_struct("Flight") | ||
| 105 | + .field("state", &secret::Redacted) | ||
| 106 | + .field("nonce", &secret::Redacted) | ||
| 107 | + .field("verifier", &secret::Redacted) | ||
| 108 | + .field("next", &self.next) | ||
| 109 | + .field("expires_at", &self.expires_at) | ||
| 110 | + .finish() | ||
| 111 | + } | ||
| 112 | +} | ||
| 113 | + | ||
| 83 | /// Redirects to the problem page with one of the fixed reason words. | 114 | /// Redirects to the problem page with one of the fixed reason words. |
| 84 | fn problem(reason: &str) -> SeeOther { | 115 | fn problem(reason: &str) -> SeeOther { |
| 85 | see_other(format!("/sign-in/problem?reason={reason}")) | 116 | see_other(format!("/sign-in/problem?reason={reason}")) |
crates/in-web/src/serve_bytes.rsmodified+2 -1
| @@ -56,7 +56,8 @@ pub struct ByteSource<'a> { | |||
| 56 | /// is checked against it while it streams (see [`check_digest`]). `None` for derived bytes such as | 56 | /// is checked against it while it streams (see [`check_digest`]). `None` for derived bytes such as |
| 57 | /// thumbnails, whose validator is not the hash of what is stored. | 57 | /// thumbnails, whose validator is not the hash of what is stored. |
| 58 | pub content_sha256: Option<&'a str>, | 58 | pub content_sha256: Option<&'a str>, |
| 59 | - /// The sniffed MIME type, as stored. It is never the uploader's claim. | 59 | + /// The MIME type, as stored. For a file uploaded through the drive it is the sniffed type, never the |
| 60 | + /// uploader's claim. For the objects API it is the calling service's claim, which is not sniffed. | ||
| 60 | pub mime: &'a str, | 61 | pub mime: &'a str, |
| 61 | /// The display name, used for the `Content-Disposition` file name. | 62 | /// The display name, used for the `Content-Disposition` file name. |
| 62 | pub name: &'a str, | 63 | pub name: &'a str, |
docs/architecture.mdmodified+4 -3
| @@ -163,8 +163,9 @@ The sweeper removes unreferenced blobs older than 24 h. | |||
| 163 | Per contracts.md 2: `/auth/login?next=` builds the flight cookie and redirects to `im`; `/auth/callback` | 163 | Per contracts.md 2: `/auth/login?next=` builds the flight cookie and redirects to `im`; `/auth/callback` |
| 164 | validates state, exchanges the code (client_secret_basic), validates the ID token, upserts the member from its | 164 | validates state, exchanges the code (client_secret_basic), validates the ID token, upserts the member from its |
| 165 | claims (so a person can use `in` before the directory stream catches up), creates a local session (12 h), and | 165 | claims (so a person can use `in` before the directory stream catches up), creates a local session (12 h), and |
| 166 | -redirects to `next`. The client secret is read from `data_dir/oidc_client_secret` (0600) or the | 166 | +redirects to `next`. The client secret is read from the file named by `client_secret_file` (0600), never |
| 167 | -`IN_OIDC_CLIENT_SECRET` environment variable, never from the TOML. A member with `disabled` set cannot sign in | 167 | +from the TOML. A secret file, and every S3 credential file, |
| 168 | +that group or world can read is refused at boot (`secret::check_private`). A member with `disabled` set cannot sign in | ||
| 168 | and has no sessions. | 169 | and has no sessions. |
| 169 | 170 | ||
| 170 | --- | 171 | --- |
| @@ -270,7 +271,7 @@ credentials (S3 secret sealed) are Restart settings. | |||
| 270 | 271 | ||
| 271 | A bare `in` (or `in serve`) runs the server. Backups are written by the server's backup worker. | 272 | A bare `in` (or `in serve`) runs the server. Backups are written by the server's backup worker. |
| 272 | `in restore --from SET` replaces the database with a verified set (server stopped; needs the same `in.key`). | 273 | `in restore --from SET` replaces the database with a verified set (server stopped; needs the same `in.key`). |
| 273 | -`in export --member <sub|email> --out DIR` writes a plain tree with real names. `in fsck [--hash] [--quarantine]` | 274 | +`in export --member <sub|email> --out DIR` writes a plain tree with real names (folders 0700, files 0600). `in fsck [--hash] [--quarantine]` |
| 274 | checks that every row has its blob and every blob has a row (sizes, and hashes with `--hash`); it changes nothing, | 275 | checks that every row has its blob and every blob has a row (sizes, and hashes with `--hash`); it changes nothing, |
| 275 | except that `--quarantine` moves orphan blobs over an hour old into `data_dir/quarantine/` (never deletes). | 276 | except that `--quarantine` moves orphan blobs over an hour old into `data_dir/quarantine/` (never deletes). |
| 276 | `in quota recompute` recomputes used bytes. | 277 | `in quota recompute` recomputes used bytes. |