From f70fcdd2072ebce5f59de19ce0be9588c456788b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 18:33:21 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=92=20owners=20revoke=20grants=20on=20?= =?UTF-8?q?trashed=20items;=20folder=20moves=20count=20the=20subtree=20hei?= =?UTF-8?q?ght;=20keyed=20ETags?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/in-core/src/authz.rs | 12 ++++- crates/in-core/src/secret.rs | 31 +++++++++++ crates/in-core/src/store/folders.rs | 70 ++++++++++++++++++++++--- crates/in-web/src/api/objects.rs | 4 +- crates/in-web/src/pages/files.rs | 9 ++-- crates/in-web/src/pages/public_share.rs | 12 +++-- crates/in-web/src/pages/share_dialog.rs | 44 ++++++++++++---- crates/in-web/src/pages/thumbs.rs | 16 +++--- crates/in-web/src/serve_bytes.rs | 23 +++++--- docs/architecture.md | 12 +++-- 10 files changed, 185 insertions(+), 48 deletions(-) diff --git a/crates/in-core/src/authz.rs b/crates/in-core/src/authz.rs index 22953b9..65d159a 100644 --- a/crates/in-core/src/authz.rs +++ b/crates/in-core/src/authz.rs @@ -5,7 +5,8 @@ //! Rules (architecture section 6): //! - Anonymous and service callers never reach drive items. //! - The owner may do everything on live items except `Purge` and `Restore`, which apply to trashed -//! items only. On trashed items the owner may only view, download, restore and purge. +//! items only. On trashed items the owner may only view, download, restore, purge, and change or +//! remove a grant that already exists (`Revoke`). A new grant or link on a trashed item is refused. //! - An admin may `Administer` any item but reads nobody else's files. //! - A grantee sees a live item with a grant, lists and views it, and downloads it only with a //! download grant. Nothing else. @@ -71,8 +72,10 @@ pub enum Action { Write, /// Restore a trashed item to its place. Restore, - /// Change who can see the item (grants and links). + /// Create a grant or a link: change who can see the item. Share, + /// Change the level of an existing grant, or remove it. + Revoke, /// Permanently delete a trashed item. Purge, /// Administer the instance. @@ -128,6 +131,8 @@ pub fn authorize( fn owner_rule(trashed: bool, action: Action) -> Result<(), Denied> { match (trashed, action) { (_, Action::Administer) => Err(Denied::NotFound), + // Taking back access never shows anything new, so it is allowed on trashed items as well. + (_, Action::Revoke) => Ok(()), (false, Action::Purge | Action::Restore) => Err(Denied::Forbidden), (false, _) => Ok(()), (true, Action::View | Action::Download | Action::Restore | Action::Purge) => Ok(()), @@ -214,6 +219,7 @@ mod tests { (owner(), live(), Grant::None, Download, Ok(())), (owner(), live(), Grant::None, Write, Ok(())), (owner(), live(), Grant::None, Share, Ok(())), + (owner(), live(), Grant::None, Revoke, Ok(())), (owner(), live(), Grant::None, Purge, Err(Forbidden)), (owner(), live(), Grant::None, Restore, Err(Forbidden)), (owner(), live(), Grant::None, Administer, Err(NotFound)), @@ -224,6 +230,7 @@ mod tests { (owner(), trashed(), Grant::None, Purge, Ok(())), (owner(), trashed(), Grant::None, Write, Err(Forbidden)), (owner(), trashed(), Grant::None, Share, Err(Forbidden)), + (owner(), trashed(), Grant::None, Revoke, Ok(())), (owner(), trashed(), Grant::None, List, Err(Forbidden)), // Grantee with view only, live. (grantee(), live(), Grant::View, List, Ok(())), @@ -233,6 +240,7 @@ mod tests { // Grantee with download. (grantee(), live(), Grant::Download, Download, Ok(())), (grantee(), live(), Grant::Download, Share, Err(Forbidden)), + (grantee(), live(), Grant::Download, Revoke, Err(Forbidden)), // Grantee without any grant, or on a trashed item, learns nothing. (grantee(), live(), Grant::None, View, Err(NotFound)), (grantee(), trashed(), Grant::Download, View, Err(NotFound)), diff --git a/crates/in-core/src/secret.rs b/crates/in-core/src/secret.rs index 89fb518..bc06361 100644 --- a/crates/in-core/src/secret.rs +++ b/crates/in-core/src/secret.rs @@ -23,6 +23,8 @@ const NONCE_LEN: usize = 24; const SEAL_LABEL: &[u8] = b"in seal v1"; /// Label of the key of the password-unlock proof of a share link (see [`unlock_proof`]). const UNLOCK_LABEL: &[u8] = b"in link unlock v1"; +/// Prefix of the label of the keys that make byte validators (see [`validator`]). The purpose follows it. +const VALIDATOR_LABEL: &str = "in validator v1"; /// What a sealed value is for. It is the associated data of [`seal`] and [`open`], so a value sealed under /// 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 hex::encode(mac.finalize().into_bytes()) } +/// The validator (`ETag`) of stored bytes: HMAC-SHA256 of their lowercase hex SHA-256 under the validator +/// subkey of `purpose`, truncated to 128 bits and in lower-case hex. The same bytes keep the same validator, so +/// conditional requests still work. Without the instance key, nobody can tell from a known hash whether those +/// bytes are stored, which the bare hash would reveal. +pub fn validator(key: &[u8; 32], purpose: &str, digest: &str) -> String { + let subkey = derive_subkey(key, format!("{VALIDATOR_LABEL}:{purpose}").as_bytes()); + let mut mac = as hmac::KeyInit>::new_from_slice(&subkey) + .expect("HMAC accepts a key of any length"); + mac.update(digest.as_bytes()); + hex::encode(&mac.finalize().into_bytes()[..16]) +} + /// A 32-byte subkey for one purpose: HMAC-SHA256 of `label` under the instance key. Different labels give /// unrelated subkeys, so a key derived for one use cannot be replayed as the key of another. pub fn derive_subkey(master: &[u8; 32], label: &[u8]) -> [u8; 32] { @@ -237,3 +251,20 @@ mod proof_tests { assert_ne!(base, unlock_proof(&[8u8; 32], "link-a", "$argon2id$hash")); } } + +#[cfg(test)] +mod validator_tests { + use super::*; + + #[test] + fn a_validator_is_stable_keyed_per_purpose_and_not_the_hash() { + let key = [7u8; 32]; + let digest = "ab".repeat(32); + let base = validator(&key, "file", &digest); + assert_eq!(base.len(), 32); + assert_eq!(base, validator(&key, "file", &digest)); + assert_ne!(base, validator(&key, "thumb", &digest)); + assert_ne!(base, validator(&[8u8; 32], "file", &digest)); + assert!(!digest.starts_with(&base)); + } +} diff --git a/crates/in-core/src/store/folders.rs b/crates/in-core/src/store/folders.rs index 53daddf..a89d3fa 100644 --- a/crates/in-core/src/store/folders.rs +++ b/crates/in-core/src/store/folders.rs @@ -11,8 +11,8 @@ use crate::error::{Error, Result}; use crate::names; use crate::store::files::{FILE_COLS, File, map_file}; use crate::store::{ - MAX_POSTFIX_TRIES, Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, - new_id, + MAX_POSTFIX_TRIES, Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, + insert_err, new_id, }; use crate::time::now_stamp; @@ -127,6 +127,25 @@ async fn chain_depth(conn: &Connection, folder: &str) -> Result { Ok(depth) } +/// How many levels lie below `folder`: 0 for a folder with no subfolders. Every descendant counts, trashed +/// ones too, since a restore brings them back under their parent. The walk stops at [`MAX_DEPTH`] levels, +/// so a corrupt cycle in the rows ends it. +async fn subtree_height(conn: &Connection, folder: &str) -> Result { + let height = fetch_opt( + conn, + "WITH RECURSIVE sub(id, level) AS ( \ + SELECT id, 0 FROM folders WHERE id = ?1 \ + UNION ALL \ + SELECT f.id, s.level + 1 FROM folders f JOIN sub s ON f.parent_id = s.id WHERE s.level < ?2 \ + ) SELECT COALESCE(MAX(level), 0) FROM sub", + (folder.to_string(), MAX_DEPTH as i64), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + Ok(usize::try_from(height).unwrap_or(0)) +} + /// Inserts a folder with the first free postfix. The partial unique index decides each attempt. async fn insert_folder_postfixed( conn: &Connection, @@ -230,10 +249,6 @@ impl Store { live_folder(&tx, owner, id).await?; if let Some(p) = parent { live_folder(&tx, owner, p).await?; - // The moved folder sits one level below `p`, so `p`'s chain must leave room for it. - if chain_depth(&tx, p).await? >= MAX_DEPTH { - return Err(Error::Invalid("folder_too_deep".into())); - } let mut cur = Some(p.to_string()); while let Some(c) = cur { if c == id { @@ -241,6 +256,11 @@ impl Store { } cur = folder_by_id(&tx, &c).await?.and_then(|f| f.parent_id); } + // The moved folder and its subtree sit below `p`: the deepest of them must stay within the limit. + let depth = chain_depth(&tx, p).await?; + if depth + 1 + subtree_height(&tx, id).await? > MAX_DEPTH { + return Err(Error::Invalid("folder_too_deep".into())); + } } tx.execute( "UPDATE folders SET parent_id = ?3, updated_at = ?4 \ @@ -383,4 +403,42 @@ mod tests { Err(Error::NotFound) )); } + + /// A move counts the height of the moved subtree: a folder with a subfolder cannot land where its + /// subtree would end past the limit, but its leaf can land exactly on it. + #[tokio::test] + async fn a_move_counts_the_height_of_the_moved_subtree() { + let (_dir, store) = store_with_member("ann").await; + // A chain of MAX_DEPTH - 1 folders built with raw inserts, so the deepest one sits at MAX_DEPTH - 1. + let mut parent: Option = None; + let mut deepest = String::new(); + { + let conn = store.inner.conn.lock().await; + for n in 0..MAX_DEPTH - 1 { + let id = new_id(); + conn.execute( + "INSERT INTO folders (id, owner, parent_id, name, created_at, updated_at) \ + VALUES (?1, 'ann', ?2, ?3, ?4, ?4)", + (id.clone(), parent.clone(), format!("d{n}"), now_stamp()), + ) + .await + .unwrap(); + parent = Some(id.clone()); + deepest = id; + } + } + let root = store.create_folder("ann", None, "Moved").await.unwrap(); + let child = store + .create_folder("ann", Some(&root.id), "Inner") + .await + .unwrap(); + assert!(matches!( + store.move_folder("ann", &root.id, Some(&deepest)).await, + Err(Error::Invalid(reason)) if reason == "folder_too_deep" + )); + store + .move_folder("ann", &child.id, Some(&deepest)) + .await + .expect("a leaf fits exactly at the limit"); + } } diff --git a/crates/in-web/src/api/objects.rs b/crates/in-web/src/api/objects.rs index a46d58e..2500a72 100644 --- a/crates/in-web/src/api/objects.rs +++ b/crates/in-web/src/api/objects.rs @@ -355,7 +355,9 @@ async fn get_object(cx: &Cx) -> Result { let source = ByteSource { blob_key: &object.blob_key, size: object.size as u64, - sha256: &object.sha256, + // The object API's validator is the content's SHA-256 (contracts.md 5). The caller holds the + // object's bytes already, so the hash reveals nothing new to it. + validator: &object.sha256, content_sha256: Some(&object.sha256), mime: &object.content_type, name: &name, diff --git a/crates/in-web/src/pages/files.rs b/crates/in-web/src/pages/files.rs index 5f493ed..89790fe 100644 --- a/crates/in-web/src/pages/files.rs +++ b/crates/in-web/src/pages/files.rs @@ -33,7 +33,9 @@ use crate::pages::drive::{ DRIVE_HOME, ItemForm, access_for, back_or, changed, check, done, optional_folder, pick_body, refusal_word, refused, tree_rows, viewer_lang, with_param, }; -use crate::serve_bytes::{ByteAnswer, ByteSource, Disposition, counts_as_download, serve_bytes}; +use crate::serve_bytes::{ + ByteAnswer, ByteSource, Disposition, counts_as_download, file_validator, serve_bytes, +}; use crate::state::AppState; use crate::views::{ViewerInfo, shell}; @@ -265,13 +267,14 @@ async fn file_bytes(cx: &Cx) -> Result { }; let file = file_for(state, &viewer, &id, action).await?; let size = u64::try_from(file.size).unwrap_or(0); - if download && counts_as_download(headers(cx), &file.sha256, size) { + let validator = file_validator(&state.key, &file.sha256); + if download && counts_as_download(headers(cx), &validator, size) { state.store.record_download(&file.id).await?; } let source = ByteSource { blob_key: &file.blob_key, size, - sha256: &file.sha256, + validator: &validator, content_sha256: Some(&file.sha256), mime: &file.mime, name: &file.name, diff --git a/crates/in-web/src/pages/public_share.rs b/crates/in-web/src/pages/public_share.rs index 06ca4a6..1c53bd8 100644 --- a/crates/in-web/src/pages/public_share.rs +++ b/crates/in-web/src/pages/public_share.rs @@ -43,7 +43,8 @@ use crate::i18n::drive::{DK, d}; use crate::i18n::share::{SK, s as share_s}; use crate::pages::thumbs::thumb_validator; use crate::serve_bytes::{ - ByteAnswer, ByteSource, Disposition, SHARE_CACHE, counts_as_download, serve_bytes_with, + ByteAnswer, ByteSource, Disposition, SHARE_CACHE, counts_as_download, file_validator, + serve_bytes_with, }; use crate::state::AppState; use crate::views::drive::size_text; @@ -526,13 +527,14 @@ async fn public_file_bytes(cx: &Cx) -> Result { visit(state, &link, ItemKind::File, &id, action).await?; let file = state.store.file(&id).await?.ok_or_else(not_found)?; let size = u64::try_from(file.size).unwrap_or(0); - if download && counts_as_download(headers(cx), &file.sha256, size) { + let validator = file_validator(&state.key, &file.sha256); + if download && counts_as_download(headers(cx), &validator, size) { state.store.record_download(&file.id).await?; } let source = ByteSource { blob_key: &file.blob_key, size, - sha256: &file.sha256, + validator: &validator, content_sha256: Some(&file.sha256), mime: &file.mime, name: &file.name, @@ -562,11 +564,11 @@ async fn public_thumb(cx: &Cx) -> Result { let size = state.blobs.size(&key).await?.ok_or_else(not_found)?; // The row holds no hash of the thumbnail bytes, only the validator derived from the file's hash, so // the thumbnail body is not checked. - let validator = thumb_validator(&file.sha256); + let validator = thumb_validator(&state.key, &file.sha256); let source = ByteSource { blob_key: &key, size, - sha256: &validator, + validator: &validator, content_sha256: None, mime: "image/webp", name: &file.name, diff --git a/crates/in-web/src/pages/share_dialog.rs b/crates/in-web/src/pages/share_dialog.rs index e39c0f4..76aa19d 100644 --- a/crates/in-web/src/pages/share_dialog.rs +++ b/crates/in-web/src/pages/share_dialog.rs @@ -2,9 +2,11 @@ //! writes of its grants: `POST /grants` (a new grant, or the level of an existing one), `POST //! /grants/{id}/update` and `POST /grants/{id}/remove`. The page also makes the item's share links. //! -//! Only the owner of a live item may share it (`authz` `Share`). A grantee is `403` on it, and anyone else -//! is `404`. The grantee of a grant is chosen from the family's members, active ones other than the owner -//! only, and the store checks that again. Each change tells the grantee's open shared page. +//! Only the owner of a live item may share it (`authz` `Share`). The owner of a trashed item may still see +//! its grants and change or remove them (`Revoke`), so access taken back does not return on restore; the +//! page then offers no new grant and no new link. A grantee is `403` on the page, and anyone else is `404`. +//! The grantee of a grant is chosen from the family's members, active ones other than the owner only, and +//! the store checks that again. Each change tells the grantee's open shared page. use in_core::authz::Action; use in_core::store::members::Member; @@ -74,6 +76,21 @@ pub async fn shareable( Ok(name) } +/// The name and trash state of an item whose grants the viewer may change or remove: the owner's, live or +/// trashed. A grantee is refused with `403` and anyone else sees `404`. +pub async fn revocable( + state: &AppState, + viewer: &Viewer, + kind: ItemKind, + id: &str, +) -> Result<(String, bool)> { + let (owner, name) = item_head(state, kind, id).await?; + let access = access_for(state, viewer, kind, id).await?; + let trashed = access.trashed; + check(viewer, &owner, access, Action::Revoke)?; + Ok((name, trashed)) +} + /// Tells the grantee's open shared page that its list changed. fn notify(state: &AppState, grantee: &str) { state.live.bump(&Topic::Shared(grantee.to_owned())); @@ -148,6 +165,7 @@ pub async fn share_body( back: &str, item_page: &str, max_days: u32, + trashed: bool, notice: &str, refusal: &str, ) -> Result { @@ -167,7 +185,7 @@ pub async fn share_body( } } - if !people.is_empty() { + if !trashed && !people.is_empty() { }

(share_s(lang, SK::ShareOwnerOnly))

+ if !trashed {

(share_s(lang, SK::ShareLinks))