forge
Explore
Log in

Don't you dare go Hollow

the drive learns to hold another app's bytes: a service account is a user row no person signs into (oidc_sub service:<key>, a shape a real subject can never wear) opened by a bearer key minted in a new admin Service-keys panel — show-once on a ten-minute ticket shelf, rotate and revoke as confirm disclosures, the refresh morph holding its banner still. Four machine routes answer that key and nothing else (a cookie means nothing to them, the key means nothing to the human ones): push under the caller's own external_id — idempotent, the partial unique index on (owner, external_id) making one row a fact rather than a habit, quota-checked in an IMMEDIATE transaction that charges a re-push only for what it adds over the row it replaces — fetch under the drive's immutable download headers, hard delete with no trash, and a status of the account's ceiling and hold. The family beat takes each key's limit from im's roster (limit_bytes, the house default when im states none) and stamps it on the account; the Everyone panel refuses to move a service account's quota by hand, because the limit is im's word now. Service files skip thumbnails and never enter the drive's browsing surfaces — the usage bar tells the whole story a person needs.

Browse files at this commit

215ffc64a1b5ba57d016bfb307331214eaccc6b6Ahmet Kaan GümüşParent: f937d23
crates/in-client/src/lib.rsmodified+7 -0
@@ -159,6 +159,11 @@ pub struct ServiceJson {
159 pub key: String,159 pub key: String,
160 pub name: String,160 pub name: String,
161 pub url: String,161 pub url: String,
162+ /// im's word on how much storage the service may hold. `None` when im
163+ /// states no limit — the service then answers to its own house default.
164+ /// Defaulted so an im from before the field still parses.
165+ #[serde(default)]
166+ pub limit_bytes: Option<u64>,
162 }167 }
163 168
164 impl InClient {169 impl InClient {
@@ -200,6 +205,8 @@ impl InClient {
200 key: key.to_string(),205 key: key.to_string(),
201 name: name.to_string(),206 name: name.to_string(),
202 url: url.to_string(),207 url: url.to_string(),
208+ // in registers itself; a limit is im's word about others.
209+ limit_bytes: None,
203 })210 })
204 .send()211 .send()
205 .await212 .await
crates/in-core/migrations/0007_service_storage.sqladded+20 -0
@@ -0,0 +1,20 @@
1+-- Service storage: the machine account a family service drives, and the key
2+-- that opens it.
3+--
4+-- A service account is a `user` row no person signs into (`oidc_sub`
5+-- `service:<key>` — a shape a real im subject can never wear); its key lives
6+-- here, hashed, one per service. `file.external_id` is the service's own
7+-- handle for an upload: two pushes of the same id are one row, which the
8+-- partial unique index below makes a fact rather than a habit. Human files
9+-- leave the column NULL and never enter that index.
10+ALTER TABLE file ADD COLUMN external_id TEXT;
11+CREATE UNIQUE INDEX file_external_by_owner ON file(owner_id, external_id)
12+ WHERE external_id IS NOT NULL;
13+CREATE TABLE service_key (
14+ token_hash TEXT PRIMARY KEY,
15+ name TEXT NOT NULL,
16+ service TEXT NOT NULL,
17+ user_id TEXT NOT NULL REFERENCES user(id),
18+ created_at TEXT NOT NULL
19+);
20+CREATE UNIQUE INDEX service_key_service ON service_key(service);
crates/in-core/src/store/mod.rsmodified+92 -0
@@ -287,6 +287,23 @@ pub struct SharedItem {
287 pub created_at: OffsetDateTime,287 pub created_at: OffsetDateTime,
288 }288 }
289 289
290+/// One service's key row beside the account it opens, as the Service keys
291+/// panel lists it. The token itself is never here — only its hash lives in
292+/// the row, and the plaintext exists once, at mint or rotate.
293+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
294+pub struct ServiceAccount {
295+ /// The family key the service answers to — `"iz"` — and the name the
296+ /// mint form was given (`"İz"`): one routes, one reads.
297+ pub service: String,
298+ pub name: String,
299+ /// The `user` row the account holds its files and quota under.
300+ pub user_id: String,
301+ /// The account's live and trashed bytes, as [`User::used_bytes`] reads.
302+ pub used_bytes: u64,
303+ /// When the key row was minted — the panel's created column.
304+ pub created_at: OffsetDateTime,
305+}
306+
290 /// A chunked upload on its way in. `state` is `active` while chunks are307 /// A chunked upload on its way in. `state` is `active` while chunks are
291 /// still arriving, `done` once the finish assembled them, `aborted` once308 /// still arriving, `done` once the finish assembled them, `aborted` once
292 /// anyone gave up on it.309 /// anyone gave up on it.
@@ -410,11 +427,86 @@ pub trait Store: 'static + Send + Sync {
410 427
411 /// Writes the person's display preferences — `theme` ('light'/'dark'),428 /// Writes the person's display preferences — `theme` ('light'/'dark'),
412 /// `language` ('en'/'tr') and `ui` ('ledger'/'instrument') — read by429 /// `language` ('en'/'tr') and `ui` ('ledger'/'instrument') — read by
430+
413 /// `root_layout` into `data-theme`, `<html lang>` and `data-ui`. A value431 /// `root_layout` into `data-theme`, `<html lang>` and `data-ui`. A value
414 /// no preferences form offers is refused with [`StoreError::Corrupt`] —432 /// no preferences form offers is refused with [`StoreError::Corrupt`] —
415 /// the same refusal a bad enum read from the row gets, because a bad433 /// the same refusal a bad enum read from the row gets, because a bad
416 /// enum written is a corrupt row.434 /// enum written is a corrupt row.
417 async fn set_preferences(&self, id: &str, theme: &str, language: &str, ui: &str) -> Result<()>;435 async fn set_preferences(&self, id: &str, theme: &str, language: &str, ui: &str) -> Result<()>;
436+ // -- service accounts --------------------------------------------------
437+
438+ /// Mints one service account: a `user` row no person can sign into
439+ /// (`oidc_sub` is `service:<key>`, a shape a real subject never wears,
440+ /// the address empty, the flag never admin) seeded at
441+ /// `default_quota_bytes`, plus one `service_key` row naming it. Returns
442+ /// the plaintext bearer token — the only moment it exists; the row keeps
443+ /// its hash. A service whose account already exists (its key was
444+ /// revoked, or a mint races a mint) reuses that row: the bytes it holds
445+ /// keep counting against the same ceiling. A service that still holds a
446+ /// key is refused — rotate, not mint again.
447+ async fn create_service_account(
448+ &self,
449+ service: &str,
450+ name: &str,
451+ default_quota_bytes: u64,
452+ ) -> Result<String>;
453+
454+ /// The live account a bearer token opens, or `None` — an unknown or
455+ /// revoked token and a wrong token answer the same, because telling a
456+ /// stranger which tokens exist is the leak the shape exists to prevent.
457+ async fn service_account_by_token(&self, token: &str) -> Result<Option<User>>;
458+
459+ /// Every service account, oldest key first — the Service keys panel.
460+ async fn list_service_accounts(&self) -> Result<Vec<ServiceAccount>>;
461+
462+ /// Replaces a service's key with a fresh one; the account and its files
463+ /// stay. Returns the new plaintext token, or `None` when the service has
464+ /// no key to rotate.
465+ async fn rotate_service_key(&self, service: &str) -> Result<Option<String>>;
466+
467+ /// Deletes a service's key. The account and its files remain — its bytes
468+ /// go back to being an admin's Everyone-panel business. `false` when
469+ /// there was no key.
470+ async fn revoke_service_key(&self, service: &str) -> Result<bool>;
471+
472+ /// Stores one service upload, keyed by the service's own handle:
473+ /// sanitises the name, checks the quota (a re-push of a known
474+ /// `external_id` is charged only for what it adds over the row it
475+ /// replaces), sniffs the mime, and upserts — the second push of an id is
476+ /// the same row with new bytes, never a sibling copy. Service bytes skip
477+ /// the thumbnail pipeline whole: the row wears [`ThumbState::None`].
478+ /// Returns the file id.
479+ async fn insert_service_file(
480+ &self,
481+ owner_id: &str,
482+ external_id: &str,
483+ name: &str,
484+ bytes: &[u8],
485+ ) -> Result<String>;
486+
487+ /// One service file's row, by the service's own handle.
488+ async fn service_file(&self, owner_id: &str, external_id: &str) -> Result<Option<File>>;
489+
490+ /// The bytes themselves, by the service's own handle. `None` when there
491+ /// is no such row, or its file went missing.
492+ async fn service_file_bytes(&self, owner_id: &str, external_id: &str)
493+ -> Result<Option<Vec<u8>>>;
494+
495+ /// Takes a service file away for good — the row, its bytes, and the
496+ /// usage they carried. No trash: a machine client's delete is a delete.
497+ /// `false` when there was no such row.
498+ async fn delete_service_file(&self, owner_id: &str, external_id: &str) -> Result<bool>;
499+
500+ /// Writes the ceiling im states for a service's account (`limit.unwrap_or
501+ /// (default_quota_bytes)` — no limit named is the house default). No-op
502+ /// when the service has no account. An unchanged ceiling writes nothing
503+ /// and wakes nobody: the family beat calls this every few minutes.
504+ async fn apply_service_limit(
505+ &self,
506+ service: &str,
507+ limit: Option<u64>,
508+ default_quota_bytes: u64,
509+ ) -> Result<()>;
418 510
419 // -- folders -----------------------------------------------------------511 // -- folders -----------------------------------------------------------
420 512
crates/in-core/src/store/reconcile.rsmodified+12 -0
@@ -219,6 +219,7 @@ fn build_maps(
219 old_has_download_count: bool,219 old_has_download_count: bool,
220 old_has_password_hash: bool,220 old_has_password_hash: bool,
221 old_has_photo_version: bool,221 old_has_photo_version: bool,
222+ old_has_external_id: bool,
222 ) -> Vec<TableMap> {223 ) -> Vec<TableMap> {
223 vec![224 vec![
224 TableMap {225 TableMap {
@@ -289,6 +290,11 @@ fn build_maps(
289 } else {290 } else {
290 ("download_count", "0".into())291 ("download_count", "0".into())
291 });292 });
293+ columns.push(if old_has_external_id {
294+ ("external_id", "old.external_id".into())
295+ } else {
296+ ("external_id", "NULL".into())
297+ });
292 columns298 columns
293 },299 },
294 },300 },
@@ -333,6 +339,10 @@ fn build_maps(
333 "expires_at",339 "expires_at",
334 ]),340 ]),
335 },341 },
342+ TableMap {
343+ name: "service_key",
344+ columns: old_cols(&["token_hash", "name", "service", "user_id", "created_at"]),
345+ },
336 TableMap {346 TableMap {
337 name: "setting",347 name: "setting",
338 columns: old_cols(&["key", "value"]),348 columns: old_cols(&["key", "value"]),
@@ -431,6 +441,7 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) ->
431 let old_has_download_count = old_has_column(old_conn, "file", "download_count").await?;441 let old_has_download_count = old_has_column(old_conn, "file", "download_count").await?;
432 let old_has_password_hash = old_has_column(old_conn, "share_link", "password_hash").await?;442 let old_has_password_hash = old_has_column(old_conn, "share_link", "password_hash").await?;
433 let old_has_photo_version = old_has_column(old_conn, "user", "photo_version").await?;443 let old_has_photo_version = old_has_column(old_conn, "user", "photo_version").await?;
444+ let old_has_external_id = old_has_column(old_conn, "file", "external_id").await?;
434 let maps = build_maps(445 let maps = build_maps(
435 old_has_ui,446 old_has_ui,
436 old_has_theme,447 old_has_theme,
@@ -438,6 +449,7 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) ->
438 old_has_download_count,449 old_has_download_count,
439 old_has_password_hash,450 old_has_password_hash,
440 old_has_photo_version,451 old_has_photo_version,
452+ old_has_external_id,
441 );453 );
442 validate_maps(new_conn, &maps).await?;454 validate_maps(new_conn, &maps).await?;
443 455
crates/in-core/src/store/schema.rsmodified+1 -0
@@ -20,6 +20,7 @@ pub(crate) const MIGRATIONS: &[&str] = &[
20 include_str!("../../migrations/0004_downloads_settings.sql"),20 include_str!("../../migrations/0004_downloads_settings.sql"),
21 include_str!("../../migrations/0005_link_password.sql"),21 include_str!("../../migrations/0005_link_password.sql"),
22 include_str!("../../migrations/0006_photo_version.sql"),22 include_str!("../../migrations/0006_photo_version.sql"),
23+ include_str!("../../migrations/0007_service_storage.sql"),
23 ];24 ];
24 25
25 /// The whole declared schema — every migration applied in order — as one26 /// The whole declared schema — every migration applied in order — as one
crates/in-core/src/store/turso_store.rsmodified+339 -2
@@ -16,8 +16,9 @@ use ulid::Ulid;
16 use super::blobs::{Blobs, LocalBlobs};16 use super::blobs::{Blobs, LocalBlobs};
17 use super::secret;17 use super::secret;
18 use super::{18 use super::{
19- CHUNK_SIZE, CreatedLink, File, Folder, Listing, Result, ShareKind, ShareLink, ShareUser,19+ CHUNK_SIZE, CreatedLink, File, Folder, Listing, Result, ServiceAccount, ShareKind, ShareLink,
20- SharedItem, Store, StoreError, ThumbState, UPLOAD_TTL_HOURS, UploadSession, UploadState, User,20+ ShareUser, SharedItem, Store, StoreError, ThumbState, UPLOAD_TTL_HOURS, UploadSession,
21+ UploadState, User,
21 };22 };
22 use super::{ReconcileOptions, reconcile, schema, sniff};23 use super::{ReconcileOptions, reconcile, schema, sniff};
23 use crate::live::{Change, Topic};24 use crate::live::{Change, Topic};
@@ -2898,6 +2899,342 @@ impl Store for TursoStore {
2898 }2899 }
2899 Ok(Listing { folders, files })2900 Ok(Listing { folders, files })
2900 }2901 }
2902+ // -- service accounts --------------------------------------------------
2903+
2904+ async fn create_service_account(
2905+ &self,
2906+ service: &str,
2907+ name: &str,
2908+ default_quota_bytes: u64,
2909+ ) -> Result<String> {
2910+ let token = new_token();
2911+ // IMMEDIATE: the account-exists read and the key write are one write
2912+ // set, and two concurrent mints of one service must land one key —
2913+ // the UNIQUE index says so, this transaction makes it a promise.
2914+ let mut conn = self.tx_conn().await?;
2915+ let tx = conn
2916+ .transaction_with_behavior(TransactionBehavior::Immediate)
2917+ .await
2918+ .map_err(backend)?;
2919+ let mut rows = tx
2920+ .query(
2921+ &format!("SELECT {USER_COLUMNS} FROM user WHERE oidc_sub = ?1"),
2922+ params![format!("service:{service}")],
2923+ )
2924+ .await
2925+ .map_err(backend)?;
2926+ let (user_id, fresh) = match rows.next().await.map_err(backend)? {
2927+ // The account outlives its keys: a re-mint after a revoke — or a
2928+ // rotate that raced — files under the row that already holds the
2929+ // service's bytes.
2930+ Some(row) => (user_from(&row)?.id, false),
2931+ None => {
2932+ let id = Ulid::new().to_string();
2933+ tx.execute(
2934+ "INSERT INTO user (id, oidc_sub, email, display_name, admin, disabled, \
2935+ quota_bytes, used_bytes, ui, theme, language, created_at, last_seen_at, \
2936+ photo_version) \
2937+ VALUES (?1, ?2, '', ?3, 0, 0, ?4, 0, 'instrument', 'dark', 'en', ?5, NULL, 0)",
2938+ params![
2939+ id.clone(),
2940+ format!("service:{service}"),
2941+ name,
2942+ default_quota_bytes as i64,
2943+ now_text()?
2944+ ],
2945+ )
2946+ .await
2947+ .map_err(backend)?;
2948+ (id, true)
2949+ }
2950+ };
2951+ drop(rows);
2952+ tx.execute(
2953+ "INSERT INTO service_key (token_hash, name, service, user_id, created_at) \
2954+ VALUES (?1, ?2, ?3, ?4, ?5)",
2955+ params![hash_share_token(&token), name, service, user_id.clone(), now_text()?],
2956+ )
2957+ .await
2958+ .map_err(backend)?;
2959+ tx.commit().await.map_err(backend)?;
2960+ if fresh {
2961+ // A new row arrived: the admin's Everyone panel may be open.
2962+ self.announce([Topic::Admin(user_id.clone()), Topic::Profile(user_id)]);
2963+ }
2964+ Ok(token)
2965+ }
2966+
2967+ async fn service_account_by_token(&self, token: &str) -> Result<Option<User>> {
2968+ let user_id = match self
2969+ .one_row(
2970+ "SELECT user_id FROM service_key WHERE token_hash = ?1",
2971+ params![hash_share_token(token)],
2972+ )
2973+ .await?
2974+ {
2975+ Some(row) => text(&row, 0)?,
2976+ None => return Ok(None),
2977+ };
2978+ self.user(&user_id).await
2979+ }
2980+
2981+ async fn list_service_accounts(&self) -> Result<Vec<ServiceAccount>> {
2982+ let conn = self.conn.lock().await;
2983+ let mut rows = conn
2984+ .query(
2985+ "SELECT k.service, k.name, k.user_id, u.used_bytes, k.created_at \
2986+ FROM service_key k JOIN user u ON u.id = k.user_id \
2987+ ORDER BY k.created_at, k.service",
2988+ (),
2989+ )
2990+ .await
2991+ .map_err(backend)?;
2992+ let mut out = Vec::new();
2993+ while let Some(row) = rows.next().await.map_err(backend)? {
2994+ out.push(ServiceAccount {
2995+ service: text(&row, 0)?,
2996+ name: text(&row, 1)?,
2997+ user_id: text(&row, 2)?,
2998+ used_bytes: row.get::<i64>(3).map_err(backend)?.max(0) as u64,
2999+ created_at: parse_stamp(&text(&row, 4)?)?,
3000+ });
3001+ }
3002+ Ok(out)
3003+ }
3004+
3005+ async fn rotate_service_key(&self, service: &str) -> Result<Option<String>> {
3006+ let token = new_token();
3007+ let conn = self.conn.lock().await;
3008+ let n = conn
3009+ .execute(
3010+ "UPDATE service_key SET token_hash = ?1 WHERE service = ?2",
3011+ params![hash_share_token(&token), service],
3012+ )
3013+ .await
3014+ .map_err(backend)?;
3015+ Ok((n > 0).then_some(token))
3016+ }
3017+
3018+ async fn revoke_service_key(&self, service: &str) -> Result<bool> {
3019+ let conn = self.conn.lock().await;
3020+ let n = conn
3021+ .execute(
3022+ "DELETE FROM service_key WHERE service = ?1",
3023+ params![service],
3024+ )
3025+ .await
3026+ .map_err(backend)?;
3027+ Ok(n > 0)
3028+ }
3029+
3030+ async fn insert_service_file(
3031+ &self,
3032+ owner_id: &str,
3033+ external_id: &str,
3034+ name: &str,
3035+ bytes: &[u8],
3036+ ) -> Result<String> {
3037+ let name = label_of(name);
3038+ let size = bytes.len() as u64;
3039+ let mime = sniff::sniff(bytes).to_string();
3040+ // IMMEDIATE: the existing-row read, the quota check and the row
3041+ // write are one write set — two concurrent pushes of one external_id
3042+ // must not each read room for themselves against the same row.
3043+ let mut conn = self.tx_conn().await?;
3044+ let tx = conn
3045+ .transaction_with_behavior(TransactionBehavior::Immediate)
3046+ .await
3047+ .map_err(backend)?;
3048+ let (quota, used) = check_quota(&tx, owner_id).await?;
3049+ let mut rows = tx
3050+ .query(
3051+ "SELECT id, size_bytes FROM file WHERE owner_id = ?1 AND external_id = ?2",
3052+ params![owner_id, external_id],
3053+ )
3054+ .await
3055+ .map_err(backend)?;
3056+ let replaced = match rows.next().await.map_err(backend)? {
3057+ Some(row) => Some((text(&row, 0)?, row.get::<i64>(1).map_err(backend)?.max(0) as u64)),
3058+ None => None,
3059+ };
3060+ drop(rows);
3061+ // A re-push of a known handle is charged only for what it adds over
3062+ // the row it replaces — the old bytes stop existing the moment the
3063+ // new ones commit.
3064+ let added_over = replaced.as_ref().map_or(0, |(_, old)| *old);
3065+ fit_quota(quota, used.saturating_sub(added_over), size)?;
3066+ // The bytes land first, then the row says they are there — the same
3067+ // order `insert_file` keeps. A crash between a re-push's blob write
3068+ // and its row update leaves old size over new bytes, and heals the
3069+ // moment the client pushes the same external_id again.
3070+ match replaced {
3071+ Some((id, _)) => {
3072+ self.blobs
3073+ .put(&format!("files/{id}"), bytes)
3074+ .await
3075+ .map_err(|e| StoreError::Backend(e.to_string()))?;
3076+ tx.execute(
3077+ "UPDATE file SET name = ?1, mime = ?2, size_bytes = ?3, updated_at = ?4 \
3078+ WHERE id = ?5",
3079+ params![name, mime, size as i64, now_text()?, id.as_str()],
3080+ )
3081+ .await
3082+ .map_err(backend)?;
3083+ refresh_usage(&tx, owner_id).await?;
3084+ tx.commit().await.map_err(backend)?;
3085+ self.announce([Topic::Library(owner_id.to_string())]);
3086+ Ok(id)
3087+ }
3088+ None => {
3089+ let id = Ulid::new().to_string();
3090+ let file_key = format!("files/{id}");
3091+ self.blobs
3092+ .put(&file_key, bytes)
3093+ .await
3094+ .map_err(|e| StoreError::Backend(e.to_string()))?;
3095+ let written = tx
3096+ .execute(
3097+ "INSERT INTO file (id, owner_id, folder_id, name, mime, size_bytes, \
3098+ thumb_state, created_at, updated_at, deleted_at, download_count, \
3099+ external_id) \
3100+ VALUES (?1, ?2, NULL, ?3, ?4, ?5, 'none', ?6, ?6, NULL, 0, ?7)",
3101+ params![
3102+ id.clone(),
3103+ owner_id,
3104+ name,
3105+ mime,
3106+ size as i64,
3107+ now_text()?,
3108+ external_id
3109+ ],
3110+ )
3111+ .await;
3112+ if let Err(e) = written {
3113+ // The row was never born, so the bytes must not outlive
3114+ // it under a name nothing points at.
3115+ let _ = self.blobs.delete(&[&file_key]).await;
3116+ return Err(backend(e));
3117+ }
3118+ refresh_usage(&tx, owner_id).await?;
3119+ tx.commit().await.map_err(backend)?;
3120+ self.announce([Topic::Library(owner_id.to_string())]);
3121+ Ok(id)
3122+ }
3123+ }
3124+ }
3125+
3126+ async fn service_file(&self, owner_id: &str, external_id: &str) -> Result<Option<File>> {
3127+ let sql = format!("SELECT {FILE_COLUMNS} FROM file WHERE owner_id = ?1 AND external_id = ?2");
3128+ match self.one_row(&sql, params![owner_id, external_id]).await? {
3129+ Some(row) => Ok(Some(file_from(&row)?)),
3130+ None => Ok(None),
3131+ }
3132+ }
3133+
3134+ async fn service_file_bytes(
3135+ &self,
3136+ owner_id: &str,
3137+ external_id: &str,
3138+ ) -> Result<Option<Vec<u8>>> {
3139+ match self.service_file(owner_id, external_id).await? {
3140+ None => Ok(None),
3141+ Some(file) => self.file_bytes(&file.id).await,
3142+ }
3143+ }
3144+
3145+ async fn delete_service_file(&self, owner_id: &str, external_id: &str) -> Result<bool> {
3146+ let mut conn = self.tx_conn().await?;
3147+ let tx = conn
3148+ .transaction_with_behavior(TransactionBehavior::Immediate)
3149+ .await
3150+ .map_err(backend)?;
3151+ let mut rows = tx
3152+ .query(
3153+ "SELECT id FROM file WHERE owner_id = ?1 AND external_id = ?2",
3154+ params![owner_id, external_id],
3155+ )
3156+ .await
3157+ .map_err(backend)?;
3158+ let Some(row) = rows.next().await.map_err(backend)? else {
3159+ return Ok(false);
3160+ };
3161+ let id = text(&row, 0)?;
3162+ drop(rows);
3163+ tx.execute("DELETE FROM file WHERE id = ?1", params![id.as_str()])
3164+ .await
3165+ .map_err(backend)?;
3166+ // A machine route's files are never granted or linked — service
3167+ // accounts cannot share — but the purge path's sweep is cheap and
3168+ // the rows must not outlive the file they name.
3169+ tx.execute(
3170+ "DELETE FROM share_user WHERE kind = 'file' AND target_id = ?1",
3171+ params![id.as_str()],
3172+ )
3173+ .await
3174+ .map_err(backend)?;
3175+ tx.execute(
3176+ "DELETE FROM share_link WHERE kind = 'file' AND target_id = ?1",
3177+ params![id.as_str()],
3178+ )
3179+ .await
3180+ .map_err(backend)?;
3181+ refresh_usage(&tx, owner_id).await?;
3182+ tx.commit().await.map_err(backend)?;
3183+ // After the delete: the bytes may only follow a delete that
3184+ // committed. Best-effort — a file that survives is orphaned bytes
3185+ // the boot sweep collects.
3186+ let _ = self
3187+ .blobs
3188+ .delete(&[&format!("files/{id}"), &format!("thumbs/{id}")])
3189+ .await;
3190+ self.announce([Topic::Library(owner_id.to_string())]);
3191+ Ok(true)
3192+ }
3193+
3194+ async fn apply_service_limit(
3195+ &self,
3196+ service: &str,
3197+ limit: Option<u64>,
3198+ default_quota_bytes: u64,
3199+ ) -> Result<()> {
3200+ let user_id = match self
3201+ .one_row(
3202+ "SELECT user_id FROM service_key WHERE service = ?1",
3203+ params![service],
3204+ )
3205+ .await?
3206+ {
3207+ Some(row) => text(&row, 0)?,
3208+ // No key, no account to ceiling — the beat moves on.
3209+ None => return Ok(()),
3210+ };
3211+ let quota_bytes = limit.unwrap_or(default_quota_bytes);
3212+ let conn = self.conn.lock().await;
3213+ let mut rows = conn
3214+ .query(
3215+ "SELECT quota_bytes FROM user WHERE id = ?1",
3216+ params![user_id.as_str()],
3217+ )
3218+ .await
3219+ .map_err(backend)?;
3220+ let current = match rows.next().await.map_err(backend)? {
3221+ Some(row) => row.get::<i64>(0).map_err(backend)?.max(0) as u64,
3222+ None => return Ok(()),
3223+ };
3224+ drop(rows);
3225+ if current == quota_bytes {
3226+ return Ok(());
3227+ }
3228+ conn.execute(
3229+ "UPDATE user SET quota_bytes = ?1 WHERE id = ?2",
3230+ params![quota_bytes as i64, user_id.as_str()],
3231+ )
3232+ .await
3233+ .map_err(backend)?;
3234+ drop(conn);
3235+ self.announce([Topic::Admin(user_id)]);
3236+ Ok(())
3237+ }
2901 } // impl Store for TursoStore3238 } // impl Store for TursoStore
2902 3239
2903 /// One folder row for a write to vet: locks nothing itself, runs on the3240 /// One folder row for a write to vet: locks nothing itself, runs on the
crates/in-core/tests/store.rsmodified+293 -0
@@ -2036,3 +2036,296 @@ async fn r2_thumbnails_round_trip() {
2036 .unwrap();2036 .unwrap();
2037 assert_eq!(stored, served);2037 assert_eq!(stored, served);
2038 }2038 }
2039+
2040+// ---------------------------------------------------------------------------
2041+// Service storage: the machine account, its key, and its file handles.
2042+// ---------------------------------------------------------------------------
2043+
2044+
2045+#[tokio::test]
2046+async fn minting_a_service_account_yields_a_key_that_opens_it() {
2047+ let scratch = Scratch::open().await;
2048+ let token = scratch
2049+ .store
2050+ .create_service_account("iz", "İz", 1024 * 1024)
2051+ .await
2052+ .unwrap();
2053+ assert!(!token.is_empty());
2054+ // The key opens the account, and the account is no person's row.
2055+ let account = scratch
2056+ .store
2057+ .service_account_by_token(&token)
2058+ .await
2059+ .unwrap()
2060+ .expect("the minted key opens");
2061+ assert_eq!(account.oidc_sub, "service:iz");
2062+ assert_eq!(account.email, "");
2063+ assert_eq!(account.display_name, "İz");
2064+ assert!(!account.admin);
2065+ assert_eq!(account.quota_bytes, 1024 * 1024);
2066+ // A wrong key answers None, never an account.
2067+ assert!(scratch
2068+ .store
2069+ .service_account_by_token("forged")
2070+ .await
2071+ .unwrap()
2072+ .is_none());
2073+ // The panel lists it with its usage.
2074+ let accounts = scratch.store.list_service_accounts().await.unwrap();
2075+ assert_eq!(accounts.len(), 1);
2076+ assert_eq!(accounts[0].service, "iz");
2077+ assert_eq!(accounts[0].used_bytes, 0);
2078+}
2079+
2080+#[tokio::test]
2081+async fn a_remint_after_revoke_reuses_the_account() {
2082+ let scratch = Scratch::open().await;
2083+ let original = scratch
2084+ .store
2085+ .create_service_account("iz", "İz", 1024 * 1024)
2086+ .await
2087+ .unwrap();
2088+ let user_id = scratch.store.list_service_accounts().await.unwrap()[0]
2089+ .user_id
2090+ .clone();
2091+ scratch
2092+ .store
2093+ .insert_service_file(&user_id, "pre", "pre.txt", b"old bytes")
2094+ .await
2095+ .unwrap();
2096+ // Revoke takes the key, never the account.
2097+ assert!(scratch.store.revoke_service_key("iz").await.unwrap());
2098+ assert!(!scratch.store.revoke_service_key("iz").await.unwrap());
2099+ assert!(scratch.store.list_service_accounts().await.unwrap().is_empty());
2100+ // The re-mint reopens the same account: its files keep counting.
2101+ scratch
2102+ .store
2103+ .create_service_account("iz", "İz", 1024 * 1024)
2104+ .await
2105+ .unwrap();
2106+ let accounts = scratch.store.list_service_accounts().await.unwrap();
2107+ assert_eq!(accounts.len(), 1);
2108+ assert_eq!(accounts[0].user_id, user_id);
2109+ let holder = scratch.store.user(&user_id).await.unwrap().unwrap();
2110+ assert_eq!(holder.used_bytes, 9);
2111+ // Rotate replaces the key; the old one stops opening, the new one opens.
2112+ let fresh = scratch.store.rotate_service_key("iz").await.unwrap().unwrap();
2113+ assert!(scratch
2114+ .store
2115+ .service_account_by_token(&original)
2116+ .await
2117+ .unwrap()
2118+ .is_none());
2119+ let opened = scratch
2120+ .store
2121+ .service_account_by_token(&fresh)
2122+ .await
2123+ .unwrap()
2124+ .expect("the rotated key opens");
2125+ assert_eq!(opened.oidc_sub, "service:iz");
2126+}
2127+
2128+#[tokio::test]
2129+async fn the_service_file_handle_is_idempotent_and_hard_deleted() {
2130+ let scratch = Scratch::open().await;
2131+ scratch
2132+ .store
2133+ .create_service_account("iz", "İz", 1024 * 1024)
2134+ .await
2135+ .unwrap();
2136+ let user_id = scratch.store.list_service_accounts().await.unwrap()[0]
2137+ .user_id
2138+ .clone();
2139+ let first = scratch
2140+ .store
2141+ .insert_service_file(&user_id, "att-1", "notes.txt", b"first")
2142+ .await
2143+ .unwrap();
2144+ let second = scratch
2145+ .store
2146+ .insert_service_file(&user_id, "att-1", "notes.txt", b"second-and-longer")
2147+ .await
2148+ .unwrap();
2149+ // One row, the bytes replaced, the id stable.
2150+ assert_eq!(first, second);
2151+ let row = scratch
2152+ .store
2153+ .service_file(&user_id, "att-1")
2154+ .await
2155+ .unwrap()
2156+ .expect("the handle names the row");
2157+ assert_eq!(row.name, "notes.txt");
2158+ assert_eq!(row.size_bytes, 17);
2159+ assert_eq!(row.thumb_state, ThumbState::None);
2160+ assert!(row.mime.starts_with("text/plain"), "sniffed: {}", row.mime);
2161+ let bytes = scratch
2162+ .store
2163+ .service_file_bytes(&user_id, "att-1")
2164+ .await
2165+ .unwrap()
2166+ .expect("bytes there");
2167+ assert_eq!(bytes, b"second-and-longer");
2168+ // Usage recomputed from the one row — never stacked.
2169+ let holder = scratch.store.user(&user_id).await.unwrap().unwrap();
2170+ assert_eq!(holder.used_bytes, 17);
2171+ // Delete: the row, the bytes and the usage all go. Second delete: false.
2172+ assert!(scratch
2173+ .store
2174+ .delete_service_file(&user_id, "att-1")
2175+ .await
2176+ .unwrap());
2177+ assert!(scratch
2178+ .store
2179+ .service_file_bytes(&user_id, "att-1")
2180+ .await
2181+ .unwrap()
2182+ .is_none());
2183+ let holder = scratch.store.user(&user_id).await.unwrap().unwrap();
2184+ assert_eq!(holder.used_bytes, 0);
2185+ assert!(!scratch
2186+ .store
2187+ .delete_service_file(&user_id, "att-1")
2188+ .await
2189+ .unwrap());
2190+}
2191+
2192+#[tokio::test]
2193+async fn the_service_quota_refuses_and_a_repush_is_charged_only_over_its_row() {
2194+ let scratch = Scratch::open().await;
2195+ scratch
2196+ .store
2197+ .create_service_account("iz", "İz", 64)
2198+ .await
2199+ .unwrap();
2200+ let user_id = scratch.store.list_service_accounts().await.unwrap()[0]
2201+ .user_id
2202+ .clone();
2203+ scratch
2204+ .store
2205+ .insert_service_file(&user_id, "small", "small.txt", b"tiny")
2206+ .await
2207+ .unwrap();
2208+ // Fresh push past the ceiling: refused.
2209+ let big = vec![b'a'; 100];
2210+ assert!(matches!(
2211+ scratch
2212+ .store
2213+ .insert_service_file(&user_id, "big", "big.bin", &big)
2214+ .await
2215+ .unwrap_err(),
2216+ StoreError::QuotaExceeded
2217+ ));
2218+ // Re-push past the ceiling *over the row it replaces*: refused, and the
2219+ // old bytes stay exactly what they were.
2220+ let overflow = vec![b'b'; 100];
2221+ assert!(matches!(
2222+ scratch
2223+ .store
2224+ .insert_service_file(&user_id, "small", "small.txt", &overflow)
2225+ .await
2226+ .unwrap_err(),
2227+ StoreError::QuotaExceeded
2228+ ));
2229+ assert_eq!(
2230+ scratch
2231+ .store
2232+ .service_file_bytes(&user_id, "small")
2233+ .await
2234+ .unwrap(),
2235+ Some(b"tiny".to_vec())
2236+ );
2237+ // A re-push that fits (small.txt replaces 4 bytes with 60): fine.
2238+ let fits = vec![b'c'; 60];
2239+ scratch
2240+ .store
2241+ .insert_service_file(&user_id, "small", "small.txt", &fits)
2242+ .await
2243+ .unwrap();
2244+ let holder = scratch.store.user(&user_id).await.unwrap().unwrap();
2245+ assert_eq!(holder.used_bytes, 60);
2246+}
2247+
2248+#[tokio::test]
2249+async fn the_family_limit_lands_on_the_account() {
2250+ let scratch = Scratch::open().await;
2251+ scratch
2252+ .store
2253+ .create_service_account("iz", "İz", 1024)
2254+ .await
2255+ .unwrap();
2256+ // im names a ceiling; the account takes it.
2257+ scratch
2258+ .store
2259+ .apply_service_limit("iz", Some(4096), 1024)
2260+ .await
2261+ .unwrap();
2262+ let accounts = scratch.store.list_service_accounts().await.unwrap();
2263+ let holder = scratch
2264+ .store
2265+ .user(&accounts[0].user_id)
2266+ .await
2267+ .unwrap()
2268+ .unwrap();
2269+ assert_eq!(holder.quota_bytes, 4096);
2270+ // No limit named: the house default.
2271+ scratch
2272+ .store
2273+ .apply_service_limit("iz", None, 1024)
2274+ .await
2275+ .unwrap();
2276+ let holder = scratch
2277+ .store
2278+ .user(&accounts[0].user_id)
2279+ .await
2280+ .unwrap()
2281+ .unwrap();
2282+ assert_eq!(holder.quota_bytes, 1024);
2283+ // A service with no key: no-op.
2284+ scratch
2285+ .store
2286+ .apply_service_limit("ghost", Some(7), 1024)
2287+ .await
2288+ .unwrap();
2289+}
2290+
2291+#[tokio::test]
2292+async fn probe_can_see_with_service_index() {
2293+ let scratch = Scratch::open().await;
2294+ let alice = alice(&scratch.store).await;
2295+ let bob = bob(&scratch.store).await;
2296+ let file = scratch
2297+ .store
2298+ .insert_file(&alice.id, None, "a.txt", b"a")
2299+ .await
2300+ .unwrap();
2301+ let seen = scratch
2302+ .store
2303+ .can_see(ShareKind::File, &file.id, &bob.id)
2304+ .await
2305+ .unwrap();
2306+ let hit_bob = scratch
2307+ .store
2308+ .search(&bob.id, "a.txt", 10)
2309+ .await
2310+ .unwrap()
2311+ .files
2312+ .len();
2313+ println!("PROBE can_see={seen} bob_search_hits={hit_bob}");
2314+ let conn = raw_conn(&scratch).await;
2315+ conn.execute("DROP INDEX file_external_by_owner", ())
2316+ .await
2317+ .unwrap();
2318+ let seen2 = scratch
2319+ .store
2320+ .can_see(ShareKind::File, &file.id, &bob.id)
2321+ .await
2322+ .unwrap();
2323+ let hit_bob2 = scratch
2324+ .store
2325+ .search(&bob.id, "a.txt", 10)
2326+ .await
2327+ .unwrap()
2328+ .files
2329+ .len();
2330+ println!("PROBE after drop can_see={seen2} bob_search_hits={hit_bob2}");
2331+}
crates/in-web/src/i18n.rsmodified+40 -1
@@ -246,7 +246,20 @@ pub enum Key {
246 EffectiveOrigin,246 EffectiveOrigin,
247 BaseUrlLabel,247 BaseUrlLabel,
248 BaseUrlNote,248 BaseUrlNote,
249- // Re-viewable share links (LinkVisible owns this block).249+ // Service keys (ServiceKeys owns this block).
250+ ServiceKeysTitle,
251+ ServiceKeyName,
252+ ServiceKeyService,
253+ ServiceKeyMint,
254+ ServiceKeyRotate,
255+ ServiceKeyRotateTitle,
256+ ServiceKeyRotateCost,
257+ ServiceKeyRevoke,
258+ ServiceKeyRevokeTitle,
259+ ServiceKeyRevokeCost,
260+ ServiceKeyShown,
261+ ServiceKeyCopy,
262+ ServiceKeyCreated,
250 Shared,263 Shared,
251 LegacyLinkNote,264 LegacyLinkNote,
252 RemintLink,265 RemintLink,
@@ -427,6 +440,19 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
427 "This link predates re-viewable addresses — revoke and mint a new one to carry it forward."440 "This link predates re-viewable addresses — revoke and mint a new one to carry it forward."
428 }441 }
429 RemintLink => "Mint a new link",442 RemintLink => "Mint a new link",
443+ ServiceKeysTitle => "Service keys",
444+ ServiceKeyName => "Name",
445+ ServiceKeyService => "Service",
446+ ServiceKeyMint => "Mint",
447+ ServiceKeyRotate => "Rotate the key",
448+ ServiceKeyRotateTitle => "Rotate this key?",
449+ ServiceKeyRotateCost => "The old key stops working.",
450+ ServiceKeyRevoke => "Revoke the key",
451+ ServiceKeyRevokeTitle => "Revoke this key?",
452+ ServiceKeyRevokeCost => "The key stops working. The account and its files stay.",
453+ ServiceKeyShown => "Copy it now. It is never shown again.",
454+ ServiceKeyCopy => "Copy",
455+ ServiceKeyCreated => "Created",
430 },456 },
431 Lang::Tr => match key {457 Lang::Tr => match key {
432 Cancel => "Vazgeç",458 Cancel => "Vazgeç",
@@ -589,6 +615,19 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
589 PasswordProtected => "Bu bağlantı kilitli",615 PasswordProtected => "Bu bağlantı kilitli",
590 PasswordPrompt => "Bağlantıyı açmak için parolayı girin.",616 PasswordPrompt => "Bağlantıyı açmak için parolayı girin.",
591 PasswordLabel => "Parola",617 PasswordLabel => "Parola",
618+ ServiceKeysTitle => "Hizmet anahtarları",
619+ ServiceKeyName => "Ad",
620+ ServiceKeyService => "Hizmet",
621+ ServiceKeyMint => "Üret",
622+ ServiceKeyRotate => "Anahtarı yenile",
623+ ServiceKeyRotateTitle => "Bu anahtar yenilensin mi?",
624+ ServiceKeyRotateCost => "Eski anahtar geçersiz olur.",
625+ ServiceKeyRevoke => "Anahtarı iptal et",
626+ ServiceKeyRevokeTitle => "Bu anahtar iptal edilsin mi?",
627+ ServiceKeyRevokeCost => "Anahtar geçersiz olur. Hesap ve dosyalar kalır.",
628+ ServiceKeyShown => "Şimdi kopyala. Bir daha gösterilmez.",
629+ ServiceKeyCopy => "Kopyala",
630+ ServiceKeyCreated => "Yaratıldı",
592 WrongPassword => "Parola hatalı.",631 WrongPassword => "Parola hatalı.",
593 Unlock => "Kilidi aç",632 Unlock => "Kilidi aç",
594 ServerAddress => "Sunucu adresi",633 ServerAddress => "Sunucu adresi",
crates/in-web/src/layout.rsmodified+1 -0
@@ -562,6 +562,7 @@ pub async fn soft_nav_script(cx: &Cx) -> Result {
562 ); \562 ); \
563 }; \563 }; \
564 window.__inRefresh = function () { \564 window.__inRefresh = function () { \
565+ if (document.querySelector('.service-secret')) { return; } \
565 var n = window.__inNav; \566 var n = window.__inNav; \
566 fetch(window.location.href).then( \567 fetch(window.location.href).then( \
567 function (r) { return r.text().then(function (t) { if (stillCurrent(n)) { swap(t, r.url, false, false, true); } }); }, \568 function (r) { return r.text().then(function (t) { if (stillCurrent(n)) { swap(t, r.url, false, false, true); } }); }, \
crates/in-web/src/lib.rsmodified+1 -0
@@ -12,6 +12,7 @@ pub mod layout;
12 pub mod live;12 pub mod live;
13 pub mod pages;13 pub mod pages;
14 pub mod server;14 pub mod server;
15+pub mod service;
15 pub mod settings;16 pub mod settings;
16 pub mod share;17 pub mod share;
17 pub mod trash;18 pub mod trash;
crates/in-web/src/main.rsmodified+21 -6
@@ -250,6 +250,7 @@ async fn main() {
250 store.clone(),250 store.clone(),
251 in_client::InClient::new(oidc.clone()),251 in_client::InClient::new(oidc.clone()),
252 public_origin,252 public_origin,
253+ default_quota_bytes,
253 ));254 ));
254 255
255 // Told when the process is stopping, so the live streams end instead of256 // Told when the process is stopping, so the live streams end instead of
@@ -267,6 +268,7 @@ async fn main() {
267 // so its guard sits at a hard 2 GiB; `/api/upload` carries single268 // so its guard sits at a hard 2 GiB; `/api/upload` carries single
268 // 8 MiB chunks, so 32 MiB leaves ample headroom.269 // 8 MiB chunks, so 32 MiB leaves ample headroom.
269 .layer(BodyLimit::max(32 * 1024 * 1024).at("/api/upload"))270 .layer(BodyLimit::max(32 * 1024 * 1024).at("/api/upload"))
271+ .layer(BodyLimit::max(512 * 1024 * 1024).at("/api/service/files"))
270 .layer(BodyLimit::max(2usize * 1024 * 1024 * 1024).at("/files"))272 .layer(BodyLimit::max(2usize * 1024 * 1024 * 1024).at("/files"))
271 .cookies()273 .cookies()
272 .assets(bundle),274 .assets(bundle),
@@ -467,6 +469,7 @@ async fn family_sync(
467 store: Arc<dyn in_core::store::Store>,469 store: Arc<dyn in_core::store::Store>,
468 client: in_client::InClient,470 client: in_client::InClient,
469 origin: String,471 origin: String,
472+ default_quota_bytes: u64,
470 ) {473 ) {
471 if origin.is_empty() {474 if origin.is_empty() {
472 eprintln!("family: no public address to register; set base_url");475 eprintln!("family: no public address to register; set base_url");
@@ -481,14 +484,26 @@ async fn family_sync(
481 eprintln!("family register: {problem}");484 eprintln!("family register: {problem}");
482 }485 }
483 match client.family().await {486 match client.family().await {
484- Some(family) => match serde_json::to_string(&family) {487+ Some(family) => {
485- Ok(json) => {488+ // The limits ride the same list: every service key's account
486- if let Err(problem) = store.set_setting("family", &json).await {489+ // takes the ceiling im states for it (the house default when
487- eprintln!("family sync: {problem}");490+ // im states none). A refused write is one log line — the
491+ // next beat carries the same word.
492+ if let Err(problem) =
493+ in_web::service::apply_family_limits(&store, &family, default_quota_bytes)
494+ .await
495+ {
496+ eprintln!("family limits: {problem}");
497+ }
498+ match serde_json::to_string(&family) {
499+ Ok(json) => {
500+ if let Err(problem) = store.set_setting("family", &json).await {
501+ eprintln!("family sync: {problem}");
502+ }
488 }503 }
504+ Err(problem) => eprintln!("family sync: {problem}"),
489 }505 }
490- Err(problem) => eprintln!("family sync: {problem}"),506+ }
491- },
492 None => eprintln!("family sync: im did not answer; keeping the list there is"),507 None => eprintln!("family sync: im did not answer; keeping the list there is"),
493 }508 }
494 tokio::time::sleep(std::time::Duration::from_secs(FAMILY_SECONDS)).await;509 tokio::time::sleep(std::time::Duration::from_secs(FAMILY_SECONDS)).await;
crates/in-web/src/server.rsmodified+72 -1
@@ -9,7 +9,9 @@
9 //! it. This module's `current_user` maps im's claims onto the local user row,9 //! it. This module's `current_user` maps im's claims onto the local user row,
10 //! provisioning it on first sight.10 //! provisioning it on first sight.
11 11
12-use std::sync::Arc;12+use std::collections::HashMap;
13+
14+use std::sync::{Arc, LazyLock, PoisonError};
13 15
14 use in_core::Config;16 use in_core::Config;
15 use in_core::store::{Store, StoreError, User};17 use in_core::store::{Store, StoreError, User};
@@ -297,6 +299,61 @@ pub async fn require_admin(cx: &Cx) -> Result<User, Refusal> {
297 }299 }
298 }300 }
299 301
302+/// The service behind this request, by bearer key — the machine half of the
303+/// auth surface. A human browser's session cookie means nothing here and a
304+/// service key means nothing to [`current_user`]: the two never meet. A
305+/// disabled account reads as no key at all, the same way a disabled person
306+/// reads as signed out.
307+pub async fn service_client(cx: &Cx) -> Option<User> {
308+ let presented = headers(cx)
309+ .get(header::AUTHORIZATION)
310+ .and_then(|value| value.to_str().ok())?;
311+ let token = presented.strip_prefix("Bearer ")?.trim();
312+ if token.is_empty() {
313+ return None;
314+ }
315+ let user = app(cx)
316+ .store
317+ .service_account_by_token(token)
318+ .await
319+ .ok()??;
320+ (!user.disabled).then_some(user)
321+}
322+
323+/// How long a freshly minted service key waits on the shelf for its one
324+/// showing: ten minutes, im's own ticket lifetime.
325+const SHOWN_TTL: std::time::Duration = std::time::Duration::from_secs(10 * 60);
326+
327+/// Where a freshly minted service key waits between its POST and the one
328+/// GET that shows it. The panel's write answers a 303 — the house idiom —
329+/// but the key itself must never ride a URL or a log line, so the query
330+/// carries only a random claim ticket: the shelf holds the plaintext, the
331+/// page's read takes it out ([`take_shown_secret`]), and a replayed or
332+/// reloaded URL finds the shelf empty and renders no key at all. A restart
333+/// drops the shelf — the admin mints another.
334+static SHOWN_SECRETS: LazyLock<std::sync::Mutex<HashMap<String, (String, std::time::Instant)>>> =
335+ LazyLock::new(|| std::sync::Mutex::new(HashMap::new()));
336+
337+/// Parks a fresh service key on the shelf and returns the claim ticket for
338+/// its URL.
339+pub fn stash_shown_secret(secret: String) -> String {
340+ let ticket = format!("{}", ulid::Ulid::new());
341+ let mut shelf = SHOWN_SECRETS.lock().unwrap_or_else(PoisonError::into_inner);
342+ shelf.retain(|_, (_, parked)| parked.elapsed() < SHOWN_TTL);
343+ shelf.insert(ticket.clone(), (secret, std::time::Instant::now()));
344+ ticket
345+}
346+
347+/// Takes a stashed key out — exactly once; the second reader of the same
348+/// ticket gets nothing.
349+pub fn take_shown_secret(ticket: &str) -> Option<String> {
350+ SHOWN_SECRETS
351+ .lock()
352+ .unwrap_or_else(PoisonError::into_inner)
353+ .remove(ticket)
354+ .map(|(secret, _)| secret)
355+}
356+
300 impl From<StoreError> for Refusal {357 impl From<StoreError> for Refusal {
301 fn from(_: StoreError) -> Refusal {358 fn from(_: StoreError) -> Refusal {
302 Refusal::Unavailable359 Refusal::Unavailable
@@ -350,6 +407,12 @@ pub enum Refusal {
350 /// The admin's server-address form named something no public link can407 /// The admin's server-address form named something no public link can
351 /// be built on — no `http`/`https` scheme, or a trailing slash.408 /// be built on — no `http`/`https` scheme, or a trailing slash.
352 BadBaseUrl,409 BadBaseUrl,
410+ /// A quota form named a service account: the ceiling is im's to set,
411+ /// and the family beat carries it.
412+ ServiceQuota,
413+ /// A Service keys form named a service that cannot take the action —
414+ /// not mintable, not keyed, or an empty name.
415+ BadServiceKey,
353 }416 }
354 417
355 impl Refusal {418 impl Refusal {
@@ -374,6 +437,8 @@ impl Refusal {
374 Refusal::BadLanguage => "That is not a language.".to_string(),437 Refusal::BadLanguage => "That is not a language.".to_string(),
375 Refusal::BadLimit => "That limit is not usable.".to_string(),438 Refusal::BadLimit => "That limit is not usable.".to_string(),
376 Refusal::BadBaseUrl => "That address is not an origin links can be built on.".to_string(),439 Refusal::BadBaseUrl => "That address is not an origin links can be built on.".to_string(),
440+ Refusal::ServiceQuota => "The limit is im's to set.".to_string(),
441+ Refusal::BadServiceKey => "That key is not usable.".to_string(),
377 }442 }
378 }443 }
379 444
@@ -400,6 +465,8 @@ impl Refusal {
400 Refusal::BadLanguage => "Bu bir dil değil.".to_string(),465 Refusal::BadLanguage => "Bu bir dil değil.".to_string(),
401 Refusal::BadLimit => "Bu sınır kullanılamaz.".to_string(),466 Refusal::BadLimit => "Bu sınır kullanılamaz.".to_string(),
402 Refusal::BadBaseUrl => "Bu adres, bağlantı kurulabilecek bir kök adres değil.".to_string(),467 Refusal::BadBaseUrl => "Bu adres, bağlantı kurulabilecek bir kök adres değil.".to_string(),
468+ Refusal::ServiceQuota => "Limit im'de belirlenir.".to_string(),
469+ Refusal::BadServiceKey => "Bu anahtar kullanılamaz.".to_string(),
403 }470 }
404 }471 }
405 472
@@ -424,6 +491,8 @@ impl Refusal {
424 "bad-language" => Refusal::BadLanguage,491 "bad-language" => Refusal::BadLanguage,
425 "bad-limit" => Refusal::BadLimit,492 "bad-limit" => Refusal::BadLimit,
426 "bad-base-url" => Refusal::BadBaseUrl,493 "bad-base-url" => Refusal::BadBaseUrl,
494+ "service-quota" => Refusal::ServiceQuota,
495+ "bad-service-key" => Refusal::BadServiceKey,
427 _ => return None,496 _ => return None,
428 })497 })
429 }498 }
@@ -452,6 +521,8 @@ impl Refusal {
452 Refusal::BadLanguage => "bad-language",521 Refusal::BadLanguage => "bad-language",
453 Refusal::BadLimit => "bad-limit",522 Refusal::BadLimit => "bad-limit",
454 Refusal::BadBaseUrl => "bad-base-url",523 Refusal::BadBaseUrl => "bad-base-url",
524+ Refusal::ServiceQuota => "service-quota",
525+ Refusal::BadServiceKey => "bad-service-key",
455 }526 }
456 }527 }
457 }528 }
crates/in-web/src/service.rsadded+278 -0
@@ -0,0 +1,278 @@
1+//! The machine API: the four routes a family service drives with its bearer
2+//! key — push a file under its own handle, fetch it back, take it away, and
3+//! read its quota. Every answer is 200 JSON in the house `{"ok": ...}` /
4+//! `{"err": <word>}` shape, except a missing or spent key, which answers
5+//! `401 {"err":"Unauthorized"}` — one word, because telling a stranger which
6+//! keys exist is the leak the shape exists to prevent.
7+//!
8+//! A human browser's session cookie means nothing on these routes, and a
9+//! bearer key means nothing on the human ones: [`crate::server::service_client`]
10+//! never reads a cookie, and [`crate::server::current_user`] never reads the
11+//! `Authorization` header.
12+
13+use in_core::store::{Store, StoreError};
14+use serde::Serialize;
15+use topcoat::Result;
16+use topcoat::context::Cx;
17+use topcoat::router::content::Json;
18+use topcoat::router::content::multipart::Multipart;
19+use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, path_param, route};
20+
21+use crate::server::{Refusal, app, service_client};
22+
23+path_param!(external_id);
24+
25+/// The machine answer: one flat JSON object, whatever the call owes. The
26+/// status route carries its facts beside `ok`, so the shape is a map built
27+/// by hand, not serde's `Result`.
28+enum Reply {
29+ /// `401 {"err":"Unauthorized"}`.
30+ Unauthorized,
31+ /// `200 {"err": <word>}` — the word the caller's contract names.
32+ Err(&'static str),
33+ /// `200 {"ok": <value>}` — a file id, or `true`.
34+ Ok(serde_json::Value),
35+ /// `200 {"ok":true,"quota_bytes":N,"used_bytes":N}`.
36+ Status { quota_bytes: u64, used_bytes: u64 },
37+}
38+
39+impl Serialize for Reply {
40+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
41+ use serde::ser::SerializeMap;
42+ let mut map = serializer.serialize_map(None)?;
43+ match self {
44+ Reply::Unauthorized => map.serialize_entry("err", "Unauthorized")?,
45+ Reply::Err(word) => map.serialize_entry("err", word)?,
46+ Reply::Ok(value) => map.serialize_entry("ok", value)?,
47+ Reply::Status {
48+ quota_bytes,
49+ used_bytes,
50+ } => {
51+ map.serialize_entry("ok", &true)?;
52+ map.serialize_entry("quota_bytes", quota_bytes)?;
53+ map.serialize_entry("used_bytes", used_bytes)?;
54+ }
55+ }
56+ map.end()
57+ }
58+}
59+
60+type ServiceReply = Result<(StatusCode, Json<Reply>)>;
61+
62+fn unauthorized() -> ServiceReply {
63+ Ok((StatusCode::UNAUTHORIZED, Json(Reply::Unauthorized)))
64+}
65+
66+fn refused(word: &'static str) -> ServiceReply {
67+ Ok((StatusCode::OK, Json(Reply::Err(word))))
68+}
69+
70+fn served(value: serde_json::Value) -> ServiceReply {
71+ Ok((StatusCode::OK, Json(Reply::Ok(value))))
72+}
73+
74+fn not_found_bytes() -> (StatusCode, HeaderMap, Vec<u8>) {
75+ (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new())
76+}
77+
78+/// The byte-route 401: no body worth parsing, the status is the answer.
79+fn unauthorized_bytes() -> (StatusCode, HeaderMap, Vec<u8>) {
80+ (StatusCode::UNAUTHORIZED, HeaderMap::new(), Vec::new())
81+}
82+
83+/// `POST /api/service/files` — one file under the service's own handle.
84+/// Multipart fields `external_id` and `name`, then the bytes as the `file`
85+/// part. A second push of a known `external_id` is the same file with new
86+/// bytes; the quota refusal is the one the contract names.
87+#[route(POST "/api/service/files")]
88+async fn service_upload(cx: &Cx, mut multipart: Multipart) -> ServiceReply {
89+ let Some(account) = service_client(cx).await else {
90+ return unauthorized();
91+ };
92+ let mut external_id: Option<String> = None;
93+ let mut name: Option<String> = None;
94+ let mut bytes: Option<Vec<u8>> = None;
95+ loop {
96+ let field = match multipart.next_field().await {
97+ Ok(Some(field)) => field,
98+ Ok(None) => break,
99+ Err(_) => return refused("Unavailable"),
100+ };
101+ match field.name() {
102+ Some("external_id") => {
103+ external_id = field.text().await.ok().filter(|value| !value.is_empty());
104+ }
105+ Some("name") => {
106+ name = field.text().await.ok().filter(|value| !value.is_empty());
107+ }
108+ Some("file") => {
109+ let mut field = field;
110+ let mut collected = Vec::new();
111+ loop {
112+ match field.chunk().await {
113+ Ok(Some(chunk)) => collected.extend_from_slice(&chunk),
114+ Ok(None) => break,
115+ Err(_) => return refused("Unavailable"),
116+ }
117+ }
118+ bytes = Some(collected);
119+ }
120+ _ => {}
121+ }
122+ }
123+ let (Some(external_id), Some(name), Some(bytes)) = (external_id, name, bytes) else {
124+ return refused("BadRequest");
125+ };
126+ let store = app(cx).store.clone();
127+ match store
128+ .insert_service_file(&account.id, &external_id, &name, &bytes)
129+ .await
130+ {
131+ Ok(id) => served(serde_json::Value::String(id)),
132+ Err(StoreError::QuotaExceeded) => refused("QuotaExceeded"),
133+ Err(_) => refused("Unavailable"),
134+ }
135+}
136+
137+/// `GET /api/service/file/{external_id}` — the bytes, under the same
138+/// download headers the human drive serves: the stored name as attachment,
139+/// and a year of `immutable`, because the handle can never outlive its
140+/// bytes. A handle that names nothing answers the same 404 a stranger's
141+/// file id would.
142+#[route(GET "/api/service/file/{external_id}")]
143+async fn service_download(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
144+ let Some(account) = service_client(cx).await else {
145+ return Ok(unauthorized_bytes());
146+ };
147+ let external_id: &str = path_param::<ExternalId>(cx);
148+ let store = app(cx).store.clone();
149+ let Some(file) = store
150+ .service_file(&account.id, external_id)
151+ .await
152+ .ok()
153+ .flatten()
154+ else {
155+ return Ok(not_found_bytes());
156+ };
157+ let Some(bytes) = store.file_bytes(&file.id).await.ok().flatten() else {
158+ return Ok(not_found_bytes());
159+ };
160+ let mut headers = HeaderMap::new();
161+ headers.insert(
162+ header::CONTENT_DISPOSITION,
163+ HeaderValue::from_str(&format!(
164+ "attachment; filename=\"{}\"",
165+ ascii_name(&file.name)
166+ ))
167+ .unwrap_or(HeaderValue::from_static("attachment")),
168+ );
169+ if let Ok(value) = HeaderValue::from_str(&file.mime) {
170+ headers.insert(header::CONTENT_TYPE, value);
171+ }
172+ headers.insert(
173+ header::CACHE_CONTROL,
174+ HeaderValue::from_static("private, max-age=31536000, immutable"),
175+ );
176+ Ok((StatusCode::OK, headers, bytes))
177+}
178+
179+/// The ASCII half of a `Content-Disposition` filename: only characters no
180+/// quoting scheme could turn into a delimiter survive.
181+fn ascii_name(file_name: &str) -> String {
182+ file_name
183+ .chars()
184+ .map(|c| {
185+ if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
186+ c
187+ } else {
188+ '_'
189+ }
190+ })
191+ .collect()
192+}
193+
194+/// `DELETE /api/service/file/{external_id}` — the bytes are gone, the
195+/// account's usage follows. A machine client's delete is a delete.
196+#[route(DELETE "/api/service/file/{external_id}")]
197+async fn service_delete(cx: &Cx) -> ServiceReply {
198+ let Some(account) = service_client(cx).await else {
199+ return unauthorized();
200+ };
201+ let external_id: &str = path_param::<ExternalId>(cx);
202+ let store = app(cx).store.clone();
203+ match store.delete_service_file(&account.id, external_id).await {
204+ Ok(_) => served(serde_json::Value::Bool(true)),
205+ Err(_) => refused("Unavailable"),
206+ }
207+}
208+
209+/// `GET /api/service/status` — the account's ceiling and what it holds, the
210+/// two numbers a service's admin page shows.
211+#[route(GET "/api/service/status")]
212+async fn service_status(cx: &Cx) -> ServiceReply {
213+ let Some(account) = service_client(cx).await else {
214+ return unauthorized();
215+ };
216+ let store = app(cx).store.clone();
217+ let Ok(Some(fresh)) = store.user(&account.id).await else {
218+ return refused("Unavailable");
219+ };
220+ Ok((
221+ StatusCode::OK,
222+ Json(Reply::Status {
223+ quota_bytes: fresh.quota_bytes,
224+ used_bytes: fresh.used_bytes,
225+ }),
226+ ))
227+}
228+
229+/// Takes every service key's ceiling from a freshly fetched family: the
230+/// limit im states for the service's key, or the house default when im
231+/// states none. The family beat calls this after every successful fetch; a
232+/// failure is one log line and nothing else — the next beat re-asks.
233+pub async fn apply_family_limits(
234+ store: &std::sync::Arc<dyn Store>,
235+ family: &[in_client::ServiceJson],
236+ default_quota_bytes: u64,
237+) -> Result<(), String> {
238+ for account in store
239+ .list_service_accounts()
240+ .await
241+ .map_err(|e| e.to_string())?
242+ {
243+ let limit = family
244+ .iter()
245+ .find(|row| row.key == account.service)
246+ .and_then(|row| row.limit_bytes);
247+ store
248+ .apply_service_limit(&account.service, limit, default_quota_bytes)
249+ .await
250+ .map_err(|e| e.to_string())?;
251+ }
252+ Ok(())
253+}
254+
255+/// The mintable services, for the panel's dropdown and the mint route's
256+/// gate: named by the family mirror, and not keyed yet.
257+pub(crate) async fn mintable_services(
258+ cx: &Cx,
259+) -> std::result::Result<Vec<in_client::ServiceJson>, Refusal> {
260+ let store = app(cx).store.clone();
261+ let family = store
262+ .get_setting("family")
263+ .await
264+ .map_err(Refusal::from)?
265+ .and_then(|json| serde_json::from_str::<Vec<in_client::ServiceJson>>(&json).ok())
266+ .unwrap_or_default();
267+ let keyed: std::collections::HashSet<String> = store
268+ .list_service_accounts()
269+ .await
270+ .map_err(Refusal::from)?
271+ .into_iter()
272+ .map(|account| account.service)
273+ .collect();
274+ Ok(family
275+ .into_iter()
276+ .filter(|row| !keyed.contains(&row.key))
277+ .collect())
278+}
crates/in-web/src/settings.rsmodified+216 -3
@@ -24,6 +24,7 @@ use topcoat::view::view;
24 use crate::server::{24 use crate::server::{
25 Refusal, app, back_to, require_admin, require_user, share_link_url, share_origin,25 Refusal, app, back_to, require_admin, require_user, share_link_url, share_origin,
26 };26 };
27+use crate::service::mintable_services;
27 use crate::share::{refusal_banner, refusal_of, share_copy_script};28 use crate::share::{refusal_banner, refusal_of, share_copy_script};
28 use crate::i18n::{Key, lang, t};29 use crate::i18n::{Key, lang, t};
29 use crate::layout::{NavPage, topbar};30 use crate::layout::{NavPage, topbar};
@@ -142,6 +143,19 @@ async fn set_quota(cx: &Cx, Form(input): Form<QuotaForm>) -> Redirect {
142 if let Err(refusal) = require_admin(cx).await {143 if let Err(refusal) = require_admin(cx).await {
143 return redirect_back(cx, "/settings?section=everyone", "quota", Some(refusal));144 return redirect_back(cx, "/settings?section=everyone", "quota", Some(refusal));
144 }145 }
146+ // A service account's ceiling is im's to set: the family beat carries
147+ // it here. The Everyone row keeps its form so the panel reads
148+ // uniformly, but the write refuses — the server-side gate is the one
149+ // that holds.
150+ let service_target = app(cx)
151+ .store
152+ .list_service_accounts()
153+ .await
154+ .map(|accounts| accounts.iter().any(|account| account.user_id == input.user_id))
155+ .unwrap_or(false);
156+ if service_target {
157+ return redirect_back(cx, "/settings?section=everyone", "quota", Some(Refusal::ServiceQuota));
158+ }
145 match unit_bytes(&input.quota, &input.quota_unit) {159 match unit_bytes(&input.quota, &input.quota_unit) {
146 Some(quota_bytes) => match app(cx)160 Some(quota_bytes) => match app(cx)
147 .store161 .store
@@ -263,6 +277,89 @@ async fn set_base_url(cx: &Cx, Form(input): Form<BaseUrlForm>) -> Redirect {
263 }277 }
264 }278 }
265 279
280+#[derive(Deserialize)]
281+struct ServiceAddForm {
282+ service: String,
283+ name: String,
284+}
285+
286+#[derive(Deserialize)]
287+struct ServiceAction {
288+ service: String,
289+}
290+
291+/// Back from a Service keys post, the fresh key's claim ticket on the query.
292+/// The ticket is all the URL ever carries; the shelf holds the key itself.
293+fn redirect_shown(cx: &Cx, ticket: &str) -> Redirect {
294+ let back = back_to(cx, "/settings?section=service");
295+ let separator = if back.contains('?') { '&' } else { '?' };
296+ Ok((
297+ StatusCode::SEE_OTHER,
298+ [(header::LOCATION, format!("{back}{separator}shown={ticket}"))],
299+ ))
300+}
301+
302+/// Mints one service account and its key. The service must be one the
303+/// family mirror names and no key yet covers; the name is what the panel
304+/// prints. The minted key is shown once.
305+#[route(POST "/api/settings/service_add")]
306+async fn service_add(cx: &Cx, Form(input): Form<ServiceAddForm>) -> Redirect {
307+ if let Err(refusal) = require_admin(cx).await {
308+ return redirect_back(cx, "/settings?section=service", "service_add", Some(refusal));
309+ }
310+ let service = input.service.trim();
311+ let name = input.name.trim();
312+ if name.is_empty() {
313+ return redirect_back(cx, "/settings?section=service", "service_add", Some(Refusal::BadServiceKey));
314+ }
315+ let mintable = match mintable_services(cx).await {
316+ Ok(mintable) => mintable,
317+ Err(refusal) => {
318+ return redirect_back(cx, "/settings?section=service", "service_add", Some(refusal));
319+ }
320+ };
321+ if !mintable.iter().any(|row| row.key == service) {
322+ return redirect_back(cx, "/settings?section=service", "service_add", Some(Refusal::BadServiceKey));
323+ }
324+ let default_quota_bytes = app(cx).config.default_quota_bytes;
325+ match app(cx)
326+ .store
327+ .create_service_account(service, name, default_quota_bytes)
328+ .await
329+ {
330+ Ok(token) => redirect_shown(cx, &crate::server::stash_shown_secret(token)),
331+ Err(_) => redirect_back(cx, "/settings?section=service", "service_add", Some(Refusal::Unavailable)),
332+ }
333+}
334+
335+/// Replaces one service's key. The account and its files stay; the fresh
336+/// key is shown once.
337+#[route(POST "/api/settings/service_rotate")]
338+async fn service_rotate(cx: &Cx, Form(input): Form<ServiceAction>) -> Redirect {
339+ if let Err(refusal) = require_admin(cx).await {
340+ return redirect_back(cx, "/settings?section=service", "service_rotate", Some(refusal));
341+ }
342+ match app(cx).store.rotate_service_key(&input.service).await {
343+ Ok(Some(token)) => redirect_shown(cx, &crate::server::stash_shown_secret(token)),
344+ Ok(None) => redirect_back(cx, "/settings?section=service", "service_rotate", Some(Refusal::BadServiceKey)),
345+ Err(_) => redirect_back(cx, "/settings?section=service", "service_rotate", Some(Refusal::Unavailable)),
346+ }
347+}
348+
349+/// Deletes one service's key. The account and its files remain — its usage
350+/// reads in the Everyone panel like any other account's.
351+#[route(POST "/api/settings/service_revoke")]
352+async fn service_revoke(cx: &Cx, Form(input): Form<ServiceAction>) -> Redirect {
353+ if let Err(refusal) = require_admin(cx).await {
354+ return redirect_back(cx, "/settings?section=service", "service_revoke", Some(refusal));
355+ }
356+ match app(cx).store.revoke_service_key(&input.service).await {
357+ Ok(true) => redirect_back(cx, "/settings?section=service", "service_revoke", None),
358+ Ok(false) => redirect_back(cx, "/settings?section=service", "service_revoke", Some(Refusal::BadServiceKey)),
359+ Err(_) => redirect_back(cx, "/settings?section=service", "service_revoke", Some(Refusal::Unavailable)),
360+ }
361+}
362+
266 /// Which rail section the page renders. Only one is drawn at a time; an363 /// Which rail section the page renders. Only one is drawn at a time; an
267 /// admin-only value asked for by anyone else falls back to `Profile`, same364 /// admin-only value asked for by anyone else falls back to `Profile`, same
268 /// as a section name it does not recognize at all.365 /// as a section name it does not recognize at all.
@@ -272,8 +369,8 @@ enum Section {
272 Links,369 Links,
273 Everyone,370 Everyone,
274 Server,371 Server,
372+ Service,
275 }373 }
276-
277 /// The class a rail link wears: `active` on the section it points to when374 /// The class a rail link wears: `active` on the section it points to when
278 /// that is the one showing, plain otherwise.375 /// that is the one showing, plain otherwise.
279 fn rail_class(current: Section, target: Section) -> &'static str {376 fn rail_class(current: Section, target: Section) -> &'static str {
@@ -342,9 +439,9 @@ async fn settings(cx: &Cx) -> Result {
342 Some("links") => Section::Links,439 Some("links") => Section::Links,
343 Some("everyone") if administers => Section::Everyone,440 Some("everyone") if administers => Section::Everyone,
344 Some("server") if administers => Section::Server,441 Some("server") if administers => Section::Server,
442+ Some("service") if administers => Section::Service,
345 _ => Section::Profile,443 _ => Section::Profile,
346 };444 };
347- let created = created_token(query);
348 // Only the section on show pays for its rows: the links panel names445 // Only the section on show pays for its rows: the links panel names
349 // each live link's target, Everyone lists the accounts, and the server446 // each live link's target, Everyone lists the accounts, and the server
350 // panel needs the origin — nothing else reads them.447 // panel needs the origin — nothing else reads them.
@@ -406,6 +503,26 @@ async fn settings(cx: &Cx) -> Result {
406 } else {503 } else {
407 String::new()504 String::new()
408 };505 };
506+ // The Service keys panel's two reads: the keyed accounts, and the
507+ // family rows no key covers yet — the mint dropdown's options. Both are
508+ // admin-only reads on an admin-only section.
509+ let (accounts, mintable) = if administers && section == Section::Service {
510+ let accounts = store.list_service_accounts().await?;
511+ let mintable = mintable_services(cx).await.unwrap_or_default();
512+ (accounts, mintable)
513+ } else {
514+ (Vec::new(), Vec::new())
515+ };
516+ // The one read that takes a stashed key off the shelf — and only on the
517+ // section that shows it, so a lost section never eats a live ticket.
518+ let created = created_token(query);
519+ let shown = if section == Section::Service {
520+ query_value(query, "shown")
521+ .as_deref()
522+ .and_then(crate::server::take_shown_secret)
523+ } else {
524+ None
525+ };
409 view! {526 view! {
410 cx =>527 cx =>
411 (topbar(cx, NavPage::Settings, &fresh, language).await?)528 (topbar(cx, NavPage::Settings, &fresh, language).await?)
@@ -416,11 +533,12 @@ async fn settings(cx: &Cx) -> Result {
416 if administers {533 if administers {
417 <a class=(rail_class(section, Section::Everyone)) href="/settings?section=everyone">(t(language, Key::AdminPanel))</a>534 <a class=(rail_class(section, Section::Everyone)) href="/settings?section=everyone">(t(language, Key::AdminPanel))</a>
418 <a class=(rail_class(section, Section::Server)) href="/settings?section=server">(t(language, Key::ServerAddress))</a>535 <a class=(rail_class(section, Section::Server)) href="/settings?section=server">(t(language, Key::ServerAddress))</a>
536+ <a class=(rail_class(section, Section::Service)) href="/settings?section=service">(t(language, Key::ServiceKeysTitle))</a>
419 }537 }
420 </nav>538 </nav>
421 <main class="settings-stage stage-wide">539 <main class="settings-stage stage-wide">
422 <h1 class="settings-title">(t(language, Key::Settings))</h1>540 <h1 class="settings-title">(t(language, Key::Settings))</h1>
423- (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "preferences", "base_url"]).await?)541+ (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "preferences", "base_url", "service_add", "service_rotate", "service_revoke"]).await?)
424 if section == Section::Profile {542 if section == Section::Profile {
425 <section class="panel">543 <section class="panel">
426 <div class="panel-head">544 <div class="panel-head">
@@ -645,6 +763,101 @@ async fn settings(cx: &Cx) -> Result {
645 </div>763 </div>
646 </section>764 </section>
647 }765 }
766+ if section == Section::Service {
767+ if let Some(key) = shown {
768+ // The show-once banner: the shelf behind it has
769+ // already handed the key over, so this is the only
770+ // render that will ever hold it. The value is
771+ // selectable text, so the copy works without script.
772+ <section class="panel">
773+ <div class="panel-head">
774+ <h2 class="panel-title">(t(language, Key::ServiceKeysTitle))</h2>
775+ </div>
776+ <div class="panel-body">
777+ <p class="field-note">(t(language, Key::ServiceKeyShown))</p>
778+ <div class="share-link-row">
779+ <p class="member-link-value share-link-url service-secret" aria-label=(t(language, Key::ServiceKeyName))>(key)</p>
780+ <button class="quiet share-copy" type="button" data-copied-label=(t(language, Key::Copied))>(t(language, Key::ServiceKeyCopy))</button>
781+ </div>
782+ </div>
783+ </section>
784+ }
785+ <section class="panel">
786+ <div class="panel-head">
787+ <h2 class="panel-title">(t(language, Key::ServiceKeysTitle))</h2>
788+ </div>
789+ <div class="panel-body">
790+ <form class="field" method="post" action="/api/settings/service_add">
791+ <label class="field">
792+ <span class="field-label">(t(language, Key::ServiceKeyService))</span>
793+ <select class="field-input" name="service">
794+ for row in &mintable {
795+ <option value=(row.key.clone())>(format!("{} · {}", row.name, row.key))</option>
796+ }
797+ </select>
798+ </label>
799+ <label class="field">
800+ <span class="field-label">(t(language, Key::ServiceKeyName))</span>
801+ <input class="field-input" type="text" name="name" required="required">
802+ </label>
803+ <div class="panel-foot">
804+ <button class="primary" type="submit">(t(language, Key::ServiceKeyMint))</button>
805+ </div>
806+ </form>
807+ <div class="table-pan">
808+ <table class="member-table">
809+ <thead>
810+ <tr>
811+ <th class="member-col-name" scope="col">(t(language, Key::ServiceKeyName))</th>
812+ <th class="member-col-address" scope="col">(t(language, Key::ServiceKeyService))</th>
813+ <th class="member-col-account" scope="col">(t(language, Key::QuotaUsage))</th>
814+ <th class="member-col-quota" scope="col">(t(language, Key::ServiceKeyCreated))</th>
815+ </tr>
816+ </thead>
817+ <tbody>
818+ for account in &accounts {
819+ <tr class="member-row">
820+ <td class="member-col-name member-name">(account.name.clone())</td>
821+ <td class="member-col-address member-address">(account.service.clone())</td>
822+ <td class="member-col-account member-account">(human_bytes(account.used_bytes))</td>
823+ <td class="member-col-quota">
824+ <div class="member-quota">
825+ <span class="field-note">(account.created_at.date().to_string())</span>
826+ </div>
827+ <details class="confirm-details">
828+ <summary class="quiet">(t(language, Key::ServiceKeyRotate))</summary>
829+ <div class="confirm">
830+ <div class="confirm-title">(t(language, Key::ServiceKeyRotateTitle))</div>
831+ <p class="field-note">(t(language, Key::ServiceKeyRotateCost))</p>
832+ <form method="post" action="/api/settings/service_rotate">
833+ <input type="hidden" name="service" value=(account.service.clone())>
834+ <button class="primary" type="submit">(t(language, Key::ServiceKeyRotate))</button>
835+ </form>
836+ </div>
837+ </details>
838+ <details class="confirm-details">
839+ <summary class="quiet quiet-danger">(t(language, Key::ServiceKeyRevoke))</summary>
840+ <div class="confirm">
841+ <div class="confirm-title">(t(language, Key::ServiceKeyRevokeTitle))</div>
842+ <p class="field-note">(t(language, Key::ServiceKeyRevokeCost))</p>
843+ <form method="post" action="/api/settings/service_revoke">
844+ <input type="hidden" name="service" value=(account.service.clone())>
845+ <button class="quiet quiet-danger" type="submit">(t(language, Key::ServiceKeyRevoke))</button>
846+ </form>
847+ </div>
848+ </details>
849+ </td>
850+ </tr>
851+ }
852+ </tbody>
853+ </table>
854+ </div>
855+ </div>
856+ </section>
857+ // The banner's copy button above; one delegated listener
858+ // serves every row, idempotent across re-renders.
859+ (share_copy_script(cx).await?)
860+ }
648 </main>861 </main>
649 </div>862 </div>
650 (crate::dropdown::dropdown_script(cx).await?)863 (crate::dropdown::dropdown_script(cx).await?)
crates/in-web/tests/http.rsmodified+555 -14
@@ -44,6 +44,7 @@ struct FakeIm {
44 tokens: Arc<Mutex<HashMap<String, serde_json::Value>>>,44 tokens: Arc<Mutex<HashMap<String, serde_json::Value>>>,
45 photos: Arc<Mutex<HashMap<String, (Vec<u8>, String)>>>,45 photos: Arc<Mutex<HashMap<String, (Vec<u8>, String)>>>,
46 directory: Arc<Mutex<Vec<serde_json::Value>>>,46 directory: Arc<Mutex<Vec<serde_json::Value>>>,
47+ family: Arc<Mutex<Vec<serde_json::Value>>>,
47 }48 }
48 49
49 impl FakeIm {50 impl FakeIm {
@@ -55,9 +56,11 @@ impl FakeIm {
55 let photos: Arc<Mutex<HashMap<String, (Vec<u8>, String)>>> =56 let photos: Arc<Mutex<HashMap<String, (Vec<u8>, String)>>> =
56 Arc::new(Mutex::new(HashMap::new()));57 Arc::new(Mutex::new(HashMap::new()));
57 let directory: Arc<Mutex<Vec<serde_json::Value>>> = Arc::new(Mutex::new(Vec::new()));58 let directory: Arc<Mutex<Vec<serde_json::Value>>> = Arc::new(Mutex::new(Vec::new()));
59+ let family: Arc<Mutex<Vec<serde_json::Value>>> = Arc::new(Mutex::new(Vec::new()));
58 let map = tokens.clone();60 let map = tokens.clone();
59 let pmap = photos.clone();61 let pmap = photos.clone();
60 let dmap = directory.clone();62 let dmap = directory.clone();
63+ let fmap = family.clone();
61 tokio::spawn(async move {64 tokio::spawn(async move {
62 loop {65 loop {
63 let Ok((socket, _)) = listener.accept().await else {66 let Ok((socket, _)) = listener.accept().await else {
@@ -66,6 +69,7 @@ impl FakeIm {
66 let map = map.clone();69 let map = map.clone();
67 let pmap = pmap.clone();70 let pmap = pmap.clone();
68 let dmap = dmap.clone();71 let dmap = dmap.clone();
72+ let fmap = fmap.clone();
69 tokio::spawn(async move {73 tokio::spawn(async move {
70 use tokio::io::{AsyncReadExt, AsyncWriteExt};74 use tokio::io::{AsyncReadExt, AsyncWriteExt};
71 let mut socket = socket;75 let mut socket = socket;
@@ -107,19 +111,25 @@ impl FakeIm {
107 Some(photo) => photo,111 Some(photo) => photo,
108 None => match directory_answer(&dmap, &head, &first) {112 None => match directory_answer(&dmap, &head, &first) {
109 Some(members) => members,113 Some(members) => members,
110- None => match answer_for(&map, &first, &body) {114+ None => match family_answer(&fmap, &head, &first) {
111- Some(answer) => (115+ Some(list) => list,
112- "200 OK",116+ None => match answer_for(&map, &first, &body) {
113- "application/json".to_string(),117+ Some(answer) => (
114- serde_json::to_vec(&answer).unwrap(),118+ "200 OK",
115- ),119+ "application/json".to_string(),
116- // Anything but the photo and directory120+ serde_json::to_vec(&answer).unwrap(),
117- // routes is nothing at all, the way the121+ ),
118- // real im 404s unknown paths rather than122+ // Anything but the photo, directory
119- // answering them.123+ // and family routes is nothing at
120- None => {124+ // all, the way the real im 404s
121- ("404 Not Found", "text/plain".to_string(), Vec::new())125+ // unknown paths rather than
122- }126+ // answering them.
127+ None => (
128+ "404 Not Found",
129+ "text/plain".to_string(),
130+ Vec::new(),
131+ ),
132+ },
123 },133 },
124 },134 },
125 };135 };
@@ -142,6 +152,7 @@ impl FakeIm {
142 tokens,152 tokens,
143 photos,153 photos,
144 directory,154 directory,
155+ family,
145 }156 }
146 }157 }
147 158
@@ -149,6 +160,13 @@ impl FakeIm {
149 format!("http://{}", self.addr)160 format!("http://{}", self.addr)
150 }161 }
151 162
163+ /// Stages the list `GET /family` answers with — the suite im keeps.
164+ /// Unset, the route is simply not there, as for an app im has not
165+ /// registered.
166+ fn set_family(&self, list: Vec<serde_json::Value>) {
167+ *self.family.lock().unwrap() = list;
168+ }
169+
152 /// Stores the photo `GET /photo/{user_id}` answers with — the bytes and170 /// Stores the photo `GET /photo/{user_id}` answers with — the bytes and
153 /// the mime im would serve for this account.171 /// the mime im would serve for this account.
154 fn set_photo(&self, user_id: &str, bytes: Vec<u8>, mime: &str) {172 fn set_photo(&self, user_id: &str, bytes: Vec<u8>, mime: &str) {
@@ -246,6 +264,46 @@ fn directory_answer(
246 ))264 ))
247 }265 }
248 266
267+/// Answers `GET /family` with the staged suite — the app's Basic credential
268+/// or nothing, and with nothing staged no route at all. `None` for anything
269+/// else, which falls through to the introspection JSON.
270+fn family_answer(
271+ family: &Arc<Mutex<Vec<serde_json::Value>>>,
272+ head: &str,
273+ request_line: &str,
274+) -> Option<(&'static str, String, Vec<u8>)> {
275+ let mut parts = request_line.split_whitespace();
276+ if parts.next() != Some("GET") {
277+ return None;
278+ }
279+ let target = parts.next().unwrap_or("");
280+ let path = target
281+ .split_once('?')
282+ .map(|(path, _)| path)
283+ .unwrap_or(target);
284+ if path != "/family" {
285+ return None;
286+ }
287+ let authed = head
288+ .lines()
289+ .filter_map(|line| line.split_once(':'))
290+ .any(|(name, value)| {
291+ name.trim().eq_ignore_ascii_case("authorization") && value.trim() == APP_BASIC
292+ });
293+ if !authed {
294+ return Some(("404 Not Found", "text/plain".to_string(), Vec::new()));
295+ }
296+ let list = family.lock().unwrap();
297+ if list.is_empty() {
298+ return Some(("404 Not Found", "text/plain".to_string(), Vec::new()));
299+ }
300+ Some((
301+ "200 OK",
302+ "application/json".to_string(),
303+ serde_json::to_vec(&*list).unwrap(),
304+ ))
305+}
306+
249 fn headers_end(req: &[u8]) -> Option<usize> {307 fn headers_end(req: &[u8]) -> Option<usize> {
250 req.windows(4)308 req.windows(4)
251 .position(|w| w == b"\r\n\r\n")309 .position(|w| w == b"\r\n\r\n")
@@ -343,6 +401,7 @@ impl TestApp {
343 key: key.to_string(),401 key: key.to_string(),
344 name: name.to_string(),402 name: name.to_string(),
345 url: url.to_string(),403 url: url.to_string(),
404+ limit_bytes: None,
346 })405 })
347 .collect();406 .collect();
348 store407 store
@@ -384,7 +443,7 @@ impl TestApp {
384 Router::builder()443 Router::builder()
385 .discover()444 .discover()
386 .layer(BodyLimit::max(32 * 1024 * 1024).at("/api/upload"))445 .layer(BodyLimit::max(32 * 1024 * 1024).at("/api/upload"))
387- .layer(BodyLimit::max(2usize * 1024 * 1024 * 1024).at("/files"))446+ .layer(BodyLimit::max(512 * 1024 * 1024).at("/api/service/files"))
388 .cookies()447 .cookies()
389 .assets(448 .assets(
390 AssetBundle::load_dir(asset_dir())449 AssetBundle::load_dir(asset_dir())
@@ -563,6 +622,77 @@ impl TestApp {
563 Answer::from_response(response).await622 Answer::from_response(response).await
564 }623 }
565 624
625+ /// Posts a multipart form with a bearer key, the way iz's storage client
626+ /// pushes an attachment. Raw bytes back — the machine answer is JSON the
627+ /// caller parses itself.
628+ async fn post_service_multipart(
629+ &self,
630+ path: &str,
631+ token: Option<&str>,
632+ fields: &[(&str, &str)],
633+ file: Option<(&str, &[u8])>,
634+ ) -> Raw {
635+ const BOUNDARY: &str = "in-test-boundary";
636+ let mut body = Vec::new();
637+ for (name, value) in fields {
638+ body.extend_from_slice(
639+ format!(
640+ "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n"
641+ )
642+ .as_bytes(),
643+ );
644+ }
645+ if let Some((filename, bytes)) = file {
646+ body.extend_from_slice(
647+ format!(
648+ "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\nContent-Type: application/octet-stream\r\n\r\n"
649+ )
650+ .as_bytes(),
651+ );
652+ body.extend_from_slice(bytes);
653+ body.extend_from_slice(b"\r\n");
654+ }
655+ body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes());
656+ let mut request = Request::builder().method("POST").uri(path).header(
657+ header::CONTENT_TYPE,
658+ format!("multipart/form-data; boundary={BOUNDARY}"),
659+ );
660+ if let Some(token) = token {
661+ request = request.header(header::AUTHORIZATION, format!("Bearer {token}"));
662+ }
663+ let response = self
664+ .router
665+ .handle(request.body(Body::from(body)).unwrap())
666+ .await;
667+ Raw::from_response(response).await
668+ }
669+
670+ /// A machine GET with (maybe) a bearer key.
671+ async fn get_bearer(&self, path: &str, token: Option<&str>) -> Raw {
672+ let mut request = Request::builder().method("GET").uri(path);
673+ if let Some(token) = token {
674+ request = request.header(header::AUTHORIZATION, format!("Bearer {token}"));
675+ }
676+ let response = self
677+ .router
678+ .handle(request.body(Body::empty()).unwrap())
679+ .await;
680+ Raw::from_response(response).await
681+ }
682+
683+ /// A machine DELETE with (maybe) a bearer key.
684+ async fn delete_bearer(&self, path: &str, token: Option<&str>) -> Raw {
685+ let mut request = Request::builder().method("DELETE").uri(path);
686+ if let Some(token) = token {
687+ request = request.header(header::AUTHORIZATION, format!("Bearer {token}"));
688+ }
689+ let response = self
690+ .router
691+ .handle(request.body(Body::empty()).unwrap())
692+ .await;
693+ Raw::from_response(response).await
694+ }
695+
566 /// Gets a page or a download the way a browser does, raw bytes back696 /// Gets a page or a download the way a browser does, raw bytes back
567 /// untouched — a download's body is not always UTF-8.697 /// untouched — a download's body is not always UTF-8.
568 async fn get(&self, path: &str, cookie: Option<&str>) -> Raw {698 async fn get(&self, path: &str, cookie: Option<&str>) -> Raw {
@@ -698,6 +828,33 @@ struct Raw {
698 bytes: Vec<u8>,828 bytes: Vec<u8>,
699 }829 }
700 830
831+impl Raw {
832+ async fn from_response(response: topcoat::router::response::Response) -> Self {
833+ let status = response.status();
834+ let headers = response.headers().clone();
835+ let header = |name| {
836+ headers
837+ .get(name)
838+ .and_then(|value| value.to_str().ok())
839+ .map(str::to_string)
840+ };
841+ let bytes = to_bytes(response.into_body(), usize::MAX)
842+ .await
843+ .unwrap()
844+ .to_vec();
845+ Raw {
846+ status,
847+ content_type: header(header::CONTENT_TYPE),
848+ disposition: header(header::CONTENT_DISPOSITION),
849+ content_range: header(header::CONTENT_RANGE),
850+ accept_ranges: header(header::ACCEPT_RANGES),
851+ cache_control: header(header::CACHE_CONTROL),
852+ etag: header(header::ETAG),
853+ location: header(header::LOCATION),
854+ bytes,
855+ }
856+ }
857+}
701 impl Raw {858 impl Raw {
702 fn text(&self) -> String {859 fn text(&self) -> String {
703 String::from_utf8(self.bytes.clone()).unwrap()860 String::from_utf8(self.bytes.clone()).unwrap()
@@ -5340,3 +5497,387 @@ async fn connection_card_shows_issuer_client_id_and_stream_state() {
5340 assert!(!body.contains("connection-on"), "green lingered: {body}");5497 assert!(!body.contains("connection-on"), "green lingered: {body}");
5341 }5498 }
5342 5499
5500+
5501+// ---------------------------------------------------------------------------
5502+// The service storage API: bearer keys, machine answers, im's ceilings.
5503+// ---------------------------------------------------------------------------
5504+
5505+/// A minted service account's bearer key, straight off the store.
5506+async fn service_key(store: &Arc<dyn Store>, service: &str, name: &str) -> (String, String) {
5507+ let token = store
5508+ .create_service_account(service, name, 1024 * 1024)
5509+ .await
5510+ .unwrap();
5511+ let account = store.list_service_accounts().await.unwrap();
5512+ let user_id = account
5513+ .iter()
5514+ .find(|account| account.service == service)
5515+ .unwrap()
5516+ .user_id
5517+ .clone();
5518+ (token, user_id)
5519+}
5520+
5521+#[tokio::test]
5522+async fn service_routes_refuse_a_missing_or_wrong_key() {
5523+ let app = TestApp::build().await;
5524+ for path in [
5525+ "/api/service/status",
5526+ "/api/service/file/some-id",
5527+ ] {
5528+ let raw = app.get_bearer(path, None).await;
5529+ assert_eq!(raw.status, StatusCode::UNAUTHORIZED, "{path}");
5530+ let raw = app.get_bearer(path, None).await;
5531+ assert_eq!(
5532+ raw.status,
5533+ StatusCode::UNAUTHORIZED,
5534+ "{path}: {} {:?}",
5535+ raw.text(),
5536+ raw.cache_control
5537+ );
5538+ assert_eq!(raw.status, StatusCode::UNAUTHORIZED, "{path}");
5539+ }
5540+ let raw = app.delete_bearer("/api/service/file/some-id", None).await;
5541+ assert_eq!(raw.status, StatusCode::UNAUTHORIZED);
5542+ let raw = app
5543+ .post_service_multipart("/api/service/files", None, &[], None)
5544+ .await;
5545+ assert_eq!(raw.status, StatusCode::UNAUTHORIZED);
5546+}
5547+
5548+#[tokio::test]
5549+async fn the_service_happy_path_pushes_fetches_counts_and_takes_away() {
5550+ let app = TestApp::build().await;
5551+ let (token, user_id) = service_key(&app.store, "iz", "İz").await;
5552+
5553+ // Push: the answer is the file id, and the bytes are the account's.
5554+ let raw = app
5555+ .post_service_multipart(
5556+ "/api/service/files",
5557+ Some(&token),
5558+ &[("external_id", "att-1"), ("name", "notes.txt")],
5559+ Some(("notes.txt", b"hello iz".as_slice())),
5560+ )
5561+ .await;
5562+ assert_eq!(raw.status, StatusCode::OK, "{:?}", raw.text());
5563+ let pushed: serde_json::Value = serde_json::from_str(&raw.text()).unwrap();
5564+ let file_id = pushed["ok"].as_str().unwrap().to_string();
5565+
5566+ // Status: the account's ceiling and what it now holds.
5567+ let raw = app
5568+ .get_bearer("/api/service/status", Some(&token))
5569+ .await;
5570+ assert_eq!(raw.status, StatusCode::OK);
5571+ let status: serde_json::Value = serde_json::from_str(&raw.text()).unwrap();
5572+ assert_eq!(status["ok"], serde_json::Value::Bool(true));
5573+ assert_eq!(status["quota_bytes"], 1024 * 1024);
5574+ assert_eq!(status["used_bytes"], 8);
5575+
5576+ // Fetch: the same bytes, the attachment disposition, a year immutable.
5577+ let raw = app
5578+ .get_bearer("/api/service/file/att-1", Some(&token))
5579+ .await;
5580+ assert_eq!(raw.status, StatusCode::OK, "GET file: {}", raw.text());
5581+ assert_eq!(raw.bytes, b"hello iz".as_slice());
5582+ assert_eq!(
5583+ raw.cache_control.as_deref(),
5584+ Some("private, max-age=31536000, immutable")
5585+ );
5586+ assert!(raw.disposition.unwrap().contains("notes.txt"));
5587+
5588+ // The account row agrees with the status: mime sniffed, no thumbnail,
5589+ // usage recomputed from the row.
5590+ let file = app.store.file(&file_id).await.unwrap().unwrap();
5591+ assert_eq!(file.owner_id, user_id);
5592+ assert_eq!(file.mime, "text/plain");
5593+ assert_eq!(file.thumb_state, in_core::store::ThumbState::None);
5594+ let holder = app.store.user(&user_id).await.unwrap().unwrap();
5595+ assert_eq!(holder.used_bytes, 8);
5596+
5597+ // Delete: the row and the bytes are gone, the usage follows.
5598+ let raw = app
5599+ .delete_bearer("/api/service/file/att-1", Some(&token))
5600+ .await;
5601+ assert_eq!(raw.status, StatusCode::OK);
5602+ assert!(raw.text().contains("\"ok\":true"), "{}", raw.text());
5603+ let raw = app
5604+ .get_bearer("/api/service/file/att-1", Some(&token))
5605+ .await;
5606+ assert_eq!(raw.status, StatusCode::NOT_FOUND);
5607+ let holder = app.store.user(&user_id).await.unwrap().unwrap();
5608+ assert_eq!(holder.used_bytes, 0);
5609+}
5610+
5611+#[tokio::test]
5612+async fn a_repush_of_a_known_handle_replaces_bytes_without_a_second_row() {
5613+ let app = TestApp::build().await;
5614+ let (token, user_id) = service_key(&app.store, "iz", "İz").await;
5615+ for payload in [b"first".as_slice(), b"second-and-longer".as_slice()] {
5616+ let raw = app
5617+ .post_service_multipart(
5618+ "/api/service/files",
5619+ Some(&token),
5620+ &[("external_id", "att-1"), ("name", "notes.txt")],
5621+ Some(("notes.txt", payload)),
5622+ )
5623+ .await;
5624+ assert_eq!(raw.status, StatusCode::OK, "{:?}", raw.text());
5625+ }
5626+ let raw = app
5627+ .get_bearer("/api/service/file/att-1", Some(&token))
5628+ .await;
5629+ assert_eq!(raw.bytes, b"second-and-longer".as_slice());
5630+ let holder = app.store.user(&user_id).await.unwrap().unwrap();
5631+ // Recomputed from the one row, never incremented past it.
5632+ assert_eq!(holder.used_bytes, 17);
5633+}
5634+
5635+#[tokio::test]
5636+async fn the_service_quota_is_the_ceiling_the_word_names() {
5637+ let app = TestApp::build().await;
5638+ // One mebibyte of headroom, then a push past it.
5639+ let (token, _) = service_key(&app.store, "iz", "İz").await;
5640+ let big = vec![0u8; 2 * 1024 * 1024];
5641+ let raw = app
5642+ .post_service_multipart(
5643+ "/api/service/files",
5644+ Some(&token),
5645+ &[("external_id", "big"), ("name", "big.bin")],
5646+ Some(("big.bin", big.as_slice())),
5647+ )
5648+ .await;
5649+ assert_eq!(raw.status, StatusCode::OK);
5650+ assert!(raw.text().contains("QuotaExceeded"), "{}", raw.text());
5651+ // A re-push that would not fit over the row it replaces is refused too,
5652+ // and the old bytes stay exactly as they were.
5653+ let raw = app
5654+ .post_service_multipart(
5655+ "/api/service/files",
5656+ Some(&token),
5657+ &[("external_id", "small"), ("name", "small.txt")],
5658+ Some(("small.txt", b"tiny".as_slice())),
5659+ )
5660+ .await;
5661+ assert_eq!(raw.status, StatusCode::OK);
5662+ // One byte past the ceiling, over the row it replaces: refused.
5663+ let overflow = vec![b'a'; 1024 * 1024 + 1];
5664+ let raw = app
5665+ .post_service_multipart(
5666+ "/api/service/files",
5667+ Some(&token),
5668+ &[("external_id", "small"), ("name", "small.txt")],
5669+ Some(("small.txt", overflow.as_slice())),
5670+ )
5671+ .await;
5672+ assert!(raw.text().contains("QuotaExceeded"), "{}", raw.text());
5673+ let raw = app
5674+ .get_bearer("/api/service/file/small", Some(&token))
5675+ .await;
5676+ assert_eq!(raw.bytes, b"tiny".as_slice());
5677+}
5678+
5679+#[tokio::test]
5680+async fn a_human_browser_is_a_stranger_on_the_machine_routes() {
5681+ let app = TestApp::build().await;
5682+ let (token, _) = service_key(&app.store, "iz", "İz").await;
5683+ let admin = app
5684+ .sign_in("sub-admin", "admin@example.com", "Admin")
5685+ .await;
5686+ // The admin's session cookie buys nothing here.
5687+ let raw = app.get("/api/service/status", Some(&admin)).await;
5688+ assert_eq!(raw.status, StatusCode::UNAUTHORIZED);
5689+ // And the bearer key buys nothing on the human drive.
5690+ let raw = app
5691+ .get_bearer("/drive", Some(&token))
5692+ .await;
5693+ assert!(raw.status.is_redirection() || raw.status == StatusCode::UNAUTHORIZED);
5694+}
5695+
5696+#[tokio::test]
5697+async fn the_everyone_quota_write_refuses_a_service_account() {
5698+ let app = TestApp::build().await;
5699+ // The admin signs in first: the first human sight is the admin, and a
5700+ // service row must not claim that.
5701+ let admin = app
5702+ .sign_in("sub-admin", "admin@example.com", "Admin")
5703+ .await;
5704+ let (_, user_id) = service_key(&app.store, "iz", "İz").await;
5705+ let answer = app
5706+ .post(
5707+ "/api/settings/quota",
5708+ Some(&admin),
5709+ &[("user_id", user_id.as_str()), ("quota", "5"), ("quota_unit", "GiB")],
5710+ )
5711+ .await;
5712+ assert!(answer.refused("service-quota", "quota"), "{} {}", answer.location.as_deref().unwrap_or(""), answer.body);
5713+ // The ceiling is untouched.
5714+ let holder = app.store.user(&user_id).await.unwrap().unwrap();
5715+ assert_eq!(holder.quota_bytes, 1024 * 1024);
5716+}
5717+
5718+#[tokio::test]
5719+async fn the_mint_shows_its_key_once_and_refuses_a_stranger() {
5720+ let app = TestApp::build().await;
5721+ app.store
5722+ .set_setting(
5723+ "family",
5724+ r#"[{"key":"iz","name":"İz","url":"http://127.0.0.1:7654","limit_bytes":5368709120}]"#,
5725+ )
5726+ .await
5727+ .unwrap();
5728+ let admin = app
5729+ .sign_in("sub-admin", "admin@example.com", "Admin")
5730+ .await;
5731+ let plain = app.sign_in("sub-plain", "plain@example.com", "Plain").await;
5732+
5733+ // Non-admin: the section reads as the profile, the mint refuses.
5734+ let page = app
5735+ .get("/settings?section=service", Some(&plain))
5736+ .await;
5737+ assert!(!page.text().contains("Service keys"), "rail leaked: {}", page.text());
5738+ let answer = app
5739+ .post(
5740+ "/api/settings/service_add",
5741+ Some(&plain),
5742+ &[("service", "iz"), ("name", "İz")],
5743+ )
5744+ .await;
5745+ assert!(answer.refused("forbidden", "service_add"), "{} {}", answer.location.as_deref().unwrap_or(""), answer.body);
5746+
5747+ // The admin mints; the redirect carries a ticket, not the key.
5748+ let answer = app
5749+ .post(
5750+ "/api/settings/service_add",
5751+ Some(&admin),
5752+ &[("service", "iz"), ("name", "İz")],
5753+ )
5754+ .await;
5755+ assert!(answer.accepted(), "{} {}", answer.location.as_deref().unwrap_or(""), answer.body);
5756+ let location = answer.location.unwrap();
5757+ let ticket = location
5758+ .split("shown=")
5759+ .nth(1)
5760+ .unwrap()
5761+ .split('&')
5762+ .next()
5763+ .unwrap()
5764+ .to_string();
5765+ assert!(!ticket.is_empty());
5766+
5767+ // First render: the key stands in the banner. Second: nothing.
5768+ let page = app
5769+ .get(&format!("/settings?section=service&shown={ticket}"), Some(&admin))
5770+ .await;
5771+ let body = page.text();
5772+ assert!(body.contains("service-secret"), "no banner: {body}");
5773+ assert!(body.contains("Copy it now"), "{body}");
5774+ let start = body.split("service-secret\"").nth(1).unwrap();
5775+ let key = start
5776+ .split('>')
5777+ .nth(1)
5778+ .unwrap()
5779+ .split('<')
5780+ .next()
5781+ .unwrap()
5782+ .to_string();
5783+ assert!(!key.is_empty());
5784+ // The store opened the account, and the account opens by that key.
5785+ let account = app
5786+ .store
5787+ .service_account_by_token(&key)
5788+ .await
5789+ .unwrap()
5790+ .expect("the shown key opens");
5791+ assert_eq!(account.oidc_sub, "service:iz");
5792+ // The replayed URL — the live tick, a reload — renders no banner.
5793+ let page = app
5794+ .get(&format!("/settings?section=service&shown={ticket}"), Some(&admin))
5795+ .await;
5796+ assert!(!page.text().contains("service-secret\""));
5797+ let page = app
5798+ .get("/settings?section=service&shown=forged-ticket", Some(&admin))
5799+ .await;
5800+ assert!(!page.text().contains("service-secret\""));
5801+
5802+ // Rotate replaces the key; revoke kills it, the account stays.
5803+ let answer = app
5804+ .post(
5805+ "/api/settings/service_rotate",
5806+ Some(&admin),
5807+ &[("service", "iz")],
5808+ )
5809+ .await;
5810+ assert!(answer.accepted(), "{} {}", answer.location.as_deref().unwrap_or(""), answer.body);
5811+ let ticket = answer.location.unwrap().split("shown=").nth(1).unwrap().to_string();
5812+ let page = app
5813+ .get(&format!("/settings?section=service&shown={ticket}"), Some(&admin))
5814+ .await;
5815+ let rotated = page
5816+ .text()
5817+ .split("service-secret\"")
5818+ .nth(1)
5819+ .unwrap()
5820+ .split('>')
5821+ .nth(1)
5822+ .unwrap()
5823+ .split('<')
5824+ .next()
5825+ .unwrap()
5826+ .to_string();
5827+ assert_ne!(rotated, key);
5828+ assert!(app.store.service_account_by_token(&key).await.unwrap().is_none());
5829+ let answer = app
5830+ .post(
5831+ "/api/settings/service_revoke",
5832+ Some(&admin),
5833+ &[("service", "iz")],
5834+ )
5835+ .await;
5836+ assert!(answer.accepted(), "{} {}", answer.location.as_deref().unwrap_or(""), answer.body);
5837+ assert!(app.store.service_account_by_token(&rotated).await.unwrap().is_none());
5838+ let accounts = app.store.list_service_accounts().await.unwrap();
5839+ assert!(accounts.is_empty(), "revoke took the row, not the account: the account row stays");
5840+}
5841+
5842+#[tokio::test]
5843+async fn the_family_limit_lands_on_the_account() {
5844+ let app = TestApp::build().await;
5845+ // im names a 5 GiB ceiling for iz; the beat carries it.
5846+ app.fake
5847+ .set_family(vec![serde_json::json!({
5848+ "key": "iz",
5849+ "name": "İz",
5850+ "url": "http://127.0.0.1:7654",
5851+ "limit_bytes": 5 * 1024 * 1024 * 1024u64,
5852+ })]);
5853+ let client = in_client::InClient::new(app.client.clone());
5854+ let family = client.family().await.expect("the fake answered");
5855+ assert_eq!(family[0].limit_bytes, Some(5 * 1024 * 1024 * 1024));
5856+ in_web::service::apply_family_limits(&app.store, &family, 1024 * 1024)
5857+ .await
5858+ .unwrap();
5859+ let accounts = app.store.list_service_accounts().await.unwrap();
5860+ assert!(accounts.is_empty(), "no key, no account to ceiling");
5861+ let (token, user_id) = service_key(&app.store, "iz", "İz").await;
5862+ let _ = token;
5863+ // Before a beat the account sits at the default; im's word moves it.
5864+ in_web::service::apply_family_limits(&app.store, &family, 1024 * 1024)
5865+ .await
5866+ .unwrap();
5867+ let holder = app.store.user(&user_id).await.unwrap().unwrap();
5868+ assert_eq!(holder.quota_bytes, 5 * 1024 * 1024 * 1024);
5869+ // No limit named: the house default.
5870+ app.fake
5871+ .set_family(vec![serde_json::json!({
5872+ "key": "iz",
5873+ "name": "İz",
5874+ "url": "http://127.0.0.1:7654",
5875+ })]);
5876+ let family = client.family().await.unwrap();
5877+ assert_eq!(family[0].limit_bytes, None);
5878+ in_web::service::apply_family_limits(&app.store, &family, 1024 * 1024)
5879+ .await
5880+ .unwrap();
5881+ let holder = app.store.user(&user_id).await.unwrap().unwrap();
5882+ assert_eq!(holder.quota_bytes, 1024 * 1024);
5883+}