forge
Explore
Log in

Don't you dare go Hollow

🔒 owners revoke grants on trashed items; folder moves count the subtree height; keyed ETags

Browse files at this commit

f70fcdd2072ebce5f59de19ce0be9588c456788bAhmet Kaan GümüşParent: f8d6187
crates/in-core/src/authz.rsmodified+10 -2
@@ -5,7 +5,8 @@
5 //! Rules (architecture section 6):5 //! Rules (architecture section 6):
6 //! - Anonymous and service callers never reach drive items.6 //! - Anonymous and service callers never reach drive items.
7 //! - The owner may do everything on live items except `Purge` and `Restore`, which apply to trashed7 //! - 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 //! - An admin may `Administer` any item but reads nobody else's files.10 //! - An admin may `Administer` any item but reads nobody else's files.
10 //! - A grantee sees a live item with a grant, lists and views it, and downloads it only with a11 //! - A grantee sees a live item with a grant, lists and views it, and downloads it only with a
11 //! download grant. Nothing else.12 //! download grant. Nothing else.
@@ -71,8 +72,10 @@ pub enum Action {
71 Write,72 Write,
72 /// Restore a trashed item to its place.73 /// Restore a trashed item to its place.
73 Restore,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 Share,76 Share,
77+ /// Change the level of an existing grant, or remove it.
78+ Revoke,
76 /// Permanently delete a trashed item.79 /// Permanently delete a trashed item.
77 Purge,80 Purge,
78 /// Administer the instance.81 /// Administer the instance.
@@ -128,6 +131,8 @@ pub fn authorize(
128 fn owner_rule(trashed: bool, action: Action) -> Result<(), Denied> {131 fn owner_rule(trashed: bool, action: Action) -> Result<(), Denied> {
129 match (trashed, action) {132 match (trashed, action) {
130 (_, Action::Administer) => Err(Denied::NotFound),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 (false, Action::Purge | Action::Restore) => Err(Denied::Forbidden),136 (false, Action::Purge | Action::Restore) => Err(Denied::Forbidden),
132 (false, _) => Ok(()),137 (false, _) => Ok(()),
133 (true, Action::View | Action::Download | Action::Restore | Action::Purge) => Ok(()),138 (true, Action::View | Action::Download | Action::Restore | Action::Purge) => Ok(()),
@@ -214,6 +219,7 @@ mod tests {
214 (owner(), live(), Grant::None, Download, Ok(())),219 (owner(), live(), Grant::None, Download, Ok(())),
215 (owner(), live(), Grant::None, Write, Ok(())),220 (owner(), live(), Grant::None, Write, Ok(())),
216 (owner(), live(), Grant::None, Share, Ok(())),221 (owner(), live(), Grant::None, Share, Ok(())),
222+ (owner(), live(), Grant::None, Revoke, Ok(())),
217 (owner(), live(), Grant::None, Purge, Err(Forbidden)),223 (owner(), live(), Grant::None, Purge, Err(Forbidden)),
218 (owner(), live(), Grant::None, Restore, Err(Forbidden)),224 (owner(), live(), Grant::None, Restore, Err(Forbidden)),
219 (owner(), live(), Grant::None, Administer, Err(NotFound)),225 (owner(), live(), Grant::None, Administer, Err(NotFound)),
@@ -224,6 +230,7 @@ mod tests {
224 (owner(), trashed(), Grant::None, Purge, Ok(())),230 (owner(), trashed(), Grant::None, Purge, Ok(())),
225 (owner(), trashed(), Grant::None, Write, Err(Forbidden)),231 (owner(), trashed(), Grant::None, Write, Err(Forbidden)),
226 (owner(), trashed(), Grant::None, Share, Err(Forbidden)),232 (owner(), trashed(), Grant::None, Share, Err(Forbidden)),
233+ (owner(), trashed(), Grant::None, Revoke, Ok(())),
227 (owner(), trashed(), Grant::None, List, Err(Forbidden)),234 (owner(), trashed(), Grant::None, List, Err(Forbidden)),
228 // Grantee with view only, live.235 // Grantee with view only, live.
229 (grantee(), live(), Grant::View, List, Ok(())),236 (grantee(), live(), Grant::View, List, Ok(())),
@@ -233,6 +240,7 @@ mod tests {
233 // Grantee with download.240 // Grantee with download.
234 (grantee(), live(), Grant::Download, Download, Ok(())),241 (grantee(), live(), Grant::Download, Download, Ok(())),
235 (grantee(), live(), Grant::Download, Share, Err(Forbidden)),242 (grantee(), live(), Grant::Download, Share, Err(Forbidden)),
243+ (grantee(), live(), Grant::Download, Revoke, Err(Forbidden)),
236 // Grantee without any grant, or on a trashed item, learns nothing.244 // Grantee without any grant, or on a trashed item, learns nothing.
237 (grantee(), live(), Grant::None, View, Err(NotFound)),245 (grantee(), live(), Grant::None, View, Err(NotFound)),
238 (grantee(), trashed(), Grant::Download, View, Err(NotFound)),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 const SEAL_LABEL: &[u8] = b"in seal v1";23 const SEAL_LABEL: &[u8] = b"in seal v1";
24 /// Label of the key of the password-unlock proof of a share link (see [`unlock_proof`]).24 /// Label of the key of the password-unlock proof of a share link (see [`unlock_proof`]).
25 const UNLOCK_LABEL: &[u8] = b"in link unlock v1";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 /// What a sealed value is for. It is the associated data of [`seal`] and [`open`], so a value sealed under29 /// What a sealed value is for. It is the associated data of [`seal`] and [`open`], so a value sealed under
28 /// one purpose fails authentication under any other.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 hex::encode(mac.finalize().into_bytes())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 /// A 32-byte subkey for one purpose: HMAC-SHA256 of `label` under the instance key. Different labels give161 /// A 32-byte subkey for one purpose: HMAC-SHA256 of `label` under the instance key. Different labels give
148 /// unrelated subkeys, so a key derived for one use cannot be replayed as the key of another.162 /// unrelated subkeys, so a key derived for one use cannot be replayed as the key of another.
149 pub fn derive_subkey(master: &[u8; 32], label: &[u8]) -> [u8; 32] {163 pub fn derive_subkey(master: &[u8; 32], label: &[u8]) -> [u8; 32] {
@@ -237,3 +251,20 @@ mod proof_tests {
237 assert_ne!(base, unlock_proof(&[8u8; 32], "link-a", "$argon2id$hash"));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 use crate::names;11 use crate::names;
12 use crate::store::files::{FILE_COLS, File, map_file};12 use crate::store::files::{FILE_COLS, File, map_file};
13 use crate::store::{13 use crate::store::{
14- MAX_POSTFIX_TRIES, Store, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err,14+ MAX_POSTFIX_TRIES, Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt,
15- new_id,15+ insert_err, new_id,
16 };16 };
17 use crate::time::now_stamp;17 use crate::time::now_stamp;
18 18
@@ -127,6 +127,25 @@ async fn chain_depth(conn: &Connection, folder: &str) -> Result<usize> {
127 Ok(depth)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 /// Inserts a folder with the first free postfix. The partial unique index decides each attempt.149 /// Inserts a folder with the first free postfix. The partial unique index decides each attempt.
131 async fn insert_folder_postfixed(150 async fn insert_folder_postfixed(
132 conn: &Connection,151 conn: &Connection,
@@ -230,10 +249,6 @@ impl Store {
230 live_folder(&tx, owner, id).await?;249 live_folder(&tx, owner, id).await?;
231 if let Some(p) = parent {250 if let Some(p) = parent {
232 live_folder(&tx, owner, p).await?;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 let mut cur = Some(p.to_string());252 let mut cur = Some(p.to_string());
238 while let Some(c) = cur {253 while let Some(c) = cur {
239 if c == id {254 if c == id {
@@ -241,6 +256,11 @@ impl Store {
241 }256 }
242 cur = folder_by_id(&tx, &c).await?.and_then(|f| f.parent_id);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 tx.execute(265 tx.execute(
246 "UPDATE folders SET parent_id = ?3, updated_at = ?4 \266 "UPDATE folders SET parent_id = ?3, updated_at = ?4 \
@@ -383,4 +403,42 @@ mod tests {
383 Err(Error::NotFound)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 let source = ByteSource {355 let source = ByteSource {
356 blob_key: &object.blob_key,356 blob_key: &object.blob_key,
357 size: object.size as u64,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 content_sha256: Some(&object.sha256),361 content_sha256: Some(&object.sha256),
360 mime: &object.content_type,362 mime: &object.content_type,
361 name: &name,363 name: &name,
crates/in-web/src/pages/files.rsmodified+6 -3
@@ -33,7 +33,9 @@ use crate::pages::drive::{
33 DRIVE_HOME, ItemForm, access_for, back_or, changed, check, done, optional_folder, pick_body,33 DRIVE_HOME, ItemForm, access_for, back_or, changed, check, done, optional_folder, pick_body,
34 refusal_word, refused, tree_rows, viewer_lang, with_param,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 use crate::state::AppState;39 use crate::state::AppState;
38 use crate::views::{ViewerInfo, shell};40 use crate::views::{ViewerInfo, shell};
39 41
@@ -265,13 +267,14 @@ async fn file_bytes(cx: &Cx) -> Result<ByteAnswer> {
265 };267 };
266 let file = file_for(state, &viewer, &id, action).await?;268 let file = file_for(state, &viewer, &id, action).await?;
267 let size = u64::try_from(file.size).unwrap_or(0);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 state.store.record_download(&file.id).await?;272 state.store.record_download(&file.id).await?;
270 }273 }
271 let source = ByteSource {274 let source = ByteSource {
272 blob_key: &file.blob_key,275 blob_key: &file.blob_key,
273 size,276 size,
274- sha256: &file.sha256,277+ validator: &validator,
275 content_sha256: Some(&file.sha256),278 content_sha256: Some(&file.sha256),
276 mime: &file.mime,279 mime: &file.mime,
277 name: &file.name,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 use crate::i18n::share::{SK, s as share_s};43 use crate::i18n::share::{SK, s as share_s};
44 use crate::pages::thumbs::thumb_validator;44 use crate::pages::thumbs::thumb_validator;
45 use crate::serve_bytes::{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 use crate::state::AppState;49 use crate::state::AppState;
49 use crate::views::drive::size_text;50 use crate::views::drive::size_text;
@@ -526,13 +527,14 @@ async fn public_file_bytes(cx: &Cx) -> Result<ByteAnswer> {
526 visit(state, &link, ItemKind::File, &id, action).await?;527 visit(state, &link, ItemKind::File, &id, action).await?;
527 let file = state.store.file(&id).await?.ok_or_else(not_found)?;528 let file = state.store.file(&id).await?.ok_or_else(not_found)?;
528 let size = u64::try_from(file.size).unwrap_or(0);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 state.store.record_download(&file.id).await?;532 state.store.record_download(&file.id).await?;
531 }533 }
532 let source = ByteSource {534 let source = ByteSource {
533 blob_key: &file.blob_key,535 blob_key: &file.blob_key,
534 size,536 size,
535- sha256: &file.sha256,537+ validator: &validator,
536 content_sha256: Some(&file.sha256),538 content_sha256: Some(&file.sha256),
537 mime: &file.mime,539 mime: &file.mime,
538 name: &file.name,540 name: &file.name,
@@ -562,11 +564,11 @@ async fn public_thumb(cx: &Cx) -> Result<ByteAnswer> {
562 let size = state.blobs.size(&key).await?.ok_or_else(not_found)?;564 let size = state.blobs.size(&key).await?.ok_or_else(not_found)?;
563 // The row holds no hash of the thumbnail bytes, only the validator derived from the file's hash, so565 // The row holds no hash of the thumbnail bytes, only the validator derived from the file's hash, so
564 // the thumbnail body is not checked.566 // the thumbnail body is not checked.
565- let validator = thumb_validator(&file.sha256);567+ let validator = thumb_validator(&state.key, &file.sha256);
566 let source = ByteSource {568 let source = ByteSource {
567 blob_key: &key,569 blob_key: &key,
568 size,570 size,
569- sha256: &validator,571+ validator: &validator,
570 content_sha256: None,572 content_sha256: None,
571 mime: "image/webp",573 mime: "image/webp",
572 name: &file.name,574 name: &file.name,
crates/in-web/src/pages/share_dialog.rsmodified+33 -11
@@ -2,9 +2,11 @@
2 //! writes of its grants: `POST /grants` (a new grant, or the level of an existing one), `POST2 //! writes of its grants: `POST /grants` (a new grant, or the level of an existing one), `POST
3 //! /grants/{id}/update` and `POST /grants/{id}/remove`. The page also makes the item's share links.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 else5+//! Only the owner of a live item may share it (`authz` `Share`). The owner of a trashed item may still see
6-//! is `404`. The grantee of a grant is chosen from the family's members, active ones other than the owner6+//! its grants and change or remove them (`Revoke`), so access taken back does not return on restore; the
7-//! only, and the store checks that again. Each change tells the grantee's open shared page.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 use in_core::authz::Action;11 use in_core::authz::Action;
10 use in_core::store::members::Member;12 use in_core::store::members::Member;
@@ -74,6 +76,21 @@ pub async fn shareable(
74 Ok(name)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 /// Tells the grantee's open shared page that its list changed.94 /// Tells the grantee's open shared page that its list changed.
78 fn notify(state: &AppState, grantee: &str) {95 fn notify(state: &AppState, grantee: &str) {
79 state.live.bump(&Topic::Shared(grantee.to_owned()));96 state.live.bump(&Topic::Shared(grantee.to_owned()));
@@ -148,6 +165,7 @@ pub async fn share_body(
148 back: &str,165 back: &str,
149 item_page: &str,166 item_page: &str,
150 max_days: u32,167 max_days: u32,
168+ trashed: bool,
151 notice: &str,169 notice: &str,
152 refusal: &str,170 refusal: &str,
153 ) -> Result<impl View> {171 ) -> Result<impl View> {
@@ -167,7 +185,7 @@ pub async fn share_body(
167 }185 }
168 </ul>186 </ul>
169 }187 }
170- if !people.is_empty() {188+ if !trashed && !people.is_empty() {
171 <form method="post" action="/grants" class="share-form">189 <form method="post" action="/grants" class="share-form">
172 <input type="hidden" name="csrf" value=(csrf)>190 <input type="hidden" name="csrf" value=(csrf)>
173 <input type="hidden" name="back" value=(back)>191 <input type="hidden" name="back" value=(back)>
@@ -185,6 +203,7 @@ pub async fn share_body(
185 </form>203 </form>
186 }204 }
187 <p class="muted">(share_s(lang, SK::ShareOwnerOnly))</p>205 <p class="muted">(share_s(lang, SK::ShareOwnerOnly))</p>
206+ if !trashed {
188 <h2>(share_s(lang, SK::ShareLinks))</h2>207 <h2>(share_s(lang, SK::ShareLinks))</h2>
189 <form method="post" action="/links" class="share-form">208 <form method="post" action="/links" class="share-form">
190 <input type="hidden" name="csrf" value=(csrf)>209 <input type="hidden" name="csrf" value=(csrf)>
@@ -207,11 +226,12 @@ pub async fn share_body(
207 }226 }
208 </ul>227 </ul>
209 }228 }
229+ }
210 </section>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 #[page("/share/{kind}/{id}")]235 #[page("/share/{kind}/{id}")]
216 async fn share_page(cx: &Cx) -> Result<impl View> {236 async fn share_page(cx: &Cx) -> Result<impl View> {
217 let state = app_context::<AppState>(cx);237 let state = app_context::<AppState>(cx);
@@ -219,7 +239,7 @@ async fn share_page(cx: &Cx) -> Result<impl View> {
219 let lang = viewer_lang(cx, &viewer);239 let lang = viewer_lang(cx, &viewer);
220 let kind = kind_from_word(path_param_segment(cx, "kind")).ok_or_else(not_found)?;240 let kind = kind_from_word(path_param_segment(cx, "kind")).ok_or_else(not_found)?;
221 let id = path_param_segment(cx, "id").to_owned();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 let me = viewer.member.sub.clone();243 let me = viewer.member.sub.clone();
224 let entries = state.store.shares_of(&me, kind, &id).await?;244 let entries = state.store.shares_of(&me, kind, &id).await?;
225 let people: Vec<Member> = state245 let people: Vec<Member> = state
@@ -251,7 +271,7 @@ async fn share_page(cx: &Cx) -> Result<impl View> {
251 share_body(lang: lang, name: name.as_str(), kind: kind_word(kind), id: id.as_str(),271 share_body(lang: lang, name: name.as_str(), kind: kind_word(kind), id: id.as_str(),
252 entries: &entries, people: &people, links: &links, csrf: csrf.as_str(),272 entries: &entries, people: &people, links: &links, csrf: csrf.as_str(),
253 back: back.as_str(), item_page: item_page.as_str(), max_days: max_days,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 .ok_or_else(not_found)?)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 #[route(POST "/grants/{id}/update")]320 #[route(POST "/grants/{id}/update")]
300 async fn update_grant(cx: &Cx, Form(form): Form<GrantForm>) -> Result<SeeOther> {321 async fn update_grant(cx: &Cx, Form(form): Form<GrantForm>) -> Result<SeeOther> {
301 let state = app_context::<AppState>(cx);322 let state = app_context::<AppState>(cx);
@@ -304,7 +325,7 @@ async fn update_grant(cx: &Cx, Form(form): Form<GrantForm>) -> Result<SeeOther>
304 let share = owned_share(state, &viewer, &id).await?;325 let share = owned_share(state, &viewer, &id).await?;
305 let default_back = format!("/share/{}/{}", kind_word(share.kind), share.target_id);326 let default_back = format!("/share/{}/{}", kind_word(share.kind), share.target_id);
306 let back = back_or(&form.back, &default_back);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 match state329 match state
309 .store330 .store
310 .set_share_level(&viewer.member.sub, &id, form.level == "download")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 /// `POST /grants/{id}/remove`: ends a grant. The grantee loses the item at once, and so does everything342 /// `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 #[route(POST "/grants/{id}/remove")]345 #[route(POST "/grants/{id}/remove")]
324 async fn remove_grant(cx: &Cx, Form(form): Form<GrantForm>) -> Result<SeeOther> {346 async fn remove_grant(cx: &Cx, Form(form): Form<GrantForm>) -> Result<SeeOther> {
325 let state = app_context::<AppState>(cx);347 let state = app_context::<AppState>(cx);
@@ -328,7 +350,7 @@ async fn remove_grant(cx: &Cx, Form(form): Form<GrantForm>) -> Result<SeeOther>
328 let share = owned_share(state, &viewer, &id).await?;350 let share = owned_share(state, &viewer, &id).await?;
329 let default_back = format!("/share/{}/{}", kind_word(share.kind), share.target_id);351 let default_back = format!("/share/{}/{}", kind_word(share.kind), share.target_id);
330 let back = back_or(&form.back, &default_back);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 match state.store.remove_share(&viewer.member.sub, &id).await {354 match state.store.remove_share(&viewer.member.sub, &id).await {
333 Ok(removed) => {355 Ok(removed) => {
334 notify(state, &removed.grantee);356 notify(state, &removed.grantee);
crates/in-web/src/pages/thumbs.rsmodified+6 -10
@@ -6,7 +6,6 @@
6 6
7 use in_core::authz::Action;7 use in_core::authz::Action;
8 use in_core::store::files::thumb_blob_key;8 use in_core::store::files::thumb_blob_key;
9-use sha2::{Digest, Sha256};
10 use topcoat::Result;9 use topcoat::Result;
11 use topcoat::context::{Cx, app_context};10 use topcoat::context::{Cx, app_context};
12 use topcoat::router::error::not_found;11 use topcoat::router::error::not_found;
@@ -17,13 +16,10 @@ use crate::pages::files::file_for;
17 use crate::serve_bytes::{ByteAnswer, ByteSource, Disposition, serve_bytes};16 use crate::serve_bytes::{ByteAnswer, ByteSource, Disposition, serve_bytes};
18 use crate::state::AppState;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 the19+/// The validator of a thumbnail: keyed under its own purpose, so it differs from the file's ETag, because the
21-/// file's ETag, because the thumbnail is other bytes, and it changes only when the file's bytes change.20+/// thumbnail is other bytes. It changes only when the file's bytes change, and it does not reveal their hash.
22-pub fn thumb_validator(file_sha256: &str) -> String {21+pub fn thumb_validator(key: &[u8; 32], file_sha256: &str) -> String {
23- Sha256::digest(format!("thumb:{file_sha256}"))22+ in_core::secret::validator(key, "thumb", file_sha256)
24- .iter()
25- .map(|b| format!("{b:02x}"))
26- .collect()
27 }23 }
28 24
29 /// `GET /thumb/{id}`: the WebP thumbnail of a picture.25 /// `GET /thumb/{id}`: the WebP thumbnail of a picture.
@@ -38,13 +34,13 @@ async fn thumb(cx: &Cx) -> Result<ByteAnswer> {
38 }34 }
39 let key = thumb_blob_key(&file.id);35 let key = thumb_blob_key(&file.id);
40 let size = state.blobs.size(&key).await?.ok_or_else(not_found)?;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 // The row holds no hash of the thumbnail bytes, only the validator derived from the file's hash, so38 // The row holds no hash of the thumbnail bytes, only the validator derived from the file's hash, so
43 // the thumbnail body is not checked.39 // the thumbnail body is not checked.
44 let source = ByteSource {40 let source = ByteSource {
45 blob_key: &key,41 blob_key: &key,
46 size,42 size,
47- sha256: &validator,43+ validator: &validator,
48 content_sha256: None,44 content_sha256: None,
49 mime: "image/webp",45 mime: "image/webp",
50 name: &file.name,46 name: &file.name,
crates/in-web/src/serve_bytes.rsmodified+16 -7
@@ -49,11 +49,12 @@ pub struct ByteSource<'a> {
49 pub blob_key: &'a str,49 pub blob_key: &'a str,
50 /// Length of the bytes in bytes.50 /// Length of the bytes in bytes.
51 pub size: u64,51 pub size: u64,
52- /// Lowercase hex SHA-256 of the bytes. It is the strong validator, so equal hashes mean equal bytes.52+ /// The validator of the bytes, unquoted; the `ETag` is its quoted form. Equal validators mean equal bytes.
53- pub sha256: &'a str,53+ /// For a stored file it is [`file_validator`], which does not reveal the file's hash.
54+ pub validator: &'a str,
54 /// The SHA-256 the bytes must hash to, when the bytes are the row's own content. A full-body answer55 /// The SHA-256 the bytes must hash to, when the bytes are the row's own content. A full-body answer
55 /// is checked against it while it streams (see [`check_digest`]). `None` for derived bytes such as56 /// 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 pub content_sha256: Option<&'a str>,58 pub content_sha256: Option<&'a str>,
58 /// The sniffed MIME type, as stored. It is never the uploader's claim.59 /// The sniffed MIME type, as stored. It is never the uploader's claim.
59 pub mime: &'a str,60 pub mime: &'a str,
@@ -164,6 +165,13 @@ fn digits(text: &str) -> Option<u64> {
164 Some(text.parse().unwrap_or(u64::MAX))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 /// Whether a conditional request `If-None-Match` names `etag`. Weak tags compare equal to their strong175 /// Whether a conditional request `If-None-Match` names `etag`. Weak tags compare equal to their strong
168 /// form here, which is the rule for `GET` validators (RFC 9110).176 /// form here, which is the rule for `GET` validators (RFC 9110).
169 fn none_match_hits(request: &HeaderMap, etag: &str) -> bool {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 /// Whether serving this request counts as a download that started at byte 0. A `304`, a range that208 /// Whether serving this request counts as a download that started at byte 0. A `304`, a range that
201 /// starts later, and an unsatisfiable range do not count; a whole file, or a range from byte 0, does.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.210+/// The download counter is bumped by the caller before it serves the body. `validator` is the bytes'
203-pub fn counts_as_download(request: &HeaderMap, sha256: &str, size: u64) -> bool {211+/// validator, as sent in [`ByteSource::validator`].
204- let etag = format!("\"{sha256}\"");212+pub fn counts_as_download(request: &HeaderMap, validator: &str, size: u64) -> bool {
213+ let etag = format!("\"{validator}\"");
205 if none_match_hits(request, &etag) {214 if none_match_hits(request, &etag) {
206 return false;215 return false;
207 }216 }
@@ -346,7 +355,7 @@ pub async fn serve_bytes_with(
346 cache: &str,355 cache: &str,
347 ) -> Result<ByteAnswer> {356 ) -> Result<ByteAnswer> {
348 let request = headers(cx);357 let request = headers(cx);
349- let etag = format!("\"{}\"", source.sha256);358+ let etag = format!("\"{}\"", source.validator);
350 let disposition = match disposition {359 let disposition = match disposition {
351 Disposition::Inline if inline_safe(source.mime) => Disposition::Inline,360 Disposition::Inline if inline_safe(source.mime) => Disposition::Inline,
352 _ => Disposition::Attachment,361 _ => Disposition::Attachment,
docs/architecture.mdmodified+9 -3
@@ -177,8 +177,10 @@ and has no sessions.
177 - `target`: a file or folder with owner and trashed state, plus the effective grant (the most permissive grant177 - `target`: a file or folder with owner and trashed state, plus the effective grant (the most permissive grant
178 on the item or any live ancestor folder) and, for links, whether the item is inside the linked folder.178 on the item or any live ancestor folder) and, for links, whether the item is inside the linked folder.
179 - `action`: `List`, `View` (see name, preview inline), `Download`, `Write` (rename, move, upload into, trash),179 - `action`: `List`, `View` (see name, preview inline), `Download`, `Write` (rename, move, upload into, trash),
180- `Share`, `Purge`, `Administer`.180+ `Restore`, `Share` (a new grant or link), `Revoke` (change the level of an existing grant, or remove it),
181-- Rules: owner may do everything on their items (trashed items: only `View`, `Download`, restore, `Purge`);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 grantee: `List` and `View`, `Download` when `can_download`, never on trashed items; link visitor: the same as184 grantee: `List` and `View`, `Download` when `can_download`, never on trashed items; link visitor: the same as
183 a grantee within the link's subtree; admin: `Administer` only (an admin does **not** read other people's185 a grantee within the link's subtree; admin: `Administer` only (an admin does **not** read other people's
184 files); anything else is `NotFound`.186 files); anything else is `NotFound`.
@@ -187,7 +189,11 @@ and has no sessions.
187 189
188 ## 7. Byte serving (one function for every byte route)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 7233192+- 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 3.1 a `Range` that is malformed, reversed, or in another unit is ignored (200, whole file); only a valid range197 3.1 a `Range` that is malformed, reversed, or in another unit is ignored (200, whole file); only a valid range
192 the file cannot satisfy gets 416 with `Content-Range: bytes */<len>`. Several ranges get 200, whole file.198 the file cannot satisfy gets 416 with `Content-Range: bytes */<len>`. Several ranges get 200, whole file.
193 - `Content-Disposition`: `inline` only for image/* (not SVG, not HEIC), video/*, audio/*, application/pdf,199 - `Content-Disposition`: `inline` only for image/* (not SVG, not HEIC), video/*, audio/*, application/pdf,