From 9c306fbb4206f5e9ca8e2a3ed8a8c7c2ecf40526 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 10:26:47 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20sharing:=20per-person=20gra?= =?UTF-8?q?nts,=20shared=20page,=20share=20links=20with=20password=20gate?= =?UTF-8?q?=20and=20throttle,=20public=20share=20pages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/in-core/src/secret.rs | 32 ++ crates/in-core/src/store/links.rs | 325 +++++++++++ crates/in-core/src/store/mod.rs | 2 + crates/in-core/src/store/shares.rs | 611 ++++++++++++++++++++ crates/in-web/src/boot.rs | 3 + crates/in-web/src/i18n/drive.rs | 4 +- crates/in-web/src/i18n/mod.rs | 1 + crates/in-web/src/i18n/share.rs | 280 +++++++++ crates/in-web/src/main.rs | 1 + crates/in-web/src/pages/drive.rs | 173 +++++- crates/in-web/src/pages/files.rs | 8 +- crates/in-web/src/pages/links.rs | 292 ++++++++++ crates/in-web/src/pages/mod.rs | 4 + crates/in-web/src/pages/public_share.rs | 720 ++++++++++++++++++++++++ crates/in-web/src/pages/share_dialog.rs | 484 ++++++++++++++++ crates/in-web/src/pages/shared.rs | 152 +++++ crates/in-web/src/pages/view.rs | 70 ++- crates/in-web/src/security.rs | 55 +- crates/in-web/src/serve_bytes.rs | 28 +- crates/in-web/src/state.rs | 3 + crates/in-web/src/throttle.rs | 115 ++++ crates/in-web/src/views/drive.rs | 60 +- crates/in-web/src/views/mod.rs | 3 + 23 files changed, 3360 insertions(+), 66 deletions(-) create mode 100644 crates/in-core/src/store/links.rs create mode 100644 crates/in-core/src/store/shares.rs create mode 100644 crates/in-web/src/i18n/share.rs create mode 100644 crates/in-web/src/pages/links.rs create mode 100644 crates/in-web/src/pages/public_share.rs create mode 100644 crates/in-web/src/pages/share_dialog.rs create mode 100644 crates/in-web/src/pages/shared.rs create mode 100644 crates/in-web/src/throttle.rs diff --git a/crates/in-core/src/secret.rs b/crates/in-core/src/secret.rs index 4b38675..26f0074 100644 --- a/crates/in-core/src/secret.rs +++ b/crates/in-core/src/secret.rs @@ -6,6 +6,8 @@ use std::path::Path; use base64::prelude::{BASE64_STANDARD, Engine as _}; use chacha20poly1305::aead::Aead; use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce}; +use hmac::{Hmac, Mac}; +use sha2::Sha256; use crate::error::{Error, Result}; @@ -94,6 +96,20 @@ pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result { Ok(format!("{PREFIX}{}", BASE64_STANDARD.encode(blob))) } +/// The proof a share-link visitor holds after the right password: an HMAC-SHA256 under the instance key +/// over the link id and the stored password hash, in lower-case hex. Changing the password or reminting +/// the link changes one of those inputs, so every old proof stops working. It is a cookie value, so the +/// key never leaves the server and the password itself is never stored in a cookie. +pub fn unlock_proof(key: &[u8; 32], link_id: &str, password_hash: &str) -> String { + let mut mac = as hmac::KeyInit>::new_from_slice(key) + .expect("HMAC accepts a key of any length"); + mac.update(b"link-unlock:"); + mac.update(link_id.as_bytes()); + mac.update(b"|"); + mac.update(password_hash.as_bytes()); + hex::encode(mac.finalize().into_bytes()) +} + /// Opens a value produced by [`seal`]. A wrong key, a changed byte or a malformed value is an error. pub fn open(key: &[u8; 32], sealed: &str) -> Result> { let encoded = sealed @@ -135,3 +151,19 @@ mod tests { assert!(open(&key, "data").is_err(), "missing prefix must fail"); } } + +#[cfg(test)] +mod proof_tests { + use super::*; + + #[test] + fn an_unlock_proof_changes_with_any_input() { + let key = [7u8; 32]; + let base = unlock_proof(&key, "link-a", "$argon2id$hash"); + assert_eq!(base.len(), 64); + assert_eq!(base, unlock_proof(&key, "link-a", "$argon2id$hash")); + assert_ne!(base, unlock_proof(&key, "link-b", "$argon2id$hash")); + assert_ne!(base, unlock_proof(&key, "link-a", "$argon2id$other")); + assert_ne!(base, unlock_proof(&[8u8; 32], "link-a", "$argon2id$hash")); + } +} diff --git a/crates/in-core/src/store/links.rs b/crates/in-core/src/store/links.rs new file mode 100644 index 0000000..6366f12 --- /dev/null +++ b/crates/in-core/src/store/links.rs @@ -0,0 +1,325 @@ +//! Public share links (architecture sections 3 and 8). A link names one file or folder and carries the +//! token's SHA-256 (the token itself is never stored in the clear), a sealed copy of the token so the owner +//! can show the URL again, the download flag, an optional argon2id password hash and an expiry. +//! +//! This module stores and finds links. Whether a visitor may see something through a link is decided by +//! the web layer with `authz` (the link actor) and the store's `is_within` and `item_trashed`. + +use turso::{Connection, Row}; + +use crate::error::{Error, Result}; +use crate::store::files::live_file; +use crate::store::folders::live_folder; +use crate::store::shares::{kind_from_word, kind_word}; +use crate::store::trash::ItemKind; +use crate::store::{ + Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, missing_row, + new_id, +}; +use crate::time::now_stamp; + +/// Column list for [`map_link`]. Keep the two in step. +pub const LINK_COLS: &str = "id, token_hash, token_sealed, target_kind, target_id, owner, can_download, \ + password_hash, expires_at, revoked_at, created_at, last_used_at, use_count"; + +/// One row of the `links` table. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Link { + /// Link id (a lower-case ULID). It names the unlock cookie. + pub id: String, + /// Hex SHA-256 of the token. Lookups go through it. + pub token_hash: String, + /// The token, sealed under the instance key, so the owner can show the URL again. + pub token_sealed: String, + /// Whether the target is a file or a folder. + pub kind: ItemKind, + /// The file or folder the link opens. For a folder, everything below it too. + pub target_id: String, + /// The owner of the target, who made the link. + pub owner: String, + /// Whether visitors may download, not only view. + pub can_download: bool, + /// The argon2id hash of the password, when the link has one. + pub password_hash: Option, + /// When the link stops working, if it has an expiry. + pub expires_at: Option, + /// When the link was revoked. A revoked link never works again. + pub revoked_at: Option, + /// When the link was made. + pub created_at: String, + /// The last time a visitor opened the link's page. + pub last_used_at: Option, + /// How many times a visitor opened the link's page. + pub use_count: i64, +} + +impl Link { + /// Whether the link still works at `now` (a stamp of this format): not revoked and not expired. + /// The target's own trash state is checked separately. + pub fn is_live(&self, now: &str) -> bool { + self.revoked_at.is_none() && self.expires_at.as_deref().is_none_or(|at| at > now) + } +} + +/// What a new link needs. The token is generated and sealed by the caller. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NewLink { + /// Id, made by the caller so it is known before the insert. + pub id: String, + /// Hex SHA-256 of the token. + pub token_hash: String, + /// The sealed token. + pub token_sealed: String, + /// Whether the target is a file or a folder. + pub kind: ItemKind, + /// The target's id. + pub target_id: String, + /// The owner, who must own the live target. + pub owner: String, + /// Whether visitors may download. + pub can_download: bool, + /// The argon2id hash of the password, if any. + pub password_hash: Option, + /// When the link stops working, if it has an expiry. + pub expires_at: Option, +} + +/// Maps a row selected with [`LINK_COLS`]. +fn map_link(row: &Row) -> Result { + let kind = kind_from_word(&col_text(row, 3)?) + .ok_or_else(|| Error::Database("link with an unknown target kind".into()))?; + Ok(Link { + id: col_text(row, 0)?, + token_hash: col_text(row, 1)?, + token_sealed: col_text(row, 2)?, + kind, + target_id: col_text(row, 4)?, + owner: col_text(row, 5)?, + can_download: col_int(row, 6)? != 0, + password_hash: col_opt_text(row, 7)?, + expires_at: col_opt_text(row, 8)?, + revoked_at: col_opt_text(row, 9)?, + created_at: col_text(row, 10)?, + last_used_at: col_opt_text(row, 11)?, + use_count: col_int(row, 12)?, + }) +} + +/// Inserts a link row. The caller has checked the target and runs inside a transaction. +async fn insert_link_in(conn: &Connection, new: &NewLink) -> Result<()> { + conn.execute( + "INSERT INTO links (id, token_hash, token_sealed, target_kind, target_id, owner, can_download, \ + password_hash, expires_at, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", + ( + new.id.clone(), + new.token_hash.clone(), + new.token_sealed.clone(), + kind_word(new.kind).to_string(), + new.target_id.clone(), + new.owner.clone(), + i64::from(new.can_download), + new.password_hash.clone(), + new.expires_at.clone(), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + Ok(()) +} + +/// The link with this id that `owner` made, revoked or not. +async fn link_of_owner(conn: &Connection, owner: &str, id: &str) -> Result> { + fetch_opt( + conn, + &format!("SELECT {LINK_COLS} FROM links WHERE id = ?1 AND owner = ?2"), + (id.to_string(), owner.to_string()), + map_link, + ) + .await +} + +/// Checks that `owner` owns a live (not trashed) target. Anything else is `NotFound`. +async fn check_target(conn: &Connection, owner: &str, kind: ItemKind, id: &str) -> Result<()> { + match kind { + ItemKind::File => live_file(conn, owner, id).await.map(|_| ()), + ItemKind::Folder => live_folder(conn, owner, id).await.map(|_| ()), + } +} + +impl Store { + /// Creates a link to a live item of `owner`. + pub async fn create_link(&self, new: NewLink) -> Result { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + check_target(&tx, &new.owner, new.kind, &new.target_id).await?; + insert_link_in(&tx, &new).await?; + link_of_owner(&tx, &new.owner, &new.id) + .await? + .ok_or_else(missing_row) + } + .await; + finish(tx, outcome).await + } + + /// The links of `owner` that have not been revoked, oldest first. Expired ones are included, so the + /// owner sees why a link stopped. + pub async fn links_of(&self, owner: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {LINK_COLS} FROM links WHERE owner = ?1 AND revoked_at IS NULL \ + ORDER BY created_at, id" + ), + (owner.to_string(),), + map_link, + ) + .await + } + + /// The link with this id, if `owner` made it (revoked links included). + pub async fn link_of(&self, owner: &str, id: &str) -> Result> { + let conn = self.read_conn().await; + link_of_owner(&conn, owner, id).await + } + + /// Revokes a link of `owner`. Revoking again changes nothing. + pub async fn revoke_link(&self, owner: &str, id: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE links SET revoked_at = COALESCE(revoked_at, ?3) WHERE id = ?1 AND owner = ?2", + (id.to_string(), owner.to_string(), now_stamp()), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Err(Error::NotFound); + } + Ok(()) + } + + /// Gives a live link of `owner` a new token and kills the old one, in one transaction. The new link + /// keeps the target, the download flag, the password and the expiry. A link that is already revoked, + /// or expired, cannot be reminted: `NotFound` for a revoked one, `Conflict("link_expired")` for an + /// expired one. + pub async fn remint_link( + &self, + owner: &str, + id: &str, + token_hash: &str, + token_sealed: &str, + ) -> Result { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let old = link_of_owner(&tx, owner, id).await?.ok_or(Error::NotFound)?; + if old.revoked_at.is_some() { + return Err(Error::NotFound); + } + if !old.is_live(&now_stamp()) { + return Err(Error::Conflict("link_expired".into())); + } + let new = NewLink { + id: new_id(), + token_hash: token_hash.to_string(), + token_sealed: token_sealed.to_string(), + kind: old.kind, + target_id: old.target_id.clone(), + owner: owner.to_string(), + can_download: old.can_download, + password_hash: old.password_hash.clone(), + expires_at: old.expires_at.clone(), + }; + insert_link_in(&tx, &new).await?; + tx.execute( + "UPDATE links SET revoked_at = ?3 WHERE id = ?1 AND owner = ?2 AND revoked_at IS NULL", + (id.to_string(), owner.to_string(), now_stamp()), + ) + .await + .map_err(db_err)?; + link_of_owner(&tx, owner, &new.id) + .await? + .ok_or_else(missing_row) + } + .await; + finish(tx, outcome).await + } + + /// The link whose token hashes to `token_hash`, whatever its state. The caller decides whether it + /// still works. + pub async fn link_by_token_hash(&self, token_hash: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!("SELECT {LINK_COLS} FROM links WHERE token_hash = ?1"), + (token_hash.to_string(),), + map_link, + ) + .await + } + + /// Counts one visit to a link's page and stamps it. + pub async fn touch_link(&self, id: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE links SET last_used_at = ?2, use_count = use_count + 1 WHERE id = ?1", + (id.to_string(), now_stamp()), + ) + .await + .map_err(db_err)?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::store::test_support::store_with_member; + + #[tokio::test] + async fn remint_moves_the_link_to_a_new_token_and_kills_the_old() { + let (_dir, store) = store_with_member("ann").await; + let folder = store.create_folder("ann", None, "Trips").await.unwrap(); + let link = store + .create_link(NewLink { + id: new_id(), + token_hash: "a".repeat(64), + token_sealed: "v1:old".into(), + kind: ItemKind::Folder, + target_id: folder.id.clone(), + owner: "ann".into(), + can_download: true, + password_hash: None, + expires_at: Some(crate::time::stamp_after(std::time::Duration::from_secs(60))), + }) + .await + .unwrap(); + let fresh = store + .remint_link("ann", &link.id, &"b".repeat(64), "v1:new") + .await + .unwrap(); + assert!(fresh.can_download); + assert_eq!(fresh.expires_at, link.expires_at); + assert!( + store + .link_by_token_hash(&"a".repeat(64)) + .await + .unwrap() + .unwrap() + .revoked_at + .is_some() + ); + assert!( + store + .link_by_token_hash(&"b".repeat(64)) + .await + .unwrap() + .unwrap() + .revoked_at + .is_none() + ); + } +} diff --git a/crates/in-core/src/store/mod.rs b/crates/in-core/src/store/mod.rs index d2009c9..43db051 100644 --- a/crates/in-core/src/store/mod.rs +++ b/crates/in-core/src/store/mod.rs @@ -6,10 +6,12 @@ pub mod files; pub mod folders; +pub mod links; pub mod members; pub mod migrate; pub mod sessions; pub mod settings; +pub mod shares; pub mod snapshot; pub mod trash; pub mod uploads; diff --git a/crates/in-core/src/store/shares.rs b/crates/in-core/src/store/shares.rs new file mode 100644 index 0000000..e8624dd --- /dev/null +++ b/crates/in-core/src/store/shares.rs @@ -0,0 +1,611 @@ +//! Per-person shares (architecture sections 3 and 6): a grant gives one grantee a level on one file or +//! folder, `View`, or `Download` when `can_download` is set. A grant on a folder reaches everything below +//! it. That reach is computed every time access is checked, by walking the live ancestors of the item; no +//! grant is copied down the tree. So an item that leaves a granted folder loses the access on the next +//! check, with nothing to clean up. +//! +//! This module decides what the grants are and what reach they have ([`Access`]). Deciding what a viewer +//! may do with the item stays in `authz`. A grantee must be a current member (not disabled) and not the +//! owner; both are checked when a grant is written. + +use turso::{Connection, Row}; + +use crate::authz::Grant; +use crate::error::{Error, Result}; +use crate::store::files::{File, file_by_id, live_file}; +use crate::store::folders::{Folder, folder_by_id, has_trashed_chain, live_folder}; +use crate::store::trash::ItemKind; +use crate::store::{ + Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish, missing_row, new_id, +}; +use crate::time::now_stamp; + +/// Column list for [`map_share`]. Keep the two in step. +pub const SHARE_COLS: &str = "id, target_kind, target_id, owner, grantee, can_download, created_at"; + +/// Deepest folder chain the walks follow. Matches the folder module's bound. +const MAX_DEPTH: usize = 512; + +/// The word a target kind has in the database and in URLs. +pub fn kind_word(kind: ItemKind) -> &'static str { + match kind { + ItemKind::File => "file", + ItemKind::Folder => "folder", + } +} + +/// The kind named by a URL or database word, or `None` for anything else. +pub fn kind_from_word(word: &str) -> Option { + match word { + "file" => Some(ItemKind::File), + "folder" => Some(ItemKind::Folder), + _ => None, + } +} + +/// One row of the `grants` table. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Share { + /// Grant id (a lower-case ULID). + pub id: String, + /// Whether the target is a file or a folder. + pub kind: ItemKind, + /// The file or folder shared. + pub target_id: String, + /// The owner of the target, who made the grant. + pub owner: String, + /// The person the target is shared with. + pub grantee: String, + /// Whether the grantee may download (the `Download` level) or only see (`View`). + pub can_download: bool, + /// When the grant was made or last changed its level. + pub created_at: String, +} + +/// The reach a person has on one item, computed from the grants on the item and its live ancestors. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Access { + /// Whether the item or one of its ancestors is in the trash. Trashed items are never shown to grantees. + pub trashed: bool, + /// The most permissive grant that reaches the item for this person. + pub grant: Grant, +} + +/// A grant as its owner sees it: the grant and the name and email of the grantee. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ShareEntry { + /// The grant. + pub share: Share, + /// The grantee's display name. + pub grantee_name: String, + /// The grantee's email address. + pub grantee_email: String, +} + +/// An item shared with a person at the top level, as the person sees it on the shared page. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SharedItem { + /// The grant that reaches the person. + pub share: Share, + /// The item's name. + pub name: String, + /// The item's MIME type; empty for a folder. + pub mime: String, + /// The item's size in bytes; zero for a folder. + pub size: i64, + /// The owner's display name. + pub owner_name: String, +} + +/// Maps a row selected with [`SHARE_COLS`] (the first seven columns of a query). +fn map_share(row: &Row) -> Result { + let kind = kind_from_word(&col_text(row, 1)?) + .ok_or_else(|| Error::Database("grant with an unknown target kind".into()))?; + Ok(Share { + id: col_text(row, 0)?, + kind, + target_id: col_text(row, 2)?, + owner: col_text(row, 3)?, + grantee: col_text(row, 4)?, + can_download: col_int(row, 5)? != 0, + created_at: col_text(row, 6)?, + }) +} + +/// The level a grant flag gives. +fn level(can_download: bool) -> Grant { + if can_download { + Grant::Download + } else { + Grant::View + } +} + +/// The state an access check needs: whether the item is trashed (itself or through an ancestor) and the +/// folder it sits in. `None` when no such item exists. +async fn trashed_state( + conn: &Connection, + kind: ItemKind, + id: &str, +) -> Result)>> { + let own = match kind { + ItemKind::File => file_by_id(conn, id) + .await? + .map(|f: File| (f.trashed_at.is_some(), f.folder_id)), + ItemKind::Folder => folder_by_id(conn, id) + .await? + .map(|f: Folder| (f.trashed_at.is_some(), f.parent_id)), + }; + let Some((own_trashed, parent)) = own else { + return Ok(None); + }; + let trashed = own_trashed || has_trashed_chain(conn, parent.as_deref()).await?; + Ok(Some((trashed, parent))) +} + +/// The folder ids from `start` up to the top level, `start` first. Empty for `None`. +async fn chain_from(conn: &Connection, start: Option<&str>) -> Result> { + let mut out = Vec::new(); + let mut cur = start.map(str::to_string); + while let Some(id) = cur { + if out.len() >= MAX_DEPTH { + return Err(Error::Database("folder tree is too deep".into())); + } + let Some(folder) = folder_by_id(conn, &id).await? else { + break; + }; + cur = folder.parent_id; + out.push(id); + } + Ok(out) +} + +/// The grant flag `grantee` holds directly on the item, if there is a grant on exactly that item. +async fn direct( + conn: &Connection, + grantee: &str, + kind: ItemKind, + id: &str, +) -> Result> { + fetch_opt( + conn, + "SELECT can_download FROM grants WHERE target_kind = ?1 AND target_id = ?2 AND grantee = ?3", + ( + kind_word(kind).to_string(), + id.to_string(), + grantee.to_string(), + ), + |row| Ok(col_int(row, 0)? != 0), + ) + .await +} + +/// The access `grantee` has to an item: its own grant and the grants on every ancestor folder, the most +/// permissive one wins. `None` when the item does not exist. +pub(crate) async fn access_in( + conn: &Connection, + grantee: &str, + kind: ItemKind, + id: &str, +) -> Result> { + let Some((trashed, parent)) = trashed_state(conn, kind, id).await? else { + return Ok(None); + }; + let mut grant = Grant::None; + if let Some(can_download) = direct(conn, grantee, kind, id).await? { + grant = grant.max(level(can_download)); + } + for folder in chain_from(conn, parent.as_deref()).await? { + if let Some(can_download) = direct(conn, grantee, ItemKind::Folder, &folder).await? { + grant = grant.max(level(can_download)); + } + } + Ok(Some(Access { trashed, grant })) +} + +/// Whether an ancestor folder of the item (from `parent` up) carries a grant to `grantee`. +async fn granted_above(conn: &Connection, grantee: &str, parent: Option<&str>) -> Result { + for folder in chain_from(conn, parent).await? { + if direct(conn, grantee, ItemKind::Folder, &folder) + .await? + .is_some() + { + return Ok(true); + } + } + Ok(false) +} + +/// The grant row of `owner` with this id. +async fn share_by_id(conn: &Connection, owner: &str, id: &str) -> Result> { + fetch_opt( + conn, + &format!("SELECT {SHARE_COLS} FROM grants WHERE id = ?1 AND owner = ?2"), + (id.to_string(), owner.to_string()), + map_share, + ) + .await +} + +impl Store { + /// The access `grantee` has to an item, or `None` when the item does not exist. Authorise with it; + /// a missing item and an item the person cannot reach must both look like "not found". + pub async fn access_of( + &self, + grantee: &str, + kind: ItemKind, + id: &str, + ) -> Result> { + let conn = self.read_conn().await; + access_in(&conn, grantee, kind, id).await + } + + /// Whether the item is trashed (itself or through an ancestor). `None` when it does not exist. + pub async fn item_trashed(&self, kind: ItemKind, id: &str) -> Result> { + let conn = self.read_conn().await; + Ok(trashed_state(&conn, kind, id) + .await? + .map(|(trashed, _)| trashed)) + } + + /// Shares a live item of `owner` with `grantee` at the given level. A grant that already exists only + /// changes its level. The grantee must be a current member other than the owner. + pub async fn share_with( + &self, + owner: &str, + kind: ItemKind, + target_id: &str, + grantee: &str, + can_download: bool, + ) -> Result { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + match kind { + ItemKind::File => { + live_file(&tx, owner, target_id).await?; + } + ItemKind::Folder => { + live_folder(&tx, owner, target_id).await?; + } + } + if owner == grantee { + return Err(Error::Invalid("self_share".into())); + } + let disabled = fetch_opt( + &tx, + "SELECT disabled FROM members WHERE sub = ?1", + (grantee.to_string(),), + |row| col_int(row, 0), + ) + .await?; + if disabled != Some(0) { + return Err(Error::Invalid("no_such_member".into())); + } + tx.execute( + "INSERT INTO grants (id, target_kind, target_id, owner, grantee, can_download, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) \ + ON CONFLICT (target_kind, target_id, grantee) DO UPDATE SET can_download = excluded.can_download", + ( + new_id(), + kind_word(kind).to_string(), + target_id.to_string(), + owner.to_string(), + grantee.to_string(), + i64::from(can_download), + now_stamp(), + ), + ) + .await + .map_err(db_err)?; + fetch_opt( + &tx, + &format!( + "SELECT {SHARE_COLS} FROM grants WHERE owner = ?1 AND target_kind = ?2 \ + AND target_id = ?3 AND grantee = ?4" + ), + ( + owner.to_string(), + kind_word(kind).to_string(), + target_id.to_string(), + grantee.to_string(), + ), + map_share, + ) + .await? + .ok_or_else(missing_row) + } + .await; + finish(tx, outcome).await + } + + /// The grant with this id, if `owner` made it. + pub async fn share_of(&self, owner: &str, id: &str) -> Result> { + let conn = self.read_conn().await; + share_by_id(&conn, owner, id).await + } + + /// Changes the level of a grant that `owner` made. + pub async fn set_share_level( + &self, + owner: &str, + share_id: &str, + can_download: bool, + ) -> Result { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE grants SET can_download = ?3 WHERE id = ?1 AND owner = ?2", + ( + share_id.to_string(), + owner.to_string(), + i64::from(can_download), + ), + ) + .await + .map_err(db_err)?; + if changed == 0 { + return Err(Error::NotFound); + } + share_by_id(&conn, owner, share_id) + .await? + .ok_or(Error::NotFound) + } + + /// Removes a grant that `owner` made and returns it, so the caller can tell the grantee. + pub async fn remove_share(&self, owner: &str, share_id: &str) -> Result { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let share = share_by_id(&tx, owner, share_id) + .await? + .ok_or(Error::NotFound)?; + tx.execute( + "DELETE FROM grants WHERE id = ?1 AND owner = ?2", + (share_id.to_string(), owner.to_string()), + ) + .await + .map_err(db_err)?; + Ok(share) + } + .await; + finish(tx, outcome).await + } + + /// Every grant on one item of `owner`, by grantee name. + pub async fn shares_of( + &self, + owner: &str, + kind: ItemKind, + target_id: &str, + ) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {SHARE_COLS}, m.name, m.email FROM grants \ + JOIN members m ON m.sub = grants.grantee \ + WHERE grants.owner = ?1 AND grants.target_kind = ?2 AND grants.target_id = ?3 \ + ORDER BY m.name, grants.id" + ), + ( + owner.to_string(), + kind_word(kind).to_string(), + target_id.to_string(), + ), + |row| { + Ok(ShareEntry { + share: map_share(row)?, + grantee_name: col_text(row, 7)?, + grantee_email: col_text(row, 8)?, + }) + }, + ) + .await + } + + /// The items shared with `grantee` at the top level: live grants whose item is not trashed and that no + /// ancestor folder already carries. Items under a shared folder are reached through that folder. + pub async fn shared_with(&self, grantee: &str) -> Result> { + let conn = self.read_conn().await; + let grants = fetch_all( + &conn, + &format!("SELECT {SHARE_COLS} FROM grants WHERE grantee = ?1 ORDER BY created_at, id"), + (grantee.to_string(),), + map_share, + ) + .await?; + let mut out = Vec::new(); + for share in grants { + let Some((trashed, parent)) = + trashed_state(&conn, share.kind, &share.target_id).await? + else { + continue; + }; + if trashed || granted_above(&conn, grantee, parent.as_deref()).await? { + continue; + } + let (name, mime, size) = match share.kind { + ItemKind::File => match file_by_id(&conn, &share.target_id).await? { + Some(file) => (file.name, file.mime, file.size), + None => continue, + }, + ItemKind::Folder => match folder_by_id(&conn, &share.target_id).await? { + Some(folder) => (folder.name, String::new(), 0), + None => continue, + }, + }; + let owner_name = fetch_opt( + &conn, + "SELECT name FROM members WHERE sub = ?1", + (share.owner.clone(),), + |row| col_text(row, 0), + ) + .await? + .unwrap_or_default(); + out.push(SharedItem { + share, + name, + mime, + size, + owner_name, + }); + } + Ok(out) + } + + /// The folders from the topmost ancestor-or-self of `folder` that carries `root` down to `folder`, + /// for breadcrumbs. Empty when `folder` is not inside `root`. Nothing above `root` is returned. + pub async fn folder_trail_to(&self, root: &str, folder: &str) -> Result> { + let conn = self.read_conn().await; + let chain = chain_from(&conn, Some(folder)).await?; + let Some(top) = chain.iter().position(|id| id == root) else { + return Ok(Vec::new()); + }; + let mut trail = Vec::with_capacity(top + 1); + for id in chain[..=top].iter().rev() { + if let Some(row) = folder_by_id(&conn, id).await? { + trail.push(row); + } + } + Ok(trail) + } + + /// The breadcrumbs a grantee sees for `folder`: from the topmost folder of its chain that the grantee + /// has a grant on, down to `folder`. Folders above that grant are never returned. Empty when the + /// grantee has no grant on the folder or any ancestor. + pub async fn shared_trail(&self, grantee: &str, folder: &str) -> Result> { + let root = { + let conn = self.read_conn().await; + let mut top = None; + for id in chain_from(&conn, Some(folder)).await? { + if direct(&conn, grantee, ItemKind::Folder, &id) + .await? + .is_some() + { + top = Some(id); + } + } + top + }; + match root { + Some(root) => self.folder_trail_to(&root, folder).await, + None => Ok(Vec::new()), + } + } + + /// Whether the item lies inside a share root. A file root holds only itself. A folder root holds + /// itself and every folder and file below it. The item's own trash state is not checked here. + pub async fn is_within( + &self, + root_kind: ItemKind, + root_id: &str, + kind: ItemKind, + id: &str, + ) -> Result { + match root_kind { + ItemKind::File => Ok(kind == ItemKind::File && id == root_id), + ItemKind::Folder => { + if kind == ItemKind::Folder && id == root_id { + return Ok(true); + } + let conn = self.read_conn().await; + let Some((_, parent)) = trashed_state(&conn, kind, id).await? else { + return Ok(false); + }; + Ok(chain_from(&conn, parent.as_deref()) + .await? + .iter() + .any(|folder| folder == root_id)) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::store::files::NewFile; + use crate::store::test_support::store_with_member; + + async fn member(store: &Store, sub: &str) { + store + .upsert_member_from_claims( + &crate::store::members::MemberFields { + sub: sub.into(), + email: format!("{sub}@example.test"), + name: sub.into(), + is_admin: false, + locale: "en".into(), + zoneinfo: "UTC".into(), + picture_version: 0, + im_updated_at: String::new(), + }, + 1 << 30, + ) + .await + .unwrap(); + } + + #[tokio::test] + async fn a_grant_reaches_the_subtree_until_the_item_leaves_it() { + let (_dir, store) = store_with_member("ann").await; + member(&store, "bob").await; + let trips = store.create_folder("ann", None, "Trips").await.unwrap(); + let other = store.create_folder("ann", None, "Other").await.unwrap(); + let file = store + .insert_file(NewFile { + id: new_id(), + owner: "ann".into(), + folder: Some(trips.id.clone()), + name: "day1.txt".into(), + mime: "text/plain".into(), + size: 1, + sha256: "0".repeat(64), + staged_claims: 0, + }) + .await + .unwrap(); + store + .share_with("ann", ItemKind::Folder, &trips.id, "bob", false) + .await + .unwrap(); + let reach = store + .access_of("bob", ItemKind::File, &file.id) + .await + .unwrap() + .unwrap(); + assert_eq!(reach.grant, Grant::View); + assert!(!reach.trashed); + + store + .move_file("ann", &file.id, Some(&other.id)) + .await + .unwrap(); + let reach = store + .access_of("bob", ItemKind::File, &file.id) + .await + .unwrap() + .unwrap(); + assert_eq!(reach.grant, Grant::None, "the file left the granted folder"); + } + + #[tokio::test] + async fn a_grant_to_the_owner_or_a_stranger_is_refused() { + let (_dir, store) = store_with_member("ann").await; + member(&store, "bob").await; + let folder = store.create_folder("ann", None, "Trips").await.unwrap(); + assert!(matches!( + store + .share_with("ann", ItemKind::Folder, &folder.id, "ann", false) + .await, + Err(Error::Invalid(_)) + )); + assert!(matches!( + store + .share_with("ann", ItemKind::Folder, &folder.id, "nobody", false) + .await, + Err(Error::Invalid(_)) + )); + } +} diff --git a/crates/in-web/src/boot.rs b/crates/in-web/src/boot.rs index d1e0482..6d96603 100644 --- a/crates/in-web/src/boot.rs +++ b/crates/in-web/src/boot.rs @@ -31,6 +31,7 @@ use crate::pages::not_found::NotFoundLayer; use crate::security::{self, SecurityHeaders}; use crate::state::AppState; use crate::sweeper; +use crate::throttle::ShareThrottles; use crate::thumbs_worker; /// Name of the instance key file inside the data directory. @@ -114,6 +115,7 @@ async fn open_state(config: Config) -> Result { key: Arc::new(key), live: Arc::new(LiveHub::default()), oidc, + throttles: Arc::new(ShareThrottles::default()), }) } @@ -240,6 +242,7 @@ mod tests { key: Arc::new(key), live: Arc::new(LiveHub::default()), oidc: None, + throttles: Arc::new(ShareThrottles::default()), }; (dir, state) } diff --git a/crates/in-web/src/i18n/drive.rs b/crates/in-web/src/i18n/drive.rs index 002b856..b5cce3c 100644 --- a/crates/in-web/src/i18n/drive.rs +++ b/crates/in-web/src/i18n/drive.rs @@ -317,7 +317,7 @@ pub fn notice_text(lang: Lang, word: &str) -> Option<&'static str> { "purged" => d(lang, DK::NoticePurged), "emptied" => d(lang, DK::NoticeEmptied), "uploaded" => d(lang, DK::NoticeUploaded), - _ => return None, + _ => return super::share::notice_text(lang, word), }) } @@ -336,6 +336,6 @@ pub fn refusal_text(lang: Lang, word: &str) -> Option<&'static str> { "too_many_names" => d(lang, DK::RefuseTooManyNames), "no_file" => d(lang, DK::RefuseNoFile), "generic" => d(lang, DK::RefuseGeneric), - _ => return None, + _ => return super::share::refusal_text(lang, word), }) } diff --git a/crates/in-web/src/i18n/mod.rs b/crates/in-web/src/i18n/mod.rs index f2476a1..e1d3654 100644 --- a/crates/in-web/src/i18n/mod.rs +++ b/crates/in-web/src/i18n/mod.rs @@ -8,6 +8,7 @@ //! helper functions next to their keys. pub mod drive; +pub mod share; pub mod shell; use topcoat::context::Cx; diff --git a/crates/in-web/src/i18n/share.rs b/crates/in-web/src/i18n/share.rs new file mode 100644 index 0000000..36c5be4 --- /dev/null +++ b/crates/in-web/src/i18n/share.rs @@ -0,0 +1,280 @@ +//! Strings of sharing: the shared page, the share page of an item, the links page, the public share pages +//! and the notices and refusals that the share forms carry back. The match in [`s`] is exhaustive over +//! `(key, lang)`, so a missing Turkish text does not compile. + +use super::Lang; + +/// One variant per phrase of sharing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SK { + /// Navigation tab: items shared with me. + NavShared, + /// Navigation tab: my share links. + NavLinks, + /// Title of the shared page. + SharedTitle, + /// Heading when nothing is shared with the viewer. + SharedEmpty, + /// Hint under that heading. + SharedEmptyHint, + /// Access label: the grantee may only see the item. + AccessView, + /// Access label: the grantee may download the item. + AccessDownload, + /// Label of the grantee's own view of a shared folder. + SharedWithYou, + /// Heading of the share page of an item. + ShareHeading, + /// Section heading: the people the item is shared with. + ShareWithPeople, + /// Shown when nobody has a grant on the item. + ShareNobody, + /// Label of the person picker. + SharePerson, + /// Placeholder option of the person picker. + SharePickPerson, + /// Label of the access picker. + ShareLevel, + /// Button that adds a grant. + ShareAdd, + /// Button that saves a grant's new level. + ShareSave, + /// Button that removes a grant. + ShareRemove, + /// Hint: only the owner decides who sees an item. + ShareOwnerOnly, + /// Section heading of the links of an item. + ShareLinks, + /// Shown when the item has no links. + ShareNoLinks, + /// Title of the links page. + LinksTitle, + /// Shown on the links page when there are none. + LinksEmpty, + /// Hint under the links page title. + LinksHint, + /// Label of the expiry field. + LinkDays, + /// Label of the optional password field. + LinkPassword, + /// Label of the download checkbox. + LinkAllowDownload, + /// Button that creates a link. + LinkCreate, + /// Label of the link URL. + LinkUrl, + /// Label of the expiry date. + LinkExpires, + /// Shown for an expired link. + LinkExpired, + /// Shown for a link with no password. + LinkNoPassword, + /// Shown for a link with a password. + LinkHasPassword, + /// Label of the access a link gives. + /// Button that revokes a link. + LinkRevoke, + /// Button that replaces a link's URL. + LinkRemint, + /// Label of the visit count. + LinkVisits, + /// Notice: a link was made, so it can be copied. + /// Heading of the public page of a protected link. + PublicGateTitle, + /// Text of the public password page. + PublicGateBody, + /// Label of the public password field. + PublicPassword, + /// Button that opens a protected link. + PublicOpen, + /// Shown after a wrong password. + PublicWrong, + /// Shown in an empty public folder. + PublicEmpty, + /// Link text on a public download. + /// Label of the public breadcrumb trail. + PublicLocation, + /// The root crumb of a shared item on the public page. + PublicRoot, + /// Notice: the grant was made. + NoticeShared, + /// Notice: the grant was changed. + NoticeShareUpdated, + /// Notice: the grant was removed. + NoticeUnshared, + /// Notice: the link was made. + NoticeLinkCreated, + /// Notice: the link was revoked. + NoticeLinkRevoked, + /// Notice: the link was replaced by a new one. + NoticeLinkReminted, + /// Refusal: the person is not an active member. + RefuseNoMember, + /// Refusal: the item is already the viewer's own. + RefuseSelfShare, + /// Refusal: the expiry days are out of range. + RefuseLinkDays, + /// Refusal: the expired link cannot be replaced. + RefuseLinkExpired, + /// Refusal: the password is too long. + RefusePasswordLong, +} + +/// The text of a phrase in a language. +pub fn s(lang: Lang, key: SK) -> &'static str { + match (key, lang) { + (SK::NavShared, Lang::En) => "Shared", + (SK::NavShared, Lang::Tr) => "Paylaşılanlar", + (SK::NavLinks, Lang::En) => "Links", + (SK::NavLinks, Lang::Tr) => "Bağlantılar", + (SK::SharedTitle, Lang::En) => "Shared with me", + (SK::SharedTitle, Lang::Tr) => "Benimle paylaşılanlar", + (SK::SharedEmpty, Lang::En) => "Nothing is shared with you yet", + (SK::SharedEmpty, Lang::Tr) => "Sizinle henüz bir şey paylaşılmadı", + (SK::SharedEmptyHint, Lang::En) => { + "When someone in the family shares a file or folder with you, it appears here." + } + (SK::SharedEmptyHint, Lang::Tr) => { + "Bir aile üyesi sizinle bir dosya ya da klasör paylaştığında burada görünür." + } + (SK::AccessView, Lang::En) => "View only", + (SK::AccessView, Lang::Tr) => "Yalnızca görüntüleme", + (SK::AccessDownload, Lang::En) => "May download", + (SK::AccessDownload, Lang::Tr) => "İndirebilir", + (SK::SharedWithYou, Lang::En) => "Shared with you", + (SK::SharedWithYou, Lang::Tr) => "Sizinle paylaşıldı", + (SK::ShareHeading, Lang::En) => "Share", + (SK::ShareHeading, Lang::Tr) => "Paylaş", + (SK::ShareWithPeople, Lang::En) => "People", + (SK::ShareWithPeople, Lang::Tr) => "Kişiler", + (SK::ShareNobody, Lang::En) => "Not shared with anyone yet.", + (SK::ShareNobody, Lang::Tr) => "Henüz kimseyle paylaşılmadı.", + (SK::SharePerson, Lang::En) => "Person", + (SK::SharePerson, Lang::Tr) => "Kişi", + (SK::SharePickPerson, Lang::En) => "Choose a person", + (SK::SharePickPerson, Lang::Tr) => "Bir kişi seçin", + (SK::ShareLevel, Lang::En) => "Access", + (SK::ShareLevel, Lang::Tr) => "Erişim", + (SK::ShareAdd, Lang::En) => "Share", + (SK::ShareAdd, Lang::Tr) => "Paylaş", + (SK::ShareSave, Lang::En) => "Save", + (SK::ShareSave, Lang::Tr) => "Kaydet", + (SK::ShareRemove, Lang::En) => "Remove", + (SK::ShareRemove, Lang::Tr) => "Kaldır", + (SK::ShareOwnerOnly, Lang::En) => "Only the owner can change who sees this item.", + (SK::ShareOwnerOnly, Lang::Tr) => { + "Bu öğeyi kimin göreceğini yalnızca sahibi değiştirebilir." + } + (SK::ShareLinks, Lang::En) => "Share links", + (SK::ShareLinks, Lang::Tr) => "Paylaşım bağlantıları", + (SK::ShareNoLinks, Lang::En) => "No share links for this item.", + (SK::ShareNoLinks, Lang::Tr) => "Bu öğe için paylaşım bağlantısı yok.", + (SK::LinksTitle, Lang::En) => "My share links", + (SK::LinksTitle, Lang::Tr) => "Paylaşım bağlantılarım", + (SK::LinksEmpty, Lang::En) => "You have no share links.", + (SK::LinksEmpty, Lang::Tr) => "Paylaşım bağlantınız yok.", + (SK::LinksHint, Lang::En) => { + "Anyone with a link can open it until it expires or you revoke it." + } + (SK::LinksHint, Lang::Tr) => { + "Bir bağlantıyı, süresi dolana ya da siz iptal edene kadar herkes açabilir." + } + (SK::LinkDays, Lang::En) => "Lasts (days)", + (SK::LinkDays, Lang::Tr) => "Geçerlilik (gün)", + (SK::LinkPassword, Lang::En) => "Password (optional)", + (SK::LinkPassword, Lang::Tr) => "Parola (isteğe bağlı)", + (SK::LinkAllowDownload, Lang::En) => "Allow download", + (SK::LinkAllowDownload, Lang::Tr) => "İndirmeye izin ver", + (SK::LinkCreate, Lang::En) => "Create link", + (SK::LinkCreate, Lang::Tr) => "Bağlantı oluştur", + (SK::LinkUrl, Lang::En) => "Link", + (SK::LinkUrl, Lang::Tr) => "Bağlantı", + (SK::LinkExpires, Lang::En) => "Expires", + (SK::LinkExpires, Lang::Tr) => "Sona erer", + (SK::LinkExpired, Lang::En) => "Expired", + (SK::LinkExpired, Lang::Tr) => "Süresi doldu", + (SK::LinkNoPassword, Lang::En) => "No password", + (SK::LinkNoPassword, Lang::Tr) => "Parola yok", + (SK::LinkHasPassword, Lang::En) => "Password set", + (SK::LinkHasPassword, Lang::Tr) => "Parola var", + (SK::LinkRevoke, Lang::En) => "Revoke", + (SK::LinkRevoke, Lang::Tr) => "İptal et", + (SK::LinkRemint, Lang::En) => "Replace URL", + (SK::LinkRemint, Lang::Tr) => "Adresi değiştir", + (SK::LinkVisits, Lang::En) => "Opened", + (SK::LinkVisits, Lang::Tr) => "Açılma", + (SK::PublicGateTitle, Lang::En) => "This link is protected", + (SK::PublicGateTitle, Lang::Tr) => "Bu bağlantı korumalı", + (SK::PublicGateBody, Lang::En) => "Enter the password to open it.", + (SK::PublicGateBody, Lang::Tr) => "Açmak için parolayı girin.", + (SK::PublicPassword, Lang::En) => "Password", + (SK::PublicPassword, Lang::Tr) => "Parola", + (SK::PublicOpen, Lang::En) => "Open", + (SK::PublicOpen, Lang::Tr) => "Aç", + (SK::PublicWrong, Lang::En) => "Wrong password.", + (SK::PublicWrong, Lang::Tr) => "Parola yanlış.", + (SK::PublicEmpty, Lang::En) => "This folder is empty.", + (SK::PublicEmpty, Lang::Tr) => "Bu klasör boş.", + (SK::PublicLocation, Lang::En) => "Location", + (SK::PublicLocation, Lang::Tr) => "Konum", + (SK::PublicRoot, Lang::En) => "Shared", + (SK::PublicRoot, Lang::Tr) => "Paylaşılan", + (SK::NoticeShared, Lang::En) => "The item is now shared.", + (SK::NoticeShared, Lang::Tr) => "Öğe artık paylaşılıyor.", + (SK::NoticeShareUpdated, Lang::En) => "The access was changed.", + (SK::NoticeShareUpdated, Lang::Tr) => "Erişim değiştirildi.", + (SK::NoticeUnshared, Lang::En) => "The person no longer has access.", + (SK::NoticeUnshared, Lang::Tr) => "Kişinin erişimi kaldırıldı.", + (SK::NoticeLinkCreated, Lang::En) => "The link was created.", + (SK::NoticeLinkCreated, Lang::Tr) => "Bağlantı oluşturuldu.", + (SK::NoticeLinkRevoked, Lang::En) => "The link was revoked.", + (SK::NoticeLinkRevoked, Lang::Tr) => "Bağlantı iptal edildi.", + (SK::NoticeLinkReminted, Lang::En) => { + "The link has a new address. The old one no longer works." + } + (SK::NoticeLinkReminted, Lang::Tr) => { + "Bağlantının yeni bir adresi var. Eskisi artık çalışmıyor." + } + (SK::RefuseNoMember, Lang::En) => "That person is not an active member of the family.", + (SK::RefuseNoMember, Lang::Tr) => "Bu kişi ailede etkin bir üye değil.", + (SK::RefuseSelfShare, Lang::En) => "You already own this item.", + (SK::RefuseSelfShare, Lang::Tr) => "Bu öğenin sahibi zaten sizsiniz.", + (SK::RefuseLinkDays, Lang::En) => { + "The link must last at least one day and no longer than the limit." + } + (SK::RefuseLinkDays, Lang::Tr) => { + "Bağlantı en az bir gün ve sınırı aşmayacak kadar geçerli olmalı." + } + (SK::RefuseLinkExpired, Lang::En) => "This link has expired. Create a new one.", + (SK::RefuseLinkExpired, Lang::Tr) => { + "Bu bağlantının süresi doldu. Yeni bir bağlantı oluşturun." + } + (SK::RefusePasswordLong, Lang::En) => "The password is too long (256 bytes at most).", + (SK::RefusePasswordLong, Lang::Tr) => "Parola çok uzun (en fazla 256 bayt).", + } +} + +/// The notice text of a share word from a redirect, or `None` for a word this build does not know. +pub fn notice_text(lang: Lang, word: &str) -> Option<&'static str> { + Some(match word { + "shared" => s(lang, SK::NoticeShared), + "share_updated" => s(lang, SK::NoticeShareUpdated), + "unshared" => s(lang, SK::NoticeUnshared), + "link_created" => s(lang, SK::NoticeLinkCreated), + "link_revoked" => s(lang, SK::NoticeLinkRevoked), + "link_reminted" => s(lang, SK::NoticeLinkReminted), + _ => return None, + }) +} + +/// The refusal text of a share word from a redirect, or `None` for a word this build does not know. +pub fn refusal_text(lang: Lang, word: &str) -> Option<&'static str> { + Some(match word { + "no_such_member" => s(lang, SK::RefuseNoMember), + "self_share" => s(lang, SK::RefuseSelfShare), + "link_days" => s(lang, SK::RefuseLinkDays), + "link_expired" => s(lang, SK::RefuseLinkExpired), + "password_long" => s(lang, SK::RefusePasswordLong), + _ => return None, + }) +} diff --git a/crates/in-web/src/main.rs b/crates/in-web/src/main.rs index 948d8b4..02fa8c8 100644 --- a/crates/in-web/src/main.rs +++ b/crates/in-web/src/main.rs @@ -18,6 +18,7 @@ mod security; mod serve_bytes; mod state; mod sweeper; +mod throttle; mod thumbs_worker; mod views; diff --git a/crates/in-web/src/pages/drive.rs b/crates/in-web/src/pages/drive.rs index ecd808c..cae01a9 100644 --- a/crates/in-web/src/pages/drive.rs +++ b/crates/in-web/src/pages/drive.rs @@ -17,6 +17,8 @@ use in_core::error::Error as CoreError; use in_core::names::validate_name; use in_core::store::files::File; use in_core::store::folders::{Folder, Listing}; +use in_core::store::shares::Access; +use in_core::store::trash::ItemKind; use serde::Deserialize; use topcoat::Result; use topcoat::context::{Cx, app_context}; @@ -30,6 +32,7 @@ use crate::auth::{Viewer, require_csrf, require_member, safe_next}; use crate::i18n::Lang; use crate::i18n::drive::{DK, d, refusal_text}; use crate::i18n::lang; +use crate::i18n::share::{SK, s as share_s}; use crate::live::{Topic, stream_changes}; use crate::oidc::percent_encode; use crate::state::AppState; @@ -119,6 +122,12 @@ pub struct Board { pub live: Option, /// The start of the sort links: the listing's URL, ending in `?` or `&`. pub base: String, + /// Whether the viewer owns the listing. Only the owner sees the write forms and row menus. + pub writable: bool, + /// Whether the viewer may download the files listed. + pub downloadable: bool, + /// `Some(can_download)` when the listing is shared with the viewer, which the page says. + pub shared: Option, } /// The language of a viewer: the stored override, else the `im` language, else the request. @@ -136,18 +145,19 @@ pub fn viewer_lang(cx: &Cx, viewer: &Viewer) -> Lang { } /// Maps a refusal of the drive's authorization to the HTTP answer. A listing or a view that is refused -/// is always `404`; a change that is refused to someone who can see the item is `403`. -pub fn check(viewer: &Viewer, owner: &str, trashed: bool, action: Action) -> Result<()> { +/// is always `404`; a change that is refused to someone who can see the item is `403`. `access` is the +/// reach the viewer has on the item, computed from its grants and its ancestors. +pub fn check(viewer: &Viewer, owner: &str, access: Access, action: Action) -> Result<()> { let target = Target { owner, - trashed, + trashed: access.trashed, inside_link: false, }; let actor = Actor::Member { sub: &viewer.member.sub, is_admin: viewer.member.is_admin, }; - match authz::authorize(actor, target, Grant::None, action) { + match authz::authorize(actor, target, access.grant, action) { Ok(()) => Ok(()), Err(Denied::NotFound) => Err(not_found().into()), Err(Denied::Forbidden) if matches!(action, Action::List | Action::View) => { @@ -157,7 +167,22 @@ pub fn check(viewer: &Viewer, owner: &str, trashed: bool, action: Action) -> Res } } -/// A live folder by id, after the authorization for `action`. A missing id is `404`. +/// The reach the viewer has on an item. An item that does not exist is `404`. +pub async fn access_for( + state: &AppState, + viewer: &Viewer, + kind: ItemKind, + id: &str, +) -> Result { + let access = state + .store + .access_of(&viewer.member.sub, kind, id) + .await? + .ok_or_else(not_found)?; + Ok(access) +} + +/// A folder by id, after the authorization for `action` with the viewer's reach on it. A missing id is `404`. pub async fn folder_for( state: &AppState, viewer: &Viewer, @@ -165,7 +190,8 @@ pub async fn folder_for( action: Action, ) -> Result { let folder = state.store.folder(id).await?.ok_or_else(not_found)?; - check(viewer, &folder.owner, folder.trashed_at.is_some(), action)?; + let access = access_for(state, viewer, ItemKind::Folder, id).await?; + check(viewer, &folder.owner, access, action)?; Ok(folder) } @@ -295,13 +321,38 @@ pub async fn folder_board( query: &ListQuery, lang: Lang, ) -> Result { - let owner = viewer.member.sub.clone(); - let (heading, trail) = match folder.as_deref() { - None => (d(lang, DK::Drive).to_owned(), Vec::new()), + let me = viewer.member.sub.clone(); + // The listing belongs to the folder's owner, which is the viewer for the drive root and for their own + // folders. A grantee sees the owner's folder through the grant, with breadcrumbs that start at the + // granted folder. + let (heading, trail, owner, writable, downloadable, shared) = match folder.as_deref() { + None => ( + d(lang, DK::Drive).to_owned(), + Vec::new(), + me.clone(), + true, + true, + None, + ), Some(id) => { let row = folder_for(state, viewer, id, Action::List).await?; - let trail = state.store.folder_path(&owner, id).await?; - (row.name.clone(), trail) + let access = access_for(state, viewer, ItemKind::Folder, id).await?; + let mine = row.owner == me; + let trail = if mine { + state.store.folder_path(&me, id).await? + } else { + state.store.shared_trail(&me, id).await? + }; + let shared = (!mine).then_some(access.grant == Grant::Download); + let downloadable = mine || access.grant == Grant::Download; + ( + row.name.clone(), + trail, + row.owner.clone(), + mine, + downloadable, + shared, + ) } }; let mut listing = state.store.list_children(&owner, folder.as_deref()).await?; @@ -335,6 +386,9 @@ pub async fn folder_board( refusal: query.refusal.clone(), live: Some(live), base, + writable, + downloadable, + shared, }) } @@ -369,6 +423,9 @@ pub async fn search_board( refusal: query.refusal.clone(), live: None, base: format!("{DRIVE_HOME}?q={enc}&"), + writable: true, + downloadable: true, + shared: None, }) } @@ -380,20 +437,36 @@ pub async fn drive_board(lang: Lang, board: &Board) -> Result { let in_search = !board.query.is_empty(); let empty = board.folders.is_empty() && board.files.is_empty(); let search_value = board.query.clone(); + let shared_note = match board.shared { + Some(true) => Some(format!( + "{} \u{b7} {}", + share_s(lang, SK::SharedWithYou), + share_s(lang, SK::AccessDownload) + )), + Some(false) => Some(format!( + "{} \u{b7} {}", + share_s(lang, SK::SharedWithYou), + share_s(lang, SK::AccessView) + )), + None => None, + }; Ok(view! {

