diff --git a/crates/in-client/src/lib.rs b/crates/in-client/src/lib.rs index 9209c1b..d8e4967 100644 --- a/crates/in-client/src/lib.rs +++ b/crates/in-client/src/lib.rs @@ -159,6 +159,11 @@ pub struct ServiceJson { pub key: String, pub name: String, pub url: String, + /// im's word on how much storage the service may hold. `None` when im + /// states no limit — the service then answers to its own house default. + /// Defaulted so an im from before the field still parses. + #[serde(default)] + pub limit_bytes: Option, } impl InClient { @@ -200,6 +205,8 @@ impl InClient { key: key.to_string(), name: name.to_string(), url: url.to_string(), + // in registers itself; a limit is im's word about others. + limit_bytes: None, }) .send() .await diff --git a/crates/in-core/migrations/0007_service_storage.sql b/crates/in-core/migrations/0007_service_storage.sql new file mode 100644 index 0000000..3d43d16 --- /dev/null +++ b/crates/in-core/migrations/0007_service_storage.sql @@ -0,0 +1,20 @@ +-- Service storage: the machine account a family service drives, and the key +-- that opens it. +-- +-- A service account is a `user` row no person signs into (`oidc_sub` +-- `service:` — a shape a real im subject can never wear); its key lives +-- here, hashed, one per service. `file.external_id` is the service's own +-- handle for an upload: two pushes of the same id are one row, which the +-- partial unique index below makes a fact rather than a habit. Human files +-- leave the column NULL and never enter that index. +ALTER TABLE file ADD COLUMN external_id TEXT; +CREATE UNIQUE INDEX file_external_by_owner ON file(owner_id, external_id) + WHERE external_id IS NOT NULL; +CREATE TABLE service_key ( + token_hash TEXT PRIMARY KEY, + name TEXT NOT NULL, + service TEXT NOT NULL, + user_id TEXT NOT NULL REFERENCES user(id), + created_at TEXT NOT NULL +); +CREATE UNIQUE INDEX service_key_service ON service_key(service); diff --git a/crates/in-core/src/store/mod.rs b/crates/in-core/src/store/mod.rs index 3bc44d0..65b0760 100644 --- a/crates/in-core/src/store/mod.rs +++ b/crates/in-core/src/store/mod.rs @@ -287,6 +287,23 @@ pub struct SharedItem { pub created_at: OffsetDateTime, } +/// One service's key row beside the account it opens, as the Service keys +/// panel lists it. The token itself is never here — only its hash lives in +/// the row, and the plaintext exists once, at mint or rotate. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ServiceAccount { + /// The family key the service answers to — `"iz"` — and the name the + /// mint form was given (`"İz"`): one routes, one reads. + pub service: String, + pub name: String, + /// The `user` row the account holds its files and quota under. + pub user_id: String, + /// The account's live and trashed bytes, as [`User::used_bytes`] reads. + pub used_bytes: u64, + /// When the key row was minted — the panel's created column. + pub created_at: OffsetDateTime, +} + /// A chunked upload on its way in. `state` is `active` while chunks are /// still arriving, `done` once the finish assembled them, `aborted` once /// anyone gave up on it. @@ -410,11 +427,86 @@ pub trait Store: 'static + Send + Sync { /// Writes the person's display preferences — `theme` ('light'/'dark'), /// `language` ('en'/'tr') and `ui` ('ledger'/'instrument') — read by + /// `root_layout` into `data-theme`, `` and `data-ui`. A value /// no preferences form offers is refused with [`StoreError::Corrupt`] — /// the same refusal a bad enum read from the row gets, because a bad /// enum written is a corrupt row. async fn set_preferences(&self, id: &str, theme: &str, language: &str, ui: &str) -> Result<()>; + // -- service accounts -------------------------------------------------- + + /// Mints one service account: a `user` row no person can sign into + /// (`oidc_sub` is `service:`, a shape a real subject never wears, + /// the address empty, the flag never admin) seeded at + /// `default_quota_bytes`, plus one `service_key` row naming it. Returns + /// the plaintext bearer token — the only moment it exists; the row keeps + /// its hash. A service whose account already exists (its key was + /// revoked, or a mint races a mint) reuses that row: the bytes it holds + /// keep counting against the same ceiling. A service that still holds a + /// key is refused — rotate, not mint again. + async fn create_service_account( + &self, + service: &str, + name: &str, + default_quota_bytes: u64, + ) -> Result; + + /// The live account a bearer token opens, or `None` — an unknown or + /// revoked token and a wrong token answer the same, because telling a + /// stranger which tokens exist is the leak the shape exists to prevent. + async fn service_account_by_token(&self, token: &str) -> Result>; + + /// Every service account, oldest key first — the Service keys panel. + async fn list_service_accounts(&self) -> Result>; + + /// Replaces a service's key with a fresh one; the account and its files + /// stay. Returns the new plaintext token, or `None` when the service has + /// no key to rotate. + async fn rotate_service_key(&self, service: &str) -> Result>; + + /// Deletes a service's key. The account and its files remain — its bytes + /// go back to being an admin's Everyone-panel business. `false` when + /// there was no key. + async fn revoke_service_key(&self, service: &str) -> Result; + + /// Stores one service upload, keyed by the service's own handle: + /// sanitises the name, checks the quota (a re-push of a known + /// `external_id` is charged only for what it adds over the row it + /// replaces), sniffs the mime, and upserts — the second push of an id is + /// the same row with new bytes, never a sibling copy. Service bytes skip + /// the thumbnail pipeline whole: the row wears [`ThumbState::None`]. + /// Returns the file id. + async fn insert_service_file( + &self, + owner_id: &str, + external_id: &str, + name: &str, + bytes: &[u8], + ) -> Result; + + /// One service file's row, by the service's own handle. + async fn service_file(&self, owner_id: &str, external_id: &str) -> Result>; + + /// The bytes themselves, by the service's own handle. `None` when there + /// is no such row, or its file went missing. + async fn service_file_bytes(&self, owner_id: &str, external_id: &str) + -> Result>>; + + /// Takes a service file away for good — the row, its bytes, and the + /// usage they carried. No trash: a machine client's delete is a delete. + /// `false` when there was no such row. + async fn delete_service_file(&self, owner_id: &str, external_id: &str) -> Result; + + /// Writes the ceiling im states for a service's account (`limit.unwrap_or + /// (default_quota_bytes)` — no limit named is the house default). No-op + /// when the service has no account. An unchanged ceiling writes nothing + /// and wakes nobody: the family beat calls this every few minutes. + async fn apply_service_limit( + &self, + service: &str, + limit: Option, + default_quota_bytes: u64, + ) -> Result<()>; // -- folders ----------------------------------------------------------- diff --git a/crates/in-core/src/store/reconcile.rs b/crates/in-core/src/store/reconcile.rs index 40b11b9..ab16916 100644 --- a/crates/in-core/src/store/reconcile.rs +++ b/crates/in-core/src/store/reconcile.rs @@ -219,6 +219,7 @@ fn build_maps( old_has_download_count: bool, old_has_password_hash: bool, old_has_photo_version: bool, + old_has_external_id: bool, ) -> Vec { vec![ TableMap { @@ -289,6 +290,11 @@ fn build_maps( } else { ("download_count", "0".into()) }); + columns.push(if old_has_external_id { + ("external_id", "old.external_id".into()) + } else { + ("external_id", "NULL".into()) + }); columns }, }, @@ -333,6 +339,10 @@ fn build_maps( "expires_at", ]), }, + TableMap { + name: "service_key", + columns: old_cols(&["token_hash", "name", "service", "user_id", "created_at"]), + }, TableMap { name: "setting", columns: old_cols(&["key", "value"]), @@ -431,6 +441,7 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) -> let old_has_download_count = old_has_column(old_conn, "file", "download_count").await?; let old_has_password_hash = old_has_column(old_conn, "share_link", "password_hash").await?; let old_has_photo_version = old_has_column(old_conn, "user", "photo_version").await?; + let old_has_external_id = old_has_column(old_conn, "file", "external_id").await?; let maps = build_maps( old_has_ui, old_has_theme, @@ -438,6 +449,7 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) -> old_has_download_count, old_has_password_hash, old_has_photo_version, + old_has_external_id, ); validate_maps(new_conn, &maps).await?; diff --git a/crates/in-core/src/store/schema.rs b/crates/in-core/src/store/schema.rs index c09a480..3994434 100644 --- a/crates/in-core/src/store/schema.rs +++ b/crates/in-core/src/store/schema.rs @@ -20,6 +20,7 @@ pub(crate) const MIGRATIONS: &[&str] = &[ include_str!("../../migrations/0004_downloads_settings.sql"), include_str!("../../migrations/0005_link_password.sql"), include_str!("../../migrations/0006_photo_version.sql"), + include_str!("../../migrations/0007_service_storage.sql"), ]; /// The whole declared schema — every migration applied in order — as one diff --git a/crates/in-core/src/store/turso_store.rs b/crates/in-core/src/store/turso_store.rs index 48e16aa..7ddb684 100644 --- a/crates/in-core/src/store/turso_store.rs +++ b/crates/in-core/src/store/turso_store.rs @@ -16,8 +16,9 @@ use ulid::Ulid; use super::blobs::{Blobs, LocalBlobs}; use super::secret; use super::{ - CHUNK_SIZE, CreatedLink, File, Folder, Listing, Result, ShareKind, ShareLink, ShareUser, - SharedItem, Store, StoreError, ThumbState, UPLOAD_TTL_HOURS, UploadSession, UploadState, User, + CHUNK_SIZE, CreatedLink, File, Folder, Listing, Result, ServiceAccount, ShareKind, ShareLink, + ShareUser, SharedItem, Store, StoreError, ThumbState, UPLOAD_TTL_HOURS, UploadSession, + UploadState, User, }; use super::{ReconcileOptions, reconcile, schema, sniff}; use crate::live::{Change, Topic}; @@ -2898,6 +2899,342 @@ impl Store for TursoStore { } Ok(Listing { folders, files }) } + // -- service accounts -------------------------------------------------- + + async fn create_service_account( + &self, + service: &str, + name: &str, + default_quota_bytes: u64, + ) -> Result { + let token = new_token(); + // IMMEDIATE: the account-exists read and the key write are one write + // set, and two concurrent mints of one service must land one key — + // the UNIQUE index says so, this transaction makes it a promise. + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + let mut rows = tx + .query( + &format!("SELECT {USER_COLUMNS} FROM user WHERE oidc_sub = ?1"), + params![format!("service:{service}")], + ) + .await + .map_err(backend)?; + let (user_id, fresh) = match rows.next().await.map_err(backend)? { + // The account outlives its keys: a re-mint after a revoke — or a + // rotate that raced — files under the row that already holds the + // service's bytes. + Some(row) => (user_from(&row)?.id, false), + None => { + let id = Ulid::new().to_string(); + tx.execute( + "INSERT INTO user (id, oidc_sub, email, display_name, admin, disabled, \ + quota_bytes, used_bytes, ui, theme, language, created_at, last_seen_at, \ + photo_version) \ + VALUES (?1, ?2, '', ?3, 0, 0, ?4, 0, 'instrument', 'dark', 'en', ?5, NULL, 0)", + params![ + id.clone(), + format!("service:{service}"), + name, + default_quota_bytes as i64, + now_text()? + ], + ) + .await + .map_err(backend)?; + (id, true) + } + }; + drop(rows); + tx.execute( + "INSERT INTO service_key (token_hash, name, service, user_id, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5)", + params![hash_share_token(&token), name, service, user_id.clone(), now_text()?], + ) + .await + .map_err(backend)?; + tx.commit().await.map_err(backend)?; + if fresh { + // A new row arrived: the admin's Everyone panel may be open. + self.announce([Topic::Admin(user_id.clone()), Topic::Profile(user_id)]); + } + Ok(token) + } + + async fn service_account_by_token(&self, token: &str) -> Result> { + let user_id = match self + .one_row( + "SELECT user_id FROM service_key WHERE token_hash = ?1", + params![hash_share_token(token)], + ) + .await? + { + Some(row) => text(&row, 0)?, + None => return Ok(None), + }; + self.user(&user_id).await + } + + async fn list_service_accounts(&self) -> Result> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT k.service, k.name, k.user_id, u.used_bytes, k.created_at \ + FROM service_key k JOIN user u ON u.id = k.user_id \ + ORDER BY k.created_at, k.service", + (), + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(ServiceAccount { + service: text(&row, 0)?, + name: text(&row, 1)?, + user_id: text(&row, 2)?, + used_bytes: row.get::(3).map_err(backend)?.max(0) as u64, + created_at: parse_stamp(&text(&row, 4)?)?, + }); + } + Ok(out) + } + + async fn rotate_service_key(&self, service: &str) -> Result> { + let token = new_token(); + let conn = self.conn.lock().await; + let n = conn + .execute( + "UPDATE service_key SET token_hash = ?1 WHERE service = ?2", + params![hash_share_token(&token), service], + ) + .await + .map_err(backend)?; + Ok((n > 0).then_some(token)) + } + + async fn revoke_service_key(&self, service: &str) -> Result { + let conn = self.conn.lock().await; + let n = conn + .execute( + "DELETE FROM service_key WHERE service = ?1", + params![service], + ) + .await + .map_err(backend)?; + Ok(n > 0) + } + + async fn insert_service_file( + &self, + owner_id: &str, + external_id: &str, + name: &str, + bytes: &[u8], + ) -> Result { + let name = label_of(name); + let size = bytes.len() as u64; + let mime = sniff::sniff(bytes).to_string(); + // IMMEDIATE: the existing-row read, the quota check and the row + // write are one write set — two concurrent pushes of one external_id + // must not each read room for themselves against the same row. + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + let (quota, used) = check_quota(&tx, owner_id).await?; + let mut rows = tx + .query( + "SELECT id, size_bytes FROM file WHERE owner_id = ?1 AND external_id = ?2", + params![owner_id, external_id], + ) + .await + .map_err(backend)?; + let replaced = match rows.next().await.map_err(backend)? { + Some(row) => Some((text(&row, 0)?, row.get::(1).map_err(backend)?.max(0) as u64)), + None => None, + }; + drop(rows); + // A re-push of a known handle is charged only for what it adds over + // the row it replaces — the old bytes stop existing the moment the + // new ones commit. + let added_over = replaced.as_ref().map_or(0, |(_, old)| *old); + fit_quota(quota, used.saturating_sub(added_over), size)?; + // The bytes land first, then the row says they are there — the same + // order `insert_file` keeps. A crash between a re-push's blob write + // and its row update leaves old size over new bytes, and heals the + // moment the client pushes the same external_id again. + match replaced { + Some((id, _)) => { + self.blobs + .put(&format!("files/{id}"), bytes) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + tx.execute( + "UPDATE file SET name = ?1, mime = ?2, size_bytes = ?3, updated_at = ?4 \ + WHERE id = ?5", + params![name, mime, size as i64, now_text()?, id.as_str()], + ) + .await + .map_err(backend)?; + refresh_usage(&tx, owner_id).await?; + tx.commit().await.map_err(backend)?; + self.announce([Topic::Library(owner_id.to_string())]); + Ok(id) + } + None => { + let id = Ulid::new().to_string(); + let file_key = format!("files/{id}"); + self.blobs + .put(&file_key, bytes) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + let written = tx + .execute( + "INSERT INTO file (id, owner_id, folder_id, name, mime, size_bytes, \ + thumb_state, created_at, updated_at, deleted_at, download_count, \ + external_id) \ + VALUES (?1, ?2, NULL, ?3, ?4, ?5, 'none', ?6, ?6, NULL, 0, ?7)", + params![ + id.clone(), + owner_id, + name, + mime, + size as i64, + now_text()?, + external_id + ], + ) + .await; + if let Err(e) = written { + // The row was never born, so the bytes must not outlive + // it under a name nothing points at. + let _ = self.blobs.delete(&[&file_key]).await; + return Err(backend(e)); + } + refresh_usage(&tx, owner_id).await?; + tx.commit().await.map_err(backend)?; + self.announce([Topic::Library(owner_id.to_string())]); + Ok(id) + } + } + } + + async fn service_file(&self, owner_id: &str, external_id: &str) -> Result> { + let sql = format!("SELECT {FILE_COLUMNS} FROM file WHERE owner_id = ?1 AND external_id = ?2"); + match self.one_row(&sql, params![owner_id, external_id]).await? { + Some(row) => Ok(Some(file_from(&row)?)), + None => Ok(None), + } + } + + async fn service_file_bytes( + &self, + owner_id: &str, + external_id: &str, + ) -> Result>> { + match self.service_file(owner_id, external_id).await? { + None => Ok(None), + Some(file) => self.file_bytes(&file.id).await, + } + } + + async fn delete_service_file(&self, owner_id: &str, external_id: &str) -> Result { + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + let mut rows = tx + .query( + "SELECT id FROM file WHERE owner_id = ?1 AND external_id = ?2", + params![owner_id, external_id], + ) + .await + .map_err(backend)?; + let Some(row) = rows.next().await.map_err(backend)? else { + return Ok(false); + }; + let id = text(&row, 0)?; + drop(rows); + tx.execute("DELETE FROM file WHERE id = ?1", params![id.as_str()]) + .await + .map_err(backend)?; + // A machine route's files are never granted or linked — service + // accounts cannot share — but the purge path's sweep is cheap and + // the rows must not outlive the file they name. + tx.execute( + "DELETE FROM share_user WHERE kind = 'file' AND target_id = ?1", + params![id.as_str()], + ) + .await + .map_err(backend)?; + tx.execute( + "DELETE FROM share_link WHERE kind = 'file' AND target_id = ?1", + params![id.as_str()], + ) + .await + .map_err(backend)?; + refresh_usage(&tx, owner_id).await?; + tx.commit().await.map_err(backend)?; + // After the delete: the bytes may only follow a delete that + // committed. Best-effort — a file that survives is orphaned bytes + // the boot sweep collects. + let _ = self + .blobs + .delete(&[&format!("files/{id}"), &format!("thumbs/{id}")]) + .await; + self.announce([Topic::Library(owner_id.to_string())]); + Ok(true) + } + + async fn apply_service_limit( + &self, + service: &str, + limit: Option, + default_quota_bytes: u64, + ) -> Result<()> { + let user_id = match self + .one_row( + "SELECT user_id FROM service_key WHERE service = ?1", + params![service], + ) + .await? + { + Some(row) => text(&row, 0)?, + // No key, no account to ceiling — the beat moves on. + None => return Ok(()), + }; + let quota_bytes = limit.unwrap_or(default_quota_bytes); + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT quota_bytes FROM user WHERE id = ?1", + params![user_id.as_str()], + ) + .await + .map_err(backend)?; + let current = match rows.next().await.map_err(backend)? { + Some(row) => row.get::(0).map_err(backend)?.max(0) as u64, + None => return Ok(()), + }; + drop(rows); + if current == quota_bytes { + return Ok(()); + } + conn.execute( + "UPDATE user SET quota_bytes = ?1 WHERE id = ?2", + params![quota_bytes as i64, user_id.as_str()], + ) + .await + .map_err(backend)?; + drop(conn); + self.announce([Topic::Admin(user_id)]); + Ok(()) + } } // impl Store for TursoStore /// One folder row for a write to vet: locks nothing itself, runs on the diff --git a/crates/in-core/tests/store.rs b/crates/in-core/tests/store.rs index a44cebe..1717f82 100644 --- a/crates/in-core/tests/store.rs +++ b/crates/in-core/tests/store.rs @@ -2036,3 +2036,296 @@ async fn r2_thumbnails_round_trip() { .unwrap(); assert_eq!(stored, served); } + +// --------------------------------------------------------------------------- +// Service storage: the machine account, its key, and its file handles. +// --------------------------------------------------------------------------- + + +#[tokio::test] +async fn minting_a_service_account_yields_a_key_that_opens_it() { + let scratch = Scratch::open().await; + let token = scratch + .store + .create_service_account("iz", "İz", 1024 * 1024) + .await + .unwrap(); + assert!(!token.is_empty()); + // The key opens the account, and the account is no person's row. + let account = scratch + .store + .service_account_by_token(&token) + .await + .unwrap() + .expect("the minted key opens"); + assert_eq!(account.oidc_sub, "service:iz"); + assert_eq!(account.email, ""); + assert_eq!(account.display_name, "İz"); + assert!(!account.admin); + assert_eq!(account.quota_bytes, 1024 * 1024); + // A wrong key answers None, never an account. + assert!(scratch + .store + .service_account_by_token("forged") + .await + .unwrap() + .is_none()); + // The panel lists it with its usage. + let accounts = scratch.store.list_service_accounts().await.unwrap(); + assert_eq!(accounts.len(), 1); + assert_eq!(accounts[0].service, "iz"); + assert_eq!(accounts[0].used_bytes, 0); +} + +#[tokio::test] +async fn a_remint_after_revoke_reuses_the_account() { + let scratch = Scratch::open().await; + let original = scratch + .store + .create_service_account("iz", "İz", 1024 * 1024) + .await + .unwrap(); + let user_id = scratch.store.list_service_accounts().await.unwrap()[0] + .user_id + .clone(); + scratch + .store + .insert_service_file(&user_id, "pre", "pre.txt", b"old bytes") + .await + .unwrap(); + // Revoke takes the key, never the account. + assert!(scratch.store.revoke_service_key("iz").await.unwrap()); + assert!(!scratch.store.revoke_service_key("iz").await.unwrap()); + assert!(scratch.store.list_service_accounts().await.unwrap().is_empty()); + // The re-mint reopens the same account: its files keep counting. + scratch + .store + .create_service_account("iz", "İz", 1024 * 1024) + .await + .unwrap(); + let accounts = scratch.store.list_service_accounts().await.unwrap(); + assert_eq!(accounts.len(), 1); + assert_eq!(accounts[0].user_id, user_id); + let holder = scratch.store.user(&user_id).await.unwrap().unwrap(); + assert_eq!(holder.used_bytes, 9); + // Rotate replaces the key; the old one stops opening, the new one opens. + let fresh = scratch.store.rotate_service_key("iz").await.unwrap().unwrap(); + assert!(scratch + .store + .service_account_by_token(&original) + .await + .unwrap() + .is_none()); + let opened = scratch + .store + .service_account_by_token(&fresh) + .await + .unwrap() + .expect("the rotated key opens"); + assert_eq!(opened.oidc_sub, "service:iz"); +} + +#[tokio::test] +async fn the_service_file_handle_is_idempotent_and_hard_deleted() { + let scratch = Scratch::open().await; + scratch + .store + .create_service_account("iz", "İz", 1024 * 1024) + .await + .unwrap(); + let user_id = scratch.store.list_service_accounts().await.unwrap()[0] + .user_id + .clone(); + let first = scratch + .store + .insert_service_file(&user_id, "att-1", "notes.txt", b"first") + .await + .unwrap(); + let second = scratch + .store + .insert_service_file(&user_id, "att-1", "notes.txt", b"second-and-longer") + .await + .unwrap(); + // One row, the bytes replaced, the id stable. + assert_eq!(first, second); + let row = scratch + .store + .service_file(&user_id, "att-1") + .await + .unwrap() + .expect("the handle names the row"); + assert_eq!(row.name, "notes.txt"); + assert_eq!(row.size_bytes, 17); + assert_eq!(row.thumb_state, ThumbState::None); + assert!(row.mime.starts_with("text/plain"), "sniffed: {}", row.mime); + let bytes = scratch + .store + .service_file_bytes(&user_id, "att-1") + .await + .unwrap() + .expect("bytes there"); + assert_eq!(bytes, b"second-and-longer"); + // Usage recomputed from the one row — never stacked. + let holder = scratch.store.user(&user_id).await.unwrap().unwrap(); + assert_eq!(holder.used_bytes, 17); + // Delete: the row, the bytes and the usage all go. Second delete: false. + assert!(scratch + .store + .delete_service_file(&user_id, "att-1") + .await + .unwrap()); + assert!(scratch + .store + .service_file_bytes(&user_id, "att-1") + .await + .unwrap() + .is_none()); + let holder = scratch.store.user(&user_id).await.unwrap().unwrap(); + assert_eq!(holder.used_bytes, 0); + assert!(!scratch + .store + .delete_service_file(&user_id, "att-1") + .await + .unwrap()); +} + +#[tokio::test] +async fn the_service_quota_refuses_and_a_repush_is_charged_only_over_its_row() { + let scratch = Scratch::open().await; + scratch + .store + .create_service_account("iz", "İz", 64) + .await + .unwrap(); + let user_id = scratch.store.list_service_accounts().await.unwrap()[0] + .user_id + .clone(); + scratch + .store + .insert_service_file(&user_id, "small", "small.txt", b"tiny") + .await + .unwrap(); + // Fresh push past the ceiling: refused. + let big = vec![b'a'; 100]; + assert!(matches!( + scratch + .store + .insert_service_file(&user_id, "big", "big.bin", &big) + .await + .unwrap_err(), + StoreError::QuotaExceeded + )); + // Re-push past the ceiling *over the row it replaces*: refused, and the + // old bytes stay exactly what they were. + let overflow = vec![b'b'; 100]; + assert!(matches!( + scratch + .store + .insert_service_file(&user_id, "small", "small.txt", &overflow) + .await + .unwrap_err(), + StoreError::QuotaExceeded + )); + assert_eq!( + scratch + .store + .service_file_bytes(&user_id, "small") + .await + .unwrap(), + Some(b"tiny".to_vec()) + ); + // A re-push that fits (small.txt replaces 4 bytes with 60): fine. + let fits = vec![b'c'; 60]; + scratch + .store + .insert_service_file(&user_id, "small", "small.txt", &fits) + .await + .unwrap(); + let holder = scratch.store.user(&user_id).await.unwrap().unwrap(); + assert_eq!(holder.used_bytes, 60); +} + +#[tokio::test] +async fn the_family_limit_lands_on_the_account() { + let scratch = Scratch::open().await; + scratch + .store + .create_service_account("iz", "İz", 1024) + .await + .unwrap(); + // im names a ceiling; the account takes it. + scratch + .store + .apply_service_limit("iz", Some(4096), 1024) + .await + .unwrap(); + let accounts = scratch.store.list_service_accounts().await.unwrap(); + let holder = scratch + .store + .user(&accounts[0].user_id) + .await + .unwrap() + .unwrap(); + assert_eq!(holder.quota_bytes, 4096); + // No limit named: the house default. + scratch + .store + .apply_service_limit("iz", None, 1024) + .await + .unwrap(); + let holder = scratch + .store + .user(&accounts[0].user_id) + .await + .unwrap() + .unwrap(); + assert_eq!(holder.quota_bytes, 1024); + // A service with no key: no-op. + scratch + .store + .apply_service_limit("ghost", Some(7), 1024) + .await + .unwrap(); +} + +#[tokio::test] +async fn probe_can_see_with_service_index() { + let scratch = Scratch::open().await; + let alice = alice(&scratch.store).await; + let bob = bob(&scratch.store).await; + let file = scratch + .store + .insert_file(&alice.id, None, "a.txt", b"a") + .await + .unwrap(); + let seen = scratch + .store + .can_see(ShareKind::File, &file.id, &bob.id) + .await + .unwrap(); + let hit_bob = scratch + .store + .search(&bob.id, "a.txt", 10) + .await + .unwrap() + .files + .len(); + println!("PROBE can_see={seen} bob_search_hits={hit_bob}"); + let conn = raw_conn(&scratch).await; + conn.execute("DROP INDEX file_external_by_owner", ()) + .await + .unwrap(); + let seen2 = scratch + .store + .can_see(ShareKind::File, &file.id, &bob.id) + .await + .unwrap(); + let hit_bob2 = scratch + .store + .search(&bob.id, "a.txt", 10) + .await + .unwrap() + .files + .len(); + println!("PROBE after drop can_see={seen2} bob_search_hits={hit_bob2}"); +} diff --git a/crates/in-web/src/i18n.rs b/crates/in-web/src/i18n.rs index aba8370..1342ec1 100644 --- a/crates/in-web/src/i18n.rs +++ b/crates/in-web/src/i18n.rs @@ -246,7 +246,20 @@ pub enum Key { EffectiveOrigin, BaseUrlLabel, BaseUrlNote, - // Re-viewable share links (LinkVisible owns this block). + // Service keys (ServiceKeys owns this block). + ServiceKeysTitle, + ServiceKeyName, + ServiceKeyService, + ServiceKeyMint, + ServiceKeyRotate, + ServiceKeyRotateTitle, + ServiceKeyRotateCost, + ServiceKeyRevoke, + ServiceKeyRevokeTitle, + ServiceKeyRevokeCost, + ServiceKeyShown, + ServiceKeyCopy, + ServiceKeyCreated, Shared, LegacyLinkNote, RemintLink, @@ -427,6 +440,19 @@ pub fn t(lang: Lang, key: Key) -> &'static str { "This link predates re-viewable addresses — revoke and mint a new one to carry it forward." } RemintLink => "Mint a new link", + ServiceKeysTitle => "Service keys", + ServiceKeyName => "Name", + ServiceKeyService => "Service", + ServiceKeyMint => "Mint", + ServiceKeyRotate => "Rotate the key", + ServiceKeyRotateTitle => "Rotate this key?", + ServiceKeyRotateCost => "The old key stops working.", + ServiceKeyRevoke => "Revoke the key", + ServiceKeyRevokeTitle => "Revoke this key?", + ServiceKeyRevokeCost => "The key stops working. The account and its files stay.", + ServiceKeyShown => "Copy it now. It is never shown again.", + ServiceKeyCopy => "Copy", + ServiceKeyCreated => "Created", }, Lang::Tr => match key { Cancel => "Vazgeç", @@ -589,6 +615,19 @@ pub fn t(lang: Lang, key: Key) -> &'static str { PasswordProtected => "Bu bağlantı kilitli", PasswordPrompt => "Bağlantıyı açmak için parolayı girin.", PasswordLabel => "Parola", + ServiceKeysTitle => "Hizmet anahtarları", + ServiceKeyName => "Ad", + ServiceKeyService => "Hizmet", + ServiceKeyMint => "Üret", + ServiceKeyRotate => "Anahtarı yenile", + ServiceKeyRotateTitle => "Bu anahtar yenilensin mi?", + ServiceKeyRotateCost => "Eski anahtar geçersiz olur.", + ServiceKeyRevoke => "Anahtarı iptal et", + ServiceKeyRevokeTitle => "Bu anahtar iptal edilsin mi?", + ServiceKeyRevokeCost => "Anahtar geçersiz olur. Hesap ve dosyalar kalır.", + ServiceKeyShown => "Şimdi kopyala. Bir daha gösterilmez.", + ServiceKeyCopy => "Kopyala", + ServiceKeyCreated => "Yaratıldı", WrongPassword => "Parola hatalı.", Unlock => "Kilidi aç", ServerAddress => "Sunucu adresi", diff --git a/crates/in-web/src/layout.rs b/crates/in-web/src/layout.rs index 55da84f..979a560 100644 --- a/crates/in-web/src/layout.rs +++ b/crates/in-web/src/layout.rs @@ -562,6 +562,7 @@ pub async fn soft_nav_script(cx: &Cx) -> Result { ); \ }; \ window.__inRefresh = function () { \ + if (document.querySelector('.service-secret')) { return; } \ var n = window.__inNav; \ fetch(window.location.href).then( \ function (r) { return r.text().then(function (t) { if (stillCurrent(n)) { swap(t, r.url, false, false, true); } }); }, \ diff --git a/crates/in-web/src/lib.rs b/crates/in-web/src/lib.rs index 78115a5..f0518e9 100644 --- a/crates/in-web/src/lib.rs +++ b/crates/in-web/src/lib.rs @@ -12,6 +12,7 @@ pub mod layout; pub mod live; pub mod pages; pub mod server; +pub mod service; pub mod settings; pub mod share; pub mod trash; diff --git a/crates/in-web/src/main.rs b/crates/in-web/src/main.rs index 055ad03..3fbf3ec 100644 --- a/crates/in-web/src/main.rs +++ b/crates/in-web/src/main.rs @@ -250,6 +250,7 @@ async fn main() { store.clone(), in_client::InClient::new(oidc.clone()), public_origin, + default_quota_bytes, )); // Told when the process is stopping, so the live streams end instead of @@ -267,6 +268,7 @@ async fn main() { // so its guard sits at a hard 2 GiB; `/api/upload` carries single // 8 MiB chunks, so 32 MiB leaves ample headroom. .layer(BodyLimit::max(32 * 1024 * 1024).at("/api/upload")) + .layer(BodyLimit::max(512 * 1024 * 1024).at("/api/service/files")) .layer(BodyLimit::max(2usize * 1024 * 1024 * 1024).at("/files")) .cookies() .assets(bundle), @@ -467,6 +469,7 @@ async fn family_sync( store: Arc, client: in_client::InClient, origin: String, + default_quota_bytes: u64, ) { if origin.is_empty() { eprintln!("family: no public address to register; set base_url"); @@ -481,14 +484,26 @@ async fn family_sync( eprintln!("family register: {problem}"); } match client.family().await { - Some(family) => match serde_json::to_string(&family) { - Ok(json) => { - if let Err(problem) = store.set_setting("family", &json).await { - eprintln!("family sync: {problem}"); + Some(family) => { + // The limits ride the same list: every service key's account + // takes the ceiling im states for it (the house default when + // im states none). A refused write is one log line — the + // next beat carries the same word. + if let Err(problem) = + in_web::service::apply_family_limits(&store, &family, default_quota_bytes) + .await + { + eprintln!("family limits: {problem}"); + } + match serde_json::to_string(&family) { + Ok(json) => { + if let Err(problem) = store.set_setting("family", &json).await { + eprintln!("family sync: {problem}"); + } } + Err(problem) => eprintln!("family sync: {problem}"), } - Err(problem) => eprintln!("family sync: {problem}"), - }, + } None => eprintln!("family sync: im did not answer; keeping the list there is"), } tokio::time::sleep(std::time::Duration::from_secs(FAMILY_SECONDS)).await; diff --git a/crates/in-web/src/server.rs b/crates/in-web/src/server.rs index d9f5a97..058e8e5 100644 --- a/crates/in-web/src/server.rs +++ b/crates/in-web/src/server.rs @@ -9,7 +9,9 @@ //! it. This module's `current_user` maps im's claims onto the local user row, //! provisioning it on first sight. -use std::sync::Arc; +use std::collections::HashMap; + +use std::sync::{Arc, LazyLock, PoisonError}; use in_core::Config; use in_core::store::{Store, StoreError, User}; @@ -297,6 +299,61 @@ pub async fn require_admin(cx: &Cx) -> Result { } } +/// The service behind this request, by bearer key — the machine half of the +/// auth surface. A human browser's session cookie means nothing here and a +/// service key means nothing to [`current_user`]: the two never meet. A +/// disabled account reads as no key at all, the same way a disabled person +/// reads as signed out. +pub async fn service_client(cx: &Cx) -> Option { + let presented = headers(cx) + .get(header::AUTHORIZATION) + .and_then(|value| value.to_str().ok())?; + let token = presented.strip_prefix("Bearer ")?.trim(); + if token.is_empty() { + return None; + } + let user = app(cx) + .store + .service_account_by_token(token) + .await + .ok()??; + (!user.disabled).then_some(user) +} + +/// How long a freshly minted service key waits on the shelf for its one +/// showing: ten minutes, im's own ticket lifetime. +const SHOWN_TTL: std::time::Duration = std::time::Duration::from_secs(10 * 60); + +/// Where a freshly minted service key waits between its POST and the one +/// GET that shows it. The panel's write answers a 303 — the house idiom — +/// but the key itself must never ride a URL or a log line, so the query +/// carries only a random claim ticket: the shelf holds the plaintext, the +/// page's read takes it out ([`take_shown_secret`]), and a replayed or +/// reloaded URL finds the shelf empty and renders no key at all. A restart +/// drops the shelf — the admin mints another. +static SHOWN_SECRETS: LazyLock>> = + LazyLock::new(|| std::sync::Mutex::new(HashMap::new())); + +/// Parks a fresh service key on the shelf and returns the claim ticket for +/// its URL. +pub fn stash_shown_secret(secret: String) -> String { + let ticket = format!("{}", ulid::Ulid::new()); + let mut shelf = SHOWN_SECRETS.lock().unwrap_or_else(PoisonError::into_inner); + shelf.retain(|_, (_, parked)| parked.elapsed() < SHOWN_TTL); + shelf.insert(ticket.clone(), (secret, std::time::Instant::now())); + ticket +} + +/// Takes a stashed key out — exactly once; the second reader of the same +/// ticket gets nothing. +pub fn take_shown_secret(ticket: &str) -> Option { + SHOWN_SECRETS + .lock() + .unwrap_or_else(PoisonError::into_inner) + .remove(ticket) + .map(|(secret, _)| secret) +} + impl From for Refusal { fn from(_: StoreError) -> Refusal { Refusal::Unavailable @@ -350,6 +407,12 @@ pub enum Refusal { /// The admin's server-address form named something no public link can /// be built on — no `http`/`https` scheme, or a trailing slash. BadBaseUrl, + /// A quota form named a service account: the ceiling is im's to set, + /// and the family beat carries it. + ServiceQuota, + /// A Service keys form named a service that cannot take the action — + /// not mintable, not keyed, or an empty name. + BadServiceKey, } impl Refusal { @@ -374,6 +437,8 @@ impl Refusal { Refusal::BadLanguage => "That is not a language.".to_string(), Refusal::BadLimit => "That limit is not usable.".to_string(), Refusal::BadBaseUrl => "That address is not an origin links can be built on.".to_string(), + Refusal::ServiceQuota => "The limit is im's to set.".to_string(), + Refusal::BadServiceKey => "That key is not usable.".to_string(), } } @@ -400,6 +465,8 @@ impl Refusal { Refusal::BadLanguage => "Bu bir dil değil.".to_string(), Refusal::BadLimit => "Bu sınır kullanılamaz.".to_string(), Refusal::BadBaseUrl => "Bu adres, bağlantı kurulabilecek bir kök adres değil.".to_string(), + Refusal::ServiceQuota => "Limit im'de belirlenir.".to_string(), + Refusal::BadServiceKey => "Bu anahtar kullanılamaz.".to_string(), } } @@ -424,6 +491,8 @@ impl Refusal { "bad-language" => Refusal::BadLanguage, "bad-limit" => Refusal::BadLimit, "bad-base-url" => Refusal::BadBaseUrl, + "service-quota" => Refusal::ServiceQuota, + "bad-service-key" => Refusal::BadServiceKey, _ => return None, }) } @@ -452,6 +521,8 @@ impl Refusal { Refusal::BadLanguage => "bad-language", Refusal::BadLimit => "bad-limit", Refusal::BadBaseUrl => "bad-base-url", + Refusal::ServiceQuota => "service-quota", + Refusal::BadServiceKey => "bad-service-key", } } } diff --git a/crates/in-web/src/service.rs b/crates/in-web/src/service.rs new file mode 100644 index 0000000..a399530 --- /dev/null +++ b/crates/in-web/src/service.rs @@ -0,0 +1,278 @@ +//! The machine API: the four routes a family service drives with its bearer +//! key — push a file under its own handle, fetch it back, take it away, and +//! read its quota. Every answer is 200 JSON in the house `{"ok": ...}` / +//! `{"err": }` shape, except a missing or spent key, which answers +//! `401 {"err":"Unauthorized"}` — one word, because telling a stranger which +//! keys exist is the leak the shape exists to prevent. +//! +//! A human browser's session cookie means nothing on these routes, and a +//! bearer key means nothing on the human ones: [`crate::server::service_client`] +//! never reads a cookie, and [`crate::server::current_user`] never reads the +//! `Authorization` header. + +use in_core::store::{Store, StoreError}; +use serde::Serialize; +use topcoat::Result; +use topcoat::context::Cx; +use topcoat::router::content::Json; +use topcoat::router::content::multipart::Multipart; +use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, path_param, route}; + +use crate::server::{Refusal, app, service_client}; + +path_param!(external_id); + +/// The machine answer: one flat JSON object, whatever the call owes. The +/// status route carries its facts beside `ok`, so the shape is a map built +/// by hand, not serde's `Result`. +enum Reply { + /// `401 {"err":"Unauthorized"}`. + Unauthorized, + /// `200 {"err": }` — the word the caller's contract names. + Err(&'static str), + /// `200 {"ok": }` — a file id, or `true`. + Ok(serde_json::Value), + /// `200 {"ok":true,"quota_bytes":N,"used_bytes":N}`. + Status { quota_bytes: u64, used_bytes: u64 }, +} + +impl Serialize for Reply { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::SerializeMap; + let mut map = serializer.serialize_map(None)?; + match self { + Reply::Unauthorized => map.serialize_entry("err", "Unauthorized")?, + Reply::Err(word) => map.serialize_entry("err", word)?, + Reply::Ok(value) => map.serialize_entry("ok", value)?, + Reply::Status { + quota_bytes, + used_bytes, + } => { + map.serialize_entry("ok", &true)?; + map.serialize_entry("quota_bytes", quota_bytes)?; + map.serialize_entry("used_bytes", used_bytes)?; + } + } + map.end() + } +} + +type ServiceReply = Result<(StatusCode, Json)>; + +fn unauthorized() -> ServiceReply { + Ok((StatusCode::UNAUTHORIZED, Json(Reply::Unauthorized))) +} + +fn refused(word: &'static str) -> ServiceReply { + Ok((StatusCode::OK, Json(Reply::Err(word)))) +} + +fn served(value: serde_json::Value) -> ServiceReply { + Ok((StatusCode::OK, Json(Reply::Ok(value)))) +} + +fn not_found_bytes() -> (StatusCode, HeaderMap, Vec) { + (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new()) +} + +/// The byte-route 401: no body worth parsing, the status is the answer. +fn unauthorized_bytes() -> (StatusCode, HeaderMap, Vec) { + (StatusCode::UNAUTHORIZED, HeaderMap::new(), Vec::new()) +} + +/// `POST /api/service/files` — one file under the service's own handle. +/// Multipart fields `external_id` and `name`, then the bytes as the `file` +/// part. A second push of a known `external_id` is the same file with new +/// bytes; the quota refusal is the one the contract names. +#[route(POST "/api/service/files")] +async fn service_upload(cx: &Cx, mut multipart: Multipart) -> ServiceReply { + let Some(account) = service_client(cx).await else { + return unauthorized(); + }; + let mut external_id: Option = None; + let mut name: Option = None; + let mut bytes: Option> = None; + loop { + let field = match multipart.next_field().await { + Ok(Some(field)) => field, + Ok(None) => break, + Err(_) => return refused("Unavailable"), + }; + match field.name() { + Some("external_id") => { + external_id = field.text().await.ok().filter(|value| !value.is_empty()); + } + Some("name") => { + name = field.text().await.ok().filter(|value| !value.is_empty()); + } + Some("file") => { + let mut field = field; + let mut collected = Vec::new(); + loop { + match field.chunk().await { + Ok(Some(chunk)) => collected.extend_from_slice(&chunk), + Ok(None) => break, + Err(_) => return refused("Unavailable"), + } + } + bytes = Some(collected); + } + _ => {} + } + } + let (Some(external_id), Some(name), Some(bytes)) = (external_id, name, bytes) else { + return refused("BadRequest"); + }; + let store = app(cx).store.clone(); + match store + .insert_service_file(&account.id, &external_id, &name, &bytes) + .await + { + Ok(id) => served(serde_json::Value::String(id)), + Err(StoreError::QuotaExceeded) => refused("QuotaExceeded"), + Err(_) => refused("Unavailable"), + } +} + +/// `GET /api/service/file/{external_id}` — the bytes, under the same +/// download headers the human drive serves: the stored name as attachment, +/// and a year of `immutable`, because the handle can never outlive its +/// bytes. A handle that names nothing answers the same 404 a stranger's +/// file id would. +#[route(GET "/api/service/file/{external_id}")] +async fn service_download(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec)> { + let Some(account) = service_client(cx).await else { + return Ok(unauthorized_bytes()); + }; + let external_id: &str = path_param::(cx); + let store = app(cx).store.clone(); + let Some(file) = store + .service_file(&account.id, external_id) + .await + .ok() + .flatten() + else { + return Ok(not_found_bytes()); + }; + let Some(bytes) = store.file_bytes(&file.id).await.ok().flatten() else { + return Ok(not_found_bytes()); + }; + let mut headers = HeaderMap::new(); + headers.insert( + header::CONTENT_DISPOSITION, + HeaderValue::from_str(&format!( + "attachment; filename=\"{}\"", + ascii_name(&file.name) + )) + .unwrap_or(HeaderValue::from_static("attachment")), + ); + if let Ok(value) = HeaderValue::from_str(&file.mime) { + headers.insert(header::CONTENT_TYPE, value); + } + headers.insert( + header::CACHE_CONTROL, + HeaderValue::from_static("private, max-age=31536000, immutable"), + ); + Ok((StatusCode::OK, headers, bytes)) +} + +/// The ASCII half of a `Content-Disposition` filename: only characters no +/// quoting scheme could turn into a delimiter survive. +fn ascii_name(file_name: &str) -> String { + file_name + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') { + c + } else { + '_' + } + }) + .collect() +} + +/// `DELETE /api/service/file/{external_id}` — the bytes are gone, the +/// account's usage follows. A machine client's delete is a delete. +#[route(DELETE "/api/service/file/{external_id}")] +async fn service_delete(cx: &Cx) -> ServiceReply { + let Some(account) = service_client(cx).await else { + return unauthorized(); + }; + let external_id: &str = path_param::(cx); + let store = app(cx).store.clone(); + match store.delete_service_file(&account.id, external_id).await { + Ok(_) => served(serde_json::Value::Bool(true)), + Err(_) => refused("Unavailable"), + } +} + +/// `GET /api/service/status` — the account's ceiling and what it holds, the +/// two numbers a service's admin page shows. +#[route(GET "/api/service/status")] +async fn service_status(cx: &Cx) -> ServiceReply { + let Some(account) = service_client(cx).await else { + return unauthorized(); + }; + let store = app(cx).store.clone(); + let Ok(Some(fresh)) = store.user(&account.id).await else { + return refused("Unavailable"); + }; + Ok(( + StatusCode::OK, + Json(Reply::Status { + quota_bytes: fresh.quota_bytes, + used_bytes: fresh.used_bytes, + }), + )) +} + +/// Takes every service key's ceiling from a freshly fetched family: the +/// limit im states for the service's key, or the house default when im +/// states none. The family beat calls this after every successful fetch; a +/// failure is one log line and nothing else — the next beat re-asks. +pub async fn apply_family_limits( + store: &std::sync::Arc, + family: &[in_client::ServiceJson], + default_quota_bytes: u64, +) -> Result<(), String> { + for account in store + .list_service_accounts() + .await + .map_err(|e| e.to_string())? + { + let limit = family + .iter() + .find(|row| row.key == account.service) + .and_then(|row| row.limit_bytes); + store + .apply_service_limit(&account.service, limit, default_quota_bytes) + .await + .map_err(|e| e.to_string())?; + } + Ok(()) +} + +/// The mintable services, for the panel's dropdown and the mint route's +/// gate: named by the family mirror, and not keyed yet. +pub(crate) async fn mintable_services( + cx: &Cx, +) -> std::result::Result, Refusal> { + let store = app(cx).store.clone(); + let family = store + .get_setting("family") + .await + .map_err(Refusal::from)? + .and_then(|json| serde_json::from_str::>(&json).ok()) + .unwrap_or_default(); + let keyed: std::collections::HashSet = store + .list_service_accounts() + .await + .map_err(Refusal::from)? + .into_iter() + .map(|account| account.service) + .collect(); + Ok(family + .into_iter() + .filter(|row| !keyed.contains(&row.key)) + .collect()) +} diff --git a/crates/in-web/src/settings.rs b/crates/in-web/src/settings.rs index d35814e..8b9ac87 100644 --- a/crates/in-web/src/settings.rs +++ b/crates/in-web/src/settings.rs @@ -24,6 +24,7 @@ use topcoat::view::view; use crate::server::{ Refusal, app, back_to, require_admin, require_user, share_link_url, share_origin, }; +use crate::service::mintable_services; use crate::share::{refusal_banner, refusal_of, share_copy_script}; use crate::i18n::{Key, lang, t}; use crate::layout::{NavPage, topbar}; @@ -142,6 +143,19 @@ async fn set_quota(cx: &Cx, Form(input): Form) -> Redirect { if let Err(refusal) = require_admin(cx).await { return redirect_back(cx, "/settings?section=everyone", "quota", Some(refusal)); } + // A service account's ceiling is im's to set: the family beat carries + // it here. The Everyone row keeps its form so the panel reads + // uniformly, but the write refuses — the server-side gate is the one + // that holds. + let service_target = app(cx) + .store + .list_service_accounts() + .await + .map(|accounts| accounts.iter().any(|account| account.user_id == input.user_id)) + .unwrap_or(false); + if service_target { + return redirect_back(cx, "/settings?section=everyone", "quota", Some(Refusal::ServiceQuota)); + } match unit_bytes(&input.quota, &input.quota_unit) { Some(quota_bytes) => match app(cx) .store @@ -263,6 +277,89 @@ async fn set_base_url(cx: &Cx, Form(input): Form) -> Redirect { } } +#[derive(Deserialize)] +struct ServiceAddForm { + service: String, + name: String, +} + +#[derive(Deserialize)] +struct ServiceAction { + service: String, +} + +/// Back from a Service keys post, the fresh key's claim ticket on the query. +/// The ticket is all the URL ever carries; the shelf holds the key itself. +fn redirect_shown(cx: &Cx, ticket: &str) -> Redirect { + let back = back_to(cx, "/settings?section=service"); + let separator = if back.contains('?') { '&' } else { '?' }; + Ok(( + StatusCode::SEE_OTHER, + [(header::LOCATION, format!("{back}{separator}shown={ticket}"))], + )) +} + +/// Mints one service account and its key. The service must be one the +/// family mirror names and no key yet covers; the name is what the panel +/// prints. The minted key is shown once. +#[route(POST "/api/settings/service_add")] +async fn service_add(cx: &Cx, Form(input): Form) -> Redirect { + if let Err(refusal) = require_admin(cx).await { + return redirect_back(cx, "/settings?section=service", "service_add", Some(refusal)); + } + let service = input.service.trim(); + let name = input.name.trim(); + if name.is_empty() { + return redirect_back(cx, "/settings?section=service", "service_add", Some(Refusal::BadServiceKey)); + } + let mintable = match mintable_services(cx).await { + Ok(mintable) => mintable, + Err(refusal) => { + return redirect_back(cx, "/settings?section=service", "service_add", Some(refusal)); + } + }; + if !mintable.iter().any(|row| row.key == service) { + return redirect_back(cx, "/settings?section=service", "service_add", Some(Refusal::BadServiceKey)); + } + let default_quota_bytes = app(cx).config.default_quota_bytes; + match app(cx) + .store + .create_service_account(service, name, default_quota_bytes) + .await + { + Ok(token) => redirect_shown(cx, &crate::server::stash_shown_secret(token)), + Err(_) => redirect_back(cx, "/settings?section=service", "service_add", Some(Refusal::Unavailable)), + } +} + +/// Replaces one service's key. The account and its files stay; the fresh +/// key is shown once. +#[route(POST "/api/settings/service_rotate")] +async fn service_rotate(cx: &Cx, Form(input): Form) -> Redirect { + if let Err(refusal) = require_admin(cx).await { + return redirect_back(cx, "/settings?section=service", "service_rotate", Some(refusal)); + } + match app(cx).store.rotate_service_key(&input.service).await { + Ok(Some(token)) => redirect_shown(cx, &crate::server::stash_shown_secret(token)), + Ok(None) => redirect_back(cx, "/settings?section=service", "service_rotate", Some(Refusal::BadServiceKey)), + Err(_) => redirect_back(cx, "/settings?section=service", "service_rotate", Some(Refusal::Unavailable)), + } +} + +/// Deletes one service's key. The account and its files remain — its usage +/// reads in the Everyone panel like any other account's. +#[route(POST "/api/settings/service_revoke")] +async fn service_revoke(cx: &Cx, Form(input): Form) -> Redirect { + if let Err(refusal) = require_admin(cx).await { + return redirect_back(cx, "/settings?section=service", "service_revoke", Some(refusal)); + } + match app(cx).store.revoke_service_key(&input.service).await { + Ok(true) => redirect_back(cx, "/settings?section=service", "service_revoke", None), + Ok(false) => redirect_back(cx, "/settings?section=service", "service_revoke", Some(Refusal::BadServiceKey)), + Err(_) => redirect_back(cx, "/settings?section=service", "service_revoke", Some(Refusal::Unavailable)), + } +} + /// Which rail section the page renders. Only one is drawn at a time; an /// admin-only value asked for by anyone else falls back to `Profile`, same /// as a section name it does not recognize at all. @@ -272,8 +369,8 @@ enum Section { Links, Everyone, Server, + Service, } - /// The class a rail link wears: `active` on the section it points to when /// that is the one showing, plain otherwise. fn rail_class(current: Section, target: Section) -> &'static str { @@ -342,9 +439,9 @@ async fn settings(cx: &Cx) -> Result { Some("links") => Section::Links, Some("everyone") if administers => Section::Everyone, Some("server") if administers => Section::Server, + Some("service") if administers => Section::Service, _ => Section::Profile, }; - let created = created_token(query); // Only the section on show pays for its rows: the links panel names // each live link's target, Everyone lists the accounts, and the server // panel needs the origin — nothing else reads them. @@ -406,6 +503,26 @@ async fn settings(cx: &Cx) -> Result { } else { String::new() }; + // The Service keys panel's two reads: the keyed accounts, and the + // family rows no key covers yet — the mint dropdown's options. Both are + // admin-only reads on an admin-only section. + let (accounts, mintable) = if administers && section == Section::Service { + let accounts = store.list_service_accounts().await?; + let mintable = mintable_services(cx).await.unwrap_or_default(); + (accounts, mintable) + } else { + (Vec::new(), Vec::new()) + }; + // The one read that takes a stashed key off the shelf — and only on the + // section that shows it, so a lost section never eats a live ticket. + let created = created_token(query); + let shown = if section == Section::Service { + query_value(query, "shown") + .as_deref() + .and_then(crate::server::take_shown_secret) + } else { + None + }; view! { cx => (topbar(cx, NavPage::Settings, &fresh, language).await?) @@ -416,11 +533,12 @@ async fn settings(cx: &Cx) -> Result { if administers { (t(language, Key::AdminPanel)) (t(language, Key::ServerAddress)) + (t(language, Key::ServiceKeysTitle)) }

(t(language, Key::Settings))

- (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "preferences", "base_url"]).await?) + (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "preferences", "base_url", "service_add", "service_rotate", "service_revoke"]).await?) if section == Section::Profile {
@@ -645,6 +763,101 @@ async fn settings(cx: &Cx) -> Result {
} + if section == Section::Service { + if let Some(key) = shown { + // The show-once banner: the shelf behind it has + // already handed the key over, so this is the only + // render that will ever hold it. The value is + // selectable text, so the copy works without script. +
+
+

(t(language, Key::ServiceKeysTitle))

+
+
+

(t(language, Key::ServiceKeyShown))

+ +
+
+ } +
+
+

(t(language, Key::ServiceKeysTitle))

+
+
+
+ + +
+ +
+
+
+ + + + + + + + + + + for account in &accounts { + + + + + + + } + +
(t(language, Key::ServiceKeyName))(t(language, Key::ServiceKeyService))(t(language, Key::ServiceKeyCreated))
(account.name.clone())(account.service.clone()) +
+ (account.created_at.date().to_string()) +
+
+ (t(language, Key::ServiceKeyRotate)) +
+
(t(language, Key::ServiceKeyRotateTitle))
+

(t(language, Key::ServiceKeyRotateCost))

+
+ + +
+
+
+
+ (t(language, Key::ServiceKeyRevoke)) +
+
(t(language, Key::ServiceKeyRevokeTitle))
+

(t(language, Key::ServiceKeyRevokeCost))

+
+ + +
+
+
+
+
+
+
+ // The banner's copy button above; one delegated listener + // serves every row, idempotent across re-renders. + (share_copy_script(cx).await?) + }
(crate::dropdown::dropdown_script(cx).await?) diff --git a/crates/in-web/tests/http.rs b/crates/in-web/tests/http.rs index bb2675a..3d27873 100644 --- a/crates/in-web/tests/http.rs +++ b/crates/in-web/tests/http.rs @@ -44,6 +44,7 @@ struct FakeIm { tokens: Arc>>, photos: Arc, String)>>>, directory: Arc>>, + family: Arc>>, } impl FakeIm { @@ -55,9 +56,11 @@ impl FakeIm { let photos: Arc, String)>>> = Arc::new(Mutex::new(HashMap::new())); let directory: Arc>> = Arc::new(Mutex::new(Vec::new())); + let family: Arc>> = Arc::new(Mutex::new(Vec::new())); let map = tokens.clone(); let pmap = photos.clone(); let dmap = directory.clone(); + let fmap = family.clone(); tokio::spawn(async move { loop { let Ok((socket, _)) = listener.accept().await else { @@ -66,6 +69,7 @@ impl FakeIm { let map = map.clone(); let pmap = pmap.clone(); let dmap = dmap.clone(); + let fmap = fmap.clone(); tokio::spawn(async move { use tokio::io::{AsyncReadExt, AsyncWriteExt}; let mut socket = socket; @@ -107,19 +111,25 @@ impl FakeIm { Some(photo) => photo, None => match directory_answer(&dmap, &head, &first) { Some(members) => members, - None => match answer_for(&map, &first, &body) { - Some(answer) => ( - "200 OK", - "application/json".to_string(), - serde_json::to_vec(&answer).unwrap(), - ), - // Anything but the photo and directory - // routes is nothing at all, the way the - // real im 404s unknown paths rather than - // answering them. - None => { - ("404 Not Found", "text/plain".to_string(), Vec::new()) - } + None => match family_answer(&fmap, &head, &first) { + Some(list) => list, + None => match answer_for(&map, &first, &body) { + Some(answer) => ( + "200 OK", + "application/json".to_string(), + serde_json::to_vec(&answer).unwrap(), + ), + // Anything but the photo, directory + // and family routes is nothing at + // all, the way the real im 404s + // unknown paths rather than + // answering them. + None => ( + "404 Not Found", + "text/plain".to_string(), + Vec::new(), + ), + }, }, }, }; @@ -142,6 +152,7 @@ impl FakeIm { tokens, photos, directory, + family, } } @@ -149,6 +160,13 @@ impl FakeIm { format!("http://{}", self.addr) } + /// Stages the list `GET /family` answers with — the suite im keeps. + /// Unset, the route is simply not there, as for an app im has not + /// registered. + fn set_family(&self, list: Vec) { + *self.family.lock().unwrap() = list; + } + /// Stores the photo `GET /photo/{user_id}` answers with — the bytes and /// the mime im would serve for this account. fn set_photo(&self, user_id: &str, bytes: Vec, mime: &str) { @@ -246,6 +264,46 @@ fn directory_answer( )) } +/// Answers `GET /family` with the staged suite — the app's Basic credential +/// or nothing, and with nothing staged no route at all. `None` for anything +/// else, which falls through to the introspection JSON. +fn family_answer( + family: &Arc>>, + head: &str, + request_line: &str, +) -> Option<(&'static str, String, Vec)> { + let mut parts = request_line.split_whitespace(); + if parts.next() != Some("GET") { + return None; + } + let target = parts.next().unwrap_or(""); + let path = target + .split_once('?') + .map(|(path, _)| path) + .unwrap_or(target); + if path != "/family" { + return None; + } + let authed = head + .lines() + .filter_map(|line| line.split_once(':')) + .any(|(name, value)| { + name.trim().eq_ignore_ascii_case("authorization") && value.trim() == APP_BASIC + }); + if !authed { + return Some(("404 Not Found", "text/plain".to_string(), Vec::new())); + } + let list = family.lock().unwrap(); + if list.is_empty() { + return Some(("404 Not Found", "text/plain".to_string(), Vec::new())); + } + Some(( + "200 OK", + "application/json".to_string(), + serde_json::to_vec(&*list).unwrap(), + )) +} + fn headers_end(req: &[u8]) -> Option { req.windows(4) .position(|w| w == b"\r\n\r\n") @@ -343,6 +401,7 @@ impl TestApp { key: key.to_string(), name: name.to_string(), url: url.to_string(), + limit_bytes: None, }) .collect(); store @@ -384,7 +443,7 @@ impl TestApp { Router::builder() .discover() .layer(BodyLimit::max(32 * 1024 * 1024).at("/api/upload")) - .layer(BodyLimit::max(2usize * 1024 * 1024 * 1024).at("/files")) + .layer(BodyLimit::max(512 * 1024 * 1024).at("/api/service/files")) .cookies() .assets( AssetBundle::load_dir(asset_dir()) @@ -563,6 +622,77 @@ impl TestApp { Answer::from_response(response).await } + /// Posts a multipart form with a bearer key, the way iz's storage client + /// pushes an attachment. Raw bytes back — the machine answer is JSON the + /// caller parses itself. + async fn post_service_multipart( + &self, + path: &str, + token: Option<&str>, + fields: &[(&str, &str)], + file: Option<(&str, &[u8])>, + ) -> Raw { + const BOUNDARY: &str = "in-test-boundary"; + let mut body = Vec::new(); + for (name, value) in fields { + body.extend_from_slice( + format!( + "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n" + ) + .as_bytes(), + ); + } + if let Some((filename, bytes)) = file { + body.extend_from_slice( + format!( + "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\nContent-Type: application/octet-stream\r\n\r\n" + ) + .as_bytes(), + ); + body.extend_from_slice(bytes); + body.extend_from_slice(b"\r\n"); + } + body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes()); + let mut request = Request::builder().method("POST").uri(path).header( + header::CONTENT_TYPE, + format!("multipart/form-data; boundary={BOUNDARY}"), + ); + if let Some(token) = token { + request = request.header(header::AUTHORIZATION, format!("Bearer {token}")); + } + let response = self + .router + .handle(request.body(Body::from(body)).unwrap()) + .await; + Raw::from_response(response).await + } + + /// A machine GET with (maybe) a bearer key. + async fn get_bearer(&self, path: &str, token: Option<&str>) -> Raw { + let mut request = Request::builder().method("GET").uri(path); + if let Some(token) = token { + request = request.header(header::AUTHORIZATION, format!("Bearer {token}")); + } + let response = self + .router + .handle(request.body(Body::empty()).unwrap()) + .await; + Raw::from_response(response).await + } + + /// A machine DELETE with (maybe) a bearer key. + async fn delete_bearer(&self, path: &str, token: Option<&str>) -> Raw { + let mut request = Request::builder().method("DELETE").uri(path); + if let Some(token) = token { + request = request.header(header::AUTHORIZATION, format!("Bearer {token}")); + } + let response = self + .router + .handle(request.body(Body::empty()).unwrap()) + .await; + Raw::from_response(response).await + } + /// Gets a page or a download the way a browser does, raw bytes back /// untouched — a download's body is not always UTF-8. async fn get(&self, path: &str, cookie: Option<&str>) -> Raw { @@ -698,6 +828,33 @@ struct Raw { bytes: Vec, } +impl Raw { + async fn from_response(response: topcoat::router::response::Response) -> Self { + let status = response.status(); + let headers = response.headers().clone(); + let header = |name| { + headers + .get(name) + .and_then(|value| value.to_str().ok()) + .map(str::to_string) + }; + let bytes = to_bytes(response.into_body(), usize::MAX) + .await + .unwrap() + .to_vec(); + Raw { + status, + content_type: header(header::CONTENT_TYPE), + disposition: header(header::CONTENT_DISPOSITION), + content_range: header(header::CONTENT_RANGE), + accept_ranges: header(header::ACCEPT_RANGES), + cache_control: header(header::CACHE_CONTROL), + etag: header(header::ETAG), + location: header(header::LOCATION), + bytes, + } + } +} impl Raw { fn text(&self) -> String { String::from_utf8(self.bytes.clone()).unwrap() @@ -5340,3 +5497,387 @@ async fn connection_card_shows_issuer_client_id_and_stream_state() { assert!(!body.contains("connection-on"), "green lingered: {body}"); } + +// --------------------------------------------------------------------------- +// The service storage API: bearer keys, machine answers, im's ceilings. +// --------------------------------------------------------------------------- + +/// A minted service account's bearer key, straight off the store. +async fn service_key(store: &Arc, service: &str, name: &str) -> (String, String) { + let token = store + .create_service_account(service, name, 1024 * 1024) + .await + .unwrap(); + let account = store.list_service_accounts().await.unwrap(); + let user_id = account + .iter() + .find(|account| account.service == service) + .unwrap() + .user_id + .clone(); + (token, user_id) +} + +#[tokio::test] +async fn service_routes_refuse_a_missing_or_wrong_key() { + let app = TestApp::build().await; + for path in [ + "/api/service/status", + "/api/service/file/some-id", + ] { + let raw = app.get_bearer(path, None).await; + assert_eq!(raw.status, StatusCode::UNAUTHORIZED, "{path}"); + let raw = app.get_bearer(path, None).await; + assert_eq!( + raw.status, + StatusCode::UNAUTHORIZED, + "{path}: {} {:?}", + raw.text(), + raw.cache_control + ); + assert_eq!(raw.status, StatusCode::UNAUTHORIZED, "{path}"); + } + let raw = app.delete_bearer("/api/service/file/some-id", None).await; + assert_eq!(raw.status, StatusCode::UNAUTHORIZED); + let raw = app + .post_service_multipart("/api/service/files", None, &[], None) + .await; + assert_eq!(raw.status, StatusCode::UNAUTHORIZED); +} + +#[tokio::test] +async fn the_service_happy_path_pushes_fetches_counts_and_takes_away() { + let app = TestApp::build().await; + let (token, user_id) = service_key(&app.store, "iz", "İz").await; + + // Push: the answer is the file id, and the bytes are the account's. + let raw = app + .post_service_multipart( + "/api/service/files", + Some(&token), + &[("external_id", "att-1"), ("name", "notes.txt")], + Some(("notes.txt", b"hello iz".as_slice())), + ) + .await; + assert_eq!(raw.status, StatusCode::OK, "{:?}", raw.text()); + let pushed: serde_json::Value = serde_json::from_str(&raw.text()).unwrap(); + let file_id = pushed["ok"].as_str().unwrap().to_string(); + + // Status: the account's ceiling and what it now holds. + let raw = app + .get_bearer("/api/service/status", Some(&token)) + .await; + assert_eq!(raw.status, StatusCode::OK); + let status: serde_json::Value = serde_json::from_str(&raw.text()).unwrap(); + assert_eq!(status["ok"], serde_json::Value::Bool(true)); + assert_eq!(status["quota_bytes"], 1024 * 1024); + assert_eq!(status["used_bytes"], 8); + + // Fetch: the same bytes, the attachment disposition, a year immutable. + let raw = app + .get_bearer("/api/service/file/att-1", Some(&token)) + .await; + assert_eq!(raw.status, StatusCode::OK, "GET file: {}", raw.text()); + assert_eq!(raw.bytes, b"hello iz".as_slice()); + assert_eq!( + raw.cache_control.as_deref(), + Some("private, max-age=31536000, immutable") + ); + assert!(raw.disposition.unwrap().contains("notes.txt")); + + // The account row agrees with the status: mime sniffed, no thumbnail, + // usage recomputed from the row. + let file = app.store.file(&file_id).await.unwrap().unwrap(); + assert_eq!(file.owner_id, user_id); + assert_eq!(file.mime, "text/plain"); + assert_eq!(file.thumb_state, in_core::store::ThumbState::None); + let holder = app.store.user(&user_id).await.unwrap().unwrap(); + assert_eq!(holder.used_bytes, 8); + + // Delete: the row and the bytes are gone, the usage follows. + let raw = app + .delete_bearer("/api/service/file/att-1", Some(&token)) + .await; + assert_eq!(raw.status, StatusCode::OK); + assert!(raw.text().contains("\"ok\":true"), "{}", raw.text()); + let raw = app + .get_bearer("/api/service/file/att-1", Some(&token)) + .await; + assert_eq!(raw.status, StatusCode::NOT_FOUND); + let holder = app.store.user(&user_id).await.unwrap().unwrap(); + assert_eq!(holder.used_bytes, 0); +} + +#[tokio::test] +async fn a_repush_of_a_known_handle_replaces_bytes_without_a_second_row() { + let app = TestApp::build().await; + let (token, user_id) = service_key(&app.store, "iz", "İz").await; + for payload in [b"first".as_slice(), b"second-and-longer".as_slice()] { + let raw = app + .post_service_multipart( + "/api/service/files", + Some(&token), + &[("external_id", "att-1"), ("name", "notes.txt")], + Some(("notes.txt", payload)), + ) + .await; + assert_eq!(raw.status, StatusCode::OK, "{:?}", raw.text()); + } + let raw = app + .get_bearer("/api/service/file/att-1", Some(&token)) + .await; + assert_eq!(raw.bytes, b"second-and-longer".as_slice()); + let holder = app.store.user(&user_id).await.unwrap().unwrap(); + // Recomputed from the one row, never incremented past it. + assert_eq!(holder.used_bytes, 17); +} + +#[tokio::test] +async fn the_service_quota_is_the_ceiling_the_word_names() { + let app = TestApp::build().await; + // One mebibyte of headroom, then a push past it. + let (token, _) = service_key(&app.store, "iz", "İz").await; + let big = vec![0u8; 2 * 1024 * 1024]; + let raw = app + .post_service_multipart( + "/api/service/files", + Some(&token), + &[("external_id", "big"), ("name", "big.bin")], + Some(("big.bin", big.as_slice())), + ) + .await; + assert_eq!(raw.status, StatusCode::OK); + assert!(raw.text().contains("QuotaExceeded"), "{}", raw.text()); + // A re-push that would not fit over the row it replaces is refused too, + // and the old bytes stay exactly as they were. + let raw = app + .post_service_multipart( + "/api/service/files", + Some(&token), + &[("external_id", "small"), ("name", "small.txt")], + Some(("small.txt", b"tiny".as_slice())), + ) + .await; + assert_eq!(raw.status, StatusCode::OK); + // One byte past the ceiling, over the row it replaces: refused. + let overflow = vec![b'a'; 1024 * 1024 + 1]; + let raw = app + .post_service_multipart( + "/api/service/files", + Some(&token), + &[("external_id", "small"), ("name", "small.txt")], + Some(("small.txt", overflow.as_slice())), + ) + .await; + assert!(raw.text().contains("QuotaExceeded"), "{}", raw.text()); + let raw = app + .get_bearer("/api/service/file/small", Some(&token)) + .await; + assert_eq!(raw.bytes, b"tiny".as_slice()); +} + +#[tokio::test] +async fn a_human_browser_is_a_stranger_on_the_machine_routes() { + let app = TestApp::build().await; + let (token, _) = service_key(&app.store, "iz", "İz").await; + let admin = app + .sign_in("sub-admin", "admin@example.com", "Admin") + .await; + // The admin's session cookie buys nothing here. + let raw = app.get("/api/service/status", Some(&admin)).await; + assert_eq!(raw.status, StatusCode::UNAUTHORIZED); + // And the bearer key buys nothing on the human drive. + let raw = app + .get_bearer("/drive", Some(&token)) + .await; + assert!(raw.status.is_redirection() || raw.status == StatusCode::UNAUTHORIZED); +} + +#[tokio::test] +async fn the_everyone_quota_write_refuses_a_service_account() { + let app = TestApp::build().await; + // The admin signs in first: the first human sight is the admin, and a + // service row must not claim that. + let admin = app + .sign_in("sub-admin", "admin@example.com", "Admin") + .await; + let (_, user_id) = service_key(&app.store, "iz", "İz").await; + let answer = app + .post( + "/api/settings/quota", + Some(&admin), + &[("user_id", user_id.as_str()), ("quota", "5"), ("quota_unit", "GiB")], + ) + .await; + assert!(answer.refused("service-quota", "quota"), "{} {}", answer.location.as_deref().unwrap_or(""), answer.body); + // The ceiling is untouched. + let holder = app.store.user(&user_id).await.unwrap().unwrap(); + assert_eq!(holder.quota_bytes, 1024 * 1024); +} + +#[tokio::test] +async fn the_mint_shows_its_key_once_and_refuses_a_stranger() { + let app = TestApp::build().await; + app.store + .set_setting( + "family", + r#"[{"key":"iz","name":"İz","url":"http://127.0.0.1:7654","limit_bytes":5368709120}]"#, + ) + .await + .unwrap(); + let admin = app + .sign_in("sub-admin", "admin@example.com", "Admin") + .await; + let plain = app.sign_in("sub-plain", "plain@example.com", "Plain").await; + + // Non-admin: the section reads as the profile, the mint refuses. + let page = app + .get("/settings?section=service", Some(&plain)) + .await; + assert!(!page.text().contains("Service keys"), "rail leaked: {}", page.text()); + let answer = app + .post( + "/api/settings/service_add", + Some(&plain), + &[("service", "iz"), ("name", "İz")], + ) + .await; + assert!(answer.refused("forbidden", "service_add"), "{} {}", answer.location.as_deref().unwrap_or(""), answer.body); + + // The admin mints; the redirect carries a ticket, not the key. + let answer = app + .post( + "/api/settings/service_add", + Some(&admin), + &[("service", "iz"), ("name", "İz")], + ) + .await; + assert!(answer.accepted(), "{} {}", answer.location.as_deref().unwrap_or(""), answer.body); + let location = answer.location.unwrap(); + let ticket = location + .split("shown=") + .nth(1) + .unwrap() + .split('&') + .next() + .unwrap() + .to_string(); + assert!(!ticket.is_empty()); + + // First render: the key stands in the banner. Second: nothing. + let page = app + .get(&format!("/settings?section=service&shown={ticket}"), Some(&admin)) + .await; + let body = page.text(); + assert!(body.contains("service-secret"), "no banner: {body}"); + assert!(body.contains("Copy it now"), "{body}"); + let start = body.split("service-secret\"").nth(1).unwrap(); + let key = start + .split('>') + .nth(1) + .unwrap() + .split('<') + .next() + .unwrap() + .to_string(); + assert!(!key.is_empty()); + // The store opened the account, and the account opens by that key. + let account = app + .store + .service_account_by_token(&key) + .await + .unwrap() + .expect("the shown key opens"); + assert_eq!(account.oidc_sub, "service:iz"); + // The replayed URL — the live tick, a reload — renders no banner. + let page = app + .get(&format!("/settings?section=service&shown={ticket}"), Some(&admin)) + .await; + assert!(!page.text().contains("service-secret\"")); + let page = app + .get("/settings?section=service&shown=forged-ticket", Some(&admin)) + .await; + assert!(!page.text().contains("service-secret\"")); + + // Rotate replaces the key; revoke kills it, the account stays. + let answer = app + .post( + "/api/settings/service_rotate", + Some(&admin), + &[("service", "iz")], + ) + .await; + assert!(answer.accepted(), "{} {}", answer.location.as_deref().unwrap_or(""), answer.body); + let ticket = answer.location.unwrap().split("shown=").nth(1).unwrap().to_string(); + let page = app + .get(&format!("/settings?section=service&shown={ticket}"), Some(&admin)) + .await; + let rotated = page + .text() + .split("service-secret\"") + .nth(1) + .unwrap() + .split('>') + .nth(1) + .unwrap() + .split('<') + .next() + .unwrap() + .to_string(); + assert_ne!(rotated, key); + assert!(app.store.service_account_by_token(&key).await.unwrap().is_none()); + let answer = app + .post( + "/api/settings/service_revoke", + Some(&admin), + &[("service", "iz")], + ) + .await; + assert!(answer.accepted(), "{} {}", answer.location.as_deref().unwrap_or(""), answer.body); + assert!(app.store.service_account_by_token(&rotated).await.unwrap().is_none()); + let accounts = app.store.list_service_accounts().await.unwrap(); + assert!(accounts.is_empty(), "revoke took the row, not the account: the account row stays"); +} + +#[tokio::test] +async fn the_family_limit_lands_on_the_account() { + let app = TestApp::build().await; + // im names a 5 GiB ceiling for iz; the beat carries it. + app.fake + .set_family(vec![serde_json::json!({ + "key": "iz", + "name": "İz", + "url": "http://127.0.0.1:7654", + "limit_bytes": 5 * 1024 * 1024 * 1024u64, + })]); + let client = in_client::InClient::new(app.client.clone()); + let family = client.family().await.expect("the fake answered"); + assert_eq!(family[0].limit_bytes, Some(5 * 1024 * 1024 * 1024)); + in_web::service::apply_family_limits(&app.store, &family, 1024 * 1024) + .await + .unwrap(); + let accounts = app.store.list_service_accounts().await.unwrap(); + assert!(accounts.is_empty(), "no key, no account to ceiling"); + let (token, user_id) = service_key(&app.store, "iz", "İz").await; + let _ = token; + // Before a beat the account sits at the default; im's word moves it. + in_web::service::apply_family_limits(&app.store, &family, 1024 * 1024) + .await + .unwrap(); + let holder = app.store.user(&user_id).await.unwrap().unwrap(); + assert_eq!(holder.quota_bytes, 5 * 1024 * 1024 * 1024); + // No limit named: the house default. + app.fake + .set_family(vec![serde_json::json!({ + "key": "iz", + "name": "İz", + "url": "http://127.0.0.1:7654", + })]); + let family = client.family().await.unwrap(); + assert_eq!(family[0].limit_bytes, None); + in_web::service::apply_family_limits(&app.store, &family, 1024 * 1024) + .await + .unwrap(); + let holder = app.store.user(&user_id).await.unwrap().unwrap(); + assert_eq!(holder.quota_bytes, 1024 * 1024); +}