forge
Explore
Log in

Don't you dare go Hollow

View-only grants preview media, never download it

Browse files at this commit

0d80173e50a873d678d93c18b081a13eca3530bcAhmet Kaan GümüşParent: 5cc7c91
  • feat
    • view-only grants preview media, never download it
Show full message
feat(share): view-only grants preview media, never download it

"View only: preview, no downloads" was the promise on the share form, but
the bytes route gated everything on the download grant, so a view-only
reader got no preview at all. Inline bytes now serve to anyone who may see
the file — that is what a preview is — while ?dl=1 stays the stranger's
404 without the grant, and only it moves the counter.

The viewer stage offers no save path: the media elements carry
controlslist=nodownload and draggable=false, and a delegated contextmenu
guard over .viewer-stage keeps "save as" from opening on a preview.
Documents (PDF, text) frame the bytes in the browser's own chrome, whose
toolbar downloads, so they preview only under the grant. Public view-only
links already previewed through the 512px webp thumb and never served raw
bytes; unchanged.

Bytes on the wire can always be captured by a determined reader — the
grant now means the surface never offers the download, which is all a
view-only promise can honestly mean.
crates/in-web/src/files.rsmodified+46 -23
@@ -201,8 +201,9 @@ async fn visible_file(
201 201
202 /// Serves one file's bytes, or the same not-found a stranger would see for202 /// Serves one file's bytes, or the same not-found a stranger would see for
203 /// a file that does not exist — never a `403`, which would confirm the id203 /// a file that does not exist — never a `403`, which would confirm the id
204-/// belongs to somebody else's drive. Only `?dl=1` counts a download: the204+/// belongs to somebody else's drive. Inline bytes are the viewer's preview:
205-/// viewer reads the same bytes inline, and looking is not downloading.205+/// anyone who may see the file reads them. Taking the file away is a
206+/// different act — `?dl=1` needs the download grant, and only it counts.
206 #[route(GET "/file/{id}")]207 #[route(GET "/file/{id}")]
207 async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {208 async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {
208 let id: &str = path_param::<Id>(cx);209 let id: &str = path_param::<Id>(cx);
@@ -218,23 +219,23 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)>
218 let Some(file) = visible_file(store.as_ref(), &user.id, id).await else {219 let Some(file) = visible_file(store.as_ref(), &user.id, id).await else {
219 return Ok(not_found());220 return Ok(not_found());
220 };221 };
221- // A view-only grant opens the file's page but not its bytes.222+ let forced = query_params::<DownloadQuery>(cx)
222- if file.owner_id != user.id223+ .ok()
223- && !store224+ .and_then(|query| query.dl.clone())
225+ .is_some();
226+ // A view-only grant previews but never downloads.
227+ let may_download = file.owner_id == user.id
228+ || store
224 .can_download(ShareKind::File, id, &user.id)229 .can_download(ShareKind::File, id, &user.id)
225 .await230 .await
226- .unwrap_or(false)231+ .unwrap_or(false);
227- {232+ if forced && !may_download {
228 return Ok(not_found());233 return Ok(not_found());
229 }234 }
230 let Ok(Some(bytes)) = store.file_bytes(id).await else {235 let Ok(Some(bytes)) = store.file_bytes(id).await else {
231 return Ok(not_found());236 return Ok(not_found());
232 };237 };
233 238
234- let forced = query_params::<DownloadQuery>(cx)
235- .ok()
236- .and_then(|query| query.dl.clone())
237- .is_some();
238 let inline = !forced && inline_ok(&file.mime);239 let inline = !forced && inline_ok(&file.mime);
239 240
240 let mut headers = HeaderMap::new();241 let mut headers = HeaderMap::new();
@@ -432,11 +433,14 @@ fn is_archive_mime(mime: &str) -> bool {
432 433
433 /// `GET /view/{id}`: one file's viewer page — its name, the inline viewer434 /// `GET /view/{id}`: one file's viewer page — its name, the inline viewer
434 /// for its kind, a download link and its details. Authorization mirrors435 /// for its kind, a download link and its details. Authorization mirrors
435-/// trashed files open for nobody. A view-only grant opens the page but not436+/// trashed files open for nobody. Anyone who may see the file gets the
436-/// the bytes: the download link shows only while the reader may download,437+/// media preview — "view only" means preview, no download: the media
437-/// and the inline viewer gives way to the unavailable note, since every438+/// elements carry no save affordance (no download in the controls, no
438-/// viewer element reads the same gated bytes. Bytes for another owner's439+/// drag, no context menu — `viewer_guard_script`), the Download link shows
439-/// file answer 404, not 403.440+/// only while the reader may download, and `?dl=1` stays gated on the
441+/// byte route. Documents (PDF, text) frame the bytes in the browser's own
442+/// chrome, whose toolbar downloads — they preview only under the grant.
443+/// Bytes for another owner's file answer 404, not 403.
440 #[page("/view/{id}")]444 #[page("/view/{id}")]
441 async fn view_file(cx: &Cx) -> Result {445 async fn view_file(cx: &Cx) -> Result {
442 let id: &str = path_param::<Id>(cx);446 let id: &str = path_param::<Id>(cx);
@@ -486,11 +490,13 @@ async fn view_file(cx: &Cx) -> Result {
486 <h1 class="settings-title viewer-title">(entry_chip(cx, &file).await?) (file.name.clone())</h1>490 <h1 class="settings-title viewer-title">(entry_chip(cx, &file).await?) (file.name.clone())</h1>
487 <p class="field-note">(meta)</p>491 <p class="field-note">(meta)</p>
488 <div class="viewer-stage">492 <div class="viewer-stage">
489- if may_download {493+ // Media previews for every reader; documents only under the
494+ // download grant (their browser chrome saves the file).
495+ if matches!(viewer_kind(&file.mime), Some(ViewerKind::Image | ViewerKind::Video | ViewerKind::Audio)) || may_download {
490 match viewer_kind(&file.mime) {496 match viewer_kind(&file.mime) {
491- Some(ViewerKind::Image) => <img class="viewer-media" src=(src.clone()) alt=(file.name.clone())>,497+ Some(ViewerKind::Image) => <img class="viewer-media" src=(src.clone()) alt=(file.name.clone()) draggable="false">,
492- Some(ViewerKind::Video) => <video class="viewer-media" src=(src.clone()) controls="" preload="metadata"></video>,498+ Some(ViewerKind::Video) => <video class="viewer-media" src=(src.clone()) controls="" controlslist="nodownload" preload="metadata"></video>,
493- Some(ViewerKind::Audio) => <div class="viewer-audio-wrap"><audio class="viewer-audio" src=(src.clone()) controls="" preload="metadata"></audio></div>,499+ Some(ViewerKind::Audio) => <div class="viewer-audio-wrap"><audio class="viewer-audio" src=(src.clone()) controls="" controlslist="nodownload" preload="metadata"></audio></div>,
494 Some(ViewerKind::Pdf) => <object class="viewer-media viewer-pdf" data=(src.clone()) type="application/pdf">500 Some(ViewerKind::Pdf) => <object class="viewer-media viewer-pdf" data=(src.clone()) type="application/pdf">
495 <p class="field-note">(t(language, Key::PreviewUnavailable))</p>501 <p class="field-note">(t(language, Key::PreviewUnavailable))</p>
496 </object>,502 </object>,
@@ -500,9 +506,6 @@ async fn view_file(cx: &Cx) -> Result {
500 </div>506 </div>
501 }507 }
502 } else {508 } else {
503- // A view-only grant opens the page but not the bytes, so
504- // the viewer elements — every one reads /file/{id} —
505- // would only frame a 404. The note instead.
506 <div class="viewer-fallback">509 <div class="viewer-fallback">
507 <p class="field-note">(t(language, Key::PreviewUnavailable))</p>510 <p class="field-note">(t(language, Key::PreviewUnavailable))</p>
508 </div>511 </div>
@@ -528,9 +531,29 @@ async fn view_file(cx: &Cx) -> Result {
528 </div>531 </div>
529 </section>532 </section>
530 </main>533 </main>
534+ (viewer_guard_script(cx).await?)
531 }535 }
532 }536 }
533 537
538+/// The preview's save-path cleanup: the media elements already carry no
539+/// download affordance (`controlslist="nodownload"`, `draggable="false"`),
540+/// and this drops the context menu over the stage, so "save as" never
541+/// opens on a preview. A page's bytes on the wire can always be captured —
542+/// this keeps the surface from offering it, which is what a view-only
543+/// grant promises.
544+async fn viewer_guard_script(cx: &Cx) -> Result {
545+ use topcoat::view::Unescaped;
546+ const JS: &str = "\
547+ (function () { \
548+ if (window.__inViewerGuard) { return; } \
549+ window.__inViewerGuard = true; \
550+ document.addEventListener('contextmenu', function (e) { \
551+ if (e.target && e.target.closest && e.target.closest('.viewer-stage')) { e.preventDefault(); } \
552+ }); \
553+ })();";
554+ view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }
555+}
556+
534 /// Takes the files the drive's upload form carries — one per `file` part,557 /// Takes the files the drive's upload form carries — one per `file` part,
535 /// and a `multiple` picker posts several. The route's body guard sits at 2558 /// and a `multiple` picker posts several. The route's body guard sits at 2
536 /// GiB (`main.rs`); each part is buffered whole because the store writes559 /// GiB (`main.rs`); each part is buffered whole because the store writes
crates/in-web/tests/http.rsmodified+54 -0
@@ -1639,6 +1639,60 @@ async fn per_user_share_lands_in_shared_with_me() {
1639 assert!(!bobs.text().contains("joint.txt"), "{}", bobs.text());1639 assert!(!bobs.text().contains("joint.txt"), "{}", bobs.text());
1640 }1640 }
1641 1641
1642+/// View only means preview, no download: the reader sees the media inline
1643+/// on the viewer page and reads the inline bytes, while `?dl=1` stays dead
1644+/// and the page never offers the Download link.
1645+#[tokio::test]
1646+async fn view_only_reader_previews_media_but_cannot_download() {
1647+ let app = TestApp::build().await;
1648+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1649+ let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
1650+ let owner = owner_of(&app, "sub-admin").await;
1651+ let file = file_id(
1652+ &app,
1653+ &owner,
1654+ "photo.png",
1655+ b"\x89PNG\r\n\x1a\n preview bytes",
1656+ )
1657+ .await;
1658+
1659+ let answer = app
1660+ .post(
1661+ "/api/share/user/add",
1662+ Some(&admin),
1663+ &[
1664+ ("kind", "file"),
1665+ ("target_id", &file),
1666+ ("email", "bob@in.test"),
1667+ ("can_download", "0"),
1668+ ],
1669+ )
1670+ .await;
1671+ assert!(answer.accepted(), "add refused: {:?}", answer.location);
1672+
1673+ // The viewer page renders the media, not the unavailable note, and
1674+ // offers no download.
1675+ let page = app.get(&format!("/view/{file}"), Some(&bob)).await;
1676+ assert_eq!(page.status, StatusCode::OK, "{}", page.text());
1677+ assert!(page.text().contains("viewer-media"), "{}", page.text());
1678+ assert!(!page.text().contains("No preview"), "{}", page.text());
1679+ assert!(!page.text().contains("?dl=1"), "{}", page.text());
1680+
1681+ // The inline bytes serve for the preview...
1682+ let inline = app.get(&format!("/file/{file}"), Some(&bob)).await;
1683+ assert_eq!(inline.status, StatusCode::OK, "{}", inline.text());
1684+ assert_eq!(inline.bytes, b"\x89PNG\r\n\x1a\n preview bytes");
1685+ // ...and taking the file away stays the stranger's answer.
1686+ let taken = app.get(&format!("/file/{file}?dl=1"), Some(&bob)).await;
1687+ assert_eq!(taken.status, StatusCode::NOT_FOUND, "{}", taken.text());
1688+
1689+ // A preview is not a download: the counter never moves.
1690+ assert_eq!(
1691+ app.store.file(&file).await.unwrap().unwrap().download_count,
1692+ 0
1693+ );
1694+}
1695+
1642 // -- trash ------------------------------------------------------------------1696 // -- trash ------------------------------------------------------------------
1643 1697
1644 #[tokio::test]1698 #[tokio::test]