(board.heading.as_str())

if board.folder.is_some() { - crumbs(lang: lang, trail: &board.trail) + crumbs(lang: lang, trail: &board.trail, shared: board.shared.is_some()) + } + if let Some(note) = shared_note { +

(note)

} flash(lang: lang, notice: board.notice.as_str(), refusal: board.refusal.as_str())
- - if !in_search { + if !in_search && board.writable {
@@ -423,7 +496,7 @@ pub async fn drive_board(lang: Lang, board: &Board) -> Result { empty_state(title: d(lang, DK::EmptyFolder),

(d(lang, DK::EmptyFolderHint))

) } } else { - listing_table(lang: lang, folders: &board.folders, files: &board.files, csrf: board.csrf.as_str(), back: board.back.as_str(), sort: board.sort.word(), dir: if board.descending { "desc" } else { "asc" }, base: board.base.as_str()) + listing_table(lang: lang, folders: &board.folders, files: &board.files, csrf: board.csrf.as_str(), back: board.back.as_str(), sort: board.sort.word(), dir: if board.descending { "desc" } else { "asc" }, base: board.base.as_str(), writable: board.writable, downloadable: board.downloadable) }
}) @@ -503,15 +576,19 @@ async fn drive_live(cx: &Cx, query: Option>) -> Result let folder = query .map(|Form(query)| query.folder) .filter(|folder| !folder.trim().is_empty()); - if let Some(id) = folder.as_deref() { - folder_for(state, &viewer, id, Action::List).await?; - } - let owner = viewer.member.sub.clone(); + // The folder's owner is the one whose changes the stream follows: the viewer's own, or the owner of a + // folder shared with the viewer. + let owner = match folder.as_deref() { + Some(id) => folder_for(state, &viewer, id, Action::List).await?.owner, + None => viewer.member.sub.clone(), + }; + let me = viewer.member.sub.clone(); let token_hash = viewer.session.token_hash.clone(); let store = state.store.clone(); let topics = vec![Topic::Drive(owner.clone())]; stream_changes(cx, &state.live, &topics, move || { let store = store.clone(); + let me = me.clone(); let owner = owner.clone(); let folder = folder.clone(); let token_hash = token_hash.clone(); @@ -520,6 +597,16 @@ async fn drive_live(cx: &Cx, query: Option>) -> Result if store.session_by_token_hash(&token_hash).await?.is_none() { return Err(not_found().into()); } + // A grant that was taken away ends the stream too, even though the folder still exists. + if let Some(id) = folder.as_deref() { + let access = store + .access_of(&me, ItemKind::Folder, id) + .await? + .ok_or_else(not_found)?; + if access.trashed || access.grant == Grant::None { + return Err(not_found().into()); + } + } let listing = store.list_children(&owner, folder.as_deref()).await?; Ok(fingerprint(&listing)) } @@ -712,8 +799,56 @@ mod tests { use http::Request; use http::header::{COOKIE, LOCATION}; use in_core::quota::DEFAULT_MEMBER_QUOTA; + use in_core::store::trash::ItemKind; use topcoat::router::{Body, to_bytes}; + /// A grantee who opens a shared folder sees its name and the folders beneath it, never the owner's + /// folders above the grant: the breadcrumb trail stops at the granted folder. + #[tokio::test] + async fn breadcrumbs_of_a_grantee_stop_at_the_granted_folder() { + let (_dir, state) = test_state().await; + let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; + let _bob = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await; + let secret = state + .store + .create_folder("ann", None, "Secret plans") + .await + .expect("folder"); + let trips = state + .store + .create_folder("ann", Some(&secret.id), "Trips") + .await + .expect("folder"); + state + .store + .share_with("ann", ItemKind::Folder, &trips.id, "bob", false) + .await + .expect("grant"); + let get = |path: String, token: &str| { + Request::get(path) + .header(COOKIE, format!("{SESSION_COOKIE}={token}")) + .body(Body::empty()) + .expect("request") + }; + let bob = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await; + let response = router(state.clone()) + .handle(get(format!("/drive/{}", trips.id), &bob)) + .await; + assert_eq!(response.status(), 200); + let body = to_bytes(response.into_body(), 1 << 20).await.expect("body"); + let html = String::from_utf8_lossy(&body); + assert!(html.contains("Trips"), "the shared folder is shown"); + assert!( + !html.contains("Secret plans"), + "the owner's parent folder is not revealed" + ); + // The parent itself is not granted, so the grantee cannot open it. + let response = router(state.clone()) + .handle(get(format!("/drive/{}", secret.id), &bob)) + .await; + assert_eq!(response.status(), 404); + } + #[tokio::test] async fn the_start_page_goes_to_the_drive_and_the_drive_lists_its_root() { let (_dir, state) = test_state().await; diff --git a/crates/in-web/src/pages/files.rs b/crates/in-web/src/pages/files.rs index 078683d..3a2a41b 100644 --- a/crates/in-web/src/pages/files.rs +++ b/crates/in-web/src/pages/files.rs @@ -15,6 +15,7 @@ use in_core::sniff::sniff; use in_core::staging::{Staged, StagedFile}; use in_core::store::files::{File, NewFile, files_blob_key}; use in_core::store::new_id; +use in_core::store::trash::ItemKind; use serde::Deserialize; use topcoat::Result; use topcoat::context::{Cx, app_context}; @@ -29,8 +30,8 @@ use topcoat::view::{View, view}; use crate::auth::{Viewer, require_csrf, require_member}; use crate::i18n::drive::{DK, d}; use crate::pages::drive::{ - DRIVE_HOME, ItemForm, back_or, changed, check, done, optional_folder, pick_body, refusal_word, - refused, tree_rows, viewer_lang, with_param, + 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::state::AppState; @@ -66,7 +67,8 @@ pub async fn upload_limit(state: &AppState) -> Result { /// A live or trashed file by id, after the authorization for `action`. A missing id is `404`. pub async fn file_for(state: &AppState, viewer: &Viewer, id: &str, action: Action) -> Result { let file = state.store.file(id).await?.ok_or_else(not_found)?; - check(viewer, &file.owner, file.trashed_at.is_some(), action)?; + let access = access_for(state, viewer, ItemKind::File, id).await?; + check(viewer, &file.owner, access, action)?; Ok(file) } diff --git a/crates/in-web/src/pages/links.rs b/crates/in-web/src/pages/links.rs new file mode 100644 index 0000000..d4c623b --- /dev/null +++ b/crates/in-web/src/pages/links.rs @@ -0,0 +1,292 @@ +//! The owner's share links: the list (`GET /links`), creation (`POST /links`), revoking and reminting. +//! +//! A link is made from the share page of an item, which checks the item is the viewer's and live. Its token +//! is random, shown in full from the sealed copy (so the URL can be copied again), and stored only as its +//! SHA-256. Expiry is at most `link_max_days` (a setting, 365 by default). The password is hashed with +//! argon2id on the blocking pool and is never shown again. Revoking and reminting need the owner; anything +//! else is `404`. + +use std::time::Duration; + +use in_core::error::Error as CoreError; +use in_core::password::hash_password_async; +use in_core::secret; +use in_core::store::links::{Link, NewLink}; +use in_core::store::new_id; +use in_core::store::shares::kind_from_word; +use in_core::store::trash::ItemKind; +use in_core::time::{now_stamp, stamp_after}; +use in_core::token::{generate_token, hash_token}; +use serde::Deserialize; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::{SeeOther, not_found}; +use topcoat::router::{page, path_param_segment, route}; +use topcoat::view::{View, component, view}; + +use crate::auth::{Viewer, require_csrf, require_member}; +use crate::i18n::Lang; +use crate::i18n::share::{SK, s as share_s}; +use crate::pages::drive::{back_or, done, refused, viewer_lang}; +use crate::pages::share_dialog::shareable; +use crate::state::AppState; +use crate::views::drive::stamp_text; +use crate::views::{ViewerInfo, empty_state, shell}; + +/// The settings key of the longest a link may last, in days. +pub const LINK_MAX_DAYS_SETTING: &str = "link_max_days"; + +/// The longest a link may last when the settings say nothing: a year. +pub const DEFAULT_LINK_MAX_DAYS: u32 = 365; + +/// Longest password accepted, in bytes. Longer ones are refused rather than cut. +pub const MAX_PASSWORD_BYTES: usize = 256; + +/// Seconds in a day, for the expiry arithmetic. +const DAY_SECONDS: u64 = 24 * 60 * 60; + +/// The longest a link may last, from the settings, else the default. Never zero. +pub async fn link_max_days(state: &AppState) -> Result { + let setting = state.store.get_setting(LINK_MAX_DAYS_SETTING).await?; + Ok(setting + .and_then(|value| value.trim().parse::().ok()) + .filter(|days| *days >= 1) + .unwrap_or(DEFAULT_LINK_MAX_DAYS)) +} + +/// A link as the owner sees it: the link, the name of its target, and the full URL. +#[derive(Debug, Clone)] +pub struct LinkView { + /// The link. + pub link: Link, + /// The target's name, or a dash when the target is gone. + pub name: String, + /// The full address `{base}/s/{token}`, or empty when the sealed token cannot be opened. + pub url: String, +} + +/// The URL of a link from its sealed token. Empty when the token cannot be opened. +pub fn public_url(state: &AppState, token_sealed: &str) -> String { + match secret::open(&state.key, token_sealed) + .ok() + .and_then(|bytes| String::from_utf8(bytes).ok()) + { + Some(token) => format!("{}/s/{token}", state.config.base_url.trim_end_matches('/')), + None => String::new(), + } +} + +/// The name of a link's target. +async fn target_name(state: &AppState, kind: ItemKind, id: &str) -> Result { + Ok(match kind { + ItemKind::File => state.store.file(id).await?.map(|f| f.name), + ItemKind::Folder => state.store.folder(id).await?.map(|f| f.name), + } + .unwrap_or_else(|| "\u{2014}".to_owned())) +} + +/// The views of a viewer's links, in the order the store gives them. +pub async fn link_views(state: &AppState, links: Vec) -> Result> { + let mut out = Vec::with_capacity(links.len()); + for link in links { + let name = target_name(state, link.kind, &link.target_id).await?; + let url = public_url(state, &link.token_sealed); + out.push(LinkView { link, name, url }); + } + Ok(out) +} + +/// One link in a list: its name and flags, its URL for copying while it works, and the owner's actions. A +/// link past its expiry only offers revoking. +#[component] +pub async fn link_row(lang: Lang, view: &LinkView, csrf: &str, back: &str) -> Result { + let link = &view.link; + let id = link.id.as_str(); + let live = link.is_live(&now_stamp()); + let expires = link + .expires_at + .as_deref() + .map(stamp_text) + .unwrap_or_default(); + let access = if link.can_download { + share_s(lang, SK::AccessDownload) + } else { + share_s(lang, SK::AccessView) + }; + let password = if link.password_hash.is_some() { + share_s(lang, SK::LinkHasPassword) + } else { + share_s(lang, SK::LinkNoPassword) + }; + let revoke_action = format!("/links/{id}/revoke"); + let remint_action = format!("/links/{id}/remint"); + let url_id = format!("url-{id}"); + Ok(view! { + + }) +} + +/// The content of the links page: the list of the owner's links, or the empty state. +#[component] +pub async fn links_body(lang: Lang, rows: &[LinkView], csrf: &str) -> Result { + Ok(view! { +
+

