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 @@
55 //! Rules (architecture section 6):
66 //! - Anonymous and service callers never reach drive items.
77 //! - 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.
910 //! - An admin may `Administer` any item but reads nobody else's files.
1011 //! - A grantee sees a live item with a grant, lists and views it, and downloads it only with a
1112 //! download grant. Nothing else.
@@ -71,8 +72,10 @@ pub enum Action {
7172 Write,
7273 /// Restore a trashed item to its place.
7374 Restore,
74- /// Change who can see the item (grants and links).
75+ /// Create a grant or a link: change who can see the item.
7576 Share,
77+ /// Change the level of an existing grant, or remove it.
78+ Revoke,
7679 /// Permanently delete a trashed item.
7780 Purge,
7881 /// Administer the instance.
@@ -128,6 +131,8 @@ pub fn authorize(
128131 fn owner_rule(trashed: bool, action: Action) -> Result<(), Denied> {
129132 match (trashed, action) {
130133 (_, 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(()),
131136 (false, Action::Purge | Action::Restore) => Err(Denied::Forbidden),
132137 (false, _) => Ok(()),
133138 (true, Action::View | Action::Download | Action::Restore | Action::Purge) => Ok(()),
@@ -214,6 +219,7 @@ mod tests {
214219 (owner(), live(), Grant::None, Download, Ok(())),
215220 (owner(), live(), Grant::None, Write, Ok(())),
216221 (owner(), live(), Grant::None, Share, Ok(())),
222+ (owner(), live(), Grant::None, Revoke, Ok(())),
217223 (owner(), live(), Grant::None, Purge, Err(Forbidden)),
218224 (owner(), live(), Grant::None, Restore, Err(Forbidden)),
219225 (owner(), live(), Grant::None, Administer, Err(NotFound)),
@@ -224,6 +230,7 @@ mod tests {
224230 (owner(), trashed(), Grant::None, Purge, Ok(())),
225231 (owner(), trashed(), Grant::None, Write, Err(Forbidden)),
226232 (owner(), trashed(), Grant::None, Share, Err(Forbidden)),
233+ (owner(), trashed(), Grant::None, Revoke, Ok(())),
227234 (owner(), trashed(), Grant::None, List, Err(Forbidden)),
228235 // Grantee with view only, live.
229236 (grantee(), live(), Grant::View, List, Ok(())),
@@ -233,6 +240,7 @@ mod tests {
233240 // Grantee with download.
234241 (grantee(), live(), Grant::Download, Download, Ok(())),
235242 (grantee(), live(), Grant::Download, Share, Err(Forbidden)),
243+ (grantee(), live(), Grant::Download, Revoke, Err(Forbidden)),
236244 // Grantee without any grant, or on a trashed item, learns nothing.
237245 (grantee(), live(), Grant::None, View, Err(NotFound)),
238246 (grantee(), trashed(), Grant::Download, View, Err(NotFound)),
crates/in-core/src/secret.rsmodified+31 -0
@@ -23,6 +23,8 @@ const NONCE_LEN: usize = 24;
2323 const SEAL_LABEL: &[u8] = b"in seal v1";
2424 /// Label of the key of the password-unlock proof of a share link (see [`unlock_proof`]).
2525 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";
2628
2729 /// What a sealed value is for. It is the associated data of [`seal`] and [`open`], so a value sealed under
2830 /// 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
144146 hex::encode(mac.finalize().into_bytes())
145147 }
146148
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+
147161 /// A 32-byte subkey for one purpose: HMAC-SHA256 of `label` under the instance key. Different labels give
148162 /// unrelated subkeys, so a key derived for one use cannot be replayed as the key of another.
149163 pub fn derive_subkey(master: &[u8; 32], label: &[u8]) -> [u8; 32] {
@@ -237,3 +251,20 @@ mod proof_tests {
237251 assert_ne!(base, unlock_proof(&[8u8; 32], "link-a", "$argon2id$hash"));
238252 }
239253 }
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};
1111 use crate::names;
1212 use crate::store::files::{FILE_COLS, File, map_file};
1313 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,
1616 };
1717 use crate::time::now_stamp;
1818
@@ -127,6 +127,25 @@ async fn chain_depth(conn: &Connection, folder: &str) -> Result<usize> {
127127 Ok(depth)
128128 }
129129
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+
130149 /// Inserts a folder with the first free postfix. The partial unique index decides each attempt.
131150 async fn insert_folder_postfixed(
132151 conn: &Connection,
@@ -230,10 +249,6 @@ impl Store {
230249 live_folder(&tx, owner, id).await?;
231250 if let Some(p) = parent {
232251 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- }
237252 let mut cur = Some(p.to_string());
238253 while let Some(c) = cur {
239254 if c == id {
@@ -241,6 +256,11 @@ impl Store {
241256 }
242257 cur = folder_by_id(&tx, &c).await?.and_then(|f| f.parent_id);
243258 }
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+ }
244264 }
245265 tx.execute(
246266 "UPDATE folders SET parent_id = ?3, updated_at = ?4 \
@@ -383,4 +403,42 @@ mod tests {
383403 Err(Error::NotFound)
384404 ));
385405 }
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+ }
386444 }
crates/in-web/src/api/objects.rsmodified+3 -1
@@ -355,7 +355,9 @@ async fn get_object(cx: &Cx) -> Result<Response> {
355355 let source = ByteSource {
356356 blob_key: &object.blob_key,
357357 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,
359361 content_sha256: Some(&object.sha256),
360362 mime: &object.content_type,
361363 name: &name,
crates/in-web/src/pages/files.rsmodified+6 -3
@@ -33,7 +33,9 @@ use crate::pages::drive::{
3333 DRIVE_HOME, ItemForm, access_for, back_or, changed, check, done, optional_folder, pick_body,
3434 refusal_word, refused, tree_rows, viewer_lang, with_param,
3535 };
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+};
3739 use crate::state::AppState;
3840 use crate::views::{ViewerInfo, shell};
3941
@@ -265,13 +267,14 @@ async fn file_bytes(cx: &Cx) -> Result<ByteAnswer> {
265267 };
266268 let file = file_for(state, &viewer, &id, action).await?;
267269 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) {
269272 state.store.record_download(&file.id).await?;
270273 }
271274 let source = ByteSource {
272275 blob_key: &file.blob_key,
273276 size,
274- sha256: &file.sha256,
277+ validator: &validator,
275278 content_sha256: Some(&file.sha256),
276279 mime: &file.mime,
277280 name: &file.name,
crates/in-web/src/pages/public_share.rsmodified+7 -5
@@ -43,7 +43,8 @@ use crate::i18n::drive::{DK, d};
4343 use crate::i18n::share::{SK, s as share_s};
4444 use crate::pages::thumbs::thumb_validator;
4545 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,
4748 };
4849 use crate::state::AppState;
4950 use crate::views::drive::size_text;
@@ -526,13 +527,14 @@ async fn public_file_bytes(cx: &Cx) -> Result<ByteAnswer> {
526527 visit(state, &link, ItemKind::File, &id, action).await?;
527528 let file = state.store.file(&id).await?.ok_or_else(not_found)?;
528529 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) {
530532 state.store.record_download(&file.id).await?;
531533 }
532534 let source = ByteSource {
533535 blob_key: &file.blob_key,
534536 size,
535- sha256: &file.sha256,
537+ validator: &validator,
536538 content_sha256: Some(&file.sha256),
537539 mime: &file.mime,
538540 name: &file.name,
@@ -562,11 +564,11 @@ async fn public_thumb(cx: &Cx) -> Result<ByteAnswer> {
562564 let size = state.blobs.size(&key).await?.ok_or_else(not_found)?;
563565 // The row holds no hash of the thumbnail bytes, only the validator derived from the file's hash, so
564566 // the thumbnail body is not checked.
565- let validator = thumb_validator(&file.sha256);
567+ let validator = thumb_validator(&state.key, &file.sha256);
566568 let source = ByteSource {
567569 blob_key: &key,
568570 size,
569- sha256: &validator,
571+ validator: &validator,
570572 content_sha256: None,
571573 mime: "image/webp",
572574 name: &file.name,
crates/in-web/src/pages/share_dialog.rsmodified+33 -11
@@ -2,9 +2,11 @@
22 //! writes of its grants: `POST /grants` (a new grant, or the level of an existing one), `POST
33 //! /grants/{id}/update` and `POST /grants/{id}/remove`. The page also makes the item's share links.
44 //!
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.
810
911 use in_core::authz::Action;
1012 use in_core::store::members::Member;
@@ -74,6 +76,21 @@ pub async fn shareable(
7476 Ok(name)
7577 }
7678
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+
7794 /// Tells the grantee's open shared page that its list changed.
7895 fn notify(state: &AppState, grantee: &str) {
7996 state.live.bump(&Topic::Shared(grantee.to_owned()));
@@ -148,6 +165,7 @@ pub async fn share_body(
148165 back: &str,
149166 item_page: &str,
150167 max_days: u32,
168+ trashed: bool,
151169 notice: &str,
152170 refusal: &str,
153171 ) -> Result<impl View> {
@@ -167,7 +185,7 @@ pub async fn share_body(
167185 }
168186 </ul>
169187 }
170- if !people.is_empty() {
188+ if !trashed && !people.is_empty() {
171189 <form method="post" action="/grants" class="share-form">
172190 <input type="hidden" name="csrf" value=(csrf)>
173191 <input type="hidden" name="back" value=(back)>
@@ -185,6 +203,7 @@ pub async fn share_body(
185203 </form>
186204 }
187205 <p class="muted">(share_s(lang, SK::ShareOwnerOnly))</p>
206+ if !trashed {
188207 <h2>(share_s(lang, SK::ShareLinks))</h2>
189208 <form method="post" action="/links" class="share-form">
190209 <input type="hidden" name="csrf" value=(csrf)>
@@ -207,11 +226,12 @@ pub async fn share_body(
207226 }
208227 </ul>
209228 }
229+ }
210230 </section>
211231 })
212232 }
213233
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.
215235 #[page("/share/{kind}/{id}")]
216236 async fn share_page(cx: &Cx) -> Result<impl View> {
217237 let state = app_context::<AppState>(cx);
@@ -219,7 +239,7 @@ async fn share_page(cx: &Cx) -> Result<impl View> {
219239 let lang = viewer_lang(cx, &viewer);
220240 let kind = kind_from_word(path_param_segment(cx, "kind")).ok_or_else(not_found)?;
221241 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?;
223243 let me = viewer.member.sub.clone();
224244 let entries = state.store.shares_of(&me, kind, &id).await?;
225245 let people: Vec<Member> = state
@@ -251,7 +271,7 @@ async fn share_page(cx: &Cx) -> Result<impl View> {
251271 share_body(lang: lang, name: name.as_str(), kind: kind_word(kind), id: id.as_str(),
252272 entries: &entries, people: &people, links: &links, csrf: csrf.as_str(),
253273 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())
255275 )
256276 })
257277 }
@@ -295,7 +315,8 @@ async fn owned_share(state: &AppState, viewer: &Viewer, id: &str) -> Result<Shar
295315 .ok_or_else(not_found)?)
296316 }
297317
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.
299320 #[route(POST "/grants/{id}/update")]
300321 async fn update_grant(cx: &Cx, Form(form): Form<GrantForm>) -> Result<SeeOther> {
301322 let state = app_context::<AppState>(cx);
@@ -304,7 +325,7 @@ async fn update_grant(cx: &Cx, Form(form): Form<GrantForm>) -> Result<SeeOther>
304325 let share = owned_share(state, &viewer, &id).await?;
305326 let default_back = format!("/share/{}/{}", kind_word(share.kind), share.target_id);
306327 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?;
308329 match state
309330 .store
310331 .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>
319340 }
320341
321342 /// `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.
323345 #[route(POST "/grants/{id}/remove")]
324346 async fn remove_grant(cx: &Cx, Form(form): Form<GrantForm>) -> Result<SeeOther> {
325347 let state = app_context::<AppState>(cx);
@@ -328,7 +350,7 @@ async fn remove_grant(cx: &Cx, Form(form): Form<GrantForm>) -> Result<SeeOther>
328350 let share = owned_share(state, &viewer, &id).await?;
329351 let default_back = format!("/share/{}/{}", kind_word(share.kind), share.target_id);
330352 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?;
332354 match state.store.remove_share(&viewer.member.sub, &id).await {
333355 Ok(removed) => {
334356 notify(state, &removed.grantee);
crates/in-web/src/pages/thumbs.rsmodified+6 -10
@@ -6,7 +6,6 @@
66
77 use in_core::authz::Action;
88 use in_core::store::files::thumb_blob_key;
9-use sha2::{Digest, Sha256};
109 use topcoat::Result;
1110 use topcoat::context::{Cx, app_context};
1211 use topcoat::router::error::not_found;
@@ -17,13 +16,10 @@ use crate::pages::files::file_for;
1716 use crate::serve_bytes::{ByteAnswer, ByteSource, Disposition, serve_bytes};
1817 use crate::state::AppState;
1918
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)
2723 }
2824
2925 /// `GET /thumb/{id}`: the WebP thumbnail of a picture.
@@ -38,13 +34,13 @@ async fn thumb(cx: &Cx) -> Result<ByteAnswer> {
3834 }
3935 let key = thumb_blob_key(&file.id);
4036 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);
4238 // The row holds no hash of the thumbnail bytes, only the validator derived from the file's hash, so
4339 // the thumbnail body is not checked.
4440 let source = ByteSource {
4541 blob_key: &key,
4642 size,
47- sha256: &validator,
43+ validator: &validator,
4844 content_sha256: None,
4945 mime: "image/webp",
5046 name: &file.name,
crates/in-web/src/serve_bytes.rsmodified+16 -7
@@ -49,11 +49,12 @@ pub struct ByteSource<'a> {
4949 pub blob_key: &'a str,
5050 /// Length of the bytes in bytes.
5151 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,
5455 /// The SHA-256 the bytes must hash to, when the bytes are the row's own content. A full-body answer
5556 /// 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.
5758 pub content_sha256: Option<&'a str>,
5859 /// The sniffed MIME type, as stored. It is never the uploader's claim.
5960 pub mime: &'a str,
@@ -164,6 +165,13 @@ fn digits(text: &str) -> Option<u64> {
164165 Some(text.parse().unwrap_or(u64::MAX))
165166 }
166167
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+
167175 /// Whether a conditional request `If-None-Match` names `etag`. Weak tags compare equal to their strong
168176 /// form here, which is the rule for `GET` validators (RFC 9110).
169177 fn none_match_hits(request: &HeaderMap, etag: &str) -> bool {
@@ -199,9 +207,10 @@ fn requested_range(request: &HeaderMap, etag: &str, len: u64) -> Ranged {
199207
200208 /// Whether serving this request counts as a download that started at byte 0. A `304`, a range that
201209 /// 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}\"");
205214 if none_match_hits(request, &etag) {
206215 return false;
207216 }
@@ -346,7 +355,7 @@ pub async fn serve_bytes_with(
346355 cache: &str,
347356 ) -> Result<ByteAnswer> {
348357 let request = headers(cx);
349- let etag = format!("\"{}\"", source.sha256);
358+ let etag = format!("\"{}\"", source.validator);
350359 let disposition = match disposition {
351360 Disposition::Inline if inline_safe(source.mime) => Disposition::Inline,
352361 _ => Disposition::Attachment,
docs/architecture.mdmodified+9 -3
@@ -177,8 +177,10 @@ and has no sessions.
177177 - `target`: a file or folder with owner and trashed state, plus the effective grant (the most permissive grant
178178 on the item or any live ancestor folder) and, for links, whether the item is inside the linked folder.
179179 - `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);
182184 grantee: `List` and `View`, `Download` when `can_download`, never on trashed items; link visitor: the same as
183185 a grantee within the link's subtree; admin: `Administer` only (an admin does **not** read other people's
184186 files); anything else is `NotFound`.
@@ -187,7 +189,11 @@ and has no sessions.
187189
188190 ## 7. Byte serving (one function for every byte route)
189191
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
191197 3.1 a `Range` that is malformed, reversed, or in another unit is ignored (200, whole file); only a valid range
192198 the file cannot satisfy gets 416 with `Content-Range: bytes */<len>`. Several ranges get 200, whole file.
193199 - `Content-Disposition`: `inline` only for image/* (not SVG, not HEIC), video/*, audio/*, application/pdf,