🔒 owners revoke grants on trashed items; folder moves count the subtree height; keyed ETags
Browse files at this commitf70fcdd2072ebce5f59de19ce0be9588c456788bParent: f8d618710 changed files +185 -48
- crates/in-core/src/authz.rs +10 -2
- crates/in-core/src/secret.rs +31 -0
- crates/in-core/src/store/folders.rs +64 -6
- crates/in-web/src/api/objects.rs +3 -1
- crates/in-web/src/pages/files.rs +6 -3
- crates/in-web/src/pages/public_share.rs +7 -5
- crates/in-web/src/pages/share_dialog.rs +33 -11
- crates/in-web/src/pages/thumbs.rs +6 -10
- crates/in-web/src/serve_bytes.rs +16 -7
- docs/architecture.md +9 -3
crates/in-core/src/authz.rsmodified+10 -2
| @@ -5,7 +5,8 @@ | ||
| 5 | 5 | //! Rules (architecture section 6): |
| 6 | 6 | //! - Anonymous and service callers never reach drive items. |
| 7 | 7 | //! - The owner may do everything on live items except `Purge` and `Restore`, which apply to trashed |
| 8 | -//! items only. On trashed items the owner may only view, download, restore and purge. | |
| 8 | +//! items only. On trashed items the owner may only view, download, restore, purge, and change or | |
| 9 | +//! remove a grant that already exists (`Revoke`). A new grant or link on a trashed item is refused. | |
| 9 | 10 | //! - An admin may `Administer` any item but reads nobody else's files. |
| 10 | 11 | //! - A grantee sees a live item with a grant, lists and views it, and downloads it only with a |
| 11 | 12 | //! download grant. Nothing else. |
| @@ -71,8 +72,10 @@ pub enum Action { | ||
| 71 | 72 | Write, |
| 72 | 73 | /// Restore a trashed item to its place. |
| 73 | 74 | Restore, |
| 74 | - /// Change who can see the item (grants and links). | |
| 75 | + /// Create a grant or a link: change who can see the item. | |
| 75 | 76 | Share, |
| 77 | + /// Change the level of an existing grant, or remove it. | |
| 78 | + Revoke, | |
| 76 | 79 | /// Permanently delete a trashed item. |
| 77 | 80 | Purge, |
| 78 | 81 | /// Administer the instance. |
| @@ -128,6 +131,8 @@ pub fn authorize( | ||
| 128 | 131 | fn owner_rule(trashed: bool, action: Action) -> Result<(), Denied> { |
| 129 | 132 | match (trashed, action) { |
| 130 | 133 | (_, Action::Administer) => Err(Denied::NotFound), |
| 134 | + // Taking back access never shows anything new, so it is allowed on trashed items as well. | |
| 135 | + (_, Action::Revoke) => Ok(()), | |
| 131 | 136 | (false, Action::Purge | Action::Restore) => Err(Denied::Forbidden), |
| 132 | 137 | (false, _) => Ok(()), |
| 133 | 138 | (true, Action::View | Action::Download | Action::Restore | Action::Purge) => Ok(()), |
| @@ -214,6 +219,7 @@ mod tests { | ||
| 214 | 219 | (owner(), live(), Grant::None, Download, Ok(())), |
| 215 | 220 | (owner(), live(), Grant::None, Write, Ok(())), |
| 216 | 221 | (owner(), live(), Grant::None, Share, Ok(())), |
| 222 | + (owner(), live(), Grant::None, Revoke, Ok(())), | |
| 217 | 223 | (owner(), live(), Grant::None, Purge, Err(Forbidden)), |
| 218 | 224 | (owner(), live(), Grant::None, Restore, Err(Forbidden)), |
| 219 | 225 | (owner(), live(), Grant::None, Administer, Err(NotFound)), |
| @@ -224,6 +230,7 @@ mod tests { | ||
| 224 | 230 | (owner(), trashed(), Grant::None, Purge, Ok(())), |
| 225 | 231 | (owner(), trashed(), Grant::None, Write, Err(Forbidden)), |
| 226 | 232 | (owner(), trashed(), Grant::None, Share, Err(Forbidden)), |
| 233 | + (owner(), trashed(), Grant::None, Revoke, Ok(())), | |
| 227 | 234 | (owner(), trashed(), Grant::None, List, Err(Forbidden)), |
| 228 | 235 | // Grantee with view only, live. |
| 229 | 236 | (grantee(), live(), Grant::View, List, Ok(())), |
| @@ -233,6 +240,7 @@ mod tests { | ||
| 233 | 240 | // Grantee with download. |
| 234 | 241 | (grantee(), live(), Grant::Download, Download, Ok(())), |
| 235 | 242 | (grantee(), live(), Grant::Download, Share, Err(Forbidden)), |
| 243 | + (grantee(), live(), Grant::Download, Revoke, Err(Forbidden)), | |
| 236 | 244 | // Grantee without any grant, or on a trashed item, learns nothing. |
| 237 | 245 | (grantee(), live(), Grant::None, View, Err(NotFound)), |
| 238 | 246 | (grantee(), trashed(), Grant::Download, View, Err(NotFound)), |
crates/in-core/src/secret.rsmodified+31 -0
| @@ -23,6 +23,8 @@ const NONCE_LEN: usize = 24; | ||
| 23 | 23 | const SEAL_LABEL: &[u8] = b"in seal v1"; |
| 24 | 24 | /// Label of the key of the password-unlock proof of a share link (see [`unlock_proof`]). |
| 25 | 25 | const UNLOCK_LABEL: &[u8] = b"in link unlock v1"; |
| 26 | +/// Prefix of the label of the keys that make byte validators (see [`validator`]). The purpose follows it. | |
| 27 | +const VALIDATOR_LABEL: &str = "in validator v1"; | |
| 26 | 28 | |
| 27 | 29 | /// What a sealed value is for. It is the associated data of [`seal`] and [`open`], so a value sealed under |
| 28 | 30 | /// one purpose fails authentication under any other. |
| @@ -144,6 +146,18 @@ pub fn unlock_proof(key: &[u8; 32], link_id: &str, password_hash: &str) -> Strin | ||
| 144 | 146 | hex::encode(mac.finalize().into_bytes()) |
| 145 | 147 | } |
| 146 | 148 | |
| 149 | +/// The validator (`ETag`) of stored bytes: HMAC-SHA256 of their lowercase hex SHA-256 under the validator | |
| 150 | +/// subkey of `purpose`, truncated to 128 bits and in lower-case hex. The same bytes keep the same validator, so | |
| 151 | +/// conditional requests still work. Without the instance key, nobody can tell from a known hash whether those | |
| 152 | +/// bytes are stored, which the bare hash would reveal. | |
| 153 | +pub fn validator(key: &[u8; 32], purpose: &str, digest: &str) -> String { | |
| 154 | + let subkey = derive_subkey(key, format!("{VALIDATOR_LABEL}:{purpose}").as_bytes()); | |
| 155 | + let mut mac = <Hmac<Sha256> as hmac::KeyInit>::new_from_slice(&subkey) | |
| 156 | + .expect("HMAC accepts a key of any length"); | |
| 157 | + mac.update(digest.as_bytes()); | |
| 158 | + hex::encode(&mac.finalize().into_bytes()[..16]) | |
| 159 | +} | |
| 160 | + | |
| 147 | 161 | /// A 32-byte subkey for one purpose: HMAC-SHA256 of `label` under the instance key. Different labels give |
| 148 | 162 | /// unrelated subkeys, so a key derived for one use cannot be replayed as the key of another. |
| 149 | 163 | pub fn derive_subkey(master: &[u8; 32], label: &[u8]) -> [u8; 32] { |
| @@ -237,3 +251,20 @@ mod proof_tests { | ||
| 237 | 251 | assert_ne!(base, unlock_proof(&[8u8; 32], "link-a", "$argon2id$hash")); |
| 238 | 252 | } |
| 239 | 253 | } |
| 254 | + | |
| 255 | +#[cfg(test)] | |
| 256 | +mod validator_tests { | |
| 257 | + use super::*; | |
| 258 | + | |
| 259 | + #[test] | |
| 260 | + fn a_validator_is_stable_keyed_per_purpose_and_not_the_hash() { | |
| 261 | + let key = [7u8; 32]; | |
| 262 | + let digest = "ab".repeat(32); | |
| 263 | + let base = validator(&key, "file", &digest); | |
| 264 | + assert_eq!(base.len(), 32); | |
| 265 | + assert_eq!(base, validator(&key, "file", &digest)); | |
| 266 | + assert_ne!(base, validator(&key, "thumb", &digest)); | |
| 267 | + assert_ne!(base, validator(&[8u8; 32], "file", &digest)); | |
| 268 | + assert!(!digest.starts_with(&base)); | |
| 269 | + } | |
| 270 | +} |
crates/in-core/src/store/folders.rsmodified+64 -6
| @@ -11,8 +11,8 @@ use crate::error::{Error, Result}; | ||
| 11 | 11 | use crate::names; |
| 12 | 12 | use crate::store::files::{FILE_COLS, File, map_file}; |
| 13 | 13 | use crate::store::{ |
| 14 | - MAX_POSTFIX_TRIES, Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, | |
| 15 | - new_id, | |
| 14 | + MAX_POSTFIX_TRIES, Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, | |
| 15 | + insert_err, new_id, | |
| 16 | 16 | }; |
| 17 | 17 | use crate::time::now_stamp; |
| 18 | 18 | |
| @@ -127,6 +127,25 @@ async fn chain_depth(conn: &Connection, folder: &str) -> Result<usize> { | ||
| 127 | 127 | Ok(depth) |
| 128 | 128 | } |
| 129 | 129 | |
| 130 | +/// How many levels lie below `folder`: 0 for a folder with no subfolders. Every descendant counts, trashed | |
| 131 | +/// ones too, since a restore brings them back under their parent. The walk stops at [`MAX_DEPTH`] levels, | |
| 132 | +/// so a corrupt cycle in the rows ends it. | |
| 133 | +async fn subtree_height(conn: &Connection, folder: &str) -> Result<usize> { | |
| 134 | + let height = fetch_opt( | |
| 135 | + conn, | |
| 136 | + "WITH RECURSIVE sub(id, level) AS ( \ | |
| 137 | + SELECT id, 0 FROM folders WHERE id = ?1 \ | |
| 138 | + UNION ALL \ | |
| 139 | + SELECT f.id, s.level + 1 FROM folders f JOIN sub s ON f.parent_id = s.id WHERE s.level < ?2 \ | |
| 140 | + ) SELECT COALESCE(MAX(level), 0) FROM sub", | |
| 141 | + (folder.to_string(), MAX_DEPTH as i64), | |
| 142 | + |row| col_int(row, 0), | |
| 143 | + ) | |
| 144 | + .await? | |
| 145 | + .unwrap_or(0); | |
| 146 | + Ok(usize::try_from(height).unwrap_or(0)) | |
| 147 | +} | |
| 148 | + | |
| 130 | 149 | /// Inserts a folder with the first free postfix. The partial unique index decides each attempt. |
| 131 | 150 | async fn insert_folder_postfixed( |
| 132 | 151 | conn: &Connection, |
| @@ -230,10 +249,6 @@ impl Store { | ||
| 230 | 249 | live_folder(&tx, owner, id).await?; |
| 231 | 250 | if let Some(p) = parent { |
| 232 | 251 | live_folder(&tx, owner, p).await?; |
| 233 | - // The moved folder sits one level below `p`, so `p`'s chain must leave room for it. | |
| 234 | - if chain_depth(&tx, p).await? >= MAX_DEPTH { | |
| 235 | - return Err(Error::Invalid("folder_too_deep".into())); | |
| 236 | - } | |
| 237 | 252 | let mut cur = Some(p.to_string()); |
| 238 | 253 | while let Some(c) = cur { |
| 239 | 254 | if c == id { |
| @@ -241,6 +256,11 @@ impl Store { | ||
| 241 | 256 | } |
| 242 | 257 | cur = folder_by_id(&tx, &c).await?.and_then(|f| f.parent_id); |
| 243 | 258 | } |
| 259 | + // The moved folder and its subtree sit below `p`: the deepest of them must stay within the limit. | |
| 260 | + let depth = chain_depth(&tx, p).await?; | |
| 261 | + if depth + 1 + subtree_height(&tx, id).await? > MAX_DEPTH { | |
| 262 | + return Err(Error::Invalid("folder_too_deep".into())); | |
| 263 | + } | |
| 244 | 264 | } |
| 245 | 265 | tx.execute( |
| 246 | 266 | "UPDATE folders SET parent_id = ?3, updated_at = ?4 \ |
| @@ -383,4 +403,42 @@ mod tests { | ||
| 383 | 403 | Err(Error::NotFound) |
| 384 | 404 | )); |
| 385 | 405 | } |
| 406 | + | |
| 407 | + /// A move counts the height of the moved subtree: a folder with a subfolder cannot land where its | |
| 408 | + /// subtree would end past the limit, but its leaf can land exactly on it. | |
| 409 | + #[tokio::test] | |
| 410 | + async fn a_move_counts_the_height_of_the_moved_subtree() { | |
| 411 | + let (_dir, store) = store_with_member("ann").await; | |
| 412 | + // A chain of MAX_DEPTH - 1 folders built with raw inserts, so the deepest one sits at MAX_DEPTH - 1. | |
| 413 | + let mut parent: Option<String> = None; | |
| 414 | + let mut deepest = String::new(); | |
| 415 | + { | |
| 416 | + let conn = store.inner.conn.lock().await; | |
| 417 | + for n in 0..MAX_DEPTH - 1 { | |
| 418 | + let id = new_id(); | |
| 419 | + conn.execute( | |
| 420 | + "INSERT INTO folders (id, owner, parent_id, name, created_at, updated_at) \ | |
| 421 | + VALUES (?1, 'ann', ?2, ?3, ?4, ?4)", | |
| 422 | + (id.clone(), parent.clone(), format!("d{n}"), now_stamp()), | |
| 423 | + ) | |
| 424 | + .await | |
| 425 | + .unwrap(); | |
| 426 | + parent = Some(id.clone()); | |
| 427 | + deepest = id; | |
| 428 | + } | |
| 429 | + } | |
| 430 | + let root = store.create_folder("ann", None, "Moved").await.unwrap(); | |
| 431 | + let child = store | |
| 432 | + .create_folder("ann", Some(&root.id), "Inner") | |
| 433 | + .await | |
| 434 | + .unwrap(); | |
| 435 | + assert!(matches!( | |
| 436 | + store.move_folder("ann", &root.id, Some(&deepest)).await, | |
| 437 | + Err(Error::Invalid(reason)) if reason == "folder_too_deep" | |
| 438 | + )); | |
| 439 | + store | |
| 440 | + .move_folder("ann", &child.id, Some(&deepest)) | |
| 441 | + .await | |
| 442 | + .expect("a leaf fits exactly at the limit"); | |
| 443 | + } | |
| 386 | 444 | } |
crates/in-web/src/api/objects.rsmodified+3 -1
| @@ -355,7 +355,9 @@ async fn get_object(cx: &Cx) -> Result<Response> { | ||
| 355 | 355 | let source = ByteSource { |
| 356 | 356 | blob_key: &object.blob_key, |
| 357 | 357 | size: object.size as u64, |
| 358 | - sha256: &object.sha256, | |
| 358 | + // The object API's validator is the content's SHA-256 (contracts.md 5). The caller holds the | |
| 359 | + // object's bytes already, so the hash reveals nothing new to it. | |
| 360 | + validator: &object.sha256, | |
| 359 | 361 | content_sha256: Some(&object.sha256), |
| 360 | 362 | mime: &object.content_type, |
| 361 | 363 | name: &name, |
crates/in-web/src/pages/files.rsmodified+6 -3
| @@ -33,7 +33,9 @@ use crate::pages::drive::{ | ||
| 33 | 33 | DRIVE_HOME, ItemForm, access_for, back_or, changed, check, done, optional_folder, pick_body, |
| 34 | 34 | refusal_word, refused, tree_rows, viewer_lang, with_param, |
| 35 | 35 | }; |
| 36 | -use crate::serve_bytes::{ByteAnswer, ByteSource, Disposition, counts_as_download, serve_bytes}; | |
| 36 | +use crate::serve_bytes::{ | |
| 37 | + ByteAnswer, ByteSource, Disposition, counts_as_download, file_validator, serve_bytes, | |
| 38 | +}; | |
| 37 | 39 | use crate::state::AppState; |
| 38 | 40 | use crate::views::{ViewerInfo, shell}; |
| 39 | 41 | |
| @@ -265,13 +267,14 @@ async fn file_bytes(cx: &Cx) -> Result<ByteAnswer> { | ||
| 265 | 267 | }; |
| 266 | 268 | let file = file_for(state, &viewer, &id, action).await?; |
| 267 | 269 | let size = u64::try_from(file.size).unwrap_or(0); |
| 268 | - if download && counts_as_download(headers(cx), &file.sha256, size) { | |
| 270 | + let validator = file_validator(&state.key, &file.sha256); | |
| 271 | + if download && counts_as_download(headers(cx), &validator, size) { | |
| 269 | 272 | state.store.record_download(&file.id).await?; |
| 270 | 273 | } |
| 271 | 274 | let source = ByteSource { |
| 272 | 275 | blob_key: &file.blob_key, |
| 273 | 276 | size, |
| 274 | - sha256: &file.sha256, | |
| 277 | + validator: &validator, | |
| 275 | 278 | content_sha256: Some(&file.sha256), |
| 276 | 279 | mime: &file.mime, |
| 277 | 280 | name: &file.name, |
crates/in-web/src/pages/public_share.rsmodified+7 -5
| @@ -43,7 +43,8 @@ use crate::i18n::drive::{DK, d}; | ||
| 43 | 43 | use crate::i18n::share::{SK, s as share_s}; |
| 44 | 44 | use crate::pages::thumbs::thumb_validator; |
| 45 | 45 | use crate::serve_bytes::{ |
| 46 | - ByteAnswer, ByteSource, Disposition, SHARE_CACHE, counts_as_download, serve_bytes_with, | |
| 46 | + ByteAnswer, ByteSource, Disposition, SHARE_CACHE, counts_as_download, file_validator, | |
| 47 | + serve_bytes_with, | |
| 47 | 48 | }; |
| 48 | 49 | use crate::state::AppState; |
| 49 | 50 | use crate::views::drive::size_text; |
| @@ -526,13 +527,14 @@ async fn public_file_bytes(cx: &Cx) -> Result<ByteAnswer> { | ||
| 526 | 527 | visit(state, &link, ItemKind::File, &id, action).await?; |
| 527 | 528 | let file = state.store.file(&id).await?.ok_or_else(not_found)?; |
| 528 | 529 | let size = u64::try_from(file.size).unwrap_or(0); |
| 529 | - if download && counts_as_download(headers(cx), &file.sha256, size) { | |
| 530 | + let validator = file_validator(&state.key, &file.sha256); | |
| 531 | + if download && counts_as_download(headers(cx), &validator, size) { | |
| 530 | 532 | state.store.record_download(&file.id).await?; |
| 531 | 533 | } |
| 532 | 534 | let source = ByteSource { |
| 533 | 535 | blob_key: &file.blob_key, |
| 534 | 536 | size, |
| 535 | - sha256: &file.sha256, | |
| 537 | + validator: &validator, | |
| 536 | 538 | content_sha256: Some(&file.sha256), |
| 537 | 539 | mime: &file.mime, |
| 538 | 540 | name: &file.name, |
| @@ -562,11 +564,11 @@ async fn public_thumb(cx: &Cx) -> Result<ByteAnswer> { | ||
| 562 | 564 | let size = state.blobs.size(&key).await?.ok_or_else(not_found)?; |
| 563 | 565 | // The row holds no hash of the thumbnail bytes, only the validator derived from the file's hash, so |
| 564 | 566 | // the thumbnail body is not checked. |
| 565 | - let validator = thumb_validator(&file.sha256); | |
| 567 | + let validator = thumb_validator(&state.key, &file.sha256); | |
| 566 | 568 | let source = ByteSource { |
| 567 | 569 | blob_key: &key, |
| 568 | 570 | size, |
| 569 | - sha256: &validator, | |
| 571 | + validator: &validator, | |
| 570 | 572 | content_sha256: None, |
| 571 | 573 | mime: "image/webp", |
| 572 | 574 | name: &file.name, |
crates/in-web/src/pages/share_dialog.rsmodified+33 -11
| @@ -2,9 +2,11 @@ | ||
| 2 | 2 | //! writes of its grants: `POST /grants` (a new grant, or the level of an existing one), `POST |
| 3 | 3 | //! /grants/{id}/update` and `POST /grants/{id}/remove`. The page also makes the item's share links. |
| 4 | 4 | //! |
| 5 | -//! Only the owner of a live item may share it (`authz` `Share`). A grantee is `403` on it, and anyone else | |
| 6 | -//! is `404`. The grantee of a grant is chosen from the family's members, active ones other than the owner | |
| 7 | -//! only, and the store checks that again. Each change tells the grantee's open shared page. | |
| 5 | +//! Only the owner of a live item may share it (`authz` `Share`). The owner of a trashed item may still see | |
| 6 | +//! its grants and change or remove them (`Revoke`), so access taken back does not return on restore; the | |
| 7 | +//! page then offers no new grant and no new link. A grantee is `403` on the page, and anyone else is `404`. | |
| 8 | +//! The grantee of a grant is chosen from the family's members, active ones other than the owner only, and | |
| 9 | +//! the store checks that again. Each change tells the grantee's open shared page. | |
| 8 | 10 | |
| 9 | 11 | use in_core::authz::Action; |
| 10 | 12 | use in_core::store::members::Member; |
| @@ -74,6 +76,21 @@ pub async fn shareable( | ||
| 74 | 76 | Ok(name) |
| 75 | 77 | } |
| 76 | 78 | |
| 79 | +/// The name and trash state of an item whose grants the viewer may change or remove: the owner's, live or | |
| 80 | +/// trashed. A grantee is refused with `403` and anyone else sees `404`. | |
| 81 | +pub async fn revocable( | |
| 82 | + state: &AppState, | |
| 83 | + viewer: &Viewer, | |
| 84 | + kind: ItemKind, | |
| 85 | + id: &str, | |
| 86 | +) -> Result<(String, bool)> { | |
| 87 | + let (owner, name) = item_head(state, kind, id).await?; | |
| 88 | + let access = access_for(state, viewer, kind, id).await?; | |
| 89 | + let trashed = access.trashed; | |
| 90 | + check(viewer, &owner, access, Action::Revoke)?; | |
| 91 | + Ok((name, trashed)) | |
| 92 | +} | |
| 93 | + | |
| 77 | 94 | /// Tells the grantee's open shared page that its list changed. |
| 78 | 95 | fn notify(state: &AppState, grantee: &str) { |
| 79 | 96 | state.live.bump(&Topic::Shared(grantee.to_owned())); |
| @@ -148,6 +165,7 @@ pub async fn share_body( | ||
| 148 | 165 | back: &str, |
| 149 | 166 | item_page: &str, |
| 150 | 167 | max_days: u32, |
| 168 | + trashed: bool, | |
| 151 | 169 | notice: &str, |
| 152 | 170 | refusal: &str, |
| 153 | 171 | ) -> Result<impl View> { |
| @@ -167,7 +185,7 @@ pub async fn share_body( | ||
| 167 | 185 | } |
| 168 | 186 | </ul> |
| 169 | 187 | } |
| 170 | - if !people.is_empty() { | |
| 188 | + if !trashed && !people.is_empty() { | |
| 171 | 189 | <form method="post" action="/grants" class="share-form"> |
| 172 | 190 | <input type="hidden" name="csrf" value=(csrf)> |
| 173 | 191 | <input type="hidden" name="back" value=(back)> |
| @@ -185,6 +203,7 @@ pub async fn share_body( | ||
| 185 | 203 | </form> |
| 186 | 204 | } |
| 187 | 205 | <p class="muted">(share_s(lang, SK::ShareOwnerOnly))</p> |
| 206 | + if !trashed { | |
| 188 | 207 | <h2>(share_s(lang, SK::ShareLinks))</h2> |
| 189 | 208 | <form method="post" action="/links" class="share-form"> |
| 190 | 209 | <input type="hidden" name="csrf" value=(csrf)> |
| @@ -207,11 +226,12 @@ pub async fn share_body( | ||
| 207 | 226 | } |
| 208 | 227 | </ul> |
| 209 | 228 | } |
| 229 | + } | |
| 210 | 230 | </section> |
| 211 | 231 | }) |
| 212 | 232 | } |
| 213 | 233 | |
| 214 | -/// `GET /share/{kind}/{id}`: the share page of an item the viewer owns. | |
| 234 | +/// `GET /share/{kind}/{id}`: the share page of an item the viewer owns, live or trashed. | |
| 215 | 235 | #[page("/share/{kind}/{id}")] |
| 216 | 236 | async fn share_page(cx: &Cx) -> Result<impl View> { |
| 217 | 237 | let state = app_context::<AppState>(cx); |
| @@ -219,7 +239,7 @@ async fn share_page(cx: &Cx) -> Result<impl View> { | ||
| 219 | 239 | let lang = viewer_lang(cx, &viewer); |
| 220 | 240 | let kind = kind_from_word(path_param_segment(cx, "kind")).ok_or_else(not_found)?; |
| 221 | 241 | let id = path_param_segment(cx, "id").to_owned(); |
| 222 | - let name = shareable(state, &viewer, kind, &id).await?; | |
| 242 | + let (name, trashed) = revocable(state, &viewer, kind, &id).await?; | |
| 223 | 243 | let me = viewer.member.sub.clone(); |
| 224 | 244 | let entries = state.store.shares_of(&me, kind, &id).await?; |
| 225 | 245 | let people: Vec<Member> = state |
| @@ -251,7 +271,7 @@ async fn share_page(cx: &Cx) -> Result<impl View> { | ||
| 251 | 271 | share_body(lang: lang, name: name.as_str(), kind: kind_word(kind), id: id.as_str(), |
| 252 | 272 | entries: &entries, people: &people, links: &links, csrf: csrf.as_str(), |
| 253 | 273 | back: back.as_str(), item_page: item_page.as_str(), max_days: max_days, |
| 254 | - notice: query.notice.as_str(), refusal: query.refusal.as_str()) | |
| 274 | + trashed: trashed, notice: query.notice.as_str(), refusal: query.refusal.as_str()) | |
| 255 | 275 | ) |
| 256 | 276 | }) |
| 257 | 277 | } |
| @@ -295,7 +315,8 @@ async fn owned_share(state: &AppState, viewer: &Viewer, id: &str) -> Result<Shar | ||
| 295 | 315 | .ok_or_else(not_found)?) |
| 296 | 316 | } |
| 297 | 317 | |
| 298 | -/// `POST /grants/{id}/update`: changes a grant's level between view only and download. | |
| 318 | +/// `POST /grants/{id}/update`: changes a grant's level between view only and download. Allowed on trashed | |
| 319 | +/// items too, since the grant already exists. | |
| 299 | 320 | #[route(POST "/grants/{id}/update")] |
| 300 | 321 | async fn update_grant(cx: &Cx, Form(form): Form<GrantForm>) -> Result<SeeOther> { |
| 301 | 322 | let state = app_context::<AppState>(cx); |
| @@ -304,7 +325,7 @@ async fn update_grant(cx: &Cx, Form(form): Form<GrantForm>) -> Result<SeeOther> | ||
| 304 | 325 | let share = owned_share(state, &viewer, &id).await?; |
| 305 | 326 | let default_back = format!("/share/{}/{}", kind_word(share.kind), share.target_id); |
| 306 | 327 | let back = back_or(&form.back, &default_back); |
| 307 | - shareable(state, &viewer, share.kind, &share.target_id).await?; | |
| 328 | + revocable(state, &viewer, share.kind, &share.target_id).await?; | |
| 308 | 329 | match state |
| 309 | 330 | .store |
| 310 | 331 | .set_share_level(&viewer.member.sub, &id, form.level == "download") |
| @@ -319,7 +340,8 @@ async fn update_grant(cx: &Cx, Form(form): Form<GrantForm>) -> Result<SeeOther> | ||
| 319 | 340 | } |
| 320 | 341 | |
| 321 | 342 | /// `POST /grants/{id}/remove`: ends a grant. The grantee loses the item at once, and so does everything |
| 322 | -/// below it that they reached through this grant. | |
| 343 | +/// below it that they reached through this grant. Allowed on trashed items too, so the access stays gone | |
| 344 | +/// when the item is restored. | |
| 323 | 345 | #[route(POST "/grants/{id}/remove")] |
| 324 | 346 | async fn remove_grant(cx: &Cx, Form(form): Form<GrantForm>) -> Result<SeeOther> { |
| 325 | 347 | let state = app_context::<AppState>(cx); |
| @@ -328,7 +350,7 @@ async fn remove_grant(cx: &Cx, Form(form): Form<GrantForm>) -> Result<SeeOther> | ||
| 328 | 350 | let share = owned_share(state, &viewer, &id).await?; |
| 329 | 351 | let default_back = format!("/share/{}/{}", kind_word(share.kind), share.target_id); |
| 330 | 352 | let back = back_or(&form.back, &default_back); |
| 331 | - shareable(state, &viewer, share.kind, &share.target_id).await?; | |
| 353 | + revocable(state, &viewer, share.kind, &share.target_id).await?; | |
| 332 | 354 | match state.store.remove_share(&viewer.member.sub, &id).await { |
| 333 | 355 | Ok(removed) => { |
| 334 | 356 | notify(state, &removed.grantee); |
crates/in-web/src/pages/thumbs.rsmodified+6 -10
| @@ -6,7 +6,6 @@ | ||
| 6 | 6 | |
| 7 | 7 | use in_core::authz::Action; |
| 8 | 8 | use in_core::store::files::thumb_blob_key; |
| 9 | -use sha2::{Digest, Sha256}; | |
| 10 | 9 | use topcoat::Result; |
| 11 | 10 | use topcoat::context::{Cx, app_context}; |
| 12 | 11 | use topcoat::router::error::not_found; |
| @@ -17,13 +16,10 @@ use crate::pages::files::file_for; | ||
| 17 | 16 | use crate::serve_bytes::{ByteAnswer, ByteSource, Disposition, serve_bytes}; |
| 18 | 17 | use crate::state::AppState; |
| 19 | 18 | |
| 20 | -/// The validator of a thumbnail: the SHA-256 of a fixed label and the file's own digest. It differs from the | |
| 21 | -/// file's ETag, because the thumbnail is other bytes, and it changes only when the file's bytes change. | |
| 22 | -pub fn thumb_validator(file_sha256: &str) -> String { | |
| 23 | - Sha256::digest(format!("thumb:{file_sha256}")) | |
| 24 | - .iter() | |
| 25 | - .map(|b| format!("{b:02x}")) | |
| 26 | - .collect() | |
| 19 | +/// The validator of a thumbnail: keyed under its own purpose, so it differs from the file's ETag, because the | |
| 20 | +/// thumbnail is other bytes. It changes only when the file's bytes change, and it does not reveal their hash. | |
| 21 | +pub fn thumb_validator(key: &[u8; 32], file_sha256: &str) -> String { | |
| 22 | + in_core::secret::validator(key, "thumb", file_sha256) | |
| 27 | 23 | } |
| 28 | 24 | |
| 29 | 25 | /// `GET /thumb/{id}`: the WebP thumbnail of a picture. |
| @@ -38,13 +34,13 @@ async fn thumb(cx: &Cx) -> Result<ByteAnswer> { | ||
| 38 | 34 | } |
| 39 | 35 | let key = thumb_blob_key(&file.id); |
| 40 | 36 | let size = state.blobs.size(&key).await?.ok_or_else(not_found)?; |
| 41 | - let validator = thumb_validator(&file.sha256); | |
| 37 | + let validator = thumb_validator(&state.key, &file.sha256); | |
| 42 | 38 | // The row holds no hash of the thumbnail bytes, only the validator derived from the file's hash, so |
| 43 | 39 | // the thumbnail body is not checked. |
| 44 | 40 | let source = ByteSource { |
| 45 | 41 | blob_key: &key, |
| 46 | 42 | size, |
| 47 | - sha256: &validator, | |
| 43 | + validator: &validator, | |
| 48 | 44 | content_sha256: None, |
| 49 | 45 | mime: "image/webp", |
| 50 | 46 | name: &file.name, |
crates/in-web/src/serve_bytes.rsmodified+16 -7
| @@ -49,11 +49,12 @@ pub struct ByteSource<'a> { | ||
| 49 | 49 | pub blob_key: &'a str, |
| 50 | 50 | /// Length of the bytes in bytes. |
| 51 | 51 | pub size: u64, |
| 52 | - /// Lowercase hex SHA-256 of the bytes. It is the strong validator, so equal hashes mean equal bytes. | |
| 53 | - pub sha256: &'a str, | |
| 52 | + /// The validator of the bytes, unquoted; the `ETag` is its quoted form. Equal validators mean equal bytes. | |
| 53 | + /// For a stored file it is [`file_validator`], which does not reveal the file's hash. | |
| 54 | + pub validator: &'a str, | |
| 54 | 55 | /// The SHA-256 the bytes must hash to, when the bytes are the row's own content. A full-body answer |
| 55 | 56 | /// is checked against it while it streams (see [`check_digest`]). `None` for derived bytes such as |
| 56 | - /// thumbnails, whose `sha256` is a validator and not the hash of what is stored. | |
| 57 | + /// thumbnails, whose validator is not the hash of what is stored. | |
| 57 | 58 | pub content_sha256: Option<&'a str>, |
| 58 | 59 | /// The sniffed MIME type, as stored. It is never the uploader's claim. |
| 59 | 60 | pub mime: &'a str, |
| @@ -164,6 +165,13 @@ fn digits(text: &str) -> Option<u64> { | ||
| 164 | 165 | Some(text.parse().unwrap_or(u64::MAX)) |
| 165 | 166 | } |
| 166 | 167 | |
| 168 | +/// The validator of a stored file's bytes. It is keyed (see [`in_core::secret::validator`]), so a viewer of | |
| 169 | +/// the bytes learns nothing about the file's SHA-256 from the `ETag`, and cannot tell whether a file they know | |
| 170 | +/// is stored in the drive. | |
| 171 | +pub fn file_validator(key: &[u8; 32], sha256: &str) -> String { | |
| 172 | + in_core::secret::validator(key, "file", sha256) | |
| 173 | +} | |
| 174 | + | |
| 167 | 175 | /// Whether a conditional request `If-None-Match` names `etag`. Weak tags compare equal to their strong |
| 168 | 176 | /// form here, which is the rule for `GET` validators (RFC 9110). |
| 169 | 177 | fn none_match_hits(request: &HeaderMap, etag: &str) -> bool { |
| @@ -199,9 +207,10 @@ fn requested_range(request: &HeaderMap, etag: &str, len: u64) -> Ranged { | ||
| 199 | 207 | |
| 200 | 208 | /// Whether serving this request counts as a download that started at byte 0. A `304`, a range that |
| 201 | 209 | /// starts later, and an unsatisfiable range do not count; a whole file, or a range from byte 0, does. |
| 202 | -/// The download counter is bumped by the caller before it serves the body. | |
| 203 | -pub fn counts_as_download(request: &HeaderMap, sha256: &str, size: u64) -> bool { | |
| 204 | - let etag = format!("\"{sha256}\""); | |
| 210 | +/// The download counter is bumped by the caller before it serves the body. `validator` is the bytes' | |
| 211 | +/// validator, as sent in [`ByteSource::validator`]. | |
| 212 | +pub fn counts_as_download(request: &HeaderMap, validator: &str, size: u64) -> bool { | |
| 213 | + let etag = format!("\"{validator}\""); | |
| 205 | 214 | if none_match_hits(request, &etag) { |
| 206 | 215 | return false; |
| 207 | 216 | } |
| @@ -346,7 +355,7 @@ pub async fn serve_bytes_with( | ||
| 346 | 355 | cache: &str, |
| 347 | 356 | ) -> Result<ByteAnswer> { |
| 348 | 357 | let request = headers(cx); |
| 349 | - let etag = format!("\"{}\"", source.sha256); | |
| 358 | + let etag = format!("\"{}\"", source.validator); | |
| 350 | 359 | let disposition = match disposition { |
| 351 | 360 | Disposition::Inline if inline_safe(source.mime) => Disposition::Inline, |
| 352 | 361 | _ => Disposition::Attachment, |
docs/architecture.mdmodified+9 -3
| @@ -177,8 +177,10 @@ and has no sessions. | ||
| 177 | 177 | - `target`: a file or folder with owner and trashed state, plus the effective grant (the most permissive grant |
| 178 | 178 | on the item or any live ancestor folder) and, for links, whether the item is inside the linked folder. |
| 179 | 179 | - `action`: `List`, `View` (see name, preview inline), `Download`, `Write` (rename, move, upload into, trash), |
| 180 | - `Share`, `Purge`, `Administer`. | |
| 181 | -- Rules: owner may do everything on their items (trashed items: only `View`, `Download`, restore, `Purge`); | |
| 180 | + `Restore`, `Share` (a new grant or link), `Revoke` (change the level of an existing grant, or remove it), | |
| 181 | + `Purge`, `Administer`. | |
| 182 | +- Rules: owner may do everything on their items (trashed items: only `View`, `Download`, restore, `Purge`, | |
| 183 | + and `Revoke`, so access taken back stays gone after a restore; no new grant or link on a trashed item); | |
| 182 | 184 | grantee: `List` and `View`, `Download` when `can_download`, never on trashed items; link visitor: the same as |
| 183 | 185 | a grantee within the link's subtree; admin: `Administer` only (an admin does **not** read other people's |
| 184 | 186 | files); anything else is `NotFound`. |
| @@ -187,7 +189,11 @@ and has no sessions. | ||
| 187 | 189 | |
| 188 | 190 | ## 7. Byte serving (one function for every byte route) |
| 189 | 191 | |
| 190 | -- Single `Range` (`a-b`, `a-`, `-n`), 206 / 416; `ETag` = `"<sha256>"`; `If-None-Match` → 304. Per RFC 7233 | |
| 192 | +- Single `Range` (`a-b`, `a-`, `-n`), 206 / 416; `ETag` = `"<validator>"`, where the validator of a stored file is | |
| 193 | + `secret::validator` (HMAC-SHA256 of the SHA-256 under a subkey of the instance key, `file` purpose, 128 bits | |
| 194 | + in hex; thumbnails use the `thumb` purpose). The same bytes keep it, but a viewer cannot learn the hash or | |
| 195 | + test whether a known file is stored. Object API answers keep `"<sha256>"` (contracts.md 5). `If-None-Match` → | |
| 196 | + 304, and `If-Range` compares against the same validator. Per RFC 7233 | |
| 191 | 197 | 3.1 a `Range` that is malformed, reversed, or in another unit is ignored (200, whole file); only a valid range |
| 192 | 198 | the file cannot satisfy gets 416 with `Content-Range: bytes */<len>`. Several ranges get 200, whole file. |
| 193 | 199 | - `Content-Disposition`: `inline` only for image/* (not SVG, not HEIC), video/*, audio/*, application/pdf, |