(share_s(lang, SK::LinksTitle))

+

(share_s(lang, SK::LinksHint))

+ if rows.is_empty() { + empty_state(title: share_s(lang, SK::LinksEmpty)) + } else { + + } +
+ }) +} + +/// `GET /links`: every link the viewer has made that is not revoked. +#[page("/links")] +async fn links_page(cx: &Cx) -> Result { + let state = app_context::(cx); + let viewer = require_member(cx).await?; + let lang = viewer_lang(cx, &viewer); + let links = state.store.links_of(&viewer.member.sub).await?; + let rows = link_views(state, links).await?; + let csrf = viewer.session.csrf_token.clone(); + let info = ViewerInfo::of(&viewer); + let title = share_s(lang, SK::LinksTitle); + Ok(view! { + shell(title: title, lang: lang, viewer: Some(&info), + links_body(lang: lang, rows: &rows, csrf: csrf.as_str()) + ) + }) +} + +/// The form of link writes: the CSRF token, the return page, and for a creation the item, the expiry in +/// days (blank for the maximum), an optional password and the download flag. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct LinkForm { + /// The CSRF token of the session. + pub csrf: String, + /// The page to return to. + pub back: String, + /// `file` or `folder`. + pub kind: String, + /// The item the link opens. + pub target_id: String, + /// Days the link lasts; blank means the maximum. + pub days: String, + /// The optional password. Empty means none. + pub password: String, + /// `1` when visitors may download. + pub download: String, +} + +/// Makes a fresh token and its sealed copy: `(token hash, sealed token, token)`. +fn new_token(state: &AppState) -> Result<(String, String, String)> { + let token = generate_token(); + let sealed = secret::seal(&state.key, token.as_bytes())?; + Ok((hash_token(&token), sealed, token)) +} + +/// `POST /links`: makes a link to an item the viewer owns and can share. +#[route(POST "/links")] +async fn create_link(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + let viewer: Viewer = require_csrf(cx, &form.csrf).await?; + let kind = kind_from_word(form.kind.trim()).ok_or_else(not_found)?; + let target = form.target_id.trim().to_owned(); + let back = back_or(&form.back, "/links"); + shareable(state, &viewer, kind, &target).await?; + + let max = link_max_days(state).await?; + let raw = form.days.trim(); + let days = if raw.is_empty() { + max + } else { + match raw.parse::() { + Ok(days) if (1..=max).contains(&days) => days, + _ => return refused(&back, CoreError::Invalid("link_days".into())), + } + }; + let password_hash = if form.password.is_empty() { + None + } else if form.password.len() > MAX_PASSWORD_BYTES { + return refused(&back, CoreError::Invalid("password_long".into())); + } else { + Some(hash_password_async(form.password.clone()).await?) + }; + + let (token_hash, token_sealed, _token) = new_token(state)?; + let new = NewLink { + id: new_id(), + token_hash, + token_sealed, + kind, + target_id: target, + owner: viewer.member.sub.clone(), + can_download: form.download == "1", + password_hash, + expires_at: Some(stamp_after(Duration::from_secs( + u64::from(days) * DAY_SECONDS, + ))), + }; + match state.store.create_link(new).await { + Ok(_) => Ok(done(&back, "link_created")), + Err(error) => refused(&back, error), + } +} + +/// `POST /links/{id}/revoke`: the link stops working at once. +#[route(POST "/links/{id}/revoke")] +async fn revoke_link(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + let viewer = require_csrf(cx, &form.csrf).await?; + let id = path_param_segment(cx, "id").to_owned(); + let back = back_or(&form.back, "/links"); + match state.store.revoke_link(&viewer.member.sub, &id).await { + Ok(()) => Ok(done(&back, "link_revoked")), + Err(error) => refused(&back, error), + } +} + +/// `POST /links/{id}/remint`: a new token for the same link; the old token stops working. +#[route(POST "/links/{id}/remint")] +async fn remint_link(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + let viewer = require_csrf(cx, &form.csrf).await?; + let id = path_param_segment(cx, "id").to_owned(); + let back = back_or(&form.back, "/links"); + let (token_hash, token_sealed, _token) = new_token(state)?; + match state + .store + .remint_link(&viewer.member.sub, &id, &token_hash, &token_sealed) + .await + { + Ok(_) => Ok(done(&back, "link_reminted")), + Err(error) => refused(&back, error), + } +} diff --git a/crates/in-web/src/pages/mod.rs b/crates/in-web/src/pages/mod.rs index 00254b9..2cd677b 100644 --- a/crates/in-web/src/pages/mod.rs +++ b/crates/in-web/src/pages/mod.rs @@ -4,8 +4,12 @@ pub mod backchannel; pub mod drive; pub mod files; pub mod home; +pub mod links; pub mod not_found; pub mod photo; +pub mod public_share; +pub mod share_dialog; +pub mod shared; pub mod sign_in; pub mod thumbs; pub mod trash; diff --git a/crates/in-web/src/pages/public_share.rs b/crates/in-web/src/pages/public_share.rs new file mode 100644 index 0000000..dd70a62 --- /dev/null +++ b/crates/in-web/src/pages/public_share.rs @@ -0,0 +1,720 @@ +//! The public share pages of a link, anonymous (`/s/{token}`), with their bytes (`/s/{token}/file/{id}`) +//! and thumbnails (`/s/{token}/thumb/{id}`). +//! +//! A link opens one item. A file link shows that file. A folder link lists its folder and browses down +//! inside it; a `?folder=` or `?file=` outside the linked root is `404`, as is any unknown, revoked, +//! expired or trashed link, all alike. A link with a password shows a gate until the visitor posts the +//! right one. The unlock cookie is HMAC-keyed to the link and its password hash, so a changed password +//! locks everyone out again. Wrong passwords are throttled per link and per client address (see +//! `throttle.rs`); the sixth wrong one within the window is `429`. +//! +//! No session is read here and no member's details are shown. The pages send `Referrer-Policy: no-referrer` +//! and `X-Robots-Tag: noindex` (set in `security.rs`). + +use in_core::authz::{Action, Actor, Grant, Target, authorize}; +use in_core::password::verify_password_async; +use in_core::secret::unlock_proof; +use in_core::store::files::File; +use in_core::store::files::thumb_blob_key; +use in_core::store::folders::{Folder, Listing}; +use in_core::store::links::Link; +use in_core::store::trash::ItemKind; +use in_core::time::now_stamp; +use in_core::token::{constant_time_eq, generate_token, hash_token}; +use serde::Deserialize; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; +use topcoat::router::content::Form; +use topcoat::router::error::{SeeOther, forbidden, not_found, see_other, too_many_requests}; +use topcoat::router::request::{client_ip, headers}; +use topcoat::router::{page, parse_query_params, path_param_segment, route}; +use topcoat::view::{View, component, view}; + +use crate::auth::cookie_value; +use crate::i18n::Lang; +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, +}; +use crate::state::AppState; +use crate::views::drive::size_text; +use crate::views::{empty_state, shell}; + +/// The cookie that carries the CSRF token of the password gate. `__Host-` makes it host-only, secure and +/// path `/`. +const GATE_CSRF_COOKIE: &str = "__Host-in_precsrf"; + +/// How long a successful password keeps a visitor unlocked: twelve hours. +const UNLOCK_HOURS: i64 = 12; + +/// The unlock cookie name of a link. It is scoped to the link's own path, so the name only needs the id. +fn unlock_cookie_name(link_id: &str) -> String { + format!("in_link_{link_id}") +} + +/// The link of a token, when it is live and its target is not in the trash. Every other case is `404`, so +/// an unknown token and a dead one cannot be told apart. +async fn live_link(state: &AppState, token: &str) -> Result { + let link = state + .store + .link_by_token_hash(&hash_token(token)) + .await? + .ok_or_else(not_found)?; + if !link.is_live(&now_stamp()) { + return Err(not_found().into()); + } + if state.store.item_trashed(link.kind, &link.target_id).await? != Some(false) { + return Err(not_found().into()); + } + Ok(link) +} + +/// Checks that the link may show `(kind, id)` for `action`. The item must lie inside the linked root and +/// be live. Anything else is `404`, including a download the link does not allow. +async fn visit( + state: &AppState, + link: &Link, + kind: ItemKind, + id: &str, + action: Action, +) -> Result<()> { + let trashed = state + .store + .item_trashed(kind, id) + .await? + .ok_or_else(not_found)?; + let inside_link = state + .store + .is_within(link.kind, &link.target_id, kind, id) + .await?; + let target = Target { + owner: &link.owner, + trashed, + inside_link, + }; + authorize( + Actor::Link { + can_download: link.can_download, + }, + target, + Grant::None, + action, + ) + .map_err(|_| not_found())?; + Ok(()) +} + +/// Whether the visitor holds the unlock cookie of a link that has a password. A link without one is always +/// unlocked. +fn unlocked(cx: &Cx, state: &AppState, link: &Link) -> bool { + let Some(hash) = link.password_hash.as_deref() else { + return true; + }; + let expected = unlock_proof(&state.key, &link.id, hash); + cookie_value(cx, &unlock_cookie_name(&link.id)) + .is_some_and(|given| constant_time_eq(given.as_bytes(), expected.as_bytes())) +} + +/// The gate's CSRF token: the one already in the cookie, or a new one, which the response sets. +fn gate_csrf(cx: &Cx) -> String { + if let Some(existing) = cookie_value(cx, GATE_CSRF_COOKIE) { + return existing; + } + let token = generate_token(); + let cookie = Cookie::build((GATE_CSRF_COOKIE, token.clone())) + .path("/") + .http_only(true) + .secure(true) + .same_site(SameSite::Strict) + .build(); + cookies(cx).add(cookie); + token +} + +/// The query of the public page: a folder to browse, a file to show, and whether the last password was +/// wrong. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct PublicQuery { + /// A folder inside the link's root. + pub folder: String, + /// A file inside the link's root. + pub file: String, + /// `1` after a wrong password. + pub wrong: String, +} + +/// The form of the password gate. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct GateForm { + /// The CSRF token that the gate cookie must match. + pub csrf: String, + /// The password the visitor typed. + pub password: String, +} + +/// A folder listing inside a folder link: its breadcrumbs, its current folder, and what it holds. +pub struct FolderPanel { + /// The folders from the link's root down to the current one. + pub trail: Vec, + /// The children of the current folder. + pub listing: Listing, + /// Whether the link allows downloads. + pub can_download: bool, +} + +/// One file of a link: its name, size, and the way back to where the visitor came from. +pub struct FilePanel { + /// The file. + pub file: File, + /// The link's path with the query that returns to the folder; empty when there is none. + pub back: String, + /// Whether the link allows downloads. + pub can_download: bool, +} + +/// What the public page shows. +pub enum Panel { + /// The password gate, with the wrong-password flag and the CSRF token. + Gate { wrong: bool, csrf: String }, + /// A folder browsing inside its link. + Folder(Box), + /// One file. + File(Box), +} + +/// One row of a public listing: where it leads, its name, its size text and its download link (empty +/// when there is none). +pub struct Entry { + /// Where the row leads. + pub href: String, + /// The name shown. + pub name: String, + /// The size shown, or empty for a folder. + pub size: String, + /// The download link, or empty when the visitor may not download. + pub download: String, +} + +/// The breadcrumb of a public folder: the link's root, then each folder down to the current one. +#[component] +async fn public_crumbs(lang: Lang, token: &str, trail: &[Folder]) -> Result { + let root_href = format!("/s/{token}"); + let steps: Vec = trail + .iter() + .map(|folder| Entry { + href: format!("/s/{token}?folder={}", folder.id), + name: folder.name.clone(), + size: String::new(), + download: String::new(), + }) + .collect(); + Ok(view! { + + }) +} + +/// The password gate: the notice after a wrong password and the form. +#[component] +async fn gate_panel(lang: Lang, token: &str, wrong: bool, csrf: &str) -> Result { + let action = format!("/s/{token}"); + Ok(view! { +
+

