diff --git a/crates/in-core/migrations/0003_objects_shared_blobs.sql b/crates/in-core/migrations/0003_objects_shared_blobs.sql new file mode 100644 index 0000000..b245891 --- /dev/null +++ b/crates/in-core/migrations/0003_objects_shared_blobs.sql @@ -0,0 +1,26 @@ +-- 0003: lets objects of one service share a blob. The blob key is now `objects//`, so two +-- objects with the same bytes name the same key, and the key is no longer unique. The table is rebuilt +-- because SQLite cannot drop a UNIQUE constraint in place. The CHECK keeps the key tied to its service and +-- hash, so no row can name a blob of another service. + +CREATE TABLE objects_new ( + service TEXT NOT NULL REFERENCES services (key) ON DELETE RESTRICT, + external_id TEXT NOT NULL, + size INTEGER NOT NULL CHECK (size >= 0), + sha256 TEXT NOT NULL CHECK (length(sha256) = 64), + content_type TEXT NOT NULL, + name TEXT, + blob_key TEXT NOT NULL CHECK (blob_key = 'objects/' || service || '/' || sha256), + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + PRIMARY KEY (service, external_id) +); + +INSERT INTO objects_new (service, external_id, size, sha256, content_type, name, blob_key, created_at, updated_at) + SELECT service, external_id, size, sha256, content_type, name, blob_key, created_at, updated_at FROM objects; + +DROP TABLE objects; + +ALTER TABLE objects_new RENAME TO objects; + +CREATE INDEX objects_blob_key ON objects (blob_key); diff --git a/crates/in-core/src/store/migrate.rs b/crates/in-core/src/store/migrate.rs index 41626c8..c4c5809 100644 --- a/crates/in-core/src/store/migrate.rs +++ b/crates/in-core/src/store/migrate.rs @@ -15,6 +15,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ 2, include_str!("../../migrations/0002_session_id_token.sql"), ), + ( + 3, + include_str!("../../migrations/0003_objects_shared_blobs.sql"), + ), ]; fn migration_err(e: turso::Error) -> Error { diff --git a/crates/in-core/src/store/mod.rs b/crates/in-core/src/store/mod.rs index 43db051..c647599 100644 --- a/crates/in-core/src/store/mod.rs +++ b/crates/in-core/src/store/mod.rs @@ -9,6 +9,7 @@ pub mod folders; pub mod links; pub mod members; pub mod migrate; +pub mod objects; pub mod sessions; pub mod settings; pub mod shares; @@ -51,6 +52,8 @@ struct Inner { readers: Vec>, /// Round-robin start index for [`Store::read_conn`]. next_reader: AtomicUsize, + /// Orders blob writes against blob removal for the object store (`objects.rs`). + blobs: objects::BlobGate, } impl Store { @@ -78,6 +81,7 @@ impl Store { conn: Mutex::new(conn), readers, next_reader: AtomicUsize::new(0), + blobs: objects::BlobGate::default(), }), }) } diff --git a/crates/in-core/src/store/objects.rs b/crates/in-core/src/store/objects.rs new file mode 100644 index 0000000..dc8ed38 --- /dev/null +++ b/crates/in-core/src/store/objects.rs @@ -0,0 +1,628 @@ +//! The object store's rows (contracts.md 5): services, which are namespaces with a quota, and the objects +//! each service keeps under its own ids. +//! +//! Namespace: every function takes the service key from the caller's verified token (`svc`). Nothing a +//! request says picks the namespace, so the same `external_id` in two services is two rows. +//! +//! Blobs: an object's bytes live at `objects//`, so objects of one service with the same +//! bytes share one blob. A blob is removed only by [`Store::retire_blob`], and only when no row names it +//! and no write is in the middle of storing it. [`Store::hold_blob`] is that write's claim on the key, taken +//! before the bytes are put and released after the row commits. +//! +//! Quota: `services.used_bytes` is the sum of the sizes of the service's objects. A put checks the new total +//! inside its write transaction, which the single writer serialises, so two parallel puts cannot both pass. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex as StdMutex, PoisonError}; + +use turso::{Connection, Row}; + +use crate::blob::BlobStore; +use crate::error::{Error, Result}; +use crate::store::{ + Inner, Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, + missing_row, +}; +use crate::time::now_stamp; + +/// Quota of a service that has none yet: 10 GiB. Used when a service first makes an authorised call. +pub const DEFAULT_SERVICE_QUOTA: i64 = 10 * 1024 * 1024 * 1024; + +/// The settings key of the quota a new service gets. It is read when the service row is created. +pub const SERVICE_QUOTA_SETTING: &str = "default_service_quota_bytes"; + +/// Longest `external_id` the contracts allow. +pub const MAX_EXTERNAL_ID: usize = 128; + +/// Checks an `external_id` against contracts.md 5: 1 to 128 characters of `[A-Za-z0-9._-]`. The id is +/// never part of a path (blobs are named by hash), so the charset only has to keep ids printable and +/// unambiguous. +pub fn check_external_id(id: &str) -> Result<()> { + let allowed = id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')); + if id.is_empty() || id.len() > MAX_EXTERNAL_ID || !allowed { + return Err(Error::Invalid("bad_external_id".into())); + } + Ok(()) +} + +/// The blob key of an object's bytes: `objects//`. The hash is lower-case hex. +pub fn object_blob_key(service: &str, sha256: &str) -> String { + format!("objects/{service}/{sha256}") +} + +/// Column list for [`map_service`]. Keep the two in step. +const SERVICE_COLS: &str = "key, quota_bytes, used_bytes, created_at"; + +/// Column list for [`map_object`]. Keep the two in step. +const OBJECT_COLS: &str = + "service, external_id, size, sha256, content_type, name, blob_key, created_at, updated_at"; + +/// A service: a namespace of objects with its own quota. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Service { + /// The family key the token's `svc` named, such as `iz`. + pub key: String, + /// The most bytes the service may store. + pub quota_bytes: i64, + /// The bytes its objects use, counted once per object (shared blobs count twice). + pub used_bytes: i64, + /// When the service first made a call. + pub created_at: String, +} + +/// One object of a service. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Object { + /// The service that owns the object. + pub service: String, + /// The id the service chose. + pub external_id: String, + /// Length in bytes. + pub size: i64, + /// Lower-case hex SHA-256 of the bytes. + pub sha256: String, + /// The `Content-Type` the service sent, stored as given. + pub content_type: String, + /// The `X-Object-Name` the service sent, if any. + pub name: Option, + /// The blob that holds the bytes. + pub blob_key: String, + /// When the object was first stored. + pub created_at: String, + /// When the object was last replaced. + pub updated_at: String, +} + +/// A service's usage, as `GET /api/v1/usage` reports it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Usage { + /// The service quota. + pub quota_bytes: i64, + /// Bytes used by its objects. + pub used_bytes: i64, + /// Number of objects. + pub objects: i64, +} + +/// What a put stores. The bytes are already at `blob_key`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NewObject { + /// The namespace, from the verified token. + pub service: String, + /// The id the service chose. Already checked by [`check_external_id`]. + pub external_id: String, + /// Length in bytes. + pub size: i64, + /// Lower-case hex SHA-256 of the bytes. + pub sha256: String, + /// The stored `Content-Type`. + pub content_type: String, + /// The cleaned `X-Object-Name`, if any. + pub name: Option, + /// When true, a put over an existing object is refused (`If-None-Match: *`). + pub create_only: bool, +} + +/// What a put did. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PutOutcome { + /// The row is stored. `replaced_blob` is the blob the old bytes lived at, when that blob is not the new + /// one. The caller retires it with [`Store::retire_blob`]. + Stored { + /// The object as stored. Boxed, so the refusal variants stay small. + object: Box, + /// `true` when the id was new, `false` when an existing object was replaced. + created: bool, + /// The blob the replaced bytes used, when it differs from the new one. + replaced_blob: Option, + }, + /// The new total would exceed the service quota. Nothing changed. + QuotaExceeded, + /// `create_only` was set and the id is taken. Nothing changed. + Exists, +} + +/// The claim a write holds on a blob key between putting the bytes and committing the row. While it is +/// held, [`Store::retire_blob`] leaves the key alone. +pub struct BlobHold { + inner: Arc, + key: String, +} + +impl Drop for BlobHold { + fn drop(&mut self) { + let mut held = self + .inner + .blobs + .held + .lock() + .unwrap_or_else(PoisonError::into_inner); + if let Some(count) = held.get_mut(&self.key) { + *count -= 1; + if *count == 0 { + held.remove(&self.key); + } + } + } +} + +/// The gate that orders blob writes against blob removal. `retire` is held while a removal decides and +/// deletes, and while a write registers its claim, so a removal and a write of the same key never overlap. +/// `held` counts the open claims per key. Both are in-process, which is right for one `in` process. +#[derive(Default)] +pub(crate) struct BlobGate { + retire: tokio::sync::Mutex<()>, + held: StdMutex>, +} + +/// Column `i` of a row selected with [`SERVICE_COLS`]. +fn map_service(row: &Row) -> Result { + Ok(Service { + key: col_text(row, 0)?, + quota_bytes: col_int(row, 1)?, + used_bytes: col_int(row, 2)?, + created_at: col_text(row, 3)?, + }) +} + +/// Maps a row selected with [`OBJECT_COLS`]. +fn map_object(row: &Row) -> Result { + Ok(Object { + service: col_text(row, 0)?, + external_id: col_text(row, 1)?, + size: col_int(row, 2)?, + sha256: col_text(row, 3)?, + content_type: col_text(row, 4)?, + name: col_opt_text(row, 5)?, + blob_key: col_text(row, 6)?, + created_at: col_text(row, 7)?, + updated_at: col_text(row, 8)?, + }) +} + +/// A service row by key. +async fn service_row(conn: &Connection, key: &str) -> Result> { + fetch_opt( + conn, + &format!("SELECT {SERVICE_COLS} FROM services WHERE key = ?1"), + (key.to_owned(),), + map_service, + ) + .await +} + +/// An object of a service by its id. Another service's id finds nothing. +async fn object_row(conn: &Connection, service: &str, id: &str) -> Result> { + fetch_opt( + conn, + &format!("SELECT {OBJECT_COLS} FROM objects WHERE service = ?1 AND external_id = ?2"), + (service.to_owned(), id.to_owned()), + map_object, + ) + .await +} + +impl Store { + /// The service with this key, if it has made a call before. + pub async fn service(&self, key: &str) -> Result> { + let conn = self.read_conn().await; + service_row(&conn, key).await + } + + /// Every service, by key. For the admin page. + pub async fn services(&self) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!("SELECT {SERVICE_COLS} FROM services ORDER BY key"), + (), + map_service, + ) + .await + } + + /// The service with this key, created with `default_quota` when it is new. Called on every + /// authorised machine call, so the common case is a read. + pub async fn ensure_service(&self, key: &str, default_quota: i64) -> Result { + if let Some(service) = self.service(key).await? { + return Ok(service); + } + { + let conn = self.inner.conn.lock().await; + // `OR IGNORE` keeps a concurrent first call from failing on the primary key. + conn.execute( + "INSERT OR IGNORE INTO services (key, quota_bytes, used_bytes, created_at) \ + VALUES (?1, ?2, 0, ?3)", + (key.to_owned(), default_quota, now_stamp()), + ) + .await + .map_err(db_err)?; + } + self.service(key).await?.ok_or_else(missing_row) + } + + /// The usage of a service: quota, bytes used and the object count. A service that does not exist has + /// none, so the answer is `NotFound`. + pub async fn service_usage(&self, service: &str) -> Result { + let conn = self.read_conn().await; + let row = service_row(&conn, service).await?.ok_or(Error::NotFound)?; + let objects = fetch_opt( + &conn, + "SELECT COUNT(*) FROM objects WHERE service = ?1", + (service.to_owned(),), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + Ok(Usage { + quota_bytes: row.quota_bytes, + used_bytes: row.used_bytes, + objects, + }) + } + + /// An object of `service` by its id, or `None`. + pub async fn service_object(&self, service: &str, id: &str) -> Result> { + let conn = self.read_conn().await; + object_row(&conn, service, id).await + } + + /// Stores an object row, replacing the object with the same id in the same service. In one + /// transaction: the new total must fit the quota (the old object's bytes are given back first), the row + /// is inserted or updated, and `used_bytes` is moved by the difference. A replace keeps the original + /// `created_at`. + /// + /// The bytes must already be at the blob key of `new.sha256`. The old bytes are not removed here: the + /// caller retires `replaced_blob` after this returns. + pub async fn put_object(&self, new: NewObject) -> Result { + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let service = service_row(&tx, &new.service) + .await? + .ok_or(Error::NotFound)?; + let old = object_row(&tx, &new.service, &new.external_id).await?; + if new.create_only && old.is_some() { + return Ok(PutOutcome::Exists); + } + let old_size = old.as_ref().map_or(0, |object| object.size); + let used_after = service.used_bytes - old_size + new.size; + if used_after > service.quota_bytes { + return Ok(PutOutcome::QuotaExceeded); + } + let blob_key = object_blob_key(&new.service, &new.sha256); + let created = old.is_none(); + let created_at = old + .as_ref() + .map_or_else(|| now.clone(), |object| object.created_at.clone()); + if created { + tx.execute( + "INSERT INTO objects (service, external_id, size, sha256, content_type, name, \ + blob_key, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", + ( + new.service.clone(), + new.external_id.clone(), + new.size, + new.sha256.clone(), + new.content_type.clone(), + new.name.clone(), + blob_key.clone(), + created_at, + now.clone(), + ), + ) + .await + .map_err(db_err)?; + } else { + tx.execute( + "UPDATE objects SET size = ?3, sha256 = ?4, content_type = ?5, name = ?6, \ + blob_key = ?7, updated_at = ?8 WHERE service = ?1 AND external_id = ?2", + ( + new.service.clone(), + new.external_id.clone(), + new.size, + new.sha256.clone(), + new.content_type.clone(), + new.name.clone(), + blob_key.clone(), + now.clone(), + ), + ) + .await + .map_err(db_err)?; + } + tx.execute( + "UPDATE services SET used_bytes = ?2 WHERE key = ?1", + (new.service.clone(), used_after), + ) + .await + .map_err(db_err)?; + let object = object_row(&tx, &new.service, &new.external_id) + .await? + .ok_or_else(missing_row)?; + let replaced_blob = old + .map(|object| object.blob_key) + .filter(|key| *key != blob_key); + Ok(PutOutcome::Stored { + object: Box::new(object), + created, + replaced_blob, + }) + } + .await; + finish(tx, outcome).await + } + + /// Removes an object of `service` and gives its bytes back to the quota. Returns the removed row, so the + /// caller can retire its blob, or `None` when there was no such object (the caller still answers `204`). + pub async fn delete_object(&self, service: &str, id: &str) -> Result> { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result> = async { + let Some(old) = object_row(&tx, service, id).await? else { + return Ok(None); + }; + tx.execute( + "DELETE FROM objects WHERE service = ?1 AND external_id = ?2", + (service.to_owned(), id.to_owned()), + ) + .await + .map_err(db_err)?; + tx.execute( + "UPDATE services SET used_bytes = used_bytes - ?2 WHERE key = ?1", + (service.to_owned(), old.size), + ) + .await + .map_err(db_err)?; + Ok(Some(old)) + } + .await; + finish(tx, outcome).await + } + + /// Claims `key` for a write that is about to put bytes there. Waits for any removal in progress, so + /// the bytes cannot be removed between the put and the row. The claim lasts until the returned guard is + /// dropped, which the caller does once the row has committed (or the write has been refused). + pub async fn hold_blob(&self, key: &str) -> BlobHold { + let _gate = self.inner.blobs.retire.lock().await; + let mut held = self + .inner + .blobs + .held + .lock() + .unwrap_or_else(PoisonError::into_inner); + *held.entry(key.to_owned()).or_insert(0) += 1; + BlobHold { + inner: Arc::clone(&self.inner), + key: key.to_owned(), + } + } + + /// Removes the blob at `key` when it is safe: no open claim holds it and no row names it. Returns + /// `true` when the blob was deleted. `false` means it is still in use, or in the middle of a write; the + /// sweeper finds it later if it is still unreferenced. + pub async fn retire_blob(&self, key: &str, blobs: &dyn BlobStore) -> Result { + let _gate = self.inner.blobs.retire.lock().await; + let claimed = self + .inner + .blobs + .held + .lock() + .unwrap_or_else(PoisonError::into_inner) + .contains_key(key); + if claimed || self.blob_is_named(key).await? { + return Ok(false); + } + blobs.delete(key).await?; + Ok(true) + } + + /// Whether an object row names this blob key. + async fn blob_is_named(&self, key: &str) -> Result { + let conn = self.read_conn().await; + Ok(fetch_opt( + &conn, + "SELECT 1 FROM objects WHERE blob_key = ?1 LIMIT 1", + (key.to_owned(),), + |_| Ok(()), + ) + .await? + .is_some()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::blob::local::LocalBlobs; + use crate::staging::StagedFile; + + const SERVICE: &str = "iz"; + const OTHER: &str = "im"; + + /// A store with two services (`iz` and `im`) at `quota`, and a blob tree in the same temp dir. + async fn setup(quota: i64) -> (tempfile::TempDir, Store, LocalBlobs) { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("in.db")).await.unwrap(); + store.ensure_service(SERVICE, quota).await.unwrap(); + store.ensure_service(OTHER, quota).await.unwrap(); + let blobs = LocalBlobs::new(dir.path().join("blobs")).unwrap(); + (dir, store, blobs) + } + + /// Stages `bytes`, puts them at their hash key as the API does, and returns the row input for them. + async fn stage( + dir: &tempfile::TempDir, + blobs: &LocalBlobs, + service: &str, + id: &str, + bytes: &[u8], + ) -> NewObject { + let mut staged = StagedFile::create(dir.path(), 1 << 20).await.unwrap(); + staged.write(bytes).await.unwrap(); + let staged = staged.finish().await.unwrap(); + let key = object_blob_key(service, &staged.sha256); + blobs.put_file(&key, &staged.path).await.unwrap(); + NewObject { + service: service.into(), + external_id: id.into(), + size: staged.size as i64, + sha256: staged.sha256, + content_type: "application/octet-stream".into(), + name: None, + create_only: false, + } + } + + #[test] + fn external_ids_follow_the_contract_charset_and_length() { + assert!(check_external_id("task-1_a.b").is_ok()); + assert!(check_external_id(&"a".repeat(128)).is_ok()); + for bad in ["", "../x", "a/b", "a b", "ü", &"a".repeat(129)] { + assert!(check_external_id(bad).is_err(), "{bad:?}"); + } + } + + /// The same id in two services is two objects, each with its own bytes. + #[tokio::test] + async fn the_same_id_in_two_services_is_two_objects() { + let (dir, store, blobs) = setup(1 << 20).await; + let a = stage(&dir, &blobs, SERVICE, "same", b"alpha").await; + let b = stage(&dir, &blobs, OTHER, "same", b"beta!!").await; + store.put_object(a).await.unwrap(); + store.put_object(b).await.unwrap(); + let mine = store + .service_object(SERVICE, "same") + .await + .unwrap() + .unwrap(); + let theirs = store.service_object(OTHER, "same").await.unwrap().unwrap(); + assert_eq!(mine.size, 5); + assert_eq!(theirs.size, 6); + assert!( + store + .service_object(SERVICE, "missing") + .await + .unwrap() + .is_none() + ); + } + + /// A replace keeps one row, moves the quota by the difference, and names the old blob for retiring. + /// Retiring it removes the old bytes, because nothing else names them. + #[tokio::test] + async fn a_replace_keeps_one_row_and_the_old_bytes_go_when_unreferenced() { + let (dir, store, blobs) = setup(1 << 20).await; + let first = stage(&dir, &blobs, SERVICE, "doc", b"first version").await; + let old_key = object_blob_key(SERVICE, &first.sha256); + store.put_object(first).await.unwrap(); + + let second = stage(&dir, &blobs, SERVICE, "doc", b"second").await; + let new_key = object_blob_key(SERVICE, &second.sha256); + let PutOutcome::Stored { + created, + replaced_blob, + .. + } = store.put_object(second).await.unwrap() + else { + panic!("the replace must be stored"); + }; + assert!(!created); + assert_eq!(replaced_blob.as_deref(), Some(old_key.as_str())); + assert!(store.retire_blob(&old_key, &blobs).await.unwrap()); + + let usage = store.service_usage(SERVICE).await.unwrap(); + assert_eq!(usage.objects, 1); + assert_eq!(usage.used_bytes, 6); + assert_eq!(blobs.size(&old_key).await.unwrap(), None); + assert_eq!(blobs.size(&new_key).await.unwrap(), Some(6)); + } + + /// Two objects with the same bytes share one blob. Deleting one keeps the bytes for the other. + #[tokio::test] + async fn identical_content_shares_a_blob_until_the_last_object_goes() { + let (dir, store, blobs) = setup(1 << 20).await; + let a = stage(&dir, &blobs, SERVICE, "a", b"same bytes").await; + let b = stage(&dir, &blobs, SERVICE, "b", b"same bytes").await; + let key = object_blob_key(SERVICE, &a.sha256); + store.put_object(a).await.unwrap(); + store.put_object(b).await.unwrap(); + + let removed = store.delete_object(SERVICE, "a").await.unwrap().unwrap(); + assert_eq!(removed.blob_key, key); + assert!(!store.retire_blob(&key, &blobs).await.unwrap()); + assert_eq!(blobs.size(&key).await.unwrap(), Some(10)); + assert!(store.service_object(SERVICE, "b").await.unwrap().is_some()); + + store.delete_object(SERVICE, "b").await.unwrap(); + assert!(store.retire_blob(&key, &blobs).await.unwrap()); + assert_eq!(blobs.size(&key).await.unwrap(), None); + assert_eq!(store.service_usage(SERVICE).await.unwrap().used_bytes, 0); + } + + /// A put that would pass the quota is refused and changes nothing. A replace gives back its old size + /// first, so it may grow only as far as the quota allows. + #[tokio::test] + async fn the_quota_is_checked_inside_the_write() { + let (dir, store, blobs) = setup(10).await; + store + .put_object(stage(&dir, &blobs, SERVICE, "one", b"123456").await) + .await + .unwrap(); + let outcome = store + .put_object(stage(&dir, &blobs, SERVICE, "two", b"12345").await) + .await + .unwrap(); + assert_eq!(outcome, PutOutcome::QuotaExceeded); + assert!( + store + .service_object(SERVICE, "two") + .await + .unwrap() + .is_none() + ); + assert_eq!(store.service_usage(SERVICE).await.unwrap().used_bytes, 6); + + let grow = store + .put_object(stage(&dir, &blobs, SERVICE, "one", b"1234567890").await) + .await + .unwrap(); + assert!(matches!(grow, PutOutcome::Stored { created: false, .. })); + assert_eq!(store.service_usage(SERVICE).await.unwrap().used_bytes, 10); + } + + /// A blob that a write holds is not removed, even when no row names it yet. + #[tokio::test] + async fn a_held_blob_is_not_retired() { + let (dir, store, blobs) = setup(1 << 20).await; + let object = stage(&dir, &blobs, SERVICE, "x", b"pending").await; + let key = object_blob_key(SERVICE, &object.sha256); + let hold = store.hold_blob(&key).await; + assert!(!store.retire_blob(&key, &blobs).await.unwrap()); + drop(hold); + assert!(store.retire_blob(&key, &blobs).await.unwrap()); + } +} diff --git a/crates/in-web/src/api/machine_auth.rs b/crates/in-web/src/api/machine_auth.rs new file mode 100644 index 0000000..27f6337 --- /dev/null +++ b/crates/in-web/src/api/machine_auth.rs @@ -0,0 +1,213 @@ +//! Machine authentication of the object API (contracts.md 2.6 and 5). A family service calls `in` with an +//! access token that `im` issued through the client-credentials grant. This module decides whether that +//! token may be used here, and names the caller's namespace. +//! +//! A call passes these checks, in this order, and each refusal is JSON with the status of contracts.md 7: +//! 1. The `Authorization: Bearer` token verifies against `im`'s keys (EdDSA, `iss`, `exp` with 60 s leeway, +//! `iat` at most 5 minutes ahead), and its `aud` is exactly `in`. Otherwise `401 invalid_token`. +//! 2. It is a client token: `sub` starts with `client:` and `svc` is present. A user's access token or an ID +//! token has neither, so it is `401 invalid_token`. +//! 3. Its scopes contain `files.service`. Otherwise `403 insufficient_scope`. +//! 4. `svc` is a family key (`im`, `in` or `iz`). Otherwise `403 insufficient_scope`. +//! +//! The namespace is `svc` from the verified token and nothing else. No URL segment and no header can +//! change it, so a service cannot reach another service's objects by sending its ids. +//! +//! When the call passes, the service row is created on first use with the default service quota +//! (architecture section 3), so a family service needs no registration. +//! +//! When `[oidc]` is not configured there is no key set to check against, so every machine call is +//! `503 unavailable`. Nothing is accepted without verification. + +use http::header::{AUTHORIZATION, CACHE_CONTROL, CONTENT_TYPE, WWW_AUTHENTICATE}; +use http::{HeaderValue, StatusCode}; +use in_core::store::objects::{DEFAULT_SERVICE_QUOTA, SERVICE_QUOTA_SETTING}; +use serde_json::{Value, json}; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::request::headers; +use topcoat::router::response::Response; +use topcoat::router::{Body, HeaderMap}; + +use crate::oidc::{FAMILY_KEY, FILES_SERVICE_SCOPE, OidcError}; +use crate::state::AppState; + +/// The family keys that may call the object API (contracts.md 1). `in` is listed so that the rule reads the +/// same as the table; it is not a caller in practice. +pub const FAMILY_KEYS: [&str; 3] = ["im", "in", "iz"]; + +/// The prefix of a client-credentials token's subject (contracts.md 2.6). +const CLIENT_SUBJECT_PREFIX: &str = "client:"; + +/// A verified caller of the object API. Only `service` is trusted; it comes from the verified `svc` claim. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Caller { + /// The caller's family key. It names the caller's namespace. + pub service: String, +} + +/// A refused call: the status and the stable error word of contracts.md 7, with an English message for logs. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Refusal { + /// HTTP status of the answer. + pub status: StatusCode, + /// The stable machine word, such as `invalid_token`. + pub error: &'static str, + /// English text for logs and developers. It may change. + pub message: &'static str, +} + +impl Refusal { + /// The JSON answer of this refusal, with `WWW-Authenticate` on `401`. + pub fn answer(&self) -> Response { + let mut response = json_response( + self.status, + &json!({ "error": self.error, "message": self.message }), + ); + if self.status == StatusCode::UNAUTHORIZED { + response.headers_mut().insert( + WWW_AUTHENTICATE, + HeaderValue::from_static("Bearer error=\"invalid_token\""), + ); + } + response + } +} + +/// A refusal shorthand. +const fn refuse(status: StatusCode, error: &'static str, message: &'static str) -> Refusal { + Refusal { + status, + error, + message, + } +} + +/// A JSON response of the object API. Answers are never cached. +pub fn json_response(status: StatusCode, value: &Value) -> Response { + let body = serde_json::to_vec(value).unwrap_or_default(); + let mut response = http::Response::new(Body::from(body)); + *response.status_mut() = status; + response + .headers_mut() + .insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); + response + .headers_mut() + .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); + response +} + +/// The bearer token of an `Authorization` header: the scheme is matched without regard to case, and the +/// token must be non-empty with no spaces. +pub fn bearer_token(headers: &HeaderMap) -> Option<&str> { + let value = headers.get(AUTHORIZATION)?.to_str().ok()?; + let (scheme, token) = value.split_once(' ')?; + if !scheme.eq_ignore_ascii_case("bearer") || token.is_empty() || token.contains(' ') { + return None; + } + Some(token) +} + +/// The default quota of a new service: the `default_service_quota_bytes` setting when it holds a positive +/// number, else [`DEFAULT_SERVICE_QUOTA`]. +async fn default_service_quota(state: &AppState) -> Result { + let setting = state.store.get_setting(SERVICE_QUOTA_SETTING).await?; + Ok(setting + .and_then(|text| text.trim().parse::().ok()) + .filter(|quota| *quota > 0) + .unwrap_or(DEFAULT_SERVICE_QUOTA)) +} + +/// Checks the bearer token of the request in `cx` and returns the caller, or the refusal to send. +/// +/// Errors that are not refusals (a database failure) are returned as `Err` and answered as `500` by the +/// router. +pub async fn machine_caller(cx: &Cx) -> Result> { + let state = app_context::(cx); + let Some(token) = bearer_token(headers(cx)) else { + return Ok(Err(refuse( + StatusCode::UNAUTHORIZED, + "invalid_token", + "a bearer token is required", + ))); + }; + let Some(oidc) = &state.oidc else { + return Ok(Err(refuse( + StatusCode::SERVICE_UNAVAILABLE, + "unavailable", + "the identity provider is not configured", + ))); + }; + let claims = match oidc.verify_machine_token(token, FAMILY_KEY).await { + Ok(claims) => claims, + Err(OidcError::Token(_)) => { + return Ok(Err(refuse( + StatusCode::UNAUTHORIZED, + "invalid_token", + "the token is not valid for this API", + ))); + } + Err(error) => { + tracing::warn!(error = %error, "machine auth: the keys could not be checked"); + return Ok(Err(refuse( + StatusCode::SERVICE_UNAVAILABLE, + "unavailable", + "the identity provider is unavailable", + ))); + } + }; + // A user's token or an ID token has no client subject and no `svc`, so it fails here, before any scope + // is read. + let Some(svc) = claims + .svc + .as_deref() + .filter(|_| claims.subject.starts_with(CLIENT_SUBJECT_PREFIX)) + else { + return Ok(Err(refuse( + StatusCode::UNAUTHORIZED, + "invalid_token", + "the token is not a service token", + ))); + }; + if !claims + .scopes + .iter() + .any(|scope| scope == FILES_SERVICE_SCOPE) + { + return Ok(Err(refuse( + StatusCode::FORBIDDEN, + "insufficient_scope", + "the token lacks the files.service scope", + ))); + } + if !FAMILY_KEYS.contains(&svc) { + return Ok(Err(refuse( + StatusCode::FORBIDDEN, + "insufficient_scope", + "the caller is not a family service", + ))); + } + let quota = default_service_quota(state).await?; + state.store.ensure_service(svc, quota).await?; + Ok(Ok(Caller { + service: svc.to_owned(), + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_bearer_scheme_is_case_blind_and_one_token_only() { + let mut headers = HeaderMap::new(); + headers.insert(AUTHORIZATION, HeaderValue::from_static("bearer abc.def")); + assert_eq!(bearer_token(&headers), Some("abc.def")); + headers.insert(AUTHORIZATION, HeaderValue::from_static("Basic abc")); + assert_eq!(bearer_token(&headers), None); + headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer a b")); + assert_eq!(bearer_token(&headers), None); + headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer ")); + assert_eq!(bearer_token(&headers), None); + } +} diff --git a/crates/in-web/src/api/mod.rs b/crates/in-web/src/api/mod.rs index f2339b6..dce174d 100644 --- a/crates/in-web/src/api/mod.rs +++ b/crates/in-web/src/api/mod.rs @@ -1,4 +1,7 @@ -//! The JSON APIs of the app: the chunked upload (`upload.rs`, architecture 4.2). The machine object API -//! comes later (contracts.md 5). Every route here answers JSON, including its refusals, and never -//! redirects to sign-in: a script that lost its session gets `401`. +//! The JSON APIs of the app: the chunked upload (`upload.rs`, architecture 4.2) and the machine object API +//! for family services (`objects.rs`, contracts.md 5), whose token check is `machine_auth.rs`. Every route +//! here answers JSON, including its refusals, and never redirects to sign-in: a script that lost its +//! session gets `401`. +pub mod machine_auth; +pub mod objects; pub mod upload; diff --git a/crates/in-web/src/api/objects.rs b/crates/in-web/src/api/objects.rs new file mode 100644 index 0000000..07e9ac3 --- /dev/null +++ b/crates/in-web/src/api/objects.rs @@ -0,0 +1,792 @@ +//! The object store API for family services (contracts.md 5). `iz` keeps its blobs here, under its own +//! namespace, with its own quota. Every route needs a client-credentials token with `aud = "in"` and scope +//! `files.service`, checked in `machine_auth.rs`; the namespace is the token's `svc` and nothing else. +//! +//! The routes: +//! - `PUT /api/v1/objects/{external_id}` stores the raw body. The bytes stream to a staged file while their +//! SHA-256 is computed. The body may not be longer than the quota that is left (the service quota, less +//! what the service uses, plus the bytes of the object being replaced), and the limit is enforced while it +//! is read, so nothing above it is stored. The bytes are put at `objects//`, and the row +//! is committed in the same step that moves the quota. A new id answers `201`, a replaced one `200`. +//! `If-None-Match: *` refuses an existing id with `409`. +//! - `GET` and `HEAD` send the bytes through `serve_bytes`, always as an attachment, with `Range` support. +//! The cache policy is `private, no-cache`, because a replace changes what the id names. +//! - `DELETE` removes the object. It answers `204` also when the object was already absent. +//! - `GET /api/v1/usage` answers the quota, the bytes used and the number of objects. +//! +//! Blob removal goes through `Store::retire_blob`, so bytes that another object still names, or that a +//! write is storing right now, are never removed. A removal that is refused is left to the sweeper. + +use futures_util::StreamExt; +use http::StatusCode; +use http::header::{CONTENT_LENGTH, CONTENT_TYPE, IF_NONE_MATCH}; +use in_core::error::Error as CoreError; +use in_core::names; +use in_core::staging::StagedFile; +use in_core::store::objects::{NewObject, Object, PutOutcome, check_external_id, object_blob_key}; +use serde_json::{Value, json}; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::request::headers; +use topcoat::router::response::Response; +use topcoat::router::{Body, HeaderMap, path_param_segment, route}; + +use crate::api::machine_auth::{Refusal, json_response, machine_caller}; +use crate::serve_bytes::{ByteSource, Disposition, SHARE_CACHE, serve_bytes_with}; +use crate::state::AppState; + +/// The `Content-Type` of an object whose PUT names none. +const DEFAULT_CONTENT_TYPE: &str = "application/octet-stream"; + +/// Longest `Content-Type` value kept, in bytes. +const MAX_CONTENT_TYPE_BYTES: usize = 255; + +/// Longest `X-Object-Name`, in bytes, after decoding. +const MAX_NAME_BYTES: usize = 255; + +/// The cache policy of object bytes: the id can be replaced at any time, so a cached copy must be checked. +const OBJECT_CACHE: &str = SHARE_CACHE; + +/// A `400` with the stable word `invalid_request`. +fn bad_request(message: &'static str) -> Refusal { + Refusal { + status: StatusCode::BAD_REQUEST, + error: "invalid_request", + message, + } +} + +/// The headers of a PUT that the handler reads before it touches the body. +#[derive(Debug, PartialEq, Eq)] +struct PutRequest { + /// The `Content-Length` the client declared, if any. Checked against the quota before a byte is read. + declared: Option, + /// The `Content-Type`, stored as given. + content_type: String, + /// The cleaned `X-Object-Name`, if one was sent. + name: Option, + /// `true` for `If-None-Match: *`: the PUT must create the id, not replace it. + create_only: bool, +} + +impl PutRequest { + /// Reads the PUT headers. Malformed ones are `400`, and nothing is stored. + fn from_headers(request: &HeaderMap) -> std::result::Result { + let declared = match request.get(CONTENT_LENGTH) { + None => None, + Some(value) => Some( + value + .to_str() + .ok() + .and_then(|text| text.parse::().ok()) + .ok_or_else(|| bad_request("Content-Length is not a number"))?, + ), + }; + let create_only = match request.get(IF_NONE_MATCH) { + None => false, + Some(value) if value.as_bytes() == b"*" => true, + Some(_) => return Err(bad_request("If-None-Match must be *")), + }; + Ok(Self { + declared, + content_type: content_type_of(request)?, + name: object_name(request)?, + create_only, + }) + } +} + +/// The stored `Content-Type`: the client's value when it is a `type/subtype` with printable ASCII, else +/// `application/octet-stream`. +fn content_type_of(request: &HeaderMap) -> std::result::Result { + let Some(value) = request.get(CONTENT_TYPE) else { + return Ok(DEFAULT_CONTENT_TYPE.to_owned()); + }; + let text = value + .to_str() + .map_err(|_| bad_request("Content-Type is not ASCII"))? + .trim(); + let essence = text.split(';').next().unwrap_or_default().trim(); + let well_formed = essence + .split_once('/') + .is_some_and(|(main, sub)| is_token(main) && is_token(sub)); + if !well_formed || text.len() > MAX_CONTENT_TYPE_BYTES { + return Err(bad_request("Content-Type must be type/subtype")); + } + Ok(text.to_owned()) +} + +/// Whether `text` is a non-empty HTTP token (RFC 9110 section 5.6.2). +fn is_token(text: &str) -> bool { + !text.is_empty() + && text + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)) +} + +/// The `X-Object-Name`: percent-encoded UTF-8, at most 255 bytes once decoded. It is cleaned like a file +/// name (`names::display_name`), so a path or control characters cannot reach a download header. +fn object_name(request: &HeaderMap) -> std::result::Result, Refusal> { + let Some(value) = request.get("x-object-name") else { + return Ok(None); + }; + let raw = value + .to_str() + .map_err(|_| bad_request("X-Object-Name is not ASCII"))?; + let decoded = + percent_decode(raw).ok_or_else(|| bad_request("X-Object-Name is not percent-encoded"))?; + if decoded.len() > MAX_NAME_BYTES { + return Err(bad_request("X-Object-Name is longer than 255 bytes")); + } + let text = String::from_utf8(decoded).map_err(|_| bad_request("X-Object-Name is not UTF-8"))?; + if text.trim().is_empty() { + return Ok(None); + } + Ok(Some(names::display_name(&text))) +} + +/// Decodes `%XX` escapes. Every other byte stands for itself, `+` included. `None` for a broken escape or +/// a decoded value that is not text. +fn percent_decode(raw: &str) -> Option> { + let bytes = raw.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' { + let hex = bytes.get(i + 1..i + 3)?; + let text = std::str::from_utf8(hex).ok()?; + out.push(u8::from_str_radix(text, 16).ok()?); + i += 3; + } else { + out.push(bytes[i]); + i += 1; + } + } + Some(out) +} + +/// The JSON of an object as the PUT answers it (contracts.md 5). +fn object_json(object: &Object) -> Value { + json!({ + "external_id": object.external_id, + "size": object.size, + "sha256": object.sha256, + "content_type": object.content_type, + "created_at": object.created_at, + }) +} + +/// An empty `204` with no cache. +fn no_content() -> Response { + let mut response = http::Response::new(Body::empty()); + *response.status_mut() = StatusCode::NO_CONTENT; + response +} + +/// Removes a blob that a write or a delete has released. A blob that cannot be removed now is logged and +/// left for the sweeper, because the row change has already committed. +async fn retire_quietly(state: &AppState, key: &str) { + if let Err(error) = state.store.retire_blob(key, state.blobs.as_ref()).await { + tracing::warn!(key = %key, error = %error, "objects: released blob not removed"); + } +} + +/// `PUT /api/v1/objects/{external_id}`: stores the body as the object `external_id` of the caller. +#[route(PUT "/api/v1/objects/{external_id}")] +async fn put_object(cx: &Cx, body: Body) -> Result { + let state = app_context::(cx); + let caller = match machine_caller(cx).await? { + Ok(caller) => caller, + Err(refusal) => return Ok(refusal.answer()), + }; + let external_id = path_param_segment(cx, "external_id").to_owned(); + if check_external_id(&external_id).is_err() { + return Ok( + bad_request("external_id must be 1 to 128 of A-Z, a-z, 0-9, '.', '_', '-'").answer(), + ); + } + let request = match PutRequest::from_headers(headers(cx)) { + Ok(request) => request, + Err(refusal) => return Ok(refusal.answer()), + }; + let service = caller.service; + let existing = state.store.service_object(&service, &external_id).await?; + if request.create_only && existing.is_some() { + return Ok(Refusal { + status: StatusCode::CONFLICT, + error: "conflict", + message: "an object with this external_id already exists", + } + .answer()); + } + let row = state + .store + .service(&service) + .await? + .ok_or(CoreError::NotFound)?; + // The object being replaced gives its bytes back first, so a replace may grow only as far as the quota + // allows. The same arithmetic is repeated inside the write transaction, which has the final say. + let replaced = existing.as_ref().map_or(0, |object| object.size); + let headroom = (row.quota_bytes - row.used_bytes + replaced).max(0) as u64; + let quota_refusal = Refusal { + status: StatusCode::PAYLOAD_TOO_LARGE, + error: "quota_exceeded", + message: "the service quota is used up", + }; + if request.declared.is_some_and(|length| length > headroom) { + return Ok(quota_refusal.answer()); + } + + let mut staged = StagedFile::create(&state.config.data_dir, headroom).await?; + let mut frames = body.into_data_stream(); + while let Some(frame) = frames.next().await { + let written = match frame { + Ok(bytes) => staged.write(&bytes).await, + Err(_) => { + staged.abort().await; + return Ok(bad_request("the request body could not be read").answer()); + } + }; + if let Err(error) = written { + staged.abort().await; + return match error { + CoreError::Invalid(_) => Ok(quota_refusal.answer()), + other => Err(other.into()), + }; + } + } + let staged = staged.finish().await?; + + // The claim is taken before the bytes are put, so a removal of the same blob cannot run in between. + let key = object_blob_key(&service, &staged.sha256); + let hold = state.store.hold_blob(&key).await; + if let Err(error) = state.blobs.put_file(&key, &staged.path).await { + drop(hold); + return Err(error.into()); + } + let outcome = state + .store + .put_object(NewObject { + service: service.clone(), + external_id: external_id.clone(), + size: staged.size as i64, + sha256: staged.sha256.clone(), + content_type: request.content_type, + name: request.name, + create_only: request.create_only, + }) + .await; + drop(hold); + match outcome? { + PutOutcome::Stored { + object, + created, + replaced_blob, + } => { + if let Some(old) = replaced_blob { + retire_quietly(state, &old).await; + } + let status = if created { + StatusCode::CREATED + } else { + StatusCode::OK + }; + Ok(json_response(status, &object_json(&object))) + } + PutOutcome::QuotaExceeded => { + retire_quietly(state, &key).await; + Ok(quota_refusal.answer()) + } + PutOutcome::Exists => { + retire_quietly(state, &key).await; + Ok(Refusal { + status: StatusCode::CONFLICT, + error: "conflict", + message: "an object with this external_id already exists", + } + .answer()) + } + } +} + +/// `GET /api/v1/objects/{external_id}` and `HEAD` (the router answers HEAD with this handler). +#[route(GET "/api/v1/objects/{external_id}")] +async fn get_object(cx: &Cx) -> Result { + let state = app_context::(cx); + let caller = match machine_caller(cx).await? { + Ok(caller) => caller, + Err(refusal) => return Ok(refusal.answer()), + }; + let external_id = path_param_segment(cx, "external_id").to_owned(); + if check_external_id(&external_id).is_err() { + return Ok( + bad_request("external_id must be 1 to 128 of A-Z, a-z, 0-9, '.', '_', '-'").answer(), + ); + } + let Some(object) = state + .store + .service_object(&caller.service, &external_id) + .await? + else { + return Ok(not_found().answer()); + }; + let name = object + .name + .clone() + .unwrap_or_else(|| object.external_id.clone()); + let source = ByteSource { + blob_key: &object.blob_key, + size: object.size as u64, + sha256: &object.sha256, + mime: &object.content_type, + name: &name, + }; + let (status, response_headers, body) = serve_bytes_with( + cx, + state.blobs.as_ref(), + &source, + Disposition::Attachment, + OBJECT_CACHE, + ) + .await?; + let mut response = http::Response::new(body); + *response.status_mut() = status; + *response.headers_mut() = response_headers; + Ok(response) +} + +/// The `404` of a missing object. The same answer for an id that another service holds, since namespaces +/// are separate. +fn not_found() -> Refusal { + Refusal { + status: StatusCode::NOT_FOUND, + error: "not_found", + message: "no such object", + } +} + +/// `DELETE /api/v1/objects/{external_id}`: removes the object, idempotently. +#[route(DELETE "/api/v1/objects/{external_id}")] +async fn delete_object(cx: &Cx) -> Result { + let state = app_context::(cx); + let caller = match machine_caller(cx).await? { + Ok(caller) => caller, + Err(refusal) => return Ok(refusal.answer()), + }; + let external_id = path_param_segment(cx, "external_id").to_owned(); + if check_external_id(&external_id).is_err() { + return Ok( + bad_request("external_id must be 1 to 128 of A-Z, a-z, 0-9, '.', '_', '-'").answer(), + ); + } + if let Some(removed) = state + .store + .delete_object(&caller.service, &external_id) + .await? + { + retire_quietly(state, &removed.blob_key).await; + } + Ok(no_content()) +} + +/// `PUT`, `GET` and `DELETE` on a path with more than one segment after `objects/`. The id cannot contain +/// `/`, so the answer is the contract's `400`, not a bare `404`. +#[route(PUT "/api/v1/objects/{external_id}/{rest}")] +async fn put_nested(cx: &Cx) -> Result { + nested_id(cx).await +} + +/// See [`put_nested`]. +#[route(GET "/api/v1/objects/{external_id}/{rest}")] +async fn get_nested(cx: &Cx) -> Result { + nested_id(cx).await +} + +/// See [`put_nested`]. +#[route(DELETE "/api/v1/objects/{external_id}/{rest}")] +async fn delete_nested(cx: &Cx) -> Result { + nested_id(cx).await +} + +/// The answer of a nested object path: authenticated callers get `400`, others get the token refusal. +async fn nested_id(cx: &Cx) -> Result { + if let Err(refusal) = machine_caller(cx).await? { + return Ok(refusal.answer()); + } + Ok(bad_request("external_id must not contain '/'").answer()) +} + +/// `GET /api/v1/usage`: the caller's quota, bytes used and object count. +#[route(GET "/api/v1/usage")] +async fn usage_report(cx: &Cx) -> Result { + let state = app_context::(cx); + let caller = match machine_caller(cx).await? { + Ok(caller) => caller, + Err(refusal) => return Ok(refusal.answer()), + }; + let usage = state.store.service_usage(&caller.service).await?; + Ok(json_response( + StatusCode::OK, + &json!({ + "quota_bytes": usage.quota_bytes, + "used_bytes": usage.used_bytes, + "objects": usage.objects, + }), + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use http::HeaderValue; + + #[test] + fn percent_decoding_takes_escapes_and_refuses_broken_ones() { + assert_eq!(percent_decode("a%20b+c").as_deref(), Some(&b"a b+c"[..])); + assert_eq!(percent_decode("%C3%BC").as_deref(), Some("ü".as_bytes())); + assert_eq!(percent_decode("%2"), None); + assert_eq!(percent_decode("%zz"), None); + } + + #[test] + fn content_type_must_be_a_media_type() { + let mut request = HeaderMap::new(); + request.insert( + CONTENT_TYPE, + HeaderValue::from_static("text/plain; charset=utf-8"), + ); + assert_eq!( + content_type_of(&request).unwrap(), + "text/plain; charset=utf-8" + ); + for bad in ["no-slash", "text/", "a b/c", "text/html\u{7f}"] { + let mut request = HeaderMap::new(); + if let Ok(value) = HeaderValue::from_str(bad) { + request.insert(CONTENT_TYPE, value); + assert!(content_type_of(&request).is_err(), "{bad:?}"); + } + } + assert_eq!( + content_type_of(&HeaderMap::new()).unwrap(), + DEFAULT_CONTENT_TYPE + ); + } + + #[test] + fn names_are_decoded_and_cleaned_like_file_names() { + let mut request = HeaderMap::new(); + request.insert( + "x-object-name", + HeaderValue::from_static("..%2F..%2Fetc%2Fpasswd"), + ); + assert_eq!(object_name(&request).unwrap().as_deref(), Some("passwd")); + request.insert("x-object-name", HeaderValue::from_static("%FF")); + assert!(object_name(&request).is_err()); + } +} + +#[cfg(test)] +mod router_tests { + //! Router-level tests of the object API: the token rules, the namespace, the id rules, the quota and + //! the replace and sharing of blobs. The keys are a fresh Ed25519 key injected into the JWKS cache, so + //! no request reaches `im`. + + use super::*; + use crate::boot::{router, test_state}; + use crate::oidc::OidcClient; + use crate::oidc::test_support::{CLIENT, ISSUER, sign, test_key}; + use crate::state::AppState; + use http::Request; + use http::header::{AUTHORIZATION, WWW_AUTHENTICATE}; + use in_core::store::objects::SERVICE_QUOTA_SETTING; + use serde_json::json; + use sha2::{Digest, Sha256}; + use topcoat::router::{Body, to_bytes}; + + /// A state with the object API's keys in place, and a fresh signing key for the test's tokens. + async fn setup() -> (tempfile::TempDir, AppState, Vec) { + let (dir, mut state) = test_state().await; + let (der, keys) = test_key(); + state.oidc = Some(std::sync::Arc::new(OidcClient::with_keys_for_tests( + ISSUER, CLIENT, keys, + ))); + (dir, state, der) + } + + /// A client token for `svc` with `scope` and `aud`. `sub` defaults to the client form. + fn machine_token(der: &[u8], svc: &str, scope: &str, aud: &str) -> String { + let now = crate::oidc::now_secs(); + sign( + der, + &json!({ + "iss": ISSUER, "sub": format!("client:{svc}"), "azp": svc, "aud": aud, + "scope": scope, "svc": svc, "iat": now, "exp": now + 600, "jti": "t-1", + }), + ) + } + + /// One call to the object API. Returns the status, the headers and the body bytes. + async fn call( + state: &AppState, + method: &str, + path: &str, + token: Option<&str>, + extra: &[(&str, &str)], + body: Vec, + ) -> (StatusCode, http::HeaderMap, Vec) { + let mut request = Request::builder().method(method).uri(path); + if let Some(token) = token { + request = request.header(AUTHORIZATION, format!("Bearer {token}")); + } + for (name, value) in extra { + request = request.header(*name, *value); + } + let request = request.body(Body::from(body)).expect("request"); + let response = router(state.clone()).handle(request).await; + let status = response.status(); + let headers = response.headers().clone(); + let bytes = to_bytes(response.into_body(), 1 << 20).await.expect("body"); + (status, headers, bytes.to_vec()) + } + + fn json_of(bytes: &[u8]) -> Value { + serde_json::from_slice(bytes).unwrap_or(Value::Null) + } + + fn sha_hex(bytes: &[u8]) -> String { + Sha256::digest(bytes) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() + } + + const PUT_PATH: &str = "/api/v1/objects/task-1"; + + /// A token for an audience other than `in` is refused with 401 and the Bearer challenge. A token without + /// `files.service` is 403. A user's token (no client subject, no `svc`) is 401. + #[tokio::test] + async fn the_token_must_be_for_in_and_carry_the_scope() { + let (_dir, state, der) = setup().await; + let for_im = machine_token(&der, "iz", "files.service", "im"); + let (status, headers, _) = + call(&state, "GET", "/api/v1/usage", Some(&for_im), &[], vec![]).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(headers[WWW_AUTHENTICATE], "Bearer error=\"invalid_token\""); + + let no_scope = machine_token(&der, "iz", "directory.read", "in"); + let (status, _, body) = + call(&state, "GET", "/api/v1/usage", Some(&no_scope), &[], vec![]).await; + assert_eq!(status, StatusCode::FORBIDDEN); + assert_eq!(json_of(&body)["error"], "insufficient_scope"); + + let now = crate::oidc::now_secs(); + let user = sign( + &der, + &json!({"iss": ISSUER, "sub": "01JUSER", "aud": "in", "scope": "files.service", + "iat": now, "exp": now + 600}), + ); + let (status, _, _) = call(&state, "GET", "/api/v1/usage", Some(&user), &[], vec![]).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + + let (status, _, _) = call(&state, "GET", "/api/v1/usage", None, &[], vec![]).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + } + + /// Two services that use the same id hold two objects. Service `im` cannot read, replace or delete the + /// object that `iz` stored, and its own delete leaves `iz`'s object alone. + #[tokio::test] + async fn a_service_cannot_reach_another_services_object() { + let (_dir, state, der) = setup().await; + let iz = machine_token(&der, "iz", "files.service", "in"); + let im = machine_token(&der, "im", "files.service", "in"); + let (status, _, _) = + call(&state, "PUT", PUT_PATH, Some(&iz), &[], b"from iz".to_vec()).await; + assert_eq!(status, StatusCode::CREATED); + + let (status, _, _) = call(&state, "GET", PUT_PATH, Some(&im), &[], vec![]).await; + assert_eq!(status, StatusCode::NOT_FOUND); + let (status, _, _) = call(&state, "DELETE", PUT_PATH, Some(&im), &[], vec![]).await; + assert_eq!(status, StatusCode::NO_CONTENT); + let (status, _, body) = call(&state, "GET", PUT_PATH, Some(&iz), &[], vec![]).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body, b"from iz"); + } + + /// An id with `/` or a charset break is 400, and nothing is stored under it. + #[tokio::test] + async fn an_external_id_outside_the_contract_is_400() { + let (_dir, state, der) = setup().await; + let iz = machine_token(&der, "iz", "files.service", "in"); + for path in [ + "/api/v1/objects/a/b", + "/api/v1/objects/..%2Fx", + "/api/v1/objects/a%20b", + ] { + let (status, _, body) = call(&state, "PUT", path, Some(&iz), &[], b"x".to_vec()).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{path}"); + assert_eq!(json_of(&body)["error"], "invalid_request", "{path}"); + } + let usage = state.store.service_usage("iz").await.unwrap(); + assert_eq!(usage.objects, 0); + } + + /// A body above the quota is refused with 413 `quota_exceeded`. Nothing is stored and no bytes stay + /// counted. A `Content-Length` above the quota is refused before the body is read. + #[tokio::test] + async fn a_body_over_the_quota_is_refused_and_stores_nothing() { + let (_dir, state, der) = setup().await; + state + .store + .set_setting(SERVICE_QUOTA_SETTING, "10") + .await + .unwrap(); + let iz = machine_token(&der, "iz", "files.service", "in"); + let (status, _, body) = call(&state, "PUT", PUT_PATH, Some(&iz), &[], vec![7u8; 11]).await; + assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE); + assert_eq!(json_of(&body)["error"], "quota_exceeded"); + let (status, _, _) = call( + &state, + "PUT", + PUT_PATH, + Some(&iz), + &[("content-length", "11")], + vec![7u8; 11], + ) + .await; + assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE); + let usage = state.store.service_usage("iz").await.unwrap(); + assert_eq!( + (usage.objects, usage.used_bytes, usage.quota_bytes), + (0, 0, 10) + ); + let (status, _, _) = call(&state, "GET", PUT_PATH, Some(&iz), &[], vec![]).await; + assert_eq!(status, StatusCode::NOT_FOUND); + } + + /// A replace keeps one row and reports 200. The old bytes are removed once no object names them, and + /// identical content from two ids shares one blob until the last of them is deleted. + #[tokio::test] + async fn a_replace_keeps_one_row_and_shared_bytes_outlive_one_object() { + let (_dir, state, der) = setup().await; + let iz = machine_token(&der, "iz", "files.service", "in"); + let (status, _, _) = call(&state, "PUT", PUT_PATH, Some(&iz), &[], b"first".to_vec()).await; + assert_eq!(status, StatusCode::CREATED); + let old_key = object_blob_key("iz", &sha_hex(b"first")); + let (status, _, body) = + call(&state, "PUT", PUT_PATH, Some(&iz), &[], b"second!".to_vec()).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(json_of(&body)["size"], 7); + assert_eq!(state.blobs.size(&old_key).await.unwrap(), None); + assert_eq!(state.store.service_usage("iz").await.unwrap().objects, 1); + + // Two ids with the same bytes share one blob. + let (status, _, _) = call( + &state, + "PUT", + "/api/v1/objects/copy-a", + Some(&iz), + &[], + b"same".to_vec(), + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let (status, _, _) = call( + &state, + "PUT", + "/api/v1/objects/copy-b", + Some(&iz), + &[], + b"same".to_vec(), + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let shared = object_blob_key("iz", &sha_hex(b"same")); + let (status, _, _) = call( + &state, + "DELETE", + "/api/v1/objects/copy-a", + Some(&iz), + &[], + vec![], + ) + .await; + assert_eq!(status, StatusCode::NO_CONTENT); + assert_eq!(state.blobs.size(&shared).await.unwrap(), Some(4)); + let (status, _, body) = call( + &state, + "GET", + "/api/v1/objects/copy-b", + Some(&iz), + &[], + vec![], + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body, b"same"); + } + + /// A GET answers the stored bytes as an attachment with the stored type and the sha256 as its ETag, and + /// honours one `Range`. `If-None-Match` with the same hash is `304`. A DELETE of an absent id is `204`. + #[tokio::test] + async fn get_serves_the_bytes_as_an_attachment_with_range() { + let (_dir, state, der) = setup().await; + let iz = machine_token(&der, "iz", "files.service", "in"); + let (status, _, _) = call( + &state, + "PUT", + PUT_PATH, + Some(&iz), + &[ + ("content-type", "text/plain"), + ("x-object-name", "notes%2Fa%20b.txt"), + ], + b"0123456789".to_vec(), + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let (status, headers, body) = call( + &state, + "GET", + PUT_PATH, + Some(&iz), + &[("range", "bytes=2-4")], + vec![], + ) + .await; + assert_eq!(status, StatusCode::PARTIAL_CONTENT); + assert_eq!(body, b"234"); + assert_eq!( + headers["content-disposition"] + .to_str() + .unwrap() + .split(';') + .next(), + Some("attachment") + ); + assert_eq!( + headers["etag"], + format!("\"{}\"", sha_hex(b"0123456789")).as_str() + ); + let etag = format!("\"{}\"", sha_hex(b"0123456789")); + let (status, _, _) = call( + &state, + "GET", + PUT_PATH, + Some(&iz), + &[("if-none-match", etag.as_str())], + vec![], + ) + .await; + assert_eq!(status, StatusCode::NOT_MODIFIED); + let (status, _, _) = call( + &state, + "DELETE", + "/api/v1/objects/never-was", + Some(&iz), + &[], + vec![], + ) + .await; + assert_eq!(status, StatusCode::NO_CONTENT); + } +} diff --git a/crates/in-web/src/oidc.rs b/crates/in-web/src/oidc.rs index 42aacbd..e9c497f 100644 --- a/crates/in-web/src/oidc.rs +++ b/crates/in-web/src/oidc.rs @@ -59,6 +59,12 @@ pub const IM_KEY: &str = "im"; /// The scope that reads the people directory and photos at `im`. pub const DIRECTORY_SCOPE: &str = "directory.read"; +/// The family key of `in` itself. Client-credentials tokens that call `in` carry it as `aud`. +pub const FAMILY_KEY: &str = "in"; + +/// The scope that lets a family service store and read its own objects in `in` (contracts.md 5). +pub const FILES_SERVICE_SCOPE: &str = "files.service"; + /// Why a token was refused. Every variant is a refusal; none of them says more than the cause. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum TokenError { @@ -393,30 +399,106 @@ pub fn verify_logout_token( Ok(LogoutClaims { jti, sid, sub }) } -/// Verifies an access token addressed to `audience` (for `in`, [`FAMILY_KEY`]) that grants -/// `required_scope`. Returns the caller's family key (`svc`) and its subject. -/// -/// Nothing calls this yet; the object API that accepts service calls comes next. -#[allow(dead_code)] // The object API that accepts other family apps' calls is the first caller. -pub fn verify_access_token( +/// The claims of a client-credentials access token that a machine API needs (contracts.md 2.6). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MachineClaims { + /// The token subject, `client:` for a client-credentials token. Only the prefix is checked. + pub subject: String, + /// The scopes the token grants, from the space-separated `scope` claim. Empty when there is none. + pub scopes: Vec, + /// The caller's family key from `svc`. Callers treat it as their identity. `None` when absent. + pub svc: Option, +} + +/// Verifies an access token addressed to `audience` (for `in`, [`FAMILY_KEY`]): signature, `iss`, `exp` +/// (with leeway), `iat` (at most five minutes ahead), and `aud` equal to `audience` exactly. It does not +/// judge the scopes or the `svc` claim; the caller decides what they must contain, because the refusal +/// differs (a missing `svc` is a bad token, a missing scope is a forbidden call). +pub fn verify_machine_token( keys: &KeySet, token: &str, issuer: &str, audience: &str, - required_scope: &str, -) -> Result<(String, String), TokenError> { +) -> Result { let claims = verify_signed(keys, token, issuer)?; if !audience_is(claims.get("aud"), audience) { return Err(TokenError::Claim("aud")); } check_iat(&claims, now_secs())?; - let scope = text_claim(&claims, "scope")?; - if !scope.split(' ').any(|granted| granted == required_scope) { - return Err(TokenError::Claim("scope")); + let subject = text_claim(&claims, "sub")?.to_owned(); + let scopes = optional_text_claim(&claims, "scope") + .map(|scope| { + scope + .split(' ') + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default(); + let svc = optional_text_claim(&claims, "svc").map(str::to_owned); + Ok(MachineClaims { + subject, + scopes, + svc, + }) +} + +#[cfg(test)] +impl OidcClient { + /// A client whose key set is `keys` and whose endpoints are the standard paths under `issuer`. The cache + /// is filled directly, so no request is made. Production always fetches; only tests use this. + pub(crate) fn with_keys_for_tests(issuer: &str, client_id: &str, keys: KeySet) -> Self { + let config = Oidc { + issuer: issuer.to_owned(), + client_id: client_id.to_owned(), + client_secret_file: std::path::PathBuf::new(), + }; + let mut client = + Self::new(&config, "https://in.test", "test-secret".to_owned()).expect("client"); + let endpoints = client.standard_endpoints(); + let cache = client.cache.get_mut(); + cache.endpoints = Some(Arc::new(endpoints)); + cache.keys = Some((Instant::now(), Arc::new(keys))); + client + } +} + +/// Ed25519 keys and signed tokens for the tests of this crate. Test-only; production keys come from `im`. +#[cfg(test)] +pub(crate) mod test_support { + use super::*; + use ed25519_dalek::SigningKey; + use ed25519_dalek::pkcs8::EncodePrivateKey; + use jsonwebtoken::{EncodingKey, Header, encode}; + use serde_json::json; + + /// The issuer the test tokens name. + pub(crate) const ISSUER: &str = "https://im.example.test"; + /// The client id `in` uses in the tests. + pub(crate) const CLIENT: &str = "in"; + /// The key id of the test key. + pub(crate) const KID: &str = "k1"; + + /// A fresh Ed25519 key: the signing half as PKCS#8 DER, and the key set that publishes it. + pub(crate) fn test_key() -> (Vec, KeySet) { + let mut seed = [0u8; 32]; + rand::fill(&mut seed); + let signing = SigningKey::from_bytes(&seed); + let der = signing.to_pkcs8_der().expect("pkcs8").as_bytes().to_vec(); + let x = BASE64_URL_SAFE_NO_PAD.encode(signing.verifying_key().to_bytes()); + let jwks: Jwks = serde_json::from_value(json!({ + "keys": [{"kty": "OKP", "crv": "Ed25519", "x": x, "kid": KID, "use": "sig", "alg": "EdDSA"}] + })) + .expect("jwks"); + (der, KeySet::from_jwks(&jwks)) + } + + /// Signs `claims` with `der` under [`KID`]. + pub(crate) fn sign(der: &[u8], claims: &Value) -> String { + let mut header = Header::new(Algorithm::EdDSA); + header.kid = Some(KID.to_owned()); + encode(&header, claims, &EncodingKey::from_ed_der(der)).expect("sign") } - let sub = text_claim(&claims, "sub")?.to_owned(); - let svc = text_claim(&claims, "svc")?.to_owned(); - Ok((sub, svc)) } /// The PKCE code challenge of `verifier`: base64url of its SHA-256, without padding (RFC 7636). @@ -640,6 +722,17 @@ impl OidcClient { } } + /// Verifies a client-credentials access token addressed to `audience`, with the cached key set. See + /// [`verify_machine_token`]. + pub async fn verify_machine_token( + &self, + token: &str, + audience: &str, + ) -> Result { + self.verify_with(|keys| verify_machine_token(keys, token, &self.issuer, audience)) + .await + } + /// Runs `check` against the key set. An unknown key id triggers one rate-limited refetch. async fn verify_with( &self, @@ -799,38 +892,12 @@ impl OidcClient { #[cfg(test)] mod tests { + use super::test_support::{CLIENT, ISSUER, sign, test_key}; use super::*; - use ed25519_dalek::SigningKey; - use ed25519_dalek::pkcs8::EncodePrivateKey; - use jsonwebtoken::{EncodingKey, Header, encode}; use serde_json::json; - const ISSUER: &str = "https://im.example.test"; - const CLIENT: &str = "in"; - const KID: &str = "k1"; const NONCE: &str = "nonce-value"; - /// A fresh Ed25519 key: the signing half as PKCS#8 DER, and the key set that publishes it. - fn test_key() -> (Vec, KeySet) { - let mut seed = [0u8; 32]; - rand::fill(&mut seed); - let signing = SigningKey::from_bytes(&seed); - let der = signing.to_pkcs8_der().expect("pkcs8").as_bytes().to_vec(); - let x = BASE64_URL_SAFE_NO_PAD.encode(signing.verifying_key().to_bytes()); - let jwks: Jwks = serde_json::from_value(json!({ - "keys": [{"kty": "OKP", "crv": "Ed25519", "x": x, "kid": KID, "use": "sig", "alg": "EdDSA"}] - })) - .expect("jwks"); - (der, KeySet::from_jwks(&jwks)) - } - - /// Signs `claims` with `der` under `kid`. - fn sign(der: &[u8], claims: &Value) -> String { - let mut header = Header::new(Algorithm::EdDSA); - header.kid = Some(KID.to_owned()); - encode(&header, claims, &EncodingKey::from_ed_der(der)).expect("sign") - } - fn id_claims(now: i64) -> Value { json!({ "iss": ISSUER, "sub": "01JTESTSUB", "aud": CLIENT, "exp": now + 300, "iat": now, diff --git a/docs/architecture.md b/docs/architecture.md index 23607ca..5cb4209 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -108,7 +108,7 @@ again), `target_kind`, `target_id`, `owner`, `can_download`, `password_hash` NUL `created_at`. Created on first authorised call with the default quota from settings. **objects**: `service` FK services, `external_id`, `size`, `sha256`, `content_type`, `name` NULL, `blob_key` -(`objects//`), `created_at`, `updated_at`; PK (service, external_id). +(`objects//`, shared by objects of one service with equal bytes; removed when the last one goes), `created_at`, `updated_at`; PK (service, external_id). **audit_log**, **settings**: per conventions.