Machine object API for services: im client-credentials auth, namespaced objects, content-addressed shared blobs, usage
Browse files at this commit53cbc6ba172e8d9b5792932d89013a9dc219c52bParent: 9c306fb- feat
- machine object API for services: im client-credentials auth, namespaced objects, content-addressed shared blobs, usage
9 changed files +1782 -45
- crates/in-core/migrations/0003_objects_shared_blobs.sql +26 -0
- crates/in-core/src/store/migrate.rs +4 -0
- crates/in-core/src/store/mod.rs +4 -0
- crates/in-core/src/store/objects.rs +628 -0
- crates/in-web/src/api/machine_auth.rs +213 -0
- crates/in-web/src/api/mod.rs +6 -3
- crates/in-web/src/api/objects.rs +792 -0
- crates/in-web/src/oidc.rs +108 -41
- docs/architecture.md +1 -1
crates/in-core/migrations/0003_objects_shared_blobs.sqladded+26 -0
| @@ -0,0 +1,26 @@ | |||
| 1 | +-- 0003: lets objects of one service share a blob. The blob key is now `objects/<service>/<sha256>`, so two | ||
| 2 | +-- objects with the same bytes name the same key, and the key is no longer unique. The table is rebuilt | ||
| 3 | +-- because SQLite cannot drop a UNIQUE constraint in place. The CHECK keeps the key tied to its service and | ||
| 4 | +-- hash, so no row can name a blob of another service. | ||
| 5 | + | ||
| 6 | +CREATE TABLE objects_new ( | ||
| 7 | + service TEXT NOT NULL REFERENCES services (key) ON DELETE RESTRICT, | ||
| 8 | + external_id TEXT NOT NULL, | ||
| 9 | + size INTEGER NOT NULL CHECK (size >= 0), | ||
| 10 | + sha256 TEXT NOT NULL CHECK (length(sha256) = 64), | ||
| 11 | + content_type TEXT NOT NULL, | ||
| 12 | + name TEXT, | ||
| 13 | + blob_key TEXT NOT NULL CHECK (blob_key = 'objects/' || service || '/' || sha256), | ||
| 14 | + created_at TEXT NOT NULL, | ||
| 15 | + updated_at TEXT NOT NULL, | ||
| 16 | + PRIMARY KEY (service, external_id) | ||
| 17 | +); | ||
| 18 | + | ||
| 19 | +INSERT INTO objects_new (service, external_id, size, sha256, content_type, name, blob_key, created_at, updated_at) | ||
| 20 | + SELECT service, external_id, size, sha256, content_type, name, blob_key, created_at, updated_at FROM objects; | ||
| 21 | + | ||
| 22 | +DROP TABLE objects; | ||
| 23 | + | ||
| 24 | +ALTER TABLE objects_new RENAME TO objects; | ||
| 25 | + | ||
| 26 | +CREATE INDEX objects_blob_key ON objects (blob_key); | ||
crates/in-core/src/store/migrate.rsmodified+4 -0
| @@ -15,6 +15,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ | |||
| 15 | 2, | 15 | 2, |
| 16 | include_str!("../../migrations/0002_session_id_token.sql"), | 16 | include_str!("../../migrations/0002_session_id_token.sql"), |
| 17 | ), | 17 | ), |
| 18 | + ( | ||
| 19 | + 3, | ||
| 20 | + include_str!("../../migrations/0003_objects_shared_blobs.sql"), | ||
| 21 | + ), | ||
| 18 | ]; | 22 | ]; |
| 19 | 23 | ||
| 20 | fn migration_err(e: turso::Error) -> Error { | 24 | fn migration_err(e: turso::Error) -> Error { |
crates/in-core/src/store/mod.rsmodified+4 -0
| @@ -9,6 +9,7 @@ pub mod folders; | |||
| 9 | pub mod links; | 9 | pub mod links; |
| 10 | pub mod members; | 10 | pub mod members; |
| 11 | pub mod migrate; | 11 | pub mod migrate; |
| 12 | +pub mod objects; | ||
| 12 | pub mod sessions; | 13 | pub mod sessions; |
| 13 | pub mod settings; | 14 | pub mod settings; |
| 14 | pub mod shares; | 15 | pub mod shares; |
| @@ -51,6 +52,8 @@ struct Inner { | |||
| 51 | readers: Vec<Mutex<Connection>>, | 52 | readers: Vec<Mutex<Connection>>, |
| 52 | /// Round-robin start index for [`Store::read_conn`]. | 53 | /// Round-robin start index for [`Store::read_conn`]. |
| 53 | next_reader: AtomicUsize, | 54 | next_reader: AtomicUsize, |
| 55 | + /// Orders blob writes against blob removal for the object store (`objects.rs`). | ||
| 56 | + blobs: objects::BlobGate, | ||
| 54 | } | 57 | } |
| 55 | 58 | ||
| 56 | impl Store { | 59 | impl Store { |
| @@ -78,6 +81,7 @@ impl Store { | |||
| 78 | conn: Mutex::new(conn), | 81 | conn: Mutex::new(conn), |
| 79 | readers, | 82 | readers, |
| 80 | next_reader: AtomicUsize::new(0), | 83 | next_reader: AtomicUsize::new(0), |
| 84 | + blobs: objects::BlobGate::default(), | ||
| 81 | }), | 85 | }), |
| 82 | }) | 86 | }) |
| 83 | } | 87 | } |
crates/in-core/src/store/objects.rsadded+628 -0
| @@ -0,0 +1,628 @@ | |||
| 1 | +//! The object store's rows (contracts.md 5): services, which are namespaces with a quota, and the objects | ||
| 2 | +//! each service keeps under its own ids. | ||
| 3 | +//! | ||
| 4 | +//! Namespace: every function takes the service key from the caller's verified token (`svc`). Nothing a | ||
| 5 | +//! request says picks the namespace, so the same `external_id` in two services is two rows. | ||
| 6 | +//! | ||
| 7 | +//! Blobs: an object's bytes live at `objects/<service>/<sha256>`, so objects of one service with the same | ||
| 8 | +//! bytes share one blob. A blob is removed only by [`Store::retire_blob`], and only when no row names it | ||
| 9 | +//! and no write is in the middle of storing it. [`Store::hold_blob`] is that write's claim on the key, taken | ||
| 10 | +//! before the bytes are put and released after the row commits. | ||
| 11 | +//! | ||
| 12 | +//! Quota: `services.used_bytes` is the sum of the sizes of the service's objects. A put checks the new total | ||
| 13 | +//! inside its write transaction, which the single writer serialises, so two parallel puts cannot both pass. | ||
| 14 | + | ||
| 15 | +use std::collections::HashMap; | ||
| 16 | +use std::sync::{Arc, Mutex as StdMutex, PoisonError}; | ||
| 17 | + | ||
| 18 | +use turso::{Connection, Row}; | ||
| 19 | + | ||
| 20 | +use crate::blob::BlobStore; | ||
| 21 | +use crate::error::{Error, Result}; | ||
| 22 | +use crate::store::{ | ||
| 23 | + Inner, Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, | ||
| 24 | + missing_row, | ||
| 25 | +}; | ||
| 26 | +use crate::time::now_stamp; | ||
| 27 | + | ||
| 28 | +/// Quota of a service that has none yet: 10 GiB. Used when a service first makes an authorised call. | ||
| 29 | +pub const DEFAULT_SERVICE_QUOTA: i64 = 10 * 1024 * 1024 * 1024; | ||
| 30 | + | ||
| 31 | +/// The settings key of the quota a new service gets. It is read when the service row is created. | ||
| 32 | +pub const SERVICE_QUOTA_SETTING: &str = "default_service_quota_bytes"; | ||
| 33 | + | ||
| 34 | +/// Longest `external_id` the contracts allow. | ||
| 35 | +pub const MAX_EXTERNAL_ID: usize = 128; | ||
| 36 | + | ||
| 37 | +/// Checks an `external_id` against contracts.md 5: 1 to 128 characters of `[A-Za-z0-9._-]`. The id is | ||
| 38 | +/// never part of a path (blobs are named by hash), so the charset only has to keep ids printable and | ||
| 39 | +/// unambiguous. | ||
| 40 | +pub fn check_external_id(id: &str) -> Result<()> { | ||
| 41 | + let allowed = id | ||
| 42 | + .bytes() | ||
| 43 | + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')); | ||
| 44 | + if id.is_empty() || id.len() > MAX_EXTERNAL_ID || !allowed { | ||
| 45 | + return Err(Error::Invalid("bad_external_id".into())); | ||
| 46 | + } | ||
| 47 | + Ok(()) | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// The blob key of an object's bytes: `objects/<service>/<sha256>`. The hash is lower-case hex. | ||
| 51 | +pub fn object_blob_key(service: &str, sha256: &str) -> String { | ||
| 52 | + format!("objects/{service}/{sha256}") | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +/// Column list for [`map_service`]. Keep the two in step. | ||
| 56 | +const SERVICE_COLS: &str = "key, quota_bytes, used_bytes, created_at"; | ||
| 57 | + | ||
| 58 | +/// Column list for [`map_object`]. Keep the two in step. | ||
| 59 | +const OBJECT_COLS: &str = | ||
| 60 | + "service, external_id, size, sha256, content_type, name, blob_key, created_at, updated_at"; | ||
| 61 | + | ||
| 62 | +/// A service: a namespace of objects with its own quota. | ||
| 63 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 64 | +pub struct Service { | ||
| 65 | + /// The family key the token's `svc` named, such as `iz`. | ||
| 66 | + pub key: String, | ||
| 67 | + /// The most bytes the service may store. | ||
| 68 | + pub quota_bytes: i64, | ||
| 69 | + /// The bytes its objects use, counted once per object (shared blobs count twice). | ||
| 70 | + pub used_bytes: i64, | ||
| 71 | + /// When the service first made a call. | ||
| 72 | + pub created_at: String, | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +/// One object of a service. | ||
| 76 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 77 | +pub struct Object { | ||
| 78 | + /// The service that owns the object. | ||
| 79 | + pub service: String, | ||
| 80 | + /// The id the service chose. | ||
| 81 | + pub external_id: String, | ||
| 82 | + /// Length in bytes. | ||
| 83 | + pub size: i64, | ||
| 84 | + /// Lower-case hex SHA-256 of the bytes. | ||
| 85 | + pub sha256: String, | ||
| 86 | + /// The `Content-Type` the service sent, stored as given. | ||
| 87 | + pub content_type: String, | ||
| 88 | + /// The `X-Object-Name` the service sent, if any. | ||
| 89 | + pub name: Option<String>, | ||
| 90 | + /// The blob that holds the bytes. | ||
| 91 | + pub blob_key: String, | ||
| 92 | + /// When the object was first stored. | ||
| 93 | + pub created_at: String, | ||
| 94 | + /// When the object was last replaced. | ||
| 95 | + pub updated_at: String, | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +/// A service's usage, as `GET /api/v1/usage` reports it. | ||
| 99 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 100 | +pub struct Usage { | ||
| 101 | + /// The service quota. | ||
| 102 | + pub quota_bytes: i64, | ||
| 103 | + /// Bytes used by its objects. | ||
| 104 | + pub used_bytes: i64, | ||
| 105 | + /// Number of objects. | ||
| 106 | + pub objects: i64, | ||
| 107 | +} | ||
| 108 | + | ||
| 109 | +/// What a put stores. The bytes are already at `blob_key`. | ||
| 110 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 111 | +pub struct NewObject { | ||
| 112 | + /// The namespace, from the verified token. | ||
| 113 | + pub service: String, | ||
| 114 | + /// The id the service chose. Already checked by [`check_external_id`]. | ||
| 115 | + pub external_id: String, | ||
| 116 | + /// Length in bytes. | ||
| 117 | + pub size: i64, | ||
| 118 | + /// Lower-case hex SHA-256 of the bytes. | ||
| 119 | + pub sha256: String, | ||
| 120 | + /// The stored `Content-Type`. | ||
| 121 | + pub content_type: String, | ||
| 122 | + /// The cleaned `X-Object-Name`, if any. | ||
| 123 | + pub name: Option<String>, | ||
| 124 | + /// When true, a put over an existing object is refused (`If-None-Match: *`). | ||
| 125 | + pub create_only: bool, | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +/// What a put did. | ||
| 129 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 130 | +pub enum PutOutcome { | ||
| 131 | + /// The row is stored. `replaced_blob` is the blob the old bytes lived at, when that blob is not the new | ||
| 132 | + /// one. The caller retires it with [`Store::retire_blob`]. | ||
| 133 | + Stored { | ||
| 134 | + /// The object as stored. Boxed, so the refusal variants stay small. | ||
| 135 | + object: Box<Object>, | ||
| 136 | + /// `true` when the id was new, `false` when an existing object was replaced. | ||
| 137 | + created: bool, | ||
| 138 | + /// The blob the replaced bytes used, when it differs from the new one. | ||
| 139 | + replaced_blob: Option<String>, | ||
| 140 | + }, | ||
| 141 | + /// The new total would exceed the service quota. Nothing changed. | ||
| 142 | + QuotaExceeded, | ||
| 143 | + /// `create_only` was set and the id is taken. Nothing changed. | ||
| 144 | + Exists, | ||
| 145 | +} | ||
| 146 | + | ||
| 147 | +/// The claim a write holds on a blob key between putting the bytes and committing the row. While it is | ||
| 148 | +/// held, [`Store::retire_blob`] leaves the key alone. | ||
| 149 | +pub struct BlobHold { | ||
| 150 | + inner: Arc<Inner>, | ||
| 151 | + key: String, | ||
| 152 | +} | ||
| 153 | + | ||
| 154 | +impl Drop for BlobHold { | ||
| 155 | + fn drop(&mut self) { | ||
| 156 | + let mut held = self | ||
| 157 | + .inner | ||
| 158 | + .blobs | ||
| 159 | + .held | ||
| 160 | + .lock() | ||
| 161 | + .unwrap_or_else(PoisonError::into_inner); | ||
| 162 | + if let Some(count) = held.get_mut(&self.key) { | ||
| 163 | + *count -= 1; | ||
| 164 | + if *count == 0 { | ||
| 165 | + held.remove(&self.key); | ||
| 166 | + } | ||
| 167 | + } | ||
| 168 | + } | ||
| 169 | +} | ||
| 170 | + | ||
| 171 | +/// The gate that orders blob writes against blob removal. `retire` is held while a removal decides and | ||
| 172 | +/// deletes, and while a write registers its claim, so a removal and a write of the same key never overlap. | ||
| 173 | +/// `held` counts the open claims per key. Both are in-process, which is right for one `in` process. | ||
| 174 | +#[derive(Default)] | ||
| 175 | +pub(crate) struct BlobGate { | ||
| 176 | + retire: tokio::sync::Mutex<()>, | ||
| 177 | + held: StdMutex<HashMap<String, usize>>, | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +/// Column `i` of a row selected with [`SERVICE_COLS`]. | ||
| 181 | +fn map_service(row: &Row) -> Result<Service> { | ||
| 182 | + Ok(Service { | ||
| 183 | + key: col_text(row, 0)?, | ||
| 184 | + quota_bytes: col_int(row, 1)?, | ||
| 185 | + used_bytes: col_int(row, 2)?, | ||
| 186 | + created_at: col_text(row, 3)?, | ||
| 187 | + }) | ||
| 188 | +} | ||
| 189 | + | ||
| 190 | +/// Maps a row selected with [`OBJECT_COLS`]. | ||
| 191 | +fn map_object(row: &Row) -> Result<Object> { | ||
| 192 | + Ok(Object { | ||
| 193 | + service: col_text(row, 0)?, | ||
| 194 | + external_id: col_text(row, 1)?, | ||
| 195 | + size: col_int(row, 2)?, | ||
| 196 | + sha256: col_text(row, 3)?, | ||
| 197 | + content_type: col_text(row, 4)?, | ||
| 198 | + name: col_opt_text(row, 5)?, | ||
| 199 | + blob_key: col_text(row, 6)?, | ||
| 200 | + created_at: col_text(row, 7)?, | ||
| 201 | + updated_at: col_text(row, 8)?, | ||
| 202 | + }) | ||
| 203 | +} | ||
| 204 | + | ||
| 205 | +/// A service row by key. | ||
| 206 | +async fn service_row(conn: &Connection, key: &str) -> Result<Option<Service>> { | ||
| 207 | + fetch_opt( | ||
| 208 | + conn, | ||
| 209 | + &format!("SELECT {SERVICE_COLS} FROM services WHERE key = ?1"), | ||
| 210 | + (key.to_owned(),), | ||
| 211 | + map_service, | ||
| 212 | + ) | ||
| 213 | + .await | ||
| 214 | +} | ||
| 215 | + | ||
| 216 | +/// An object of a service by its id. Another service's id finds nothing. | ||
| 217 | +async fn object_row(conn: &Connection, service: &str, id: &str) -> Result<Option<Object>> { | ||
| 218 | + fetch_opt( | ||
| 219 | + conn, | ||
| 220 | + &format!("SELECT {OBJECT_COLS} FROM objects WHERE service = ?1 AND external_id = ?2"), | ||
| 221 | + (service.to_owned(), id.to_owned()), | ||
| 222 | + map_object, | ||
| 223 | + ) | ||
| 224 | + .await | ||
| 225 | +} | ||
| 226 | + | ||
| 227 | +impl Store { | ||
| 228 | + /// The service with this key, if it has made a call before. | ||
| 229 | + pub async fn service(&self, key: &str) -> Result<Option<Service>> { | ||
| 230 | + let conn = self.read_conn().await; | ||
| 231 | + service_row(&conn, key).await | ||
| 232 | + } | ||
| 233 | + | ||
| 234 | + /// Every service, by key. For the admin page. | ||
| 235 | + pub async fn services(&self) -> Result<Vec<Service>> { | ||
| 236 | + let conn = self.read_conn().await; | ||
| 237 | + fetch_all( | ||
| 238 | + &conn, | ||
| 239 | + &format!("SELECT {SERVICE_COLS} FROM services ORDER BY key"), | ||
| 240 | + (), | ||
| 241 | + map_service, | ||
| 242 | + ) | ||
| 243 | + .await | ||
| 244 | + } | ||
| 245 | + | ||
| 246 | + /// The service with this key, created with `default_quota` when it is new. Called on every | ||
| 247 | + /// authorised machine call, so the common case is a read. | ||
| 248 | + pub async fn ensure_service(&self, key: &str, default_quota: i64) -> Result<Service> { | ||
| 249 | + if let Some(service) = self.service(key).await? { | ||
| 250 | + return Ok(service); | ||
| 251 | + } | ||
| 252 | + { | ||
| 253 | + let conn = self.inner.conn.lock().await; | ||
| 254 | + // `OR IGNORE` keeps a concurrent first call from failing on the primary key. | ||
| 255 | + conn.execute( | ||
| 256 | + "INSERT OR IGNORE INTO services (key, quota_bytes, used_bytes, created_at) \ | ||
| 257 | + VALUES (?1, ?2, 0, ?3)", | ||
| 258 | + (key.to_owned(), default_quota, now_stamp()), | ||
| 259 | + ) | ||
| 260 | + .await | ||
| 261 | + .map_err(db_err)?; | ||
| 262 | + } | ||
| 263 | + self.service(key).await?.ok_or_else(missing_row) | ||
| 264 | + } | ||
| 265 | + | ||
| 266 | + /// The usage of a service: quota, bytes used and the object count. A service that does not exist has | ||
| 267 | + /// none, so the answer is `NotFound`. | ||
| 268 | + pub async fn service_usage(&self, service: &str) -> Result<Usage> { | ||
| 269 | + let conn = self.read_conn().await; | ||
| 270 | + let row = service_row(&conn, service).await?.ok_or(Error::NotFound)?; | ||
| 271 | + let objects = fetch_opt( | ||
| 272 | + &conn, | ||
| 273 | + "SELECT COUNT(*) FROM objects WHERE service = ?1", | ||
| 274 | + (service.to_owned(),), | ||
| 275 | + |row| col_int(row, 0), | ||
| 276 | + ) | ||
| 277 | + .await? | ||
| 278 | + .unwrap_or(0); | ||
| 279 | + Ok(Usage { | ||
| 280 | + quota_bytes: row.quota_bytes, | ||
| 281 | + used_bytes: row.used_bytes, | ||
| 282 | + objects, | ||
| 283 | + }) | ||
| 284 | + } | ||
| 285 | + | ||
| 286 | + /// An object of `service` by its id, or `None`. | ||
| 287 | + pub async fn service_object(&self, service: &str, id: &str) -> Result<Option<Object>> { | ||
| 288 | + let conn = self.read_conn().await; | ||
| 289 | + object_row(&conn, service, id).await | ||
| 290 | + } | ||
| 291 | + | ||
| 292 | + /// Stores an object row, replacing the object with the same id in the same service. In one | ||
| 293 | + /// transaction: the new total must fit the quota (the old object's bytes are given back first), the row | ||
| 294 | + /// is inserted or updated, and `used_bytes` is moved by the difference. A replace keeps the original | ||
| 295 | + /// `created_at`. | ||
| 296 | + /// | ||
| 297 | + /// The bytes must already be at the blob key of `new.sha256`. The old bytes are not removed here: the | ||
| 298 | + /// caller retires `replaced_blob` after this returns. | ||
| 299 | + pub async fn put_object(&self, new: NewObject) -> Result<PutOutcome> { | ||
| 300 | + let now = now_stamp(); | ||
| 301 | + let conn = self.inner.conn.lock().await; | ||
| 302 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 303 | + let outcome: Result<PutOutcome> = async { | ||
| 304 | + let service = service_row(&tx, &new.service) | ||
| 305 | + .await? | ||
| 306 | + .ok_or(Error::NotFound)?; | ||
| 307 | + let old = object_row(&tx, &new.service, &new.external_id).await?; | ||
| 308 | + if new.create_only && old.is_some() { | ||
| 309 | + return Ok(PutOutcome::Exists); | ||
| 310 | + } | ||
| 311 | + let old_size = old.as_ref().map_or(0, |object| object.size); | ||
| 312 | + let used_after = service.used_bytes - old_size + new.size; | ||
| 313 | + if used_after > service.quota_bytes { | ||
| 314 | + return Ok(PutOutcome::QuotaExceeded); | ||
| 315 | + } | ||
| 316 | + let blob_key = object_blob_key(&new.service, &new.sha256); | ||
| 317 | + let created = old.is_none(); | ||
| 318 | + let created_at = old | ||
| 319 | + .as_ref() | ||
| 320 | + .map_or_else(|| now.clone(), |object| object.created_at.clone()); | ||
| 321 | + if created { | ||
| 322 | + tx.execute( | ||
| 323 | + "INSERT INTO objects (service, external_id, size, sha256, content_type, name, \ | ||
| 324 | + blob_key, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", | ||
| 325 | + ( | ||
| 326 | + new.service.clone(), | ||
| 327 | + new.external_id.clone(), | ||
| 328 | + new.size, | ||
| 329 | + new.sha256.clone(), | ||
| 330 | + new.content_type.clone(), | ||
| 331 | + new.name.clone(), | ||
| 332 | + blob_key.clone(), | ||
| 333 | + created_at, | ||
| 334 | + now.clone(), | ||
| 335 | + ), | ||
| 336 | + ) | ||
| 337 | + .await | ||
| 338 | + .map_err(db_err)?; | ||
| 339 | + } else { | ||
| 340 | + tx.execute( | ||
| 341 | + "UPDATE objects SET size = ?3, sha256 = ?4, content_type = ?5, name = ?6, \ | ||
| 342 | + blob_key = ?7, updated_at = ?8 WHERE service = ?1 AND external_id = ?2", | ||
| 343 | + ( | ||
| 344 | + new.service.clone(), | ||
| 345 | + new.external_id.clone(), | ||
| 346 | + new.size, | ||
| 347 | + new.sha256.clone(), | ||
| 348 | + new.content_type.clone(), | ||
| 349 | + new.name.clone(), | ||
| 350 | + blob_key.clone(), | ||
| 351 | + now.clone(), | ||
| 352 | + ), | ||
| 353 | + ) | ||
| 354 | + .await | ||
| 355 | + .map_err(db_err)?; | ||
| 356 | + } | ||
| 357 | + tx.execute( | ||
| 358 | + "UPDATE services SET used_bytes = ?2 WHERE key = ?1", | ||
| 359 | + (new.service.clone(), used_after), | ||
| 360 | + ) | ||
| 361 | + .await | ||
| 362 | + .map_err(db_err)?; | ||
| 363 | + let object = object_row(&tx, &new.service, &new.external_id) | ||
| 364 | + .await? | ||
| 365 | + .ok_or_else(missing_row)?; | ||
| 366 | + let replaced_blob = old | ||
| 367 | + .map(|object| object.blob_key) | ||
| 368 | + .filter(|key| *key != blob_key); | ||
| 369 | + Ok(PutOutcome::Stored { | ||
| 370 | + object: Box::new(object), | ||
| 371 | + created, | ||
| 372 | + replaced_blob, | ||
| 373 | + }) | ||
| 374 | + } | ||
| 375 | + .await; | ||
| 376 | + finish(tx, outcome).await | ||
| 377 | + } | ||
| 378 | + | ||
| 379 | + /// Removes an object of `service` and gives its bytes back to the quota. Returns the removed row, so the | ||
| 380 | + /// caller can retire its blob, or `None` when there was no such object (the caller still answers `204`). | ||
| 381 | + pub async fn delete_object(&self, service: &str, id: &str) -> Result<Option<Object>> { | ||
| 382 | + let conn = self.inner.conn.lock().await; | ||
| 383 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 384 | + let outcome: Result<Option<Object>> = async { | ||
| 385 | + let Some(old) = object_row(&tx, service, id).await? else { | ||
| 386 | + return Ok(None); | ||
| 387 | + }; | ||
| 388 | + tx.execute( | ||
| 389 | + "DELETE FROM objects WHERE service = ?1 AND external_id = ?2", | ||
| 390 | + (service.to_owned(), id.to_owned()), | ||
| 391 | + ) | ||
| 392 | + .await | ||
| 393 | + .map_err(db_err)?; | ||
| 394 | + tx.execute( | ||
| 395 | + "UPDATE services SET used_bytes = used_bytes - ?2 WHERE key = ?1", | ||
| 396 | + (service.to_owned(), old.size), | ||
| 397 | + ) | ||
| 398 | + .await | ||
| 399 | + .map_err(db_err)?; | ||
| 400 | + Ok(Some(old)) | ||
| 401 | + } | ||
| 402 | + .await; | ||
| 403 | + finish(tx, outcome).await | ||
| 404 | + } | ||
| 405 | + | ||
| 406 | + /// Claims `key` for a write that is about to put bytes there. Waits for any removal in progress, so | ||
| 407 | + /// the bytes cannot be removed between the put and the row. The claim lasts until the returned guard is | ||
| 408 | + /// dropped, which the caller does once the row has committed (or the write has been refused). | ||
| 409 | + pub async fn hold_blob(&self, key: &str) -> BlobHold { | ||
| 410 | + let _gate = self.inner.blobs.retire.lock().await; | ||
| 411 | + let mut held = self | ||
| 412 | + .inner | ||
| 413 | + .blobs | ||
| 414 | + .held | ||
| 415 | + .lock() | ||
| 416 | + .unwrap_or_else(PoisonError::into_inner); | ||
| 417 | + *held.entry(key.to_owned()).or_insert(0) += 1; | ||
| 418 | + BlobHold { | ||
| 419 | + inner: Arc::clone(&self.inner), | ||
| 420 | + key: key.to_owned(), | ||
| 421 | + } | ||
| 422 | + } | ||
| 423 | + | ||
| 424 | + /// Removes the blob at `key` when it is safe: no open claim holds it and no row names it. Returns | ||
| 425 | + /// `true` when the blob was deleted. `false` means it is still in use, or in the middle of a write; the | ||
| 426 | + /// sweeper finds it later if it is still unreferenced. | ||
| 427 | + pub async fn retire_blob(&self, key: &str, blobs: &dyn BlobStore) -> Result<bool> { | ||
| 428 | + let _gate = self.inner.blobs.retire.lock().await; | ||
| 429 | + let claimed = self | ||
| 430 | + .inner | ||
| 431 | + .blobs | ||
| 432 | + .held | ||
| 433 | + .lock() | ||
| 434 | + .unwrap_or_else(PoisonError::into_inner) | ||
| 435 | + .contains_key(key); | ||
| 436 | + if claimed || self.blob_is_named(key).await? { | ||
| 437 | + return Ok(false); | ||
| 438 | + } | ||
| 439 | + blobs.delete(key).await?; | ||
| 440 | + Ok(true) | ||
| 441 | + } | ||
| 442 | + | ||
| 443 | + /// Whether an object row names this blob key. | ||
| 444 | + async fn blob_is_named(&self, key: &str) -> Result<bool> { | ||
| 445 | + let conn = self.read_conn().await; | ||
| 446 | + Ok(fetch_opt( | ||
| 447 | + &conn, | ||
| 448 | + "SELECT 1 FROM objects WHERE blob_key = ?1 LIMIT 1", | ||
| 449 | + (key.to_owned(),), | ||
| 450 | + |_| Ok(()), | ||
| 451 | + ) | ||
| 452 | + .await? | ||
| 453 | + .is_some()) | ||
| 454 | + } | ||
| 455 | +} | ||
| 456 | + | ||
| 457 | +#[cfg(test)] | ||
| 458 | +mod tests { | ||
| 459 | + use super::*; | ||
| 460 | + use crate::blob::local::LocalBlobs; | ||
| 461 | + use crate::staging::StagedFile; | ||
| 462 | + | ||
| 463 | + const SERVICE: &str = "iz"; | ||
| 464 | + const OTHER: &str = "im"; | ||
| 465 | + | ||
| 466 | + /// A store with two services (`iz` and `im`) at `quota`, and a blob tree in the same temp dir. | ||
| 467 | + async fn setup(quota: i64) -> (tempfile::TempDir, Store, LocalBlobs) { | ||
| 468 | + let dir = tempfile::tempdir().unwrap(); | ||
| 469 | + let store = Store::open(&dir.path().join("in.db")).await.unwrap(); | ||
| 470 | + store.ensure_service(SERVICE, quota).await.unwrap(); | ||
| 471 | + store.ensure_service(OTHER, quota).await.unwrap(); | ||
| 472 | + let blobs = LocalBlobs::new(dir.path().join("blobs")).unwrap(); | ||
| 473 | + (dir, store, blobs) | ||
| 474 | + } | ||
| 475 | + | ||
| 476 | + /// Stages `bytes`, puts them at their hash key as the API does, and returns the row input for them. | ||
| 477 | + async fn stage( | ||
| 478 | + dir: &tempfile::TempDir, | ||
| 479 | + blobs: &LocalBlobs, | ||
| 480 | + service: &str, | ||
| 481 | + id: &str, | ||
| 482 | + bytes: &[u8], | ||
| 483 | + ) -> NewObject { | ||
| 484 | + let mut staged = StagedFile::create(dir.path(), 1 << 20).await.unwrap(); | ||
| 485 | + staged.write(bytes).await.unwrap(); | ||
| 486 | + let staged = staged.finish().await.unwrap(); | ||
| 487 | + let key = object_blob_key(service, &staged.sha256); | ||
| 488 | + blobs.put_file(&key, &staged.path).await.unwrap(); | ||
| 489 | + NewObject { | ||
| 490 | + service: service.into(), | ||
| 491 | + external_id: id.into(), | ||
| 492 | + size: staged.size as i64, | ||
| 493 | + sha256: staged.sha256, | ||
| 494 | + content_type: "application/octet-stream".into(), | ||
| 495 | + name: None, | ||
| 496 | + create_only: false, | ||
| 497 | + } | ||
| 498 | + } | ||
| 499 | + | ||
| 500 | + #[test] | ||
| 501 | + fn external_ids_follow_the_contract_charset_and_length() { | ||
| 502 | + assert!(check_external_id("task-1_a.b").is_ok()); | ||
| 503 | + assert!(check_external_id(&"a".repeat(128)).is_ok()); | ||
| 504 | + for bad in ["", "../x", "a/b", "a b", "ü", &"a".repeat(129)] { | ||
| 505 | + assert!(check_external_id(bad).is_err(), "{bad:?}"); | ||
| 506 | + } | ||
| 507 | + } | ||
| 508 | + | ||
| 509 | + /// The same id in two services is two objects, each with its own bytes. | ||
| 510 | + #[tokio::test] | ||
| 511 | + async fn the_same_id_in_two_services_is_two_objects() { | ||
| 512 | + let (dir, store, blobs) = setup(1 << 20).await; | ||
| 513 | + let a = stage(&dir, &blobs, SERVICE, "same", b"alpha").await; | ||
| 514 | + let b = stage(&dir, &blobs, OTHER, "same", b"beta!!").await; | ||
| 515 | + store.put_object(a).await.unwrap(); | ||
| 516 | + store.put_object(b).await.unwrap(); | ||
| 517 | + let mine = store | ||
| 518 | + .service_object(SERVICE, "same") | ||
| 519 | + .await | ||
| 520 | + .unwrap() | ||
| 521 | + .unwrap(); | ||
| 522 | + let theirs = store.service_object(OTHER, "same").await.unwrap().unwrap(); | ||
| 523 | + assert_eq!(mine.size, 5); | ||
| 524 | + assert_eq!(theirs.size, 6); | ||
| 525 | + assert!( | ||
| 526 | + store | ||
| 527 | + .service_object(SERVICE, "missing") | ||
| 528 | + .await | ||
| 529 | + .unwrap() | ||
| 530 | + .is_none() | ||
| 531 | + ); | ||
| 532 | + } | ||
| 533 | + | ||
| 534 | + /// A replace keeps one row, moves the quota by the difference, and names the old blob for retiring. | ||
| 535 | + /// Retiring it removes the old bytes, because nothing else names them. | ||
| 536 | + #[tokio::test] | ||
| 537 | + async fn a_replace_keeps_one_row_and_the_old_bytes_go_when_unreferenced() { | ||
| 538 | + let (dir, store, blobs) = setup(1 << 20).await; | ||
| 539 | + let first = stage(&dir, &blobs, SERVICE, "doc", b"first version").await; | ||
| 540 | + let old_key = object_blob_key(SERVICE, &first.sha256); | ||
| 541 | + store.put_object(first).await.unwrap(); | ||
| 542 | + | ||
| 543 | + let second = stage(&dir, &blobs, SERVICE, "doc", b"second").await; | ||
| 544 | + let new_key = object_blob_key(SERVICE, &second.sha256); | ||
| 545 | + let PutOutcome::Stored { | ||
| 546 | + created, | ||
| 547 | + replaced_blob, | ||
| 548 | + .. | ||
| 549 | + } = store.put_object(second).await.unwrap() | ||
| 550 | + else { | ||
| 551 | + panic!("the replace must be stored"); | ||
| 552 | + }; | ||
| 553 | + assert!(!created); | ||
| 554 | + assert_eq!(replaced_blob.as_deref(), Some(old_key.as_str())); | ||
| 555 | + assert!(store.retire_blob(&old_key, &blobs).await.unwrap()); | ||
| 556 | + | ||
| 557 | + let usage = store.service_usage(SERVICE).await.unwrap(); | ||
| 558 | + assert_eq!(usage.objects, 1); | ||
| 559 | + assert_eq!(usage.used_bytes, 6); | ||
| 560 | + assert_eq!(blobs.size(&old_key).await.unwrap(), None); | ||
| 561 | + assert_eq!(blobs.size(&new_key).await.unwrap(), Some(6)); | ||
| 562 | + } | ||
| 563 | + | ||
| 564 | + /// Two objects with the same bytes share one blob. Deleting one keeps the bytes for the other. | ||
| 565 | + #[tokio::test] | ||
| 566 | + async fn identical_content_shares_a_blob_until_the_last_object_goes() { | ||
| 567 | + let (dir, store, blobs) = setup(1 << 20).await; | ||
| 568 | + let a = stage(&dir, &blobs, SERVICE, "a", b"same bytes").await; | ||
| 569 | + let b = stage(&dir, &blobs, SERVICE, "b", b"same bytes").await; | ||
| 570 | + let key = object_blob_key(SERVICE, &a.sha256); | ||
| 571 | + store.put_object(a).await.unwrap(); | ||
| 572 | + store.put_object(b).await.unwrap(); | ||
| 573 | + | ||
| 574 | + let removed = store.delete_object(SERVICE, "a").await.unwrap().unwrap(); | ||
| 575 | + assert_eq!(removed.blob_key, key); | ||
| 576 | + assert!(!store.retire_blob(&key, &blobs).await.unwrap()); | ||
| 577 | + assert_eq!(blobs.size(&key).await.unwrap(), Some(10)); | ||
| 578 | + assert!(store.service_object(SERVICE, "b").await.unwrap().is_some()); | ||
| 579 | + | ||
| 580 | + store.delete_object(SERVICE, "b").await.unwrap(); | ||
| 581 | + assert!(store.retire_blob(&key, &blobs).await.unwrap()); | ||
| 582 | + assert_eq!(blobs.size(&key).await.unwrap(), None); | ||
| 583 | + assert_eq!(store.service_usage(SERVICE).await.unwrap().used_bytes, 0); | ||
| 584 | + } | ||
| 585 | + | ||
| 586 | + /// A put that would pass the quota is refused and changes nothing. A replace gives back its old size | ||
| 587 | + /// first, so it may grow only as far as the quota allows. | ||
| 588 | + #[tokio::test] | ||
| 589 | + async fn the_quota_is_checked_inside_the_write() { | ||
| 590 | + let (dir, store, blobs) = setup(10).await; | ||
| 591 | + store | ||
| 592 | + .put_object(stage(&dir, &blobs, SERVICE, "one", b"123456").await) | ||
| 593 | + .await | ||
| 594 | + .unwrap(); | ||
| 595 | + let outcome = store | ||
| 596 | + .put_object(stage(&dir, &blobs, SERVICE, "two", b"12345").await) | ||
| 597 | + .await | ||
| 598 | + .unwrap(); | ||
| 599 | + assert_eq!(outcome, PutOutcome::QuotaExceeded); | ||
| 600 | + assert!( | ||
| 601 | + store | ||
| 602 | + .service_object(SERVICE, "two") | ||
| 603 | + .await | ||
| 604 | + .unwrap() | ||
| 605 | + .is_none() | ||
| 606 | + ); | ||
| 607 | + assert_eq!(store.service_usage(SERVICE).await.unwrap().used_bytes, 6); | ||
| 608 | + | ||
| 609 | + let grow = store | ||
| 610 | + .put_object(stage(&dir, &blobs, SERVICE, "one", b"1234567890").await) | ||
| 611 | + .await | ||
| 612 | + .unwrap(); | ||
| 613 | + assert!(matches!(grow, PutOutcome::Stored { created: false, .. })); | ||
| 614 | + assert_eq!(store.service_usage(SERVICE).await.unwrap().used_bytes, 10); | ||
| 615 | + } | ||
| 616 | + | ||
| 617 | + /// A blob that a write holds is not removed, even when no row names it yet. | ||
| 618 | + #[tokio::test] | ||
| 619 | + async fn a_held_blob_is_not_retired() { | ||
| 620 | + let (dir, store, blobs) = setup(1 << 20).await; | ||
| 621 | + let object = stage(&dir, &blobs, SERVICE, "x", b"pending").await; | ||
| 622 | + let key = object_blob_key(SERVICE, &object.sha256); | ||
| 623 | + let hold = store.hold_blob(&key).await; | ||
| 624 | + assert!(!store.retire_blob(&key, &blobs).await.unwrap()); | ||
| 625 | + drop(hold); | ||
| 626 | + assert!(store.retire_blob(&key, &blobs).await.unwrap()); | ||
| 627 | + } | ||
| 628 | +} | ||
crates/in-web/src/api/machine_auth.rsadded+213 -0
| @@ -0,0 +1,213 @@ | |||
| 1 | +//! Machine authentication of the object API (contracts.md 2.6 and 5). A family service calls `in` with an | ||
| 2 | +//! access token that `im` issued through the client-credentials grant. This module decides whether that | ||
| 3 | +//! token may be used here, and names the caller's namespace. | ||
| 4 | +//! | ||
| 5 | +//! A call passes these checks, in this order, and each refusal is JSON with the status of contracts.md 7: | ||
| 6 | +//! 1. The `Authorization: Bearer` token verifies against `im`'s keys (EdDSA, `iss`, `exp` with 60 s leeway, | ||
| 7 | +//! `iat` at most 5 minutes ahead), and its `aud` is exactly `in`. Otherwise `401 invalid_token`. | ||
| 8 | +//! 2. It is a client token: `sub` starts with `client:` and `svc` is present. A user's access token or an ID | ||
| 9 | +//! token has neither, so it is `401 invalid_token`. | ||
| 10 | +//! 3. Its scopes contain `files.service`. Otherwise `403 insufficient_scope`. | ||
| 11 | +//! 4. `svc` is a family key (`im`, `in` or `iz`). Otherwise `403 insufficient_scope`. | ||
| 12 | +//! | ||
| 13 | +//! The namespace is `svc` from the verified token and nothing else. No URL segment and no header can | ||
| 14 | +//! change it, so a service cannot reach another service's objects by sending its ids. | ||
| 15 | +//! | ||
| 16 | +//! When the call passes, the service row is created on first use with the default service quota | ||
| 17 | +//! (architecture section 3), so a family service needs no registration. | ||
| 18 | +//! | ||
| 19 | +//! When `[oidc]` is not configured there is no key set to check against, so every machine call is | ||
| 20 | +//! `503 unavailable`. Nothing is accepted without verification. | ||
| 21 | + | ||
| 22 | +use http::header::{AUTHORIZATION, CACHE_CONTROL, CONTENT_TYPE, WWW_AUTHENTICATE}; | ||
| 23 | +use http::{HeaderValue, StatusCode}; | ||
| 24 | +use in_core::store::objects::{DEFAULT_SERVICE_QUOTA, SERVICE_QUOTA_SETTING}; | ||
| 25 | +use serde_json::{Value, json}; | ||
| 26 | +use topcoat::Result; | ||
| 27 | +use topcoat::context::{Cx, app_context}; | ||
| 28 | +use topcoat::router::request::headers; | ||
| 29 | +use topcoat::router::response::Response; | ||
| 30 | +use topcoat::router::{Body, HeaderMap}; | ||
| 31 | + | ||
| 32 | +use crate::oidc::{FAMILY_KEY, FILES_SERVICE_SCOPE, OidcError}; | ||
| 33 | +use crate::state::AppState; | ||
| 34 | + | ||
| 35 | +/// The family keys that may call the object API (contracts.md 1). `in` is listed so that the rule reads the | ||
| 36 | +/// same as the table; it is not a caller in practice. | ||
| 37 | +pub const FAMILY_KEYS: [&str; 3] = ["im", "in", "iz"]; | ||
| 38 | + | ||
| 39 | +/// The prefix of a client-credentials token's subject (contracts.md 2.6). | ||
| 40 | +const CLIENT_SUBJECT_PREFIX: &str = "client:"; | ||
| 41 | + | ||
| 42 | +/// A verified caller of the object API. Only `service` is trusted; it comes from the verified `svc` claim. | ||
| 43 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 44 | +pub struct Caller { | ||
| 45 | + /// The caller's family key. It names the caller's namespace. | ||
| 46 | + pub service: String, | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +/// A refused call: the status and the stable error word of contracts.md 7, with an English message for logs. | ||
| 50 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 51 | +pub struct Refusal { | ||
| 52 | + /// HTTP status of the answer. | ||
| 53 | + pub status: StatusCode, | ||
| 54 | + /// The stable machine word, such as `invalid_token`. | ||
| 55 | + pub error: &'static str, | ||
| 56 | + /// English text for logs and developers. It may change. | ||
| 57 | + pub message: &'static str, | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +impl Refusal { | ||
| 61 | + /// The JSON answer of this refusal, with `WWW-Authenticate` on `401`. | ||
| 62 | + pub fn answer(&self) -> Response { | ||
| 63 | + let mut response = json_response( | ||
| 64 | + self.status, | ||
| 65 | + &json!({ "error": self.error, "message": self.message }), | ||
| 66 | + ); | ||
| 67 | + if self.status == StatusCode::UNAUTHORIZED { | ||
| 68 | + response.headers_mut().insert( | ||
| 69 | + WWW_AUTHENTICATE, | ||
| 70 | + HeaderValue::from_static("Bearer error=\"invalid_token\""), | ||
| 71 | + ); | ||
| 72 | + } | ||
| 73 | + response | ||
| 74 | + } | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +/// A refusal shorthand. | ||
| 78 | +const fn refuse(status: StatusCode, error: &'static str, message: &'static str) -> Refusal { | ||
| 79 | + Refusal { | ||
| 80 | + status, | ||
| 81 | + error, | ||
| 82 | + message, | ||
| 83 | + } | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +/// A JSON response of the object API. Answers are never cached. | ||
| 87 | +pub fn json_response(status: StatusCode, value: &Value) -> Response { | ||
| 88 | + let body = serde_json::to_vec(value).unwrap_or_default(); | ||
| 89 | + let mut response = http::Response::new(Body::from(body)); | ||
| 90 | + *response.status_mut() = status; | ||
| 91 | + response | ||
| 92 | + .headers_mut() | ||
| 93 | + .insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); | ||
| 94 | + response | ||
| 95 | + .headers_mut() | ||
| 96 | + .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); | ||
| 97 | + response | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +/// The bearer token of an `Authorization` header: the scheme is matched without regard to case, and the | ||
| 101 | +/// token must be non-empty with no spaces. | ||
| 102 | +pub fn bearer_token(headers: &HeaderMap) -> Option<&str> { | ||
| 103 | + let value = headers.get(AUTHORIZATION)?.to_str().ok()?; | ||
| 104 | + let (scheme, token) = value.split_once(' ')?; | ||
| 105 | + if !scheme.eq_ignore_ascii_case("bearer") || token.is_empty() || token.contains(' ') { | ||
| 106 | + return None; | ||
| 107 | + } | ||
| 108 | + Some(token) | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +/// The default quota of a new service: the `default_service_quota_bytes` setting when it holds a positive | ||
| 112 | +/// number, else [`DEFAULT_SERVICE_QUOTA`]. | ||
| 113 | +async fn default_service_quota(state: &AppState) -> Result<i64> { | ||
| 114 | + let setting = state.store.get_setting(SERVICE_QUOTA_SETTING).await?; | ||
| 115 | + Ok(setting | ||
| 116 | + .and_then(|text| text.trim().parse::<i64>().ok()) | ||
| 117 | + .filter(|quota| *quota > 0) | ||
| 118 | + .unwrap_or(DEFAULT_SERVICE_QUOTA)) | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +/// Checks the bearer token of the request in `cx` and returns the caller, or the refusal to send. | ||
| 122 | +/// | ||
| 123 | +/// Errors that are not refusals (a database failure) are returned as `Err` and answered as `500` by the | ||
| 124 | +/// router. | ||
| 125 | +pub async fn machine_caller(cx: &Cx) -> Result<std::result::Result<Caller, Refusal>> { | ||
| 126 | + let state = app_context::<AppState>(cx); | ||
| 127 | + let Some(token) = bearer_token(headers(cx)) else { | ||
| 128 | + return Ok(Err(refuse( | ||
| 129 | + StatusCode::UNAUTHORIZED, | ||
| 130 | + "invalid_token", | ||
| 131 | + "a bearer token is required", | ||
| 132 | + ))); | ||
| 133 | + }; | ||
| 134 | + let Some(oidc) = &state.oidc else { | ||
| 135 | + return Ok(Err(refuse( | ||
| 136 | + StatusCode::SERVICE_UNAVAILABLE, | ||
| 137 | + "unavailable", | ||
| 138 | + "the identity provider is not configured", | ||
| 139 | + ))); | ||
| 140 | + }; | ||
| 141 | + let claims = match oidc.verify_machine_token(token, FAMILY_KEY).await { | ||
| 142 | + Ok(claims) => claims, | ||
| 143 | + Err(OidcError::Token(_)) => { | ||
| 144 | + return Ok(Err(refuse( | ||
| 145 | + StatusCode::UNAUTHORIZED, | ||
| 146 | + "invalid_token", | ||
| 147 | + "the token is not valid for this API", | ||
| 148 | + ))); | ||
| 149 | + } | ||
| 150 | + Err(error) => { | ||
| 151 | + tracing::warn!(error = %error, "machine auth: the keys could not be checked"); | ||
| 152 | + return Ok(Err(refuse( | ||
| 153 | + StatusCode::SERVICE_UNAVAILABLE, | ||
| 154 | + "unavailable", | ||
| 155 | + "the identity provider is unavailable", | ||
| 156 | + ))); | ||
| 157 | + } | ||
| 158 | + }; | ||
| 159 | + // A user's token or an ID token has no client subject and no `svc`, so it fails here, before any scope | ||
| 160 | + // is read. | ||
| 161 | + let Some(svc) = claims | ||
| 162 | + .svc | ||
| 163 | + .as_deref() | ||
| 164 | + .filter(|_| claims.subject.starts_with(CLIENT_SUBJECT_PREFIX)) | ||
| 165 | + else { | ||
| 166 | + return Ok(Err(refuse( | ||
| 167 | + StatusCode::UNAUTHORIZED, | ||
| 168 | + "invalid_token", | ||
| 169 | + "the token is not a service token", | ||
| 170 | + ))); | ||
| 171 | + }; | ||
| 172 | + if !claims | ||
| 173 | + .scopes | ||
| 174 | + .iter() | ||
| 175 | + .any(|scope| scope == FILES_SERVICE_SCOPE) | ||
| 176 | + { | ||
| 177 | + return Ok(Err(refuse( | ||
| 178 | + StatusCode::FORBIDDEN, | ||
| 179 | + "insufficient_scope", | ||
| 180 | + "the token lacks the files.service scope", | ||
| 181 | + ))); | ||
| 182 | + } | ||
| 183 | + if !FAMILY_KEYS.contains(&svc) { | ||
| 184 | + return Ok(Err(refuse( | ||
| 185 | + StatusCode::FORBIDDEN, | ||
| 186 | + "insufficient_scope", | ||
| 187 | + "the caller is not a family service", | ||
| 188 | + ))); | ||
| 189 | + } | ||
| 190 | + let quota = default_service_quota(state).await?; | ||
| 191 | + state.store.ensure_service(svc, quota).await?; | ||
| 192 | + Ok(Ok(Caller { | ||
| 193 | + service: svc.to_owned(), | ||
| 194 | + })) | ||
| 195 | +} | ||
| 196 | + | ||
| 197 | +#[cfg(test)] | ||
| 198 | +mod tests { | ||
| 199 | + use super::*; | ||
| 200 | + | ||
| 201 | + #[test] | ||
| 202 | + fn the_bearer_scheme_is_case_blind_and_one_token_only() { | ||
| 203 | + let mut headers = HeaderMap::new(); | ||
| 204 | + headers.insert(AUTHORIZATION, HeaderValue::from_static("bearer abc.def")); | ||
| 205 | + assert_eq!(bearer_token(&headers), Some("abc.def")); | ||
| 206 | + headers.insert(AUTHORIZATION, HeaderValue::from_static("Basic abc")); | ||
| 207 | + assert_eq!(bearer_token(&headers), None); | ||
| 208 | + headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer a b")); | ||
| 209 | + assert_eq!(bearer_token(&headers), None); | ||
| 210 | + headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer ")); | ||
| 211 | + assert_eq!(bearer_token(&headers), None); | ||
| 212 | + } | ||
| 213 | +} | ||
crates/in-web/src/api/mod.rsmodified+6 -3
| @@ -1,4 +1,7 @@ | |||
| 1 | -//! The JSON APIs of the app: the chunked upload (`upload.rs`, architecture 4.2). The machine object API | 1 | +//! The JSON APIs of the app: the chunked upload (`upload.rs`, architecture 4.2) and the machine object API |
| 2 | -//! comes later (contracts.md 5). Every route here answers JSON, including its refusals, and never | 2 | +//! for family services (`objects.rs`, contracts.md 5), whose token check is `machine_auth.rs`. Every route |
| 3 | -//! redirects to sign-in: a script that lost its session gets `401`. | 3 | +//! here answers JSON, including its refusals, and never redirects to sign-in: a script that lost its |
| 4 | +//! session gets `401`. | ||
| 5 | +pub mod machine_auth; | ||
| 6 | +pub mod objects; | ||
| 4 | pub mod upload; | 7 | pub mod upload; |
crates/in-web/src/api/objects.rsadded+792 -0
| @@ -0,0 +1,792 @@ | |||
| 1 | +//! The object store API for family services (contracts.md 5). `iz` keeps its blobs here, under its own | ||
| 2 | +//! namespace, with its own quota. Every route needs a client-credentials token with `aud = "in"` and scope | ||
| 3 | +//! `files.service`, checked in `machine_auth.rs`; the namespace is the token's `svc` and nothing else. | ||
| 4 | +//! | ||
| 5 | +//! The routes: | ||
| 6 | +//! - `PUT /api/v1/objects/{external_id}` stores the raw body. The bytes stream to a staged file while their | ||
| 7 | +//! SHA-256 is computed. The body may not be longer than the quota that is left (the service quota, less | ||
| 8 | +//! what the service uses, plus the bytes of the object being replaced), and the limit is enforced while it | ||
| 9 | +//! is read, so nothing above it is stored. The bytes are put at `objects/<service>/<sha256>`, and the row | ||
| 10 | +//! is committed in the same step that moves the quota. A new id answers `201`, a replaced one `200`. | ||
| 11 | +//! `If-None-Match: *` refuses an existing id with `409`. | ||
| 12 | +//! - `GET` and `HEAD` send the bytes through `serve_bytes`, always as an attachment, with `Range` support. | ||
| 13 | +//! The cache policy is `private, no-cache`, because a replace changes what the id names. | ||
| 14 | +//! - `DELETE` removes the object. It answers `204` also when the object was already absent. | ||
| 15 | +//! - `GET /api/v1/usage` answers the quota, the bytes used and the number of objects. | ||
| 16 | +//! | ||
| 17 | +//! Blob removal goes through `Store::retire_blob`, so bytes that another object still names, or that a | ||
| 18 | +//! write is storing right now, are never removed. A removal that is refused is left to the sweeper. | ||
| 19 | + | ||
| 20 | +use futures_util::StreamExt; | ||
| 21 | +use http::StatusCode; | ||
| 22 | +use http::header::{CONTENT_LENGTH, CONTENT_TYPE, IF_NONE_MATCH}; | ||
| 23 | +use in_core::error::Error as CoreError; | ||
| 24 | +use in_core::names; | ||
| 25 | +use in_core::staging::StagedFile; | ||
| 26 | +use in_core::store::objects::{NewObject, Object, PutOutcome, check_external_id, object_blob_key}; | ||
| 27 | +use serde_json::{Value, json}; | ||
| 28 | +use topcoat::Result; | ||
| 29 | +use topcoat::context::{Cx, app_context}; | ||
| 30 | +use topcoat::router::request::headers; | ||
| 31 | +use topcoat::router::response::Response; | ||
| 32 | +use topcoat::router::{Body, HeaderMap, path_param_segment, route}; | ||
| 33 | + | ||
| 34 | +use crate::api::machine_auth::{Refusal, json_response, machine_caller}; | ||
| 35 | +use crate::serve_bytes::{ByteSource, Disposition, SHARE_CACHE, serve_bytes_with}; | ||
| 36 | +use crate::state::AppState; | ||
| 37 | + | ||
| 38 | +/// The `Content-Type` of an object whose PUT names none. | ||
| 39 | +const DEFAULT_CONTENT_TYPE: &str = "application/octet-stream"; | ||
| 40 | + | ||
| 41 | +/// Longest `Content-Type` value kept, in bytes. | ||
| 42 | +const MAX_CONTENT_TYPE_BYTES: usize = 255; | ||
| 43 | + | ||
| 44 | +/// Longest `X-Object-Name`, in bytes, after decoding. | ||
| 45 | +const MAX_NAME_BYTES: usize = 255; | ||
| 46 | + | ||
| 47 | +/// The cache policy of object bytes: the id can be replaced at any time, so a cached copy must be checked. | ||
| 48 | +const OBJECT_CACHE: &str = SHARE_CACHE; | ||
| 49 | + | ||
| 50 | +/// A `400` with the stable word `invalid_request`. | ||
| 51 | +fn bad_request(message: &'static str) -> Refusal { | ||
| 52 | + Refusal { | ||
| 53 | + status: StatusCode::BAD_REQUEST, | ||
| 54 | + error: "invalid_request", | ||
| 55 | + message, | ||
| 56 | + } | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// The headers of a PUT that the handler reads before it touches the body. | ||
| 60 | +#[derive(Debug, PartialEq, Eq)] | ||
| 61 | +struct PutRequest { | ||
| 62 | + /// The `Content-Length` the client declared, if any. Checked against the quota before a byte is read. | ||
| 63 | + declared: Option<u64>, | ||
| 64 | + /// The `Content-Type`, stored as given. | ||
| 65 | + content_type: String, | ||
| 66 | + /// The cleaned `X-Object-Name`, if one was sent. | ||
| 67 | + name: Option<String>, | ||
| 68 | + /// `true` for `If-None-Match: *`: the PUT must create the id, not replace it. | ||
| 69 | + create_only: bool, | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +impl PutRequest { | ||
| 73 | + /// Reads the PUT headers. Malformed ones are `400`, and nothing is stored. | ||
| 74 | + fn from_headers(request: &HeaderMap) -> std::result::Result<Self, Refusal> { | ||
| 75 | + let declared = match request.get(CONTENT_LENGTH) { | ||
| 76 | + None => None, | ||
| 77 | + Some(value) => Some( | ||
| 78 | + value | ||
| 79 | + .to_str() | ||
| 80 | + .ok() | ||
| 81 | + .and_then(|text| text.parse::<u64>().ok()) | ||
| 82 | + .ok_or_else(|| bad_request("Content-Length is not a number"))?, | ||
| 83 | + ), | ||
| 84 | + }; | ||
| 85 | + let create_only = match request.get(IF_NONE_MATCH) { | ||
| 86 | + None => false, | ||
| 87 | + Some(value) if value.as_bytes() == b"*" => true, | ||
| 88 | + Some(_) => return Err(bad_request("If-None-Match must be *")), | ||
| 89 | + }; | ||
| 90 | + Ok(Self { | ||
| 91 | + declared, | ||
| 92 | + content_type: content_type_of(request)?, | ||
| 93 | + name: object_name(request)?, | ||
| 94 | + create_only, | ||
| 95 | + }) | ||
| 96 | + } | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +/// The stored `Content-Type`: the client's value when it is a `type/subtype` with printable ASCII, else | ||
| 100 | +/// `application/octet-stream`. | ||
| 101 | +fn content_type_of(request: &HeaderMap) -> std::result::Result<String, Refusal> { | ||
| 102 | + let Some(value) = request.get(CONTENT_TYPE) else { | ||
| 103 | + return Ok(DEFAULT_CONTENT_TYPE.to_owned()); | ||
| 104 | + }; | ||
| 105 | + let text = value | ||
| 106 | + .to_str() | ||
| 107 | + .map_err(|_| bad_request("Content-Type is not ASCII"))? | ||
| 108 | + .trim(); | ||
| 109 | + let essence = text.split(';').next().unwrap_or_default().trim(); | ||
| 110 | + let well_formed = essence | ||
| 111 | + .split_once('/') | ||
| 112 | + .is_some_and(|(main, sub)| is_token(main) && is_token(sub)); | ||
| 113 | + if !well_formed || text.len() > MAX_CONTENT_TYPE_BYTES { | ||
| 114 | + return Err(bad_request("Content-Type must be type/subtype")); | ||
| 115 | + } | ||
| 116 | + Ok(text.to_owned()) | ||
| 117 | +} | ||
| 118 | + | ||
| 119 | +/// Whether `text` is a non-empty HTTP token (RFC 9110 section 5.6.2). | ||
| 120 | +fn is_token(text: &str) -> bool { | ||
| 121 | + !text.is_empty() | ||
| 122 | + && text | ||
| 123 | + .bytes() | ||
| 124 | + .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)) | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +/// The `X-Object-Name`: percent-encoded UTF-8, at most 255 bytes once decoded. It is cleaned like a file | ||
| 128 | +/// name (`names::display_name`), so a path or control characters cannot reach a download header. | ||
| 129 | +fn object_name(request: &HeaderMap) -> std::result::Result<Option<String>, Refusal> { | ||
| 130 | + let Some(value) = request.get("x-object-name") else { | ||
| 131 | + return Ok(None); | ||
| 132 | + }; | ||
| 133 | + let raw = value | ||
| 134 | + .to_str() | ||
| 135 | + .map_err(|_| bad_request("X-Object-Name is not ASCII"))?; | ||
| 136 | + let decoded = | ||
| 137 | + percent_decode(raw).ok_or_else(|| bad_request("X-Object-Name is not percent-encoded"))?; | ||
| 138 | + if decoded.len() > MAX_NAME_BYTES { | ||
| 139 | + return Err(bad_request("X-Object-Name is longer than 255 bytes")); | ||
| 140 | + } | ||
| 141 | + let text = String::from_utf8(decoded).map_err(|_| bad_request("X-Object-Name is not UTF-8"))?; | ||
| 142 | + if text.trim().is_empty() { | ||
| 143 | + return Ok(None); | ||
| 144 | + } | ||
| 145 | + Ok(Some(names::display_name(&text))) | ||
| 146 | +} | ||
| 147 | + | ||
| 148 | +/// Decodes `%XX` escapes. Every other byte stands for itself, `+` included. `None` for a broken escape or | ||
| 149 | +/// a decoded value that is not text. | ||
| 150 | +fn percent_decode(raw: &str) -> Option<Vec<u8>> { | ||
| 151 | + let bytes = raw.as_bytes(); | ||
| 152 | + let mut out = Vec::with_capacity(bytes.len()); | ||
| 153 | + let mut i = 0; | ||
| 154 | + while i < bytes.len() { | ||
| 155 | + if bytes[i] == b'%' { | ||
| 156 | + let hex = bytes.get(i + 1..i + 3)?; | ||
| 157 | + let text = std::str::from_utf8(hex).ok()?; | ||
| 158 | + out.push(u8::from_str_radix(text, 16).ok()?); | ||
| 159 | + i += 3; | ||
| 160 | + } else { | ||
| 161 | + out.push(bytes[i]); | ||
| 162 | + i += 1; | ||
| 163 | + } | ||
| 164 | + } | ||
| 165 | + Some(out) | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +/// The JSON of an object as the PUT answers it (contracts.md 5). | ||
| 169 | +fn object_json(object: &Object) -> Value { | ||
| 170 | + json!({ | ||
| 171 | + "external_id": object.external_id, | ||
| 172 | + "size": object.size, | ||
| 173 | + "sha256": object.sha256, | ||
| 174 | + "content_type": object.content_type, | ||
| 175 | + "created_at": object.created_at, | ||
| 176 | + }) | ||
| 177 | +} | ||
| 178 | + | ||
| 179 | +/// An empty `204` with no cache. | ||
| 180 | +fn no_content() -> Response { | ||
| 181 | + let mut response = http::Response::new(Body::empty()); | ||
| 182 | + *response.status_mut() = StatusCode::NO_CONTENT; | ||
| 183 | + response | ||
| 184 | +} | ||
| 185 | + | ||
| 186 | +/// Removes a blob that a write or a delete has released. A blob that cannot be removed now is logged and | ||
| 187 | +/// left for the sweeper, because the row change has already committed. | ||
| 188 | +async fn retire_quietly(state: &AppState, key: &str) { | ||
| 189 | + if let Err(error) = state.store.retire_blob(key, state.blobs.as_ref()).await { | ||
| 190 | + tracing::warn!(key = %key, error = %error, "objects: released blob not removed"); | ||
| 191 | + } | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +/// `PUT /api/v1/objects/{external_id}`: stores the body as the object `external_id` of the caller. | ||
| 195 | +#[route(PUT "/api/v1/objects/{external_id}")] | ||
| 196 | +async fn put_object(cx: &Cx, body: Body) -> Result<Response> { | ||
| 197 | + let state = app_context::<AppState>(cx); | ||
| 198 | + let caller = match machine_caller(cx).await? { | ||
| 199 | + Ok(caller) => caller, | ||
| 200 | + Err(refusal) => return Ok(refusal.answer()), | ||
| 201 | + }; | ||
| 202 | + let external_id = path_param_segment(cx, "external_id").to_owned(); | ||
| 203 | + if check_external_id(&external_id).is_err() { | ||
| 204 | + return Ok( | ||
| 205 | + bad_request("external_id must be 1 to 128 of A-Z, a-z, 0-9, '.', '_', '-'").answer(), | ||
| 206 | + ); | ||
| 207 | + } | ||
| 208 | + let request = match PutRequest::from_headers(headers(cx)) { | ||
| 209 | + Ok(request) => request, | ||
| 210 | + Err(refusal) => return Ok(refusal.answer()), | ||
| 211 | + }; | ||
| 212 | + let service = caller.service; | ||
| 213 | + let existing = state.store.service_object(&service, &external_id).await?; | ||
| 214 | + if request.create_only && existing.is_some() { | ||
| 215 | + return Ok(Refusal { | ||
| 216 | + status: StatusCode::CONFLICT, | ||
| 217 | + error: "conflict", | ||
| 218 | + message: "an object with this external_id already exists", | ||
| 219 | + } | ||
| 220 | + .answer()); | ||
| 221 | + } | ||
| 222 | + let row = state | ||
| 223 | + .store | ||
| 224 | + .service(&service) | ||
| 225 | + .await? | ||
| 226 | + .ok_or(CoreError::NotFound)?; | ||
| 227 | + // The object being replaced gives its bytes back first, so a replace may grow only as far as the quota | ||
| 228 | + // allows. The same arithmetic is repeated inside the write transaction, which has the final say. | ||
| 229 | + let replaced = existing.as_ref().map_or(0, |object| object.size); | ||
| 230 | + let headroom = (row.quota_bytes - row.used_bytes + replaced).max(0) as u64; | ||
| 231 | + let quota_refusal = Refusal { | ||
| 232 | + status: StatusCode::PAYLOAD_TOO_LARGE, | ||
| 233 | + error: "quota_exceeded", | ||
| 234 | + message: "the service quota is used up", | ||
| 235 | + }; | ||
| 236 | + if request.declared.is_some_and(|length| length > headroom) { | ||
| 237 | + return Ok(quota_refusal.answer()); | ||
| 238 | + } | ||
| 239 | + | ||
| 240 | + let mut staged = StagedFile::create(&state.config.data_dir, headroom).await?; | ||
| 241 | + let mut frames = body.into_data_stream(); | ||
| 242 | + while let Some(frame) = frames.next().await { | ||
| 243 | + let written = match frame { | ||
| 244 | + Ok(bytes) => staged.write(&bytes).await, | ||
| 245 | + Err(_) => { | ||
| 246 | + staged.abort().await; | ||
| 247 | + return Ok(bad_request("the request body could not be read").answer()); | ||
| 248 | + } | ||
| 249 | + }; | ||
| 250 | + if let Err(error) = written { | ||
| 251 | + staged.abort().await; | ||
| 252 | + return match error { | ||
| 253 | + CoreError::Invalid(_) => Ok(quota_refusal.answer()), | ||
| 254 | + other => Err(other.into()), | ||
| 255 | + }; | ||
| 256 | + } | ||
| 257 | + } | ||
| 258 | + let staged = staged.finish().await?; | ||
| 259 | + | ||
| 260 | + // The claim is taken before the bytes are put, so a removal of the same blob cannot run in between. | ||
| 261 | + let key = object_blob_key(&service, &staged.sha256); | ||
| 262 | + let hold = state.store.hold_blob(&key).await; | ||
| 263 | + if let Err(error) = state.blobs.put_file(&key, &staged.path).await { | ||
| 264 | + drop(hold); | ||
| 265 | + return Err(error.into()); | ||
| 266 | + } | ||
| 267 | + let outcome = state | ||
| 268 | + .store | ||
| 269 | + .put_object(NewObject { | ||
| 270 | + service: service.clone(), | ||
| 271 | + external_id: external_id.clone(), | ||
| 272 | + size: staged.size as i64, | ||
| 273 | + sha256: staged.sha256.clone(), | ||
| 274 | + content_type: request.content_type, | ||
| 275 | + name: request.name, | ||
| 276 | + create_only: request.create_only, | ||
| 277 | + }) | ||
| 278 | + .await; | ||
| 279 | + drop(hold); | ||
| 280 | + match outcome? { | ||
| 281 | + PutOutcome::Stored { | ||
| 282 | + object, | ||
| 283 | + created, | ||
| 284 | + replaced_blob, | ||
| 285 | + } => { | ||
| 286 | + if let Some(old) = replaced_blob { | ||
| 287 | + retire_quietly(state, &old).await; | ||
| 288 | + } | ||
| 289 | + let status = if created { | ||
| 290 | + StatusCode::CREATED | ||
| 291 | + } else { | ||
| 292 | + StatusCode::OK | ||
| 293 | + }; | ||
| 294 | + Ok(json_response(status, &object_json(&object))) | ||
| 295 | + } | ||
| 296 | + PutOutcome::QuotaExceeded => { | ||
| 297 | + retire_quietly(state, &key).await; | ||
| 298 | + Ok(quota_refusal.answer()) | ||
| 299 | + } | ||
| 300 | + PutOutcome::Exists => { | ||
| 301 | + retire_quietly(state, &key).await; | ||
| 302 | + Ok(Refusal { | ||
| 303 | + status: StatusCode::CONFLICT, | ||
| 304 | + error: "conflict", | ||
| 305 | + message: "an object with this external_id already exists", | ||
| 306 | + } | ||
| 307 | + .answer()) | ||
| 308 | + } | ||
| 309 | + } | ||
| 310 | +} | ||
| 311 | + | ||
| 312 | +/// `GET /api/v1/objects/{external_id}` and `HEAD` (the router answers HEAD with this handler). | ||
| 313 | +#[route(GET "/api/v1/objects/{external_id}")] | ||
| 314 | +async fn get_object(cx: &Cx) -> Result<Response> { | ||
| 315 | + let state = app_context::<AppState>(cx); | ||
| 316 | + let caller = match machine_caller(cx).await? { | ||
| 317 | + Ok(caller) => caller, | ||
| 318 | + Err(refusal) => return Ok(refusal.answer()), | ||
| 319 | + }; | ||
| 320 | + let external_id = path_param_segment(cx, "external_id").to_owned(); | ||
| 321 | + if check_external_id(&external_id).is_err() { | ||
| 322 | + return Ok( | ||
| 323 | + bad_request("external_id must be 1 to 128 of A-Z, a-z, 0-9, '.', '_', '-'").answer(), | ||
| 324 | + ); | ||
| 325 | + } | ||
| 326 | + let Some(object) = state | ||
| 327 | + .store | ||
| 328 | + .service_object(&caller.service, &external_id) | ||
| 329 | + .await? | ||
| 330 | + else { | ||
| 331 | + return Ok(not_found().answer()); | ||
| 332 | + }; | ||
| 333 | + let name = object | ||
| 334 | + .name | ||
| 335 | + .clone() | ||
| 336 | + .unwrap_or_else(|| object.external_id.clone()); | ||
| 337 | + let source = ByteSource { | ||
| 338 | + blob_key: &object.blob_key, | ||
| 339 | + size: object.size as u64, | ||
| 340 | + sha256: &object.sha256, | ||
| 341 | + mime: &object.content_type, | ||
| 342 | + name: &name, | ||
| 343 | + }; | ||
| 344 | + let (status, response_headers, body) = serve_bytes_with( | ||
| 345 | + cx, | ||
| 346 | + state.blobs.as_ref(), | ||
| 347 | + &source, | ||
| 348 | + Disposition::Attachment, | ||
| 349 | + OBJECT_CACHE, | ||
| 350 | + ) | ||
| 351 | + .await?; | ||
| 352 | + let mut response = http::Response::new(body); | ||
| 353 | + *response.status_mut() = status; | ||
| 354 | + *response.headers_mut() = response_headers; | ||
| 355 | + Ok(response) | ||
| 356 | +} | ||
| 357 | + | ||
| 358 | +/// The `404` of a missing object. The same answer for an id that another service holds, since namespaces | ||
| 359 | +/// are separate. | ||
| 360 | +fn not_found() -> Refusal { | ||
| 361 | + Refusal { | ||
| 362 | + status: StatusCode::NOT_FOUND, | ||
| 363 | + error: "not_found", | ||
| 364 | + message: "no such object", | ||
| 365 | + } | ||
| 366 | +} | ||
| 367 | + | ||
| 368 | +/// `DELETE /api/v1/objects/{external_id}`: removes the object, idempotently. | ||
| 369 | +#[route(DELETE "/api/v1/objects/{external_id}")] | ||
| 370 | +async fn delete_object(cx: &Cx) -> Result<Response> { | ||
| 371 | + let state = app_context::<AppState>(cx); | ||
| 372 | + let caller = match machine_caller(cx).await? { | ||
| 373 | + Ok(caller) => caller, | ||
| 374 | + Err(refusal) => return Ok(refusal.answer()), | ||
| 375 | + }; | ||
| 376 | + let external_id = path_param_segment(cx, "external_id").to_owned(); | ||
| 377 | + if check_external_id(&external_id).is_err() { | ||
| 378 | + return Ok( | ||
| 379 | + bad_request("external_id must be 1 to 128 of A-Z, a-z, 0-9, '.', '_', '-'").answer(), | ||
| 380 | + ); | ||
| 381 | + } | ||
| 382 | + if let Some(removed) = state | ||
| 383 | + .store | ||
| 384 | + .delete_object(&caller.service, &external_id) | ||
| 385 | + .await? | ||
| 386 | + { | ||
| 387 | + retire_quietly(state, &removed.blob_key).await; | ||
| 388 | + } | ||
| 389 | + Ok(no_content()) | ||
| 390 | +} | ||
| 391 | + | ||
| 392 | +/// `PUT`, `GET` and `DELETE` on a path with more than one segment after `objects/`. The id cannot contain | ||
| 393 | +/// `/`, so the answer is the contract's `400`, not a bare `404`. | ||
| 394 | +#[route(PUT "/api/v1/objects/{external_id}/{rest}")] | ||
| 395 | +async fn put_nested(cx: &Cx) -> Result<Response> { | ||
| 396 | + nested_id(cx).await | ||
| 397 | +} | ||
| 398 | + | ||
| 399 | +/// See [`put_nested`]. | ||
| 400 | +#[route(GET "/api/v1/objects/{external_id}/{rest}")] | ||
| 401 | +async fn get_nested(cx: &Cx) -> Result<Response> { | ||
| 402 | + nested_id(cx).await | ||
| 403 | +} | ||
| 404 | + | ||
| 405 | +/// See [`put_nested`]. | ||
| 406 | +#[route(DELETE "/api/v1/objects/{external_id}/{rest}")] | ||
| 407 | +async fn delete_nested(cx: &Cx) -> Result<Response> { | ||
| 408 | + nested_id(cx).await | ||
| 409 | +} | ||
| 410 | + | ||
| 411 | +/// The answer of a nested object path: authenticated callers get `400`, others get the token refusal. | ||
| 412 | +async fn nested_id(cx: &Cx) -> Result<Response> { | ||
| 413 | + if let Err(refusal) = machine_caller(cx).await? { | ||
| 414 | + return Ok(refusal.answer()); | ||
| 415 | + } | ||
| 416 | + Ok(bad_request("external_id must not contain '/'").answer()) | ||
| 417 | +} | ||
| 418 | + | ||
| 419 | +/// `GET /api/v1/usage`: the caller's quota, bytes used and object count. | ||
| 420 | +#[route(GET "/api/v1/usage")] | ||
| 421 | +async fn usage_report(cx: &Cx) -> Result<Response> { | ||
| 422 | + let state = app_context::<AppState>(cx); | ||
| 423 | + let caller = match machine_caller(cx).await? { | ||
| 424 | + Ok(caller) => caller, | ||
| 425 | + Err(refusal) => return Ok(refusal.answer()), | ||
| 426 | + }; | ||
| 427 | + let usage = state.store.service_usage(&caller.service).await?; | ||
| 428 | + Ok(json_response( | ||
| 429 | + StatusCode::OK, | ||
| 430 | + &json!({ | ||
| 431 | + "quota_bytes": usage.quota_bytes, | ||
| 432 | + "used_bytes": usage.used_bytes, | ||
| 433 | + "objects": usage.objects, | ||
| 434 | + }), | ||
| 435 | + )) | ||
| 436 | +} | ||
| 437 | + | ||
| 438 | +#[cfg(test)] | ||
| 439 | +mod tests { | ||
| 440 | + use super::*; | ||
| 441 | + use http::HeaderValue; | ||
| 442 | + | ||
| 443 | + #[test] | ||
| 444 | + fn percent_decoding_takes_escapes_and_refuses_broken_ones() { | ||
| 445 | + assert_eq!(percent_decode("a%20b+c").as_deref(), Some(&b"a b+c"[..])); | ||
| 446 | + assert_eq!(percent_decode("%C3%BC").as_deref(), Some("ü".as_bytes())); | ||
| 447 | + assert_eq!(percent_decode("%2"), None); | ||
| 448 | + assert_eq!(percent_decode("%zz"), None); | ||
| 449 | + } | ||
| 450 | + | ||
| 451 | + #[test] | ||
| 452 | + fn content_type_must_be_a_media_type() { | ||
| 453 | + let mut request = HeaderMap::new(); | ||
| 454 | + request.insert( | ||
| 455 | + CONTENT_TYPE, | ||
| 456 | + HeaderValue::from_static("text/plain; charset=utf-8"), | ||
| 457 | + ); | ||
| 458 | + assert_eq!( | ||
| 459 | + content_type_of(&request).unwrap(), | ||
| 460 | + "text/plain; charset=utf-8" | ||
| 461 | + ); | ||
| 462 | + for bad in ["no-slash", "text/", "a b/c", "text/html\u{7f}"] { | ||
| 463 | + let mut request = HeaderMap::new(); | ||
| 464 | + if let Ok(value) = HeaderValue::from_str(bad) { | ||
| 465 | + request.insert(CONTENT_TYPE, value); | ||
| 466 | + assert!(content_type_of(&request).is_err(), "{bad:?}"); | ||
| 467 | + } | ||
| 468 | + } | ||
| 469 | + assert_eq!( | ||
| 470 | + content_type_of(&HeaderMap::new()).unwrap(), | ||
| 471 | + DEFAULT_CONTENT_TYPE | ||
| 472 | + ); | ||
| 473 | + } | ||
| 474 | + | ||
| 475 | + #[test] | ||
| 476 | + fn names_are_decoded_and_cleaned_like_file_names() { | ||
| 477 | + let mut request = HeaderMap::new(); | ||
| 478 | + request.insert( | ||
| 479 | + "x-object-name", | ||
| 480 | + HeaderValue::from_static("..%2F..%2Fetc%2Fpasswd"), | ||
| 481 | + ); | ||
| 482 | + assert_eq!(object_name(&request).unwrap().as_deref(), Some("passwd")); | ||
| 483 | + request.insert("x-object-name", HeaderValue::from_static("%FF")); | ||
| 484 | + assert!(object_name(&request).is_err()); | ||
| 485 | + } | ||
| 486 | +} | ||
| 487 | + | ||
| 488 | +#[cfg(test)] | ||
| 489 | +mod router_tests { | ||
| 490 | + //! Router-level tests of the object API: the token rules, the namespace, the id rules, the quota and | ||
| 491 | + //! the replace and sharing of blobs. The keys are a fresh Ed25519 key injected into the JWKS cache, so | ||
| 492 | + //! no request reaches `im`. | ||
| 493 | + | ||
| 494 | + use super::*; | ||
| 495 | + use crate::boot::{router, test_state}; | ||
| 496 | + use crate::oidc::OidcClient; | ||
| 497 | + use crate::oidc::test_support::{CLIENT, ISSUER, sign, test_key}; | ||
| 498 | + use crate::state::AppState; | ||
| 499 | + use http::Request; | ||
| 500 | + use http::header::{AUTHORIZATION, WWW_AUTHENTICATE}; | ||
| 501 | + use in_core::store::objects::SERVICE_QUOTA_SETTING; | ||
| 502 | + use serde_json::json; | ||
| 503 | + use sha2::{Digest, Sha256}; | ||
| 504 | + use topcoat::router::{Body, to_bytes}; | ||
| 505 | + | ||
| 506 | + /// A state with the object API's keys in place, and a fresh signing key for the test's tokens. | ||
| 507 | + async fn setup() -> (tempfile::TempDir, AppState, Vec<u8>) { | ||
| 508 | + let (dir, mut state) = test_state().await; | ||
| 509 | + let (der, keys) = test_key(); | ||
| 510 | + state.oidc = Some(std::sync::Arc::new(OidcClient::with_keys_for_tests( | ||
| 511 | + ISSUER, CLIENT, keys, | ||
| 512 | + ))); | ||
| 513 | + (dir, state, der) | ||
| 514 | + } | ||
| 515 | + | ||
| 516 | + /// A client token for `svc` with `scope` and `aud`. `sub` defaults to the client form. | ||
| 517 | + fn machine_token(der: &[u8], svc: &str, scope: &str, aud: &str) -> String { | ||
| 518 | + let now = crate::oidc::now_secs(); | ||
| 519 | + sign( | ||
| 520 | + der, | ||
| 521 | + &json!({ | ||
| 522 | + "iss": ISSUER, "sub": format!("client:{svc}"), "azp": svc, "aud": aud, | ||
| 523 | + "scope": scope, "svc": svc, "iat": now, "exp": now + 600, "jti": "t-1", | ||
| 524 | + }), | ||
| 525 | + ) | ||
| 526 | + } | ||
| 527 | + | ||
| 528 | + /// One call to the object API. Returns the status, the headers and the body bytes. | ||
| 529 | + async fn call( | ||
| 530 | + state: &AppState, | ||
| 531 | + method: &str, | ||
| 532 | + path: &str, | ||
| 533 | + token: Option<&str>, | ||
| 534 | + extra: &[(&str, &str)], | ||
| 535 | + body: Vec<u8>, | ||
| 536 | + ) -> (StatusCode, http::HeaderMap, Vec<u8>) { | ||
| 537 | + let mut request = Request::builder().method(method).uri(path); | ||
| 538 | + if let Some(token) = token { | ||
| 539 | + request = request.header(AUTHORIZATION, format!("Bearer {token}")); | ||
| 540 | + } | ||
| 541 | + for (name, value) in extra { | ||
| 542 | + request = request.header(*name, *value); | ||
| 543 | + } | ||
| 544 | + let request = request.body(Body::from(body)).expect("request"); | ||
| 545 | + let response = router(state.clone()).handle(request).await; | ||
| 546 | + let status = response.status(); | ||
| 547 | + let headers = response.headers().clone(); | ||
| 548 | + let bytes = to_bytes(response.into_body(), 1 << 20).await.expect("body"); | ||
| 549 | + (status, headers, bytes.to_vec()) | ||
| 550 | + } | ||
| 551 | + | ||
| 552 | + fn json_of(bytes: &[u8]) -> Value { | ||
| 553 | + serde_json::from_slice(bytes).unwrap_or(Value::Null) | ||
| 554 | + } | ||
| 555 | + | ||
| 556 | + fn sha_hex(bytes: &[u8]) -> String { | ||
| 557 | + Sha256::digest(bytes) | ||
| 558 | + .iter() | ||
| 559 | + .map(|byte| format!("{byte:02x}")) | ||
| 560 | + .collect() | ||
| 561 | + } | ||
| 562 | + | ||
| 563 | + const PUT_PATH: &str = "/api/v1/objects/task-1"; | ||
| 564 | + | ||
| 565 | + /// A token for an audience other than `in` is refused with 401 and the Bearer challenge. A token without | ||
| 566 | + /// `files.service` is 403. A user's token (no client subject, no `svc`) is 401. | ||
| 567 | + #[tokio::test] | ||
| 568 | + async fn the_token_must_be_for_in_and_carry_the_scope() { | ||
| 569 | + let (_dir, state, der) = setup().await; | ||
| 570 | + let for_im = machine_token(&der, "iz", "files.service", "im"); | ||
| 571 | + let (status, headers, _) = | ||
| 572 | + call(&state, "GET", "/api/v1/usage", Some(&for_im), &[], vec![]).await; | ||
| 573 | + assert_eq!(status, StatusCode::UNAUTHORIZED); | ||
| 574 | + assert_eq!(headers[WWW_AUTHENTICATE], "Bearer error=\"invalid_token\""); | ||
| 575 | + | ||
| 576 | + let no_scope = machine_token(&der, "iz", "directory.read", "in"); | ||
| 577 | + let (status, _, body) = | ||
| 578 | + call(&state, "GET", "/api/v1/usage", Some(&no_scope), &[], vec![]).await; | ||
| 579 | + assert_eq!(status, StatusCode::FORBIDDEN); | ||
| 580 | + assert_eq!(json_of(&body)["error"], "insufficient_scope"); | ||
| 581 | + | ||
| 582 | + let now = crate::oidc::now_secs(); | ||
| 583 | + let user = sign( | ||
| 584 | + &der, | ||
| 585 | + &json!({"iss": ISSUER, "sub": "01JUSER", "aud": "in", "scope": "files.service", | ||
| 586 | + "iat": now, "exp": now + 600}), | ||
| 587 | + ); | ||
| 588 | + let (status, _, _) = call(&state, "GET", "/api/v1/usage", Some(&user), &[], vec![]).await; | ||
| 589 | + assert_eq!(status, StatusCode::UNAUTHORIZED); | ||
| 590 | + | ||
| 591 | + let (status, _, _) = call(&state, "GET", "/api/v1/usage", None, &[], vec![]).await; | ||
| 592 | + assert_eq!(status, StatusCode::UNAUTHORIZED); | ||
| 593 | + } | ||
| 594 | + | ||
| 595 | + /// Two services that use the same id hold two objects. Service `im` cannot read, replace or delete the | ||
| 596 | + /// object that `iz` stored, and its own delete leaves `iz`'s object alone. | ||
| 597 | + #[tokio::test] | ||
| 598 | + async fn a_service_cannot_reach_another_services_object() { | ||
| 599 | + let (_dir, state, der) = setup().await; | ||
| 600 | + let iz = machine_token(&der, "iz", "files.service", "in"); | ||
| 601 | + let im = machine_token(&der, "im", "files.service", "in"); | ||
| 602 | + let (status, _, _) = | ||
| 603 | + call(&state, "PUT", PUT_PATH, Some(&iz), &[], b"from iz".to_vec()).await; | ||
| 604 | + assert_eq!(status, StatusCode::CREATED); | ||
| 605 | + | ||
| 606 | + let (status, _, _) = call(&state, "GET", PUT_PATH, Some(&im), &[], vec![]).await; | ||
| 607 | + assert_eq!(status, StatusCode::NOT_FOUND); | ||
| 608 | + let (status, _, _) = call(&state, "DELETE", PUT_PATH, Some(&im), &[], vec![]).await; | ||
| 609 | + assert_eq!(status, StatusCode::NO_CONTENT); | ||
| 610 | + let (status, _, body) = call(&state, "GET", PUT_PATH, Some(&iz), &[], vec![]).await; | ||
| 611 | + assert_eq!(status, StatusCode::OK); | ||
| 612 | + assert_eq!(body, b"from iz"); | ||
| 613 | + } | ||
| 614 | + | ||
| 615 | + /// An id with `/` or a charset break is 400, and nothing is stored under it. | ||
| 616 | + #[tokio::test] | ||
| 617 | + async fn an_external_id_outside_the_contract_is_400() { | ||
| 618 | + let (_dir, state, der) = setup().await; | ||
| 619 | + let iz = machine_token(&der, "iz", "files.service", "in"); | ||
| 620 | + for path in [ | ||
| 621 | + "/api/v1/objects/a/b", | ||
| 622 | + "/api/v1/objects/..%2Fx", | ||
| 623 | + "/api/v1/objects/a%20b", | ||
| 624 | + ] { | ||
| 625 | + let (status, _, body) = call(&state, "PUT", path, Some(&iz), &[], b"x".to_vec()).await; | ||
| 626 | + assert_eq!(status, StatusCode::BAD_REQUEST, "{path}"); | ||
| 627 | + assert_eq!(json_of(&body)["error"], "invalid_request", "{path}"); | ||
| 628 | + } | ||
| 629 | + let usage = state.store.service_usage("iz").await.unwrap(); | ||
| 630 | + assert_eq!(usage.objects, 0); | ||
| 631 | + } | ||
| 632 | + | ||
| 633 | + /// A body above the quota is refused with 413 `quota_exceeded`. Nothing is stored and no bytes stay | ||
| 634 | + /// counted. A `Content-Length` above the quota is refused before the body is read. | ||
| 635 | + #[tokio::test] | ||
| 636 | + async fn a_body_over_the_quota_is_refused_and_stores_nothing() { | ||
| 637 | + let (_dir, state, der) = setup().await; | ||
| 638 | + state | ||
| 639 | + .store | ||
| 640 | + .set_setting(SERVICE_QUOTA_SETTING, "10") | ||
| 641 | + .await | ||
| 642 | + .unwrap(); | ||
| 643 | + let iz = machine_token(&der, "iz", "files.service", "in"); | ||
| 644 | + let (status, _, body) = call(&state, "PUT", PUT_PATH, Some(&iz), &[], vec![7u8; 11]).await; | ||
| 645 | + assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE); | ||
| 646 | + assert_eq!(json_of(&body)["error"], "quota_exceeded"); | ||
| 647 | + let (status, _, _) = call( | ||
| 648 | + &state, | ||
| 649 | + "PUT", | ||
| 650 | + PUT_PATH, | ||
| 651 | + Some(&iz), | ||
| 652 | + &[("content-length", "11")], | ||
| 653 | + vec![7u8; 11], | ||
| 654 | + ) | ||
| 655 | + .await; | ||
| 656 | + assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE); | ||
| 657 | + let usage = state.store.service_usage("iz").await.unwrap(); | ||
| 658 | + assert_eq!( | ||
| 659 | + (usage.objects, usage.used_bytes, usage.quota_bytes), | ||
| 660 | + (0, 0, 10) | ||
| 661 | + ); | ||
| 662 | + let (status, _, _) = call(&state, "GET", PUT_PATH, Some(&iz), &[], vec![]).await; | ||
| 663 | + assert_eq!(status, StatusCode::NOT_FOUND); | ||
| 664 | + } | ||
| 665 | + | ||
| 666 | + /// A replace keeps one row and reports 200. The old bytes are removed once no object names them, and | ||
| 667 | + /// identical content from two ids shares one blob until the last of them is deleted. | ||
| 668 | + #[tokio::test] | ||
| 669 | + async fn a_replace_keeps_one_row_and_shared_bytes_outlive_one_object() { | ||
| 670 | + let (_dir, state, der) = setup().await; | ||
| 671 | + let iz = machine_token(&der, "iz", "files.service", "in"); | ||
| 672 | + let (status, _, _) = call(&state, "PUT", PUT_PATH, Some(&iz), &[], b"first".to_vec()).await; | ||
| 673 | + assert_eq!(status, StatusCode::CREATED); | ||
| 674 | + let old_key = object_blob_key("iz", &sha_hex(b"first")); | ||
| 675 | + let (status, _, body) = | ||
| 676 | + call(&state, "PUT", PUT_PATH, Some(&iz), &[], b"second!".to_vec()).await; | ||
| 677 | + assert_eq!(status, StatusCode::OK); | ||
| 678 | + assert_eq!(json_of(&body)["size"], 7); | ||
| 679 | + assert_eq!(state.blobs.size(&old_key).await.unwrap(), None); | ||
| 680 | + assert_eq!(state.store.service_usage("iz").await.unwrap().objects, 1); | ||
| 681 | + | ||
| 682 | + // Two ids with the same bytes share one blob. | ||
| 683 | + let (status, _, _) = call( | ||
| 684 | + &state, | ||
| 685 | + "PUT", | ||
| 686 | + "/api/v1/objects/copy-a", | ||
| 687 | + Some(&iz), | ||
| 688 | + &[], | ||
| 689 | + b"same".to_vec(), | ||
| 690 | + ) | ||
| 691 | + .await; | ||
| 692 | + assert_eq!(status, StatusCode::CREATED); | ||
| 693 | + let (status, _, _) = call( | ||
| 694 | + &state, | ||
| 695 | + "PUT", | ||
| 696 | + "/api/v1/objects/copy-b", | ||
| 697 | + Some(&iz), | ||
| 698 | + &[], | ||
| 699 | + b"same".to_vec(), | ||
| 700 | + ) | ||
| 701 | + .await; | ||
| 702 | + assert_eq!(status, StatusCode::CREATED); | ||
| 703 | + let shared = object_blob_key("iz", &sha_hex(b"same")); | ||
| 704 | + let (status, _, _) = call( | ||
| 705 | + &state, | ||
| 706 | + "DELETE", | ||
| 707 | + "/api/v1/objects/copy-a", | ||
| 708 | + Some(&iz), | ||
| 709 | + &[], | ||
| 710 | + vec![], | ||
| 711 | + ) | ||
| 712 | + .await; | ||
| 713 | + assert_eq!(status, StatusCode::NO_CONTENT); | ||
| 714 | + assert_eq!(state.blobs.size(&shared).await.unwrap(), Some(4)); | ||
| 715 | + let (status, _, body) = call( | ||
| 716 | + &state, | ||
| 717 | + "GET", | ||
| 718 | + "/api/v1/objects/copy-b", | ||
| 719 | + Some(&iz), | ||
| 720 | + &[], | ||
| 721 | + vec![], | ||
| 722 | + ) | ||
| 723 | + .await; | ||
| 724 | + assert_eq!(status, StatusCode::OK); | ||
| 725 | + assert_eq!(body, b"same"); | ||
| 726 | + } | ||
| 727 | + | ||
| 728 | + /// A GET answers the stored bytes as an attachment with the stored type and the sha256 as its ETag, and | ||
| 729 | + /// honours one `Range`. `If-None-Match` with the same hash is `304`. A DELETE of an absent id is `204`. | ||
| 730 | + #[tokio::test] | ||
| 731 | + async fn get_serves_the_bytes_as_an_attachment_with_range() { | ||
| 732 | + let (_dir, state, der) = setup().await; | ||
| 733 | + let iz = machine_token(&der, "iz", "files.service", "in"); | ||
| 734 | + let (status, _, _) = call( | ||
| 735 | + &state, | ||
| 736 | + "PUT", | ||
| 737 | + PUT_PATH, | ||
| 738 | + Some(&iz), | ||
| 739 | + &[ | ||
| 740 | + ("content-type", "text/plain"), | ||
| 741 | + ("x-object-name", "notes%2Fa%20b.txt"), | ||
| 742 | + ], | ||
| 743 | + b"0123456789".to_vec(), | ||
| 744 | + ) | ||
| 745 | + .await; | ||
| 746 | + assert_eq!(status, StatusCode::CREATED); | ||
| 747 | + let (status, headers, body) = call( | ||
| 748 | + &state, | ||
| 749 | + "GET", | ||
| 750 | + PUT_PATH, | ||
| 751 | + Some(&iz), | ||
| 752 | + &[("range", "bytes=2-4")], | ||
| 753 | + vec![], | ||
| 754 | + ) | ||
| 755 | + .await; | ||
| 756 | + assert_eq!(status, StatusCode::PARTIAL_CONTENT); | ||
| 757 | + assert_eq!(body, b"234"); | ||
| 758 | + assert_eq!( | ||
| 759 | + headers["content-disposition"] | ||
| 760 | + .to_str() | ||
| 761 | + .unwrap() | ||
| 762 | + .split(';') | ||
| 763 | + .next(), | ||
| 764 | + Some("attachment") | ||
| 765 | + ); | ||
| 766 | + assert_eq!( | ||
| 767 | + headers["etag"], | ||
| 768 | + format!("\"{}\"", sha_hex(b"0123456789")).as_str() | ||
| 769 | + ); | ||
| 770 | + let etag = format!("\"{}\"", sha_hex(b"0123456789")); | ||
| 771 | + let (status, _, _) = call( | ||
| 772 | + &state, | ||
| 773 | + "GET", | ||
| 774 | + PUT_PATH, | ||
| 775 | + Some(&iz), | ||
| 776 | + &[("if-none-match", etag.as_str())], | ||
| 777 | + vec![], | ||
| 778 | + ) | ||
| 779 | + .await; | ||
| 780 | + assert_eq!(status, StatusCode::NOT_MODIFIED); | ||
| 781 | + let (status, _, _) = call( | ||
| 782 | + &state, | ||
| 783 | + "DELETE", | ||
| 784 | + "/api/v1/objects/never-was", | ||
| 785 | + Some(&iz), | ||
| 786 | + &[], | ||
| 787 | + vec![], | ||
| 788 | + ) | ||
| 789 | + .await; | ||
| 790 | + assert_eq!(status, StatusCode::NO_CONTENT); | ||
| 791 | + } | ||
| 792 | +} | ||
crates/in-web/src/oidc.rsmodified+108 -41
| @@ -59,6 +59,12 @@ pub const IM_KEY: &str = "im"; | |||
| 59 | /// The scope that reads the people directory and photos at `im`. | 59 | /// The scope that reads the people directory and photos at `im`. |
| 60 | pub const DIRECTORY_SCOPE: &str = "directory.read"; | 60 | pub const DIRECTORY_SCOPE: &str = "directory.read"; |
| 61 | 61 | ||
| 62 | +/// The family key of `in` itself. Client-credentials tokens that call `in` carry it as `aud`. | ||
| 63 | +pub const FAMILY_KEY: &str = "in"; | ||
| 64 | + | ||
| 65 | +/// The scope that lets a family service store and read its own objects in `in` (contracts.md 5). | ||
| 66 | +pub const FILES_SERVICE_SCOPE: &str = "files.service"; | ||
| 67 | + | ||
| 62 | /// Why a token was refused. Every variant is a refusal; none of them says more than the cause. | 68 | /// Why a token was refused. Every variant is a refusal; none of them says more than the cause. |
| 63 | #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] | 69 | #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] |
| 64 | pub enum TokenError { | 70 | pub enum TokenError { |
| @@ -393,30 +399,106 @@ pub fn verify_logout_token( | |||
| 393 | Ok(LogoutClaims { jti, sid, sub }) | 399 | Ok(LogoutClaims { jti, sid, sub }) |
| 394 | } | 400 | } |
| 395 | 401 | ||
| 396 | -/// Verifies an access token addressed to `audience` (for `in`, [`FAMILY_KEY`]) that grants | 402 | +/// The claims of a client-credentials access token that a machine API needs (contracts.md 2.6). |
| 397 | -/// `required_scope`. Returns the caller's family key (`svc`) and its subject. | 403 | +#[derive(Debug, Clone, PartialEq, Eq)] |
| 398 | -/// | 404 | +pub struct MachineClaims { |
| 399 | -/// Nothing calls this yet; the object API that accepts service calls comes next. | 405 | + /// The token subject, `client:<client_id>` for a client-credentials token. Only the prefix is checked. |
| 400 | -#[allow(dead_code)] // The object API that accepts other family apps' calls is the first caller. | 406 | + pub subject: String, |
| 401 | -pub fn verify_access_token( | 407 | + /// The scopes the token grants, from the space-separated `scope` claim. Empty when there is none. |
| 408 | + pub scopes: Vec<String>, | ||
| 409 | + /// The caller's family key from `svc`. Callers treat it as their identity. `None` when absent. | ||
| 410 | + pub svc: Option<String>, | ||
| 411 | +} | ||
| 412 | + | ||
| 413 | +/// Verifies an access token addressed to `audience` (for `in`, [`FAMILY_KEY`]): signature, `iss`, `exp` | ||
| 414 | +/// (with leeway), `iat` (at most five minutes ahead), and `aud` equal to `audience` exactly. It does not | ||
| 415 | +/// judge the scopes or the `svc` claim; the caller decides what they must contain, because the refusal | ||
| 416 | +/// differs (a missing `svc` is a bad token, a missing scope is a forbidden call). | ||
| 417 | +pub fn verify_machine_token( | ||
| 402 | keys: &KeySet, | 418 | keys: &KeySet, |
| 403 | token: &str, | 419 | token: &str, |
| 404 | issuer: &str, | 420 | issuer: &str, |
| 405 | audience: &str, | 421 | audience: &str, |
| 406 | - required_scope: &str, | 422 | +) -> Result<MachineClaims, TokenError> { |
| 407 | -) -> Result<(String, String), TokenError> { | ||
| 408 | let claims = verify_signed(keys, token, issuer)?; | 423 | let claims = verify_signed(keys, token, issuer)?; |
| 409 | if !audience_is(claims.get("aud"), audience) { | 424 | if !audience_is(claims.get("aud"), audience) { |
| 410 | return Err(TokenError::Claim("aud")); | 425 | return Err(TokenError::Claim("aud")); |
| 411 | } | 426 | } |
| 412 | check_iat(&claims, now_secs())?; | 427 | check_iat(&claims, now_secs())?; |
| 413 | - let scope = text_claim(&claims, "scope")?; | 428 | + let subject = text_claim(&claims, "sub")?.to_owned(); |
| 414 | - if !scope.split(' ').any(|granted| granted == required_scope) { | 429 | + let scopes = optional_text_claim(&claims, "scope") |
| 415 | - return Err(TokenError::Claim("scope")); | 430 | + .map(|scope| { |
| 431 | + scope | ||
| 432 | + .split(' ') | ||
| 433 | + .filter(|s| !s.is_empty()) | ||
| 434 | + .map(str::to_owned) | ||
| 435 | + .collect() | ||
| 436 | + }) | ||
| 437 | + .unwrap_or_default(); | ||
| 438 | + let svc = optional_text_claim(&claims, "svc").map(str::to_owned); | ||
| 439 | + Ok(MachineClaims { | ||
| 440 | + subject, | ||
| 441 | + scopes, | ||
| 442 | + svc, | ||
| 443 | + }) | ||
| 444 | +} | ||
| 445 | + | ||
| 446 | +#[cfg(test)] | ||
| 447 | +impl OidcClient { | ||
| 448 | + /// A client whose key set is `keys` and whose endpoints are the standard paths under `issuer`. The cache | ||
| 449 | + /// is filled directly, so no request is made. Production always fetches; only tests use this. | ||
| 450 | + pub(crate) fn with_keys_for_tests(issuer: &str, client_id: &str, keys: KeySet) -> Self { | ||
| 451 | + let config = Oidc { | ||
| 452 | + issuer: issuer.to_owned(), | ||
| 453 | + client_id: client_id.to_owned(), | ||
| 454 | + client_secret_file: std::path::PathBuf::new(), | ||
| 455 | + }; | ||
| 456 | + let mut client = | ||
| 457 | + Self::new(&config, "https://in.test", "test-secret".to_owned()).expect("client"); | ||
| 458 | + let endpoints = client.standard_endpoints(); | ||
| 459 | + let cache = client.cache.get_mut(); | ||
| 460 | + cache.endpoints = Some(Arc::new(endpoints)); | ||
| 461 | + cache.keys = Some((Instant::now(), Arc::new(keys))); | ||
| 462 | + client | ||
| 463 | + } | ||
| 464 | +} | ||
| 465 | + | ||
| 466 | +/// Ed25519 keys and signed tokens for the tests of this crate. Test-only; production keys come from `im`. | ||
| 467 | +#[cfg(test)] | ||
| 468 | +pub(crate) mod test_support { | ||
| 469 | + use super::*; | ||
| 470 | + use ed25519_dalek::SigningKey; | ||
| 471 | + use ed25519_dalek::pkcs8::EncodePrivateKey; | ||
| 472 | + use jsonwebtoken::{EncodingKey, Header, encode}; | ||
| 473 | + use serde_json::json; | ||
| 474 | + | ||
| 475 | + /// The issuer the test tokens name. | ||
| 476 | + pub(crate) const ISSUER: &str = "https://im.example.test"; | ||
| 477 | + /// The client id `in` uses in the tests. | ||
| 478 | + pub(crate) const CLIENT: &str = "in"; | ||
| 479 | + /// The key id of the test key. | ||
| 480 | + pub(crate) const KID: &str = "k1"; | ||
| 481 | + | ||
| 482 | + /// A fresh Ed25519 key: the signing half as PKCS#8 DER, and the key set that publishes it. | ||
| 483 | + pub(crate) fn test_key() -> (Vec<u8>, KeySet) { | ||
| 484 | + let mut seed = [0u8; 32]; | ||
| 485 | + rand::fill(&mut seed); | ||
| 486 | + let signing = SigningKey::from_bytes(&seed); | ||
| 487 | + let der = signing.to_pkcs8_der().expect("pkcs8").as_bytes().to_vec(); | ||
| 488 | + let x = BASE64_URL_SAFE_NO_PAD.encode(signing.verifying_key().to_bytes()); | ||
| 489 | + let jwks: Jwks = serde_json::from_value(json!({ | ||
| 490 | + "keys": [{"kty": "OKP", "crv": "Ed25519", "x": x, "kid": KID, "use": "sig", "alg": "EdDSA"}] | ||
| 491 | + })) | ||
| 492 | + .expect("jwks"); | ||
| 493 | + (der, KeySet::from_jwks(&jwks)) | ||
| 494 | + } | ||
| 495 | + | ||
| 496 | + /// Signs `claims` with `der` under [`KID`]. | ||
| 497 | + pub(crate) fn sign(der: &[u8], claims: &Value) -> String { | ||
| 498 | + let mut header = Header::new(Algorithm::EdDSA); | ||
| 499 | + header.kid = Some(KID.to_owned()); | ||
| 500 | + encode(&header, claims, &EncodingKey::from_ed_der(der)).expect("sign") | ||
| 416 | } | 501 | } |
| 417 | - let sub = text_claim(&claims, "sub")?.to_owned(); | ||
| 418 | - let svc = text_claim(&claims, "svc")?.to_owned(); | ||
| 419 | - Ok((sub, svc)) | ||
| 420 | } | 502 | } |
| 421 | 503 | ||
| 422 | /// The PKCE code challenge of `verifier`: base64url of its SHA-256, without padding (RFC 7636). | 504 | /// The PKCE code challenge of `verifier`: base64url of its SHA-256, without padding (RFC 7636). |
| @@ -640,6 +722,17 @@ impl OidcClient { | |||
| 640 | } | 722 | } |
| 641 | } | 723 | } |
| 642 | 724 | ||
| 725 | + /// Verifies a client-credentials access token addressed to `audience`, with the cached key set. See | ||
| 726 | + /// [`verify_machine_token`]. | ||
| 727 | + pub async fn verify_machine_token( | ||
| 728 | + &self, | ||
| 729 | + token: &str, | ||
| 730 | + audience: &str, | ||
| 731 | + ) -> Result<MachineClaims, OidcError> { | ||
| 732 | + self.verify_with(|keys| verify_machine_token(keys, token, &self.issuer, audience)) | ||
| 733 | + .await | ||
| 734 | + } | ||
| 735 | + | ||
| 643 | /// Runs `check` against the key set. An unknown key id triggers one rate-limited refetch. | 736 | /// Runs `check` against the key set. An unknown key id triggers one rate-limited refetch. |
| 644 | async fn verify_with<T>( | 737 | async fn verify_with<T>( |
| 645 | &self, | 738 | &self, |
| @@ -799,38 +892,12 @@ impl OidcClient { | |||
| 799 | 892 | ||
| 800 | #[cfg(test)] | 893 | #[cfg(test)] |
| 801 | mod tests { | 894 | mod tests { |
| 895 | + use super::test_support::{CLIENT, ISSUER, sign, test_key}; | ||
| 802 | use super::*; | 896 | use super::*; |
| 803 | - use ed25519_dalek::SigningKey; | ||
| 804 | - use ed25519_dalek::pkcs8::EncodePrivateKey; | ||
| 805 | - use jsonwebtoken::{EncodingKey, Header, encode}; | ||
| 806 | use serde_json::json; | 897 | use serde_json::json; |
| 807 | 898 | ||
| 808 | - const ISSUER: &str = "https://im.example.test"; | ||
| 809 | - const CLIENT: &str = "in"; | ||
| 810 | - const KID: &str = "k1"; | ||
| 811 | const NONCE: &str = "nonce-value"; | 899 | const NONCE: &str = "nonce-value"; |
| 812 | 900 | ||
| 813 | - /// A fresh Ed25519 key: the signing half as PKCS#8 DER, and the key set that publishes it. | ||
| 814 | - fn test_key() -> (Vec<u8>, KeySet) { | ||
| 815 | - let mut seed = [0u8; 32]; | ||
| 816 | - rand::fill(&mut seed); | ||
| 817 | - let signing = SigningKey::from_bytes(&seed); | ||
| 818 | - let der = signing.to_pkcs8_der().expect("pkcs8").as_bytes().to_vec(); | ||
| 819 | - let x = BASE64_URL_SAFE_NO_PAD.encode(signing.verifying_key().to_bytes()); | ||
| 820 | - let jwks: Jwks = serde_json::from_value(json!({ | ||
| 821 | - "keys": [{"kty": "OKP", "crv": "Ed25519", "x": x, "kid": KID, "use": "sig", "alg": "EdDSA"}] | ||
| 822 | - })) | ||
| 823 | - .expect("jwks"); | ||
| 824 | - (der, KeySet::from_jwks(&jwks)) | ||
| 825 | - } | ||
| 826 | - | ||
| 827 | - /// Signs `claims` with `der` under `kid`. | ||
| 828 | - fn sign(der: &[u8], claims: &Value) -> String { | ||
| 829 | - let mut header = Header::new(Algorithm::EdDSA); | ||
| 830 | - header.kid = Some(KID.to_owned()); | ||
| 831 | - encode(&header, claims, &EncodingKey::from_ed_der(der)).expect("sign") | ||
| 832 | - } | ||
| 833 | - | ||
| 834 | fn id_claims(now: i64) -> Value { | 901 | fn id_claims(now: i64) -> Value { |
| 835 | json!({ | 902 | json!({ |
| 836 | "iss": ISSUER, "sub": "01JTESTSUB", "aud": CLIENT, "exp": now + 300, "iat": now, | 903 | "iss": ISSUER, "sub": "01JTESTSUB", "aud": CLIENT, "exp": now + 300, "iat": now, |
docs/architecture.mdmodified+1 -1
| @@ -108,7 +108,7 @@ again), `target_kind`, `target_id`, `owner`, `can_download`, `password_hash` NUL | |||
| 108 | `created_at`. Created on first authorised call with the default quota from settings. | 108 | `created_at`. Created on first authorised call with the default quota from settings. |
| 109 | 109 | ||
| 110 | **objects**: `service` FK services, `external_id`, `size`, `sha256`, `content_type`, `name` NULL, `blob_key` | 110 | **objects**: `service` FK services, `external_id`, `size`, `sha256`, `content_type`, `name` NULL, `blob_key` |
| 111 | -(`objects/<service>/<sha256-of-external_id>`), `created_at`, `updated_at`; PK (service, external_id). | 111 | +(`objects/<service>/<sha256 of the content>`, shared by objects of one service with equal bytes; removed when the last one goes), `created_at`, `updated_at`; PK (service, external_id). |
| 112 | 112 | ||
| 113 | **audit_log**, **settings**: per conventions. | 113 | **audit_log**, **settings**: per conventions. |
| 114 | 114 | ||