(share_s(lang, SK::PublicGateTitle))

+

(share_s(lang, SK::PublicGateBody))

+ if wrong { + + } + +
+ }) +} + +/// A folder inside a folder link: its breadcrumbs, its folders, and its files. +#[component] +async fn folder_panel(lang: Lang, token: &str, panel: &FolderPanel) -> Result { + let listing = &panel.listing; + let empty = listing.folders.is_empty() && listing.files.is_empty(); + let mut rows: Vec = listing + .folders + .iter() + .map(|folder| Entry { + href: format!("/s/{token}?folder={}", folder.id), + name: folder.name.clone(), + size: String::new(), + download: String::new(), + }) + .collect(); + rows.extend(listing.files.iter().map(|file| Entry { + href: format!("/s/{token}?file={}", file.id), + name: file.name.clone(), + size: size_text(file.size), + download: if panel.can_download { + format!("/s/{token}/file/{}?dl=1", file.id) + } else { + String::new() + }, + })); + let download_label = d(lang, DK::Download); + Ok(view! { +
+ public_crumbs(lang: lang, token: token, trail: &panel.trail) + if empty { + empty_state(title: share_s(lang, SK::PublicEmpty)) + } else { +
+ + + for row in &rows { + + + + + + } + +
(row.name.as_str())(row.size.as_str()) + if !row.download.is_empty() { + (download_label) + } +
+
+ } +
+ }) +} + +/// One file of a link: a preview for a picture, its size, and the download when the link allows it. +#[component] +async fn file_panel(lang: Lang, token: &str, panel: &FilePanel) -> Result { + let file = &panel.file; + let preview = if file.thumb_state == "ready" { + format!("/s/{token}/thumb/{}", file.id) + } else { + String::new() + }; + let download = format!("/s/{token}/file/{}?dl=1", file.id); + Ok(view! { +
+ if !panel.back.is_empty() { +

"\u{2190} " (share_s(lang, SK::PublicLocation))

+ } +

(file.name.as_str())

+

(size_text(file.size))

+ if !preview.is_empty() { + (file.name.as_str()) + } + if panel.can_download { +

(d(lang, DK::Download))

+ } +
+ }) +} + +/// The body of the public page: whichever panel the link shows. +#[component] +async fn public_body(lang: Lang, token: &str, panel: &Panel) -> Result { + Ok(view! { + if let Panel::Gate { wrong, csrf } = panel { + gate_panel(lang: lang, token: token, wrong: *wrong, csrf: csrf.as_str()) + } + if let Panel::Folder(folder) = panel { + folder_panel(lang: lang, token: token, panel: folder) + } + if let Panel::File(file) = panel { + file_panel(lang: lang, token: token, panel: file) + } + }) +} + +/// Builds the panel of a live, unlocked link from its query. +async fn content_panel( + state: &AppState, + token: &str, + link: &Link, + query: &PublicQuery, +) -> Result { + match link.kind { + ItemKind::File => { + visit(state, link, ItemKind::File, &link.target_id, Action::View).await?; + let file = state + .store + .file(&link.target_id) + .await? + .ok_or_else(not_found)?; + Ok(Panel::File(Box::new(FilePanel { + file, + back: String::new(), + can_download: link.can_download, + }))) + } + ItemKind::Folder => { + visit(state, link, ItemKind::Folder, &link.target_id, Action::List).await?; + if !query.file.is_empty() { + visit(state, link, ItemKind::File, &query.file, Action::View).await?; + let file = state.store.file(&query.file).await?.ok_or_else(not_found)?; + let back = match file.folder_id.as_deref() { + Some(folder) => format!("/s/{token}?folder={folder}"), + None => format!("/s/{token}"), + }; + return Ok(Panel::File(Box::new(FilePanel { + file, + back, + can_download: link.can_download, + }))); + } + let current = if query.folder.is_empty() { + link.target_id.clone() + } else { + visit(state, link, ItemKind::Folder, &query.folder, Action::List).await?; + query.folder.clone() + }; + let trail = state + .store + .folder_trail_to(&link.target_id, ¤t) + .await?; + let listing = state + .store + .list_children(&link.owner, Some(¤t)) + .await?; + Ok(Panel::Folder(Box::new(FolderPanel { + trail, + listing, + can_download: link.can_download, + }))) + } + } +} + +/// `GET /s/{token}`: the public page of a link, or its password gate. +#[page("/s/{token}")] +async fn public_page(cx: &Cx) -> Result { + let state = app_context::(cx); + let token = path_param_segment(cx, "token").to_owned(); + let link = live_link(state, &token).await?; + let query: PublicQuery = parse_query_params(cx).unwrap_or_default(); + let lang = crate::i18n::lang(cx, None); + let title = share_s(lang, SK::PublicGateTitle); + let panel = if link.password_hash.is_some() && !unlocked(cx, state, &link) { + let wrong = query.wrong == "1"; + Panel::Gate { + wrong, + csrf: gate_csrf(cx), + } + } else { + state.store.touch_link(&link.id).await?; + content_panel(state, &token, &link, &query).await? + }; + Ok(view! { + shell(title: title, lang: lang, viewer: None, + public_body(lang: lang, token: token.as_str(), panel: &panel) + ) + }) +} + +/// `POST /s/{token}`: the password of a link. The right one sets the unlock cookie; a wrong one is counted +/// against the link and the client address. Both limits are checked before anything else. +#[route(POST "/s/{token}")] +async fn unlock(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + let token = path_param_segment(cx, "token").to_owned(); + let token_hash = hash_token(&token); + let ip = client_ip(cx).map(|ip| ip.to_string()).unwrap_or_default(); + let throttles = &state.throttles; + if let Some(wait) = throttles + .per_link + .blocked(&token_hash) + .or_else(|| throttles.per_ip.blocked(&ip)) + { + return Err(too_many_requests(wait).into()); + } + let expected_csrf = cookie_value(cx, GATE_CSRF_COOKIE).unwrap_or_default(); + if expected_csrf.is_empty() || !constant_time_eq(expected_csrf.as_bytes(), form.csrf.as_bytes()) + { + return Err(forbidden().into()); + } + let link = live_link(state, &token).await?; + let Some(hash) = link.password_hash.clone() else { + return Ok(see_other(format!("/s/{token}"))); + }; + if verify_password_async(form.password, hash.clone()).await? { + let proof = unlock_proof(&state.key, &link.id, &hash); + let cookie = Cookie::build((unlock_cookie_name(&link.id), proof)) + .path(format!("/s/{token}")) + .http_only(true) + .secure(true) + .same_site(SameSite::Lax) + .max_age(time::Duration::hours(UNLOCK_HOURS)) + .build(); + cookies(cx).add(cookie); + return Ok(see_other(format!("/s/{token}"))); + } + throttles.per_link.failure(&token_hash); + throttles.per_ip.failure(&ip); + Ok(see_other(format!("/s/{token}?wrong=1"))) +} + +/// The locked link check of the byte routes: a locked link answers `404`, as if it were not there. +fn require_unlocked(cx: &Cx, state: &AppState, link: &Link) -> Result<()> { + if unlocked(cx, state, link) { + Ok(()) + } else { + Err(not_found().into()) + } +} + +/// The query of a byte route: `dl=1` asks for a download. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct PublicBytesQuery { + /// `1` for a download. + pub dl: String, +} + +/// `GET /s/{token}/file/{id}`: the bytes of a file inside the link. +#[route(GET "/s/{token}/file/{id}")] +async fn public_file_bytes(cx: &Cx) -> Result { + let state = app_context::(cx); + let token = path_param_segment(cx, "token").to_owned(); + let id = path_param_segment(cx, "id").to_owned(); + let link = live_link(state, &token).await?; + require_unlocked(cx, state, &link)?; + let query: PublicBytesQuery = parse_query_params(cx).unwrap_or_default(); + let download = query.dl == "1"; + let action = if download { + Action::Download + } else { + Action::View + }; + 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) { + state.store.record_download(&file.id).await?; + } + let source = ByteSource { + blob_key: &file.blob_key, + size, + sha256: &file.sha256, + mime: &file.mime, + name: &file.name, + }; + let disposition = if download { + Disposition::Attachment + } else { + Disposition::Inline + }; + serve_bytes_with(cx, state.blobs.as_ref(), &source, disposition, SHARE_CACHE).await +} + +/// `GET /s/{token}/thumb/{id}`: the thumbnail of a picture inside the link. +#[route(GET "/s/{token}/thumb/{id}")] +async fn public_thumb(cx: &Cx) -> Result { + let state = app_context::(cx); + let token = path_param_segment(cx, "token").to_owned(); + let id = path_param_segment(cx, "id").to_owned(); + let link = live_link(state, &token).await?; + require_unlocked(cx, state, &link)?; + visit(state, &link, ItemKind::File, &id, Action::View).await?; + let file = state.store.file(&id).await?.ok_or_else(not_found)?; + if file.thumb_state != "ready" { + return Err(not_found().into()); + } + let key = thumb_blob_key(&file.id); + let size = state.blobs.size(&key).await?.ok_or_else(not_found)?; + let validator = thumb_validator(&file.sha256); + let source = ByteSource { + blob_key: &key, + size, + sha256: &validator, + mime: "image/webp", + name: &file.name, + }; + serve_bytes_with( + cx, + state.blobs.as_ref(), + &source, + Disposition::Inline, + SHARE_CACHE, + ) + .await +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::auth::test_support::signed_in; + use crate::boot::{router, test_state}; + use http::Request; + use http::header::{CONTENT_TYPE, COOKIE}; + use in_core::password::hash_password_async; + use in_core::quota::DEFAULT_MEMBER_QUOTA; + use in_core::secret; + use in_core::store::links::NewLink; + use in_core::store::new_id; + use topcoat::router::Body; + + /// Makes a link owned by `ann` on `target`, with an optional password. Returns `(token, link id)`. + async fn link_to( + state: &AppState, + kind: ItemKind, + target: &str, + password: Option<&str>, + ) -> (String, String) { + let token = generate_token(); + let password_hash = match password { + Some(text) => Some(hash_password_async(text.to_owned()).await.expect("hash")), + None => None, + }; + let link = state + .store + .create_link(NewLink { + id: new_id(), + token_hash: hash_token(&token), + token_sealed: secret::seal(&state.key, token.as_bytes()).expect("seal"), + kind, + target_id: target.to_owned(), + owner: "ann".to_owned(), + can_download: true, + password_hash, + expires_at: Some("9999-12-31T23:59:59.000Z".to_owned()), + }) + .await + .expect("link"); + (token, link.id) + } + + async fn get(state: &AppState, path: &str) -> u16 { + let request = Request::get(path).body(Body::empty()).expect("request"); + router(state.clone()) + .handle(request) + .await + .status() + .as_u16() + } + + /// A link to a folder shows its subfolders; a folder outside the root is `404`. + #[tokio::test] + async fn a_folder_link_does_not_reach_outside_its_root() { + let (_dir, state) = test_state().await; + let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; + let trips = state + .store + .create_folder("ann", None, "Trips") + .await + .expect("folder"); + let sub = state + .store + .create_folder("ann", Some(&trips.id), "Sub") + .await + .expect("folder"); + let other = state + .store + .create_folder("ann", None, "Other") + .await + .expect("folder"); + let (token, _) = link_to(&state, ItemKind::Folder, &trips.id, None).await; + assert_eq!( + get(&state, &format!("/s/{token}?folder={}", sub.id)).await, + 200 + ); + assert_eq!( + get(&state, &format!("/s/{token}?folder={}", other.id)).await, + 404 + ); + } + + /// A revoked link is `404`, and so is a link whose target is in the trash. + #[tokio::test] + async fn a_revoked_or_trashed_link_is_not_found() { + let (_dir, state) = test_state().await; + let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; + let trips = state + .store + .create_folder("ann", None, "Trips") + .await + .expect("folder"); + let (token, link_id) = link_to(&state, ItemKind::Folder, &trips.id, None).await; + assert_eq!(get(&state, &format!("/s/{token}")).await, 200); + state + .store + .revoke_link("ann", &link_id) + .await + .expect("revoke"); + assert_eq!(get(&state, &format!("/s/{token}")).await, 404); + + let (token, _) = link_to(&state, ItemKind::Folder, &trips.id, None).await; + state + .store + .trash_folder("ann", &trips.id) + .await + .expect("trash"); + assert_eq!(get(&state, &format!("/s/{token}")).await, 404); + } + + /// Five wrong passwords are answered with a redirect; the sixth within the window is `429`. + #[tokio::test] + async fn the_sixth_wrong_password_is_throttled() { + let (_dir, state) = test_state().await; + let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; + let trips = state + .store + .create_folder("ann", None, "Trips") + .await + .expect("folder"); + let (token, _) = link_to(&state, ItemKind::Folder, &trips.id, Some("right")).await; + let path = format!("/s/{token}"); + let mut statuses = Vec::new(); + for _ in 0..6 { + let request = Request::post(path.as_str()) + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") + .header(COOKIE, format!("{GATE_CSRF_COOKIE}=tok")) + .body(Body::from("csrf=tok&password=wrong")) + .expect("request"); + let response = router(state.clone()).handle(request).await; + statuses.push(response.status().as_u16()); + } + assert_eq!(statuses, vec![303, 303, 303, 303, 303, 429]); + } + + /// A file link answers the file's bytes only with the unlock cookie of a password-protected link. + #[tokio::test] + async fn a_locked_link_gives_no_bytes_without_the_password() { + let (_dir, state) = test_state().await; + let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; + let file = state + .store + .insert_file(in_core::store::files::NewFile { + id: new_id(), + owner: "ann".into(), + folder: None, + name: "note.bin".into(), + mime: "application/octet-stream".into(), + size: 0, + sha256: "0".repeat(64), + staged_claims: 0, + }) + .await + .expect("file"); + let (token, _) = link_to(&state, ItemKind::File, &file.id, Some("right")).await; + assert_eq!( + get(&state, &format!("/s/{token}/file/{}", file.id)).await, + 404 + ); + } +} diff --git a/crates/in-web/src/pages/share_dialog.rs b/crates/in-web/src/pages/share_dialog.rs new file mode 100644 index 0000000..537e1ad --- /dev/null +++ b/crates/in-web/src/pages/share_dialog.rs @@ -0,0 +1,484 @@ +//! The share page of one item (`GET /share/{kind}/{id}`, linked from the row menu and the viewer) and the +//! 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. + +use in_core::authz::Action; +use in_core::store::members::Member; +use in_core::store::shares::{Share, ShareEntry, kind_from_word, kind_word}; +use in_core::store::trash::ItemKind; +use serde::Deserialize; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::{SeeOther, not_found}; +use topcoat::router::{page, path_param_segment, route}; +use topcoat::view::{View, component, view}; + +use crate::auth::{Viewer, require_csrf, require_member}; +use crate::i18n::Lang; +use crate::i18n::share::{SK, s as share_s}; +use crate::live::Topic; +use crate::pages::drive::{ListQuery, access_for, back_or, check, done, refused, viewer_lang}; +use crate::pages::links::{LinkView, link_max_days, link_row, link_views}; +use crate::state::AppState; +use crate::views::drive::flash; +use crate::views::{ViewerInfo, shell}; + +/// The form of the share writes. Every field is optional; each write reads what it needs. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +pub struct GrantForm { + /// The CSRF token of the session. + pub csrf: String, + /// The page to return to. + pub back: String, + /// `file` or `folder`, for a new grant. + pub kind: String, + /// The item, for a new grant. + pub target_id: String, + /// The grantee's subject, for a new grant. + pub grantee: String, + /// `download` or `view`. + pub level: String, +} + +/// The name and owner of an item, for the share checks. A missing item is `404`. +async fn item_head(state: &AppState, kind: ItemKind, id: &str) -> Result<(String, String)> { + Ok(match kind { + ItemKind::File => { + let file = state.store.file(id).await?.ok_or_else(not_found)?; + (file.owner, file.name) + } + ItemKind::Folder => { + let folder = state.store.folder(id).await?.ok_or_else(not_found)?; + (folder.owner, folder.name) + } + }) +} + +/// The name of an item the viewer may share: it must be theirs and live. A grantee is refused with `403` +/// and anyone else sees `404`. +pub async fn shareable( + state: &AppState, + viewer: &Viewer, + kind: ItemKind, + id: &str, +) -> Result { + let (owner, name) = item_head(state, kind, id).await?; + let access = access_for(state, viewer, kind, id).await?; + check(viewer, &owner, access, Action::Share)?; + Ok(name) +} + +/// 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())); +} + +/// The level picker of a grant: `view` or `download`, with the current one selected. +#[component] +pub async fn level_select(lang: Lang, name: &str, id: &str, download: bool) -> Result { + let view_label = share_s(lang, SK::AccessView); + let download_label = share_s(lang, SK::AccessDownload); + Ok(view! { + + + }) +} + +/// The people in one grant: the name, the email, the level, and the forms that change or remove it. +#[component] +pub async fn grant_row( + lang: Lang, + entry: &ShareEntry, + csrf: &str, + back: &str, +) -> Result { + let id = entry.share.id.as_str(); + let update_action = format!("/grants/{id}/update"); + let remove_action = format!("/grants/{id}/remove"); + let select_id = format!("level-{id}"); + let access = if entry.share.can_download { + share_s(lang, SK::AccessDownload) + } else { + share_s(lang, SK::AccessView) + }; + Ok(view! { +
  • +
    (entry.grantee_name.as_str()) " " (entry.grantee_email.as_str()) " \u{b7} " (access)
    +
    + + + level_select(lang: lang, name: "level", id: select_id.as_str(), download: entry.share.can_download) + +
    +
    + + + +
    +
  • + }) +} + +/// The share page's content: the people the item is shared with, the form that adds one, the links of the +/// item and the form that makes one. +#[component] +pub async fn share_body( + lang: Lang, + name: &str, + kind: &str, + id: &str, + entries: &[ShareEntry], + people: &[Member], + links: &[LinkView], + csrf: &str, + back: &str, + item_page: &str, + max_days: u32, + notice: &str, + refusal: &str, +) -> Result { + let max_days_text = max_days.to_string(); + Ok(view! { + + }) +} + +/// `GET /share/{kind}/{id}`: the share page of an item the viewer owns. +#[page("/share/{kind}/{id}")] +async fn share_page(cx: &Cx) -> Result { + let state = app_context::(cx); + let viewer = require_member(cx).await?; + let lang = viewer_lang(cx, &viewer); + let kind = kind_from_word(path_param_segment(cx, "kind")).ok_or_else(not_found)?; + let id = path_param_segment(cx, "id").to_owned(); + let name = shareable(state, &viewer, kind, &id).await?; + let me = viewer.member.sub.clone(); + let entries = state.store.shares_of(&me, kind, &id).await?; + let people: Vec = state + .store + .list_members() + .await? + .into_iter() + .filter(|member| !member.disabled && member.sub != me) + .collect(); + let mine = state + .store + .links_of(&me) + .await? + .into_iter() + .filter(|link| link.target_id == id) + .collect(); + let links = link_views(state, mine).await?; + let max_days = link_max_days(state).await?; + let query: ListQuery = topcoat::router::parse_query_params(cx).unwrap_or_default(); + let back = format!("/share/{}/{id}", kind_word(kind)); + let item_page = match kind { + ItemKind::File => format!("/view/{id}"), + ItemKind::Folder => format!("/drive/{id}"), + }; + let csrf = viewer.session.csrf_token.clone(); + let info = ViewerInfo::of(&viewer); + Ok(view! { + shell(title: name.as_str(), lang: lang, viewer: Some(&info), + share_body(lang: lang, name: name.as_str(), kind: kind_word(kind), id: id.as_str(), + entries: &entries, people: &people, links: &links, csrf: csrf.as_str(), + back: back.as_str(), item_page: item_page.as_str(), max_days: max_days, + notice: query.notice.as_str(), refusal: query.refusal.as_str()) + ) + }) +} + +/// `POST /grants`: shares an item with a person at a level, or changes the level of the grant they already +/// have. +#[route(POST "/grants")] +async fn create_grant(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + let viewer = require_csrf(cx, &form.csrf).await?; + let kind = kind_from_word(form.kind.trim()).ok_or_else(not_found)?; + let target = form.target_id.trim().to_owned(); + let default_back = format!("/share/{}/{target}", kind_word(kind)); + let back = back_or(&form.back, &default_back); + shareable(state, &viewer, kind, &target).await?; + let result = state + .store + .share_with( + &viewer.member.sub, + kind, + &target, + form.grantee.trim(), + form.level == "download", + ) + .await; + match result { + Ok(share) => { + notify(state, &share.grantee); + Ok(done(&back, "shared")) + } + Err(error) => refused(&back, error), + } +} + +/// The grant a write names, if the viewer owns it. A grant of someone else's item is `404`. +async fn owned_share(state: &AppState, viewer: &Viewer, id: &str) -> Result { + Ok(state + .store + .share_of(&viewer.member.sub, id) + .await? + .ok_or_else(not_found)?) +} + +/// `POST /grants/{id}/update`: changes a grant's level between view only and download. +#[route(POST "/grants/{id}/update")] +async fn update_grant(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + let viewer = require_csrf(cx, &form.csrf).await?; + let id = path_param_segment(cx, "id").to_owned(); + let share = owned_share(state, &viewer, &id).await?; + let default_back = format!("/share/{}/{}", kind_word(share.kind), share.target_id); + let back = back_or(&form.back, &default_back); + shareable(state, &viewer, share.kind, &share.target_id).await?; + match state + .store + .set_share_level(&viewer.member.sub, &id, form.level == "download") + .await + { + Ok(changed) => { + notify(state, &changed.grantee); + Ok(done(&back, "share_updated")) + } + Err(error) => refused(&back, error), + } +} + +/// `POST /grants/{id}/remove`: ends a grant. The grantee loses the item at once, and so does everything +/// below it that they reached through this grant. +#[route(POST "/grants/{id}/remove")] +async fn remove_grant(cx: &Cx, Form(form): Form) -> Result { + let state = app_context::(cx); + let viewer = require_csrf(cx, &form.csrf).await?; + let id = path_param_segment(cx, "id").to_owned(); + let share = owned_share(state, &viewer, &id).await?; + let default_back = format!("/share/{}/{}", kind_word(share.kind), share.target_id); + let back = back_or(&form.back, &default_back); + shareable(state, &viewer, share.kind, &share.target_id).await?; + match state.store.remove_share(&viewer.member.sub, &id).await { + Ok(removed) => { + notify(state, &removed.grantee); + Ok(done(&back, "unshared")) + } + Err(error) => refused(&back, error), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::auth::SESSION_COOKIE; + use crate::auth::test_support::signed_in; + use crate::boot::{router, test_state}; + use http::Request; + use http::header::COOKIE; + use in_core::quota::DEFAULT_MEMBER_QUOTA; + use in_core::store::files::NewFile; + use in_core::store::new_id; + use topcoat::router::Body; + + /// A file of `owner` in `folder` (or the top level), with a type that the viewer does not read. + async fn file_in(state: &AppState, owner: &str, folder: Option<&str>, name: &str) -> String { + state + .store + .insert_file(NewFile { + id: new_id(), + owner: owner.into(), + folder: folder.map(str::to_owned), + name: name.into(), + mime: "application/octet-stream".into(), + size: 0, + sha256: "0".repeat(64), + staged_claims: 0, + }) + .await + .expect("file") + .id + } + + async fn status_as(state: &AppState, path: &str, token: &str) -> u16 { + let request = Request::get(path) + .header(COOKIE, format!("{SESSION_COOKIE}={token}")) + .body(Body::empty()) + .expect("request"); + router(state.clone()) + .handle(request) + .await + .status() + .as_u16() + } + + /// A grantee reaches a file through its folder's grant until the file is moved out of that folder; then + /// the access is gone, with nothing copied or cleaned up. + #[tokio::test] + async fn grantee_loses_access_when_the_file_leaves_the_granted_folder() { + let (_dir, state) = test_state().await; + let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; + let bob = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await; + let trips = state + .store + .create_folder("ann", None, "Trips") + .await + .expect("folder"); + let other = state + .store + .create_folder("ann", None, "Other") + .await + .expect("folder"); + let file = file_in(&state, "ann", Some(&trips.id), "day1.bin").await; + state + .store + .share_with("ann", ItemKind::Folder, &trips.id, "bob", false) + .await + .expect("grant"); + let path = format!("/view/{file}"); + assert_eq!(status_as(&state, &path, &bob).await, 200); + + state + .store + .move_file("ann", &file, Some(&other.id)) + .await + .expect("move"); + assert_eq!(status_as(&state, &path, &bob).await, 404); + assert_eq!( + status_as(&state, &format!("/drive/{}", trips.id), &bob).await, + 200, + "the folder itself is still granted" + ); + } + + /// A trashed item under a grant is invisible to the grantee: the file itself, and the folder it was in. + #[tokio::test] + async fn a_trashed_item_under_a_grant_is_not_found_to_the_grantee() { + let (_dir, state) = test_state().await; + let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; + let bob = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await; + let trips = state + .store + .create_folder("ann", None, "Trips") + .await + .expect("folder"); + let file = file_in(&state, "ann", Some(&trips.id), "day1.bin").await; + state + .store + .share_with("ann", ItemKind::Folder, &trips.id, "bob", true) + .await + .expect("grant"); + state + .store + .trash_folder("ann", &trips.id) + .await + .expect("trash"); + assert_eq!(status_as(&state, &format!("/view/{file}"), &bob).await, 404); + assert_eq!( + status_as(&state, &format!("/file/{file}?dl=1"), &bob).await, + 404 + ); + assert_eq!( + status_as(&state, &format!("/drive/{}", trips.id), &bob).await, + 404 + ); + } + + /// Only the owner of a live item may share it: a grantee is refused with `403`, a stranger sees `404`. + #[tokio::test] + async fn a_grantee_cannot_share_further() { + let (_dir, state) = test_state().await; + let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; + let bob = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await; + let _cy = signed_in(&state, "cy", DEFAULT_MEMBER_QUOTA).await; + let trips = state + .store + .create_folder("ann", None, "Trips") + .await + .expect("folder"); + state + .store + .share_with("ann", ItemKind::Folder, &trips.id, "bob", true) + .await + .expect("grant"); + let cy = signed_in(&state, "cy", DEFAULT_MEMBER_QUOTA).await; + assert_eq!( + status_as(&state, &format!("/share/folder/{}", trips.id), &bob).await, + 403 + ); + assert_eq!( + status_as(&state, &format!("/share/folder/{}", trips.id), &cy).await, + 404 + ); + } +} diff --git a/crates/in-web/src/pages/shared.rs b/crates/in-web/src/pages/shared.rs new file mode 100644 index 0000000..6c311e0 --- /dev/null +++ b/crates/in-web/src/pages/shared.rs @@ -0,0 +1,152 @@ +//! Items shared with the viewer (`GET /shared`) and the stream that refreshes it (`GET /live/shared`). +//! +//! The page lists the top-level grants only: an item that lies under a folder shared with the viewer is +//! reached through that folder, not listed twice. Trashed items and items under a trashed folder are left +//! out by the store. Folders open in the drive (`/drive/{id}`), files in the viewer (`/view/{id}`), and the +//! download link appears only with a download grant. The owner's name is shown; no owner's folder is. + +use in_core::store::shares::SharedItem; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::error::not_found; +use topcoat::router::response::Response; +use topcoat::router::{page, route}; +use topcoat::view::{View, component, view}; + +use crate::auth::require_member; +use crate::i18n::Lang; +use crate::i18n::drive::{DK, d}; +use crate::i18n::share::{SK, s as share_s}; +use crate::live::{Topic, stream_changes}; +use crate::pages::drive::viewer_lang; +use crate::state::AppState; +use crate::views::drive::size_text; +use crate::views::{ViewerInfo, empty_state, shell}; + +/// The fingerprint of the shared page: every row's grant, name, level, size and owner. Equal text means the +/// page would look the same, so the stream stays quiet. +fn fingerprint(items: &[SharedItem]) -> String { + let mut text = String::new(); + for item in items { + text.push_str(&format!( + "{}|{}|{}|{}|{}|{}\n", + item.share.id, + item.name, + item.share.can_download, + item.size, + item.owner_name, + item.share.created_at + )); + } + text +} + +/// The shared page's content: a table of the items, folders first, each group by name. +#[component] +pub async fn shared_body(lang: Lang, items: &[SharedItem]) -> Result { + let mut sorted: Vec<&SharedItem> = items.iter().collect(); + sorted.sort_by(|a, b| { + let a_folder = a.share.kind == in_core::store::trash::ItemKind::Folder; + let b_folder = b.share.kind == in_core::store::trash::ItemKind::Folder; + b_folder + .cmp(&a_folder) + .then_with(|| a.name.cmp(&b.name)) + .then_with(|| a.share.id.cmp(&b.share.id)) + }); + Ok(view! { +
    +

    (share_s(lang, SK::SharedTitle))

    + if sorted.is_empty() { + empty_state(title: share_s(lang, SK::SharedEmpty),

    (share_s(lang, SK::SharedEmptyHint))

    ) + } else { +
    + + + + + + + + + + + + for item in sorted { + + + + + + + + } + +
    (d(lang, DK::Name))(share_s(lang, SK::SharePerson))(share_s(lang, SK::ShareLevel))(d(lang, DK::Size))(d(lang, DK::Actions))
    + if item.share.kind == in_core::store::trash::ItemKind::Folder { + (item.name.as_str()) + } else { + (item.name.as_str()) + } + (item.owner_name.as_str()) + if item.share.can_download { + (share_s(lang, SK::AccessDownload)) + } else { + (share_s(lang, SK::AccessView)) + } + + if item.share.kind == in_core::store::trash::ItemKind::File { + (size_text(item.size)) + } else { + "\u{2014}" + } + + if item.share.kind == in_core::store::trash::ItemKind::File && item.share.can_download { + (d(lang, DK::Download)) + } +
    +
    + } +
    + }) +} + +/// `GET /shared`: the items shared with the signed-in person. +#[page("/shared")] +async fn shared_page(cx: &Cx) -> Result { + let state = app_context::(cx); + let viewer = require_member(cx).await?; + let lang = viewer_lang(cx, &viewer); + let items = state.store.shared_with(&viewer.member.sub).await?; + let info = ViewerInfo::of(&viewer); + let title = share_s(lang, SK::SharedTitle); + Ok(view! { + shell(title: title, lang: lang, viewer: Some(&info), + shared_body(lang: lang, items: &items) + ) + }) +} + +/// `GET /live/shared`: a data-less `changed` event whenever the viewer's shared items change. It ends when +/// the session is gone. +#[route(GET "/live/shared")] +async fn shared_live(cx: &Cx) -> Result { + let state = app_context::(cx); + let viewer = require_member(cx).await?; + let me = viewer.member.sub.clone(); + let token_hash = viewer.session.token_hash.clone(); + let store = state.store.clone(); + let topics = vec![Topic::Shared(me.clone())]; + stream_changes(cx, &state.live, &topics, move || { + let store = store.clone(); + let me = me.clone(); + let token_hash = token_hash.clone(); + async move { + if store.session_by_token_hash(&token_hash).await?.is_none() { + return Err(not_found().into()); + } + let items = store.shared_with(&me).await?; + Ok(fingerprint(&items)) + } + }) + .await +} diff --git a/crates/in-web/src/pages/view.rs b/crates/in-web/src/pages/view.rs index 4cef360..1777307 100644 --- a/crates/in-web/src/pages/view.rs +++ b/crates/in-web/src/pages/view.rs @@ -12,19 +12,21 @@ //! both, which allows the same-origin bytes this page embeds. The bytes keep their own sandboxed CSP. use futures_util::StreamExt; -use in_core::authz::Action; +use in_core::authz::{Action, Grant}; use in_core::store::files::File; use in_core::store::folders::Listing; +use in_core::store::trash::ItemKind; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::page; use topcoat::router::{parse_query_params, path_param_segment}; use topcoat::view::{View, component, view}; -use crate::auth::require_member; +use crate::auth::{Viewer, require_member}; use crate::i18n::Lang; use crate::i18n::drive::{DK, d}; -use crate::pages::drive::{ListQuery, SortKey, sort_listing, viewer_lang}; +use crate::i18n::share::{SK, s as share_s}; +use crate::pages::drive::{ListQuery, SortKey, access_for, sort_listing, viewer_lang}; use crate::pages::files::file_for; use crate::serve_bytes::inline_safe; use crate::state::AppState; @@ -76,14 +78,26 @@ async fn text_head(state: &AppState, file: &File) -> Result<(String, bool)> { )) } +/// Whether the viewer may see the folder a file sits in: it is their own, or a grant reaches it. The top +/// level is the owner's alone. A grantee's neighbours come from a listing they may see, so the folder must +/// be visible to them, not only the file. +async fn folder_visible(state: &AppState, viewer: &Viewer, file: &File) -> Result { + let Some(folder) = file.folder_id.as_deref() else { + return Ok(file.owner == viewer.member.sub); + }; + if file.owner == viewer.member.sub { + return Ok(true); + } + let access = state + .store + .access_of(&viewer.member.sub, ItemKind::Folder, folder) + .await?; + Ok(access.is_some_and(|a| !a.trashed && a.grant != Grant::None)) +} + /// The viewer links of the files before and after `file` in its folder, in the listing's sort order. Each is a /// `/view` link that carries the sort, so stepping through keeps the order. Empty when there is none. -async fn neighbours( - state: &AppState, - owner: &str, - file: &File, - query: &ListQuery, -) -> Result<(String, String)> { +async fn neighbours(state: &AppState, file: &File, query: &ListQuery) -> Result<(String, String)> { if file.trashed_at.is_some() { return Ok((String::new(), String::new())); } @@ -91,7 +105,7 @@ async fn neighbours( let descending = query.dir == "desc"; let mut listing: Listing = state .store - .list_children(owner, file.folder_id.as_deref()) + .list_children(&file.owner, file.folder_id.as_deref()) .await?; sort_listing(&mut listing, key, descending); let Some(at) = listing.files.iter().position(|f| f.id == file.id) else { @@ -183,6 +197,8 @@ pub async fn viewer_body( next: &str, notice: &str, refusal: &str, + writable: bool, + downloadable: bool, ) -> Result { let download = format!("/file/{}?dl=1", file.id); let open = format!("/file/{}", file.id); @@ -193,12 +209,19 @@ pub async fn viewer_body( flash(lang: lang, notice: notice, refusal: refusal)

    (file.name.as_str())

    (file.mime.as_str()) " \u{b7} " (size_text(file.size)) " \u{b7} " (stamp_text(&file.updated_at))

    + if !writable && !downloadable { +

    (share_s(lang, SK::AccessView))

    + } viewer_nav(lang: lang, prev: prev, next: next) viewer_stage(lang: lang, file: file, kind: kind, text: text, truncated: truncated)
    - (d(lang, DK::Download)) + if downloadable { + (d(lang, DK::Download)) + } (d(lang, DK::OpenRaw)) - row_menu(lang: lang, csrf: csrf, back: here.as_str(), kind: "file", id: file.id.as_str(), name: file.name.as_str()) + if writable { + row_menu(lang: lang, csrf: csrf, back: here.as_str(), kind: "file", id: file.id.as_str(), name: file.name.as_str()) + }
    }) @@ -213,20 +236,36 @@ async fn view_page(cx: &Cx) -> Result { let id = path_param_segment(cx, "id").to_owned(); let query: ListQuery = parse_query_params(cx).unwrap_or_default(); let file = file_for(state, &viewer, &id, Action::View).await?; + let access = access_for(state, &viewer, ItemKind::File, &id).await?; + let owned = file.owner == viewer.member.sub; + let writable = owned && file.trashed_at.is_none(); + let downloadable = owned || access.grant == Grant::Download; let kind = viewer_kind(&file.mime); let (text, truncated) = if kind == "text" { text_head(state, &file).await? } else { (String::new(), false) }; - let (prev, next) = neighbours(state, &viewer.member.sub, &file, &query).await?; + let visible = folder_visible(state, &viewer, &file).await?; + let (prev, next) = if owned || visible { + neighbours(state, &file, &query).await? + } else { + (String::new(), String::new()) + }; + // Back goes to the owner's listing, the shared page, or the trash, and never to a folder the viewer + // cannot see. let back = if file.trashed_at.is_some() { "/trash".to_owned() - } else { + } else if owned { match file.folder_id.as_deref() { Some(folder) => format!("/drive/{folder}"), None => "/drive".to_owned(), } + } else { + match (visible, file.folder_id.as_deref()) { + (true, Some(folder)) => format!("/drive/{folder}"), + _ => "/shared".to_owned(), + } }; let csrf = viewer.session.csrf_token.clone(); let info = ViewerInfo::of(&viewer); @@ -235,7 +274,8 @@ async fn view_page(cx: &Cx) -> Result { shell(title: title.as_str(), lang: lang, viewer: Some(&info), viewer_body(lang: lang, file: &file, back: back.as_str(), csrf: csrf.as_str(), kind: kind, text: text.as_str(), truncated: truncated, prev: prev.as_str(), next: next.as_str(), - notice: query.notice.as_str(), refusal: query.refusal.as_str()) + notice: query.notice.as_str(), refusal: query.refusal.as_str(), + writable: writable, downloadable: downloadable) ) }) } diff --git a/crates/in-web/src/security.rs b/crates/in-web/src/security.rs index 43cb522..1e49c78 100644 --- a/crates/in-web/src/security.rs +++ b/crates/in-web/src/security.rs @@ -6,13 +6,43 @@ //! `docs/conventions.md` section 5. use topcoat::context::Cx; +use topcoat::router::request::uri; use topcoat::router::response::response_headers; -use topcoat::router::{Body, HeaderMap, HeaderValue, Layer, LayerFuture, Next, Path, header}; +use topcoat::router::{ + Body, HeaderMap, HeaderName, HeaderValue, Layer, LayerFuture, Next, Path, header, +}; /// The Content-Security-Policy of every response. pub const CSP: &str = "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; \ form-action 'self'; frame-ancestors 'none'; base-uri 'none'"; +/// Path prefix of the public share pages and their bytes. The token is in the path, so these pages send no +/// referrer and ask search engines not to index them (architecture section 8). +pub const SHARE_PREFIX: &str = "/s/"; + +/// `Referrer-Policy` of the public share pages: the token in the URL must never reach another site. +const SHARE_REFERRER: &str = "no-referrer"; + +/// `X-Robots-Tag` of the public share pages. +const SHARE_ROBOTS: &str = "noindex"; + +/// The headers of `base` as they apply to a request for `path`: on a public share path the referrer and +/// robots headers are replaced, everywhere else `base` is used as it is. +fn for_path(base: &HeaderMap, path: &str) -> HeaderMap { + let mut headers = base.clone(); + if path.starts_with(SHARE_PREFIX) { + headers.insert( + header::REFERRER_POLICY, + HeaderValue::from_static(SHARE_REFERRER), + ); + headers.insert( + HeaderName::from_static("x-robots-tag"), + HeaderValue::from_static(SHARE_ROBOTS), + ); + } + headers +} + /// One year, in seconds. Sent only when the public origin is https. const HSTS: &str = "max-age=31536000"; @@ -63,14 +93,16 @@ impl Layer for SecurityHeaders { fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { Box::pin(async move { + let path = uri(cx).path().to_owned(); + let headers = for_path(&self.headers, &path); match next.run(cx, body).await { // A header the route set itself wins: byte responses carry their own sandboxed // policy, and two policies would apply both (the page one forbids framing). Ok(mut response) => { - let headers = response.headers_mut(); - for (name, value) in &self.headers { - if !headers.contains_key(name) { - headers.insert(name.clone(), value.clone()); + let response_map = response.headers_mut(); + for (name, value) in &headers { + if !response_map.contains_key(name) { + response_map.insert(name.clone(), value.clone()); } } Ok(response) @@ -78,7 +110,7 @@ impl Layer for SecurityHeaders { // Errors become responses after the layers have run; the per-request slot gives // them the headers too. Err(error) => { - response_headers(cx).extend(self.headers.clone()); + response_headers(cx).extend(headers); Err(error) } } @@ -90,6 +122,17 @@ impl Layer for SecurityHeaders { mod tests { use super::*; + #[test] + fn share_paths_send_no_referrer_and_no_index() { + let base = headers_for("https://in.example.com"); + let share = for_path(&base, "/s/abc"); + assert_eq!(share[header::REFERRER_POLICY], "no-referrer"); + assert_eq!(share["x-robots-tag"], "noindex"); + let drive = for_path(&base, "/drive"); + assert_eq!(drive[header::REFERRER_POLICY], "same-origin"); + assert!(!drive.contains_key("x-robots-tag")); + } + #[test] fn hsts_only_for_https_origins() { assert!( diff --git a/crates/in-web/src/serve_bytes.rs b/crates/in-web/src/serve_bytes.rs index 61e81d0..a340327 100644 --- a/crates/in-web/src/serve_bytes.rs +++ b/crates/in-web/src/serve_bytes.rs @@ -69,6 +69,10 @@ pub const PDF_CSP: &str = "default-src 'none'; img-src 'self'; media-src 'self'; /// Cache policy of content addressed by id and hash: the bytes behind a URL never change. const BYTES_CACHE: &str = "private, max-age=31536000, immutable"; +/// Cache policy of bytes behind a public share link. The link can be revoked or its password changed, so +/// a cached copy must not outlive the check: the browser asks again every time. +pub const SHARE_CACHE: &str = "private, no-cache"; + /// The outcome of reading a `Range` header against a length. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Ranged { @@ -264,7 +268,7 @@ pub fn content_disposition(kind: Disposition, name: &str) -> String { } /// The headers every byte response carries, whatever its status. -fn common_headers(etag: &str, mime: &str) -> HeaderMap { +fn common_headers(etag: &str, mime: &str, cache: &str) -> HeaderMap { let mut headers = HeaderMap::new(); insert(&mut headers, ETAG, etag); headers.insert(ACCEPT_RANGES, HeaderValue::from_static("bytes")); @@ -280,7 +284,7 @@ fn common_headers(etag: &str, mime: &str) -> HeaderMap { HeaderName::from_static("cross-origin-resource-policy"), HeaderValue::from_static("same-origin"), ); - headers.insert(CACHE_CONTROL, HeaderValue::from_static(BYTES_CACHE)); + insert(&mut headers, CACHE_CONTROL, cache); headers } @@ -293,8 +297,8 @@ fn insert(headers: &mut HeaderMap, name: http::HeaderName, value: &str) { } /// The `416` answer: no body, and the length the client may ask again within. -fn unsatisfiable(etag: &str, len: u64) -> ByteAnswer { - let mut headers = common_headers(etag, ""); +fn unsatisfiable(etag: &str, len: u64, cache: &str) -> ByteAnswer { + let mut headers = common_headers(etag, "", cache); insert(&mut headers, CONTENT_RANGE, &format!("bytes */{len}")); (StatusCode::RANGE_NOT_SATISFIABLE, headers, Body::empty()) } @@ -310,6 +314,18 @@ pub async fn serve_bytes( blobs: &dyn BlobStore, source: &ByteSource<'_>, disposition: Disposition, +) -> Result { + serve_bytes_with(cx, blobs, source, disposition, BYTES_CACHE).await +} + +/// [`serve_bytes`] with the cache policy given: the owner's bytes use [`BYTES_CACHE`], share-link bytes +/// use [`SHARE_CACHE`]. Everything else is the same. +pub async fn serve_bytes_with( + cx: &Cx, + blobs: &dyn BlobStore, + source: &ByteSource<'_>, + disposition: Disposition, + cache: &str, ) -> Result { let request = headers(cx); let etag = format!("\"{}\"", source.sha256); @@ -317,7 +333,7 @@ pub async fn serve_bytes( Disposition::Inline if inline_safe(source.mime) => Disposition::Inline, _ => Disposition::Attachment, }; - let mut answer_headers = common_headers(&etag, source.mime); + let mut answer_headers = common_headers(&etag, source.mime, cache); insert( &mut answer_headers, CONTENT_DISPOSITION, @@ -334,7 +350,7 @@ pub async fn serve_bytes( } match requested_range(request, &etag, source.size) { - Ranged::Unsatisfiable => Ok(unsatisfiable(&etag, source.size)), + Ranged::Unsatisfiable => Ok(unsatisfiable(&etag, source.size, cache)), Ranged::Full => { insert( &mut answer_headers, diff --git a/crates/in-web/src/state.rs b/crates/in-web/src/state.rs index 1f45e2b..1b8f2b9 100644 --- a/crates/in-web/src/state.rs +++ b/crates/in-web/src/state.rs @@ -8,6 +8,7 @@ use in_core::store::Store; use crate::live::LiveHub; use crate::oidc::OidcClient; +use crate::throttle::ShareThrottles; /// Everything a request handler reaches through the app context. Every field is cheap to clone. #[allow(dead_code)] // The live hub is read by the live pages, which come after sign-in. @@ -26,4 +27,6 @@ pub struct AppState { /// The OpenID Connect client of `im`. `None` when the configuration has no `[oidc]` table, in which /// case nobody can sign in and the sign-in routes say so. pub oidc: Option>, + /// The failure windows of share-link passwords. + pub throttles: Arc, } diff --git a/crates/in-web/src/throttle.rs b/crates/in-web/src/throttle.rs new file mode 100644 index 0000000..2114d06 --- /dev/null +++ b/crates/in-web/src/throttle.rs @@ -0,0 +1,115 @@ +//! Failure throttling in memory: a sliding window of failures per key, with a bounded number of keys. +//! +//! A check asks [`Throttle::blocked`] before any lookup and answers `429` with `Retry-After` when the key +//! has reached its limit. A failure is recorded with [`Throttle::failure`]. Nothing is persisted, so a +//! restart forgets the failures; that is accepted for a family instance and documented in the backlog. +//! +//! The key count is capped. When a new key would exceed the cap, the windows that have expired are +//! dropped first, and then the key whose last failure is oldest. So an attacker who spreads guesses over +//! many keys can only evict other keys, never grow the memory. + +use std::collections::HashMap; +use std::sync::{Mutex, MutexGuard, PoisonError}; +use std::time::{Duration, Instant}; + +/// Length of the sliding window for share-link passwords: 15 minutes. +pub const PASSWORD_WINDOW: Duration = Duration::from_secs(15 * 60); + +/// Failed password attempts allowed against one link in a window. The sixth is refused with `429`. +pub const LINK_PASSWORD_LIMIT: usize = 5; + +/// Failed password attempts allowed from one client address in a window, across all links. +pub const IP_PASSWORD_LIMIT: usize = 10; + +/// Most keys held at once. Each key is a short string and a short list of instants. +pub const MAX_KEYS: usize = 10_000; + +/// Failures per key within a sliding window, with a cap on the number of keys. +pub struct Throttle { + failures: Mutex>>, + window: Duration, + limit: usize, + max_keys: usize, +} + +impl Throttle { + /// A throttle that blocks a key after `limit` failures within `window`. + pub fn new(window: Duration, limit: usize, max_keys: usize) -> Self { + Self { + failures: Mutex::new(HashMap::new()), + window, + limit, + max_keys, + } + } + + /// Locks the map. A poisoned lock is used as it is: a panic elsewhere must not open the throttle. + fn map(&self) -> MutexGuard<'_, HashMap>> { + self.failures.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// The seconds `key` must wait before it may try again, or `None` when it may try now. Only failures + /// inside the window count. + pub fn blocked(&self, key: &str) -> Option { + let now = Instant::now(); + let mut map = self.map(); + let stamps = map.get_mut(key)?; + stamps.retain(|at| now.duration_since(*at) < self.window); + if stamps.len() < self.limit { + return None; + } + // The key may try again once enough failures have left the window: the one at this index is the + // last to leave before the count drops below the limit. + let index = stamps.len() - self.limit; + let free_at = stamps[index] + self.window; + let wait = free_at.saturating_duration_since(now); + // Rounded up, and at least one second, so `Retry-After` is never zero for a blocked key. + let seconds = wait.as_secs() + u64::from(wait.subsec_nanos() > 0); + Some(seconds.max(1)) + } + + /// Records one failure of `key` now. + pub fn failure(&self, key: &str) { + let now = Instant::now(); + let mut map = self.map(); + if !map.contains_key(key) && map.len() >= self.max_keys { + self.make_room(&mut map, now); + } + map.entry(key.to_owned()).or_default().push(now); + } + + /// Frees one slot: expired windows go first, then the key with the oldest last failure. + fn make_room(&self, map: &mut HashMap>, now: Instant) { + let window = self.window; + map.retain(|_, stamps| { + stamps.retain(|at| now.duration_since(*at) < window); + !stamps.is_empty() + }); + if map.len() >= self.max_keys { + let oldest = map + .iter() + .min_by_key(|(_, stamps)| stamps.last().copied()) + .map(|(key, _)| key.clone()); + if let Some(key) = oldest { + map.remove(&key); + } + } + } +} + +/// The two throttles of share-link passwords: one per link (by token hash) and one per client address. +pub struct ShareThrottles { + /// Failures per link. + pub per_link: Throttle, + /// Failures per client address. + pub per_ip: Throttle, +} + +impl Default for ShareThrottles { + fn default() -> Self { + Self { + per_link: Throttle::new(PASSWORD_WINDOW, LINK_PASSWORD_LIMIT, MAX_KEYS), + per_ip: Throttle::new(PASSWORD_WINDOW, IP_PASSWORD_LIMIT, MAX_KEYS), + } + } +} diff --git a/crates/in-web/src/views/drive.rs b/crates/in-web/src/views/drive.rs index 8f656f7..31e0f5a 100644 --- a/crates/in-web/src/views/drive.rs +++ b/crates/in-web/src/views/drive.rs @@ -10,6 +10,7 @@ use topcoat::view::{View, component, view}; use crate::i18n::Lang; use crate::i18n::drive::{DK, d, notice_text, quota_text, refusal_text}; +use crate::i18n::share::{SK, s as share_s}; use in_core::store::files::File; use in_core::store::folders::Folder; @@ -81,13 +82,20 @@ pub fn kind_glyph(mime: &str) -> &'static str { } } -/// The breadcrumb trail, top level first. Empty for the top level, which needs no trail. +/// The breadcrumb trail, top level first. Empty for the top level, which needs no trail. The first crumb is +/// the viewer's drive, or the shared page when the listing is shared with the viewer. A shared trail starts +/// at the granted folder, so nothing above it is named. #[component] -pub async fn crumbs(lang: Lang, trail: &[Folder]) -> Result { +pub async fn crumbs(lang: Lang, trail: &[Folder], shared: bool) -> Result { + let (root_href, root_label) = if shared { + ("/shared", share_s(lang, SK::SharedTitle)) + } else { + ("/drive", d(lang, DK::Drive)) + }; Ok(view! {