Sharing: per-person grants, shared page, share links with password gate and throttle, public share pages
Browse files at this commit9c306fbb4206f5e9ca8e2a3ed8a8c7c2ecf40526Parent: fea1d3f- feat
- sharing: per-person grants, shared page, share links with password gate and throttle, public share pages
23 changed files +3360 -66
- crates/in-core/src/secret.rs +32 -0
- crates/in-core/src/store/links.rs +325 -0
- crates/in-core/src/store/mod.rs +2 -0
- crates/in-core/src/store/shares.rs +611 -0
- crates/in-web/src/boot.rs +3 -0
- crates/in-web/src/i18n/drive.rs +2 -2
- crates/in-web/src/i18n/mod.rs +1 -0
- crates/in-web/src/i18n/share.rs +280 -0
- crates/in-web/src/main.rs +1 -0
- crates/in-web/src/pages/drive.rs +154 -19
- crates/in-web/src/pages/files.rs +5 -3
- crates/in-web/src/pages/links.rs +292 -0
- crates/in-web/src/pages/mod.rs +4 -0
- crates/in-web/src/pages/public_share.rs +720 -0
- crates/in-web/src/pages/share_dialog.rs +484 -0
- crates/in-web/src/pages/shared.rs +152 -0
- crates/in-web/src/pages/view.rs +55 -15
- crates/in-web/src/security.rs +49 -6
- crates/in-web/src/serve_bytes.rs +22 -6
- crates/in-web/src/state.rs +3 -0
- crates/in-web/src/throttle.rs +115 -0
- crates/in-web/src/views/drive.rs +45 -15
- crates/in-web/src/views/mod.rs +3 -0
crates/in-core/src/secret.rsmodified+32 -0
| @@ -6,6 +6,8 @@ use std::path::Path; | |||
| 6 | use base64::prelude::{BASE64_STANDARD, Engine as _}; | 6 | use base64::prelude::{BASE64_STANDARD, Engine as _}; |
| 7 | use chacha20poly1305::aead::Aead; | 7 | use chacha20poly1305::aead::Aead; |
| 8 | use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce}; | 8 | use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce}; |
| 9 | +use hmac::{Hmac, Mac}; | ||
| 10 | +use sha2::Sha256; | ||
| 9 | 11 | ||
| 10 | use crate::error::{Error, Result}; | 12 | use crate::error::{Error, Result}; |
| 11 | 13 | ||
| @@ -94,6 +96,20 @@ pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result<String> { | |||
| 94 | Ok(format!("{PREFIX}{}", BASE64_STANDARD.encode(blob))) | 96 | Ok(format!("{PREFIX}{}", BASE64_STANDARD.encode(blob))) |
| 95 | } | 97 | } |
| 96 | 98 | ||
| 99 | +/// The proof a share-link visitor holds after the right password: an HMAC-SHA256 under the instance key | ||
| 100 | +/// over the link id and the stored password hash, in lower-case hex. Changing the password or reminting | ||
| 101 | +/// the link changes one of those inputs, so every old proof stops working. It is a cookie value, so the | ||
| 102 | +/// key never leaves the server and the password itself is never stored in a cookie. | ||
| 103 | +pub fn unlock_proof(key: &[u8; 32], link_id: &str, password_hash: &str) -> String { | ||
| 104 | + let mut mac = <Hmac<Sha256> as hmac::KeyInit>::new_from_slice(key) | ||
| 105 | + .expect("HMAC accepts a key of any length"); | ||
| 106 | + mac.update(b"link-unlock:"); | ||
| 107 | + mac.update(link_id.as_bytes()); | ||
| 108 | + mac.update(b"|"); | ||
| 109 | + mac.update(password_hash.as_bytes()); | ||
| 110 | + hex::encode(mac.finalize().into_bytes()) | ||
| 111 | +} | ||
| 112 | + | ||
| 97 | /// Opens a value produced by [`seal`]. A wrong key, a changed byte or a malformed value is an error. | 113 | /// Opens a value produced by [`seal`]. A wrong key, a changed byte or a malformed value is an error. |
| 98 | pub fn open(key: &[u8; 32], sealed: &str) -> Result<Vec<u8>> { | 114 | pub fn open(key: &[u8; 32], sealed: &str) -> Result<Vec<u8>> { |
| 99 | let encoded = sealed | 115 | let encoded = sealed |
| @@ -135,3 +151,19 @@ mod tests { | |||
| 135 | assert!(open(&key, "data").is_err(), "missing prefix must fail"); | 151 | assert!(open(&key, "data").is_err(), "missing prefix must fail"); |
| 136 | } | 152 | } |
| 137 | } | 153 | } |
| 154 | + | ||
| 155 | +#[cfg(test)] | ||
| 156 | +mod proof_tests { | ||
| 157 | + use super::*; | ||
| 158 | + | ||
| 159 | + #[test] | ||
| 160 | + fn an_unlock_proof_changes_with_any_input() { | ||
| 161 | + let key = [7u8; 32]; | ||
| 162 | + let base = unlock_proof(&key, "link-a", "$argon2id$hash"); | ||
| 163 | + assert_eq!(base.len(), 64); | ||
| 164 | + assert_eq!(base, unlock_proof(&key, "link-a", "$argon2id$hash")); | ||
| 165 | + assert_ne!(base, unlock_proof(&key, "link-b", "$argon2id$hash")); | ||
| 166 | + assert_ne!(base, unlock_proof(&key, "link-a", "$argon2id$other")); | ||
| 167 | + assert_ne!(base, unlock_proof(&[8u8; 32], "link-a", "$argon2id$hash")); | ||
| 168 | + } | ||
| 169 | +} | ||
crates/in-core/src/store/links.rsadded+325 -0
| @@ -0,0 +1,325 @@ | |||
| 1 | +//! Public share links (architecture sections 3 and 8). A link names one file or folder and carries the | ||
| 2 | +//! token's SHA-256 (the token itself is never stored in the clear), a sealed copy of the token so the owner | ||
| 3 | +//! can show the URL again, the download flag, an optional argon2id password hash and an expiry. | ||
| 4 | +//! | ||
| 5 | +//! This module stores and finds links. Whether a visitor may see something through a link is decided by | ||
| 6 | +//! the web layer with `authz` (the link actor) and the store's `is_within` and `item_trashed`. | ||
| 7 | + | ||
| 8 | +use turso::{Connection, Row}; | ||
| 9 | + | ||
| 10 | +use crate::error::{Error, Result}; | ||
| 11 | +use crate::store::files::live_file; | ||
| 12 | +use crate::store::folders::live_folder; | ||
| 13 | +use crate::store::shares::{kind_from_word, kind_word}; | ||
| 14 | +use crate::store::trash::ItemKind; | ||
| 15 | +use crate::store::{ | ||
| 16 | + Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, missing_row, | ||
| 17 | + new_id, | ||
| 18 | +}; | ||
| 19 | +use crate::time::now_stamp; | ||
| 20 | + | ||
| 21 | +/// Column list for [`map_link`]. Keep the two in step. | ||
| 22 | +pub const LINK_COLS: &str = "id, token_hash, token_sealed, target_kind, target_id, owner, can_download, \ | ||
| 23 | + password_hash, expires_at, revoked_at, created_at, last_used_at, use_count"; | ||
| 24 | + | ||
| 25 | +/// One row of the `links` table. | ||
| 26 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 27 | +pub struct Link { | ||
| 28 | + /// Link id (a lower-case ULID). It names the unlock cookie. | ||
| 29 | + pub id: String, | ||
| 30 | + /// Hex SHA-256 of the token. Lookups go through it. | ||
| 31 | + pub token_hash: String, | ||
| 32 | + /// The token, sealed under the instance key, so the owner can show the URL again. | ||
| 33 | + pub token_sealed: String, | ||
| 34 | + /// Whether the target is a file or a folder. | ||
| 35 | + pub kind: ItemKind, | ||
| 36 | + /// The file or folder the link opens. For a folder, everything below it too. | ||
| 37 | + pub target_id: String, | ||
| 38 | + /// The owner of the target, who made the link. | ||
| 39 | + pub owner: String, | ||
| 40 | + /// Whether visitors may download, not only view. | ||
| 41 | + pub can_download: bool, | ||
| 42 | + /// The argon2id hash of the password, when the link has one. | ||
| 43 | + pub password_hash: Option<String>, | ||
| 44 | + /// When the link stops working, if it has an expiry. | ||
| 45 | + pub expires_at: Option<String>, | ||
| 46 | + /// When the link was revoked. A revoked link never works again. | ||
| 47 | + pub revoked_at: Option<String>, | ||
| 48 | + /// When the link was made. | ||
| 49 | + pub created_at: String, | ||
| 50 | + /// The last time a visitor opened the link's page. | ||
| 51 | + pub last_used_at: Option<String>, | ||
| 52 | + /// How many times a visitor opened the link's page. | ||
| 53 | + pub use_count: i64, | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +impl Link { | ||
| 57 | + /// Whether the link still works at `now` (a stamp of this format): not revoked and not expired. | ||
| 58 | + /// The target's own trash state is checked separately. | ||
| 59 | + pub fn is_live(&self, now: &str) -> bool { | ||
| 60 | + self.revoked_at.is_none() && self.expires_at.as_deref().is_none_or(|at| at > now) | ||
| 61 | + } | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +/// What a new link needs. The token is generated and sealed by the caller. | ||
| 65 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 66 | +pub struct NewLink { | ||
| 67 | + /// Id, made by the caller so it is known before the insert. | ||
| 68 | + pub id: String, | ||
| 69 | + /// Hex SHA-256 of the token. | ||
| 70 | + pub token_hash: String, | ||
| 71 | + /// The sealed token. | ||
| 72 | + pub token_sealed: String, | ||
| 73 | + /// Whether the target is a file or a folder. | ||
| 74 | + pub kind: ItemKind, | ||
| 75 | + /// The target's id. | ||
| 76 | + pub target_id: String, | ||
| 77 | + /// The owner, who must own the live target. | ||
| 78 | + pub owner: String, | ||
| 79 | + /// Whether visitors may download. | ||
| 80 | + pub can_download: bool, | ||
| 81 | + /// The argon2id hash of the password, if any. | ||
| 82 | + pub password_hash: Option<String>, | ||
| 83 | + /// When the link stops working, if it has an expiry. | ||
| 84 | + pub expires_at: Option<String>, | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +/// Maps a row selected with [`LINK_COLS`]. | ||
| 88 | +fn map_link(row: &Row) -> Result<Link> { | ||
| 89 | + let kind = kind_from_word(&col_text(row, 3)?) | ||
| 90 | + .ok_or_else(|| Error::Database("link with an unknown target kind".into()))?; | ||
| 91 | + Ok(Link { | ||
| 92 | + id: col_text(row, 0)?, | ||
| 93 | + token_hash: col_text(row, 1)?, | ||
| 94 | + token_sealed: col_text(row, 2)?, | ||
| 95 | + kind, | ||
| 96 | + target_id: col_text(row, 4)?, | ||
| 97 | + owner: col_text(row, 5)?, | ||
| 98 | + can_download: col_int(row, 6)? != 0, | ||
| 99 | + password_hash: col_opt_text(row, 7)?, | ||
| 100 | + expires_at: col_opt_text(row, 8)?, | ||
| 101 | + revoked_at: col_opt_text(row, 9)?, | ||
| 102 | + created_at: col_text(row, 10)?, | ||
| 103 | + last_used_at: col_opt_text(row, 11)?, | ||
| 104 | + use_count: col_int(row, 12)?, | ||
| 105 | + }) | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +/// Inserts a link row. The caller has checked the target and runs inside a transaction. | ||
| 109 | +async fn insert_link_in(conn: &Connection, new: &NewLink) -> Result<()> { | ||
| 110 | + conn.execute( | ||
| 111 | + "INSERT INTO links (id, token_hash, token_sealed, target_kind, target_id, owner, can_download, \ | ||
| 112 | + password_hash, expires_at, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)", | ||
| 113 | + ( | ||
| 114 | + new.id.clone(), | ||
| 115 | + new.token_hash.clone(), | ||
| 116 | + new.token_sealed.clone(), | ||
| 117 | + kind_word(new.kind).to_string(), | ||
| 118 | + new.target_id.clone(), | ||
| 119 | + new.owner.clone(), | ||
| 120 | + i64::from(new.can_download), | ||
| 121 | + new.password_hash.clone(), | ||
| 122 | + new.expires_at.clone(), | ||
| 123 | + now_stamp(), | ||
| 124 | + ), | ||
| 125 | + ) | ||
| 126 | + .await | ||
| 127 | + .map_err(db_err)?; | ||
| 128 | + Ok(()) | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +/// The link with this id that `owner` made, revoked or not. | ||
| 132 | +async fn link_of_owner(conn: &Connection, owner: &str, id: &str) -> Result<Option<Link>> { | ||
| 133 | + fetch_opt( | ||
| 134 | + conn, | ||
| 135 | + &format!("SELECT {LINK_COLS} FROM links WHERE id = ?1 AND owner = ?2"), | ||
| 136 | + (id.to_string(), owner.to_string()), | ||
| 137 | + map_link, | ||
| 138 | + ) | ||
| 139 | + .await | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +/// Checks that `owner` owns a live (not trashed) target. Anything else is `NotFound`. | ||
| 143 | +async fn check_target(conn: &Connection, owner: &str, kind: ItemKind, id: &str) -> Result<()> { | ||
| 144 | + match kind { | ||
| 145 | + ItemKind::File => live_file(conn, owner, id).await.map(|_| ()), | ||
| 146 | + ItemKind::Folder => live_folder(conn, owner, id).await.map(|_| ()), | ||
| 147 | + } | ||
| 148 | +} | ||
| 149 | + | ||
| 150 | +impl Store { | ||
| 151 | + /// Creates a link to a live item of `owner`. | ||
| 152 | + pub async fn create_link(&self, new: NewLink) -> Result<Link> { | ||
| 153 | + let conn = self.inner.conn.lock().await; | ||
| 154 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 155 | + let outcome: Result<Link> = async { | ||
| 156 | + check_target(&tx, &new.owner, new.kind, &new.target_id).await?; | ||
| 157 | + insert_link_in(&tx, &new).await?; | ||
| 158 | + link_of_owner(&tx, &new.owner, &new.id) | ||
| 159 | + .await? | ||
| 160 | + .ok_or_else(missing_row) | ||
| 161 | + } | ||
| 162 | + .await; | ||
| 163 | + finish(tx, outcome).await | ||
| 164 | + } | ||
| 165 | + | ||
| 166 | + /// The links of `owner` that have not been revoked, oldest first. Expired ones are included, so the | ||
| 167 | + /// owner sees why a link stopped. | ||
| 168 | + pub async fn links_of(&self, owner: &str) -> Result<Vec<Link>> { | ||
| 169 | + let conn = self.read_conn().await; | ||
| 170 | + fetch_all( | ||
| 171 | + &conn, | ||
| 172 | + &format!( | ||
| 173 | + "SELECT {LINK_COLS} FROM links WHERE owner = ?1 AND revoked_at IS NULL \ | ||
| 174 | + ORDER BY created_at, id" | ||
| 175 | + ), | ||
| 176 | + (owner.to_string(),), | ||
| 177 | + map_link, | ||
| 178 | + ) | ||
| 179 | + .await | ||
| 180 | + } | ||
| 181 | + | ||
| 182 | + /// The link with this id, if `owner` made it (revoked links included). | ||
| 183 | + pub async fn link_of(&self, owner: &str, id: &str) -> Result<Option<Link>> { | ||
| 184 | + let conn = self.read_conn().await; | ||
| 185 | + link_of_owner(&conn, owner, id).await | ||
| 186 | + } | ||
| 187 | + | ||
| 188 | + /// Revokes a link of `owner`. Revoking again changes nothing. | ||
| 189 | + pub async fn revoke_link(&self, owner: &str, id: &str) -> Result<()> { | ||
| 190 | + let conn = self.inner.conn.lock().await; | ||
| 191 | + let changed = conn | ||
| 192 | + .execute( | ||
| 193 | + "UPDATE links SET revoked_at = COALESCE(revoked_at, ?3) WHERE id = ?1 AND owner = ?2", | ||
| 194 | + (id.to_string(), owner.to_string(), now_stamp()), | ||
| 195 | + ) | ||
| 196 | + .await | ||
| 197 | + .map_err(db_err)?; | ||
| 198 | + if changed == 0 { | ||
| 199 | + return Err(Error::NotFound); | ||
| 200 | + } | ||
| 201 | + Ok(()) | ||
| 202 | + } | ||
| 203 | + | ||
| 204 | + /// Gives a live link of `owner` a new token and kills the old one, in one transaction. The new link | ||
| 205 | + /// keeps the target, the download flag, the password and the expiry. A link that is already revoked, | ||
| 206 | + /// or expired, cannot be reminted: `NotFound` for a revoked one, `Conflict("link_expired")` for an | ||
| 207 | + /// expired one. | ||
| 208 | + pub async fn remint_link( | ||
| 209 | + &self, | ||
| 210 | + owner: &str, | ||
| 211 | + id: &str, | ||
| 212 | + token_hash: &str, | ||
| 213 | + token_sealed: &str, | ||
| 214 | + ) -> Result<Link> { | ||
| 215 | + let conn = self.inner.conn.lock().await; | ||
| 216 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 217 | + let outcome: Result<Link> = async { | ||
| 218 | + let old = link_of_owner(&tx, owner, id).await?.ok_or(Error::NotFound)?; | ||
| 219 | + if old.revoked_at.is_some() { | ||
| 220 | + return Err(Error::NotFound); | ||
| 221 | + } | ||
| 222 | + if !old.is_live(&now_stamp()) { | ||
| 223 | + return Err(Error::Conflict("link_expired".into())); | ||
| 224 | + } | ||
| 225 | + let new = NewLink { | ||
| 226 | + id: new_id(), | ||
| 227 | + token_hash: token_hash.to_string(), | ||
| 228 | + token_sealed: token_sealed.to_string(), | ||
| 229 | + kind: old.kind, | ||
| 230 | + target_id: old.target_id.clone(), | ||
| 231 | + owner: owner.to_string(), | ||
| 232 | + can_download: old.can_download, | ||
| 233 | + password_hash: old.password_hash.clone(), | ||
| 234 | + expires_at: old.expires_at.clone(), | ||
| 235 | + }; | ||
| 236 | + insert_link_in(&tx, &new).await?; | ||
| 237 | + tx.execute( | ||
| 238 | + "UPDATE links SET revoked_at = ?3 WHERE id = ?1 AND owner = ?2 AND revoked_at IS NULL", | ||
| 239 | + (id.to_string(), owner.to_string(), now_stamp()), | ||
| 240 | + ) | ||
| 241 | + .await | ||
| 242 | + .map_err(db_err)?; | ||
| 243 | + link_of_owner(&tx, owner, &new.id) | ||
| 244 | + .await? | ||
| 245 | + .ok_or_else(missing_row) | ||
| 246 | + } | ||
| 247 | + .await; | ||
| 248 | + finish(tx, outcome).await | ||
| 249 | + } | ||
| 250 | + | ||
| 251 | + /// The link whose token hashes to `token_hash`, whatever its state. The caller decides whether it | ||
| 252 | + /// still works. | ||
| 253 | + pub async fn link_by_token_hash(&self, token_hash: &str) -> Result<Option<Link>> { | ||
| 254 | + let conn = self.read_conn().await; | ||
| 255 | + fetch_opt( | ||
| 256 | + &conn, | ||
| 257 | + &format!("SELECT {LINK_COLS} FROM links WHERE token_hash = ?1"), | ||
| 258 | + (token_hash.to_string(),), | ||
| 259 | + map_link, | ||
| 260 | + ) | ||
| 261 | + .await | ||
| 262 | + } | ||
| 263 | + | ||
| 264 | + /// Counts one visit to a link's page and stamps it. | ||
| 265 | + pub async fn touch_link(&self, id: &str) -> Result<()> { | ||
| 266 | + let conn = self.inner.conn.lock().await; | ||
| 267 | + conn.execute( | ||
| 268 | + "UPDATE links SET last_used_at = ?2, use_count = use_count + 1 WHERE id = ?1", | ||
| 269 | + (id.to_string(), now_stamp()), | ||
| 270 | + ) | ||
| 271 | + .await | ||
| 272 | + .map_err(db_err)?; | ||
| 273 | + Ok(()) | ||
| 274 | + } | ||
| 275 | +} | ||
| 276 | + | ||
| 277 | +#[cfg(test)] | ||
| 278 | +mod tests { | ||
| 279 | + use super::*; | ||
| 280 | + use crate::store::test_support::store_with_member; | ||
| 281 | + | ||
| 282 | + #[tokio::test] | ||
| 283 | + async fn remint_moves_the_link_to_a_new_token_and_kills_the_old() { | ||
| 284 | + let (_dir, store) = store_with_member("ann").await; | ||
| 285 | + let folder = store.create_folder("ann", None, "Trips").await.unwrap(); | ||
| 286 | + let link = store | ||
| 287 | + .create_link(NewLink { | ||
| 288 | + id: new_id(), | ||
| 289 | + token_hash: "a".repeat(64), | ||
| 290 | + token_sealed: "v1:old".into(), | ||
| 291 | + kind: ItemKind::Folder, | ||
| 292 | + target_id: folder.id.clone(), | ||
| 293 | + owner: "ann".into(), | ||
| 294 | + can_download: true, | ||
| 295 | + password_hash: None, | ||
| 296 | + expires_at: Some(crate::time::stamp_after(std::time::Duration::from_secs(60))), | ||
| 297 | + }) | ||
| 298 | + .await | ||
| 299 | + .unwrap(); | ||
| 300 | + let fresh = store | ||
| 301 | + .remint_link("ann", &link.id, &"b".repeat(64), "v1:new") | ||
| 302 | + .await | ||
| 303 | + .unwrap(); | ||
| 304 | + assert!(fresh.can_download); | ||
| 305 | + assert_eq!(fresh.expires_at, link.expires_at); | ||
| 306 | + assert!( | ||
| 307 | + store | ||
| 308 | + .link_by_token_hash(&"a".repeat(64)) | ||
| 309 | + .await | ||
| 310 | + .unwrap() | ||
| 311 | + .unwrap() | ||
| 312 | + .revoked_at | ||
| 313 | + .is_some() | ||
| 314 | + ); | ||
| 315 | + assert!( | ||
| 316 | + store | ||
| 317 | + .link_by_token_hash(&"b".repeat(64)) | ||
| 318 | + .await | ||
| 319 | + .unwrap() | ||
| 320 | + .unwrap() | ||
| 321 | + .revoked_at | ||
| 322 | + .is_none() | ||
| 323 | + ); | ||
| 324 | + } | ||
| 325 | +} | ||
crates/in-core/src/store/mod.rsmodified+2 -0
| @@ -6,10 +6,12 @@ | |||
| 6 | 6 | ||
| 7 | pub mod files; | 7 | pub mod files; |
| 8 | pub mod folders; | 8 | pub mod folders; |
| 9 | +pub mod links; | ||
| 9 | pub mod members; | 10 | pub mod members; |
| 10 | pub mod migrate; | 11 | pub mod migrate; |
| 11 | pub mod sessions; | 12 | pub mod sessions; |
| 12 | pub mod settings; | 13 | pub mod settings; |
| 14 | +pub mod shares; | ||
| 13 | pub mod snapshot; | 15 | pub mod snapshot; |
| 14 | pub mod trash; | 16 | pub mod trash; |
| 15 | pub mod uploads; | 17 | pub mod uploads; |
crates/in-core/src/store/shares.rsadded+611 -0
| @@ -0,0 +1,611 @@ | |||
| 1 | +//! Per-person shares (architecture sections 3 and 6): a grant gives one grantee a level on one file or | ||
| 2 | +//! folder, `View`, or `Download` when `can_download` is set. A grant on a folder reaches everything below | ||
| 3 | +//! it. That reach is computed every time access is checked, by walking the live ancestors of the item; no | ||
| 4 | +//! grant is copied down the tree. So an item that leaves a granted folder loses the access on the next | ||
| 5 | +//! check, with nothing to clean up. | ||
| 6 | +//! | ||
| 7 | +//! This module decides what the grants are and what reach they have ([`Access`]). Deciding what a viewer | ||
| 8 | +//! may do with the item stays in `authz`. A grantee must be a current member (not disabled) and not the | ||
| 9 | +//! owner; both are checked when a grant is written. | ||
| 10 | + | ||
| 11 | +use turso::{Connection, Row}; | ||
| 12 | + | ||
| 13 | +use crate::authz::Grant; | ||
| 14 | +use crate::error::{Error, Result}; | ||
| 15 | +use crate::store::files::{File, file_by_id, live_file}; | ||
| 16 | +use crate::store::folders::{Folder, folder_by_id, has_trashed_chain, live_folder}; | ||
| 17 | +use crate::store::trash::ItemKind; | ||
| 18 | +use crate::store::{ | ||
| 19 | + Store, col_int, col_text, db_err, fetch_all, fetch_opt, finish, missing_row, new_id, | ||
| 20 | +}; | ||
| 21 | +use crate::time::now_stamp; | ||
| 22 | + | ||
| 23 | +/// Column list for [`map_share`]. Keep the two in step. | ||
| 24 | +pub const SHARE_COLS: &str = "id, target_kind, target_id, owner, grantee, can_download, created_at"; | ||
| 25 | + | ||
| 26 | +/// Deepest folder chain the walks follow. Matches the folder module's bound. | ||
| 27 | +const MAX_DEPTH: usize = 512; | ||
| 28 | + | ||
| 29 | +/// The word a target kind has in the database and in URLs. | ||
| 30 | +pub fn kind_word(kind: ItemKind) -> &'static str { | ||
| 31 | + match kind { | ||
| 32 | + ItemKind::File => "file", | ||
| 33 | + ItemKind::Folder => "folder", | ||
| 34 | + } | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +/// The kind named by a URL or database word, or `None` for anything else. | ||
| 38 | +pub fn kind_from_word(word: &str) -> Option<ItemKind> { | ||
| 39 | + match word { | ||
| 40 | + "file" => Some(ItemKind::File), | ||
| 41 | + "folder" => Some(ItemKind::Folder), | ||
| 42 | + _ => None, | ||
| 43 | + } | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +/// One row of the `grants` table. | ||
| 47 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 48 | +pub struct Share { | ||
| 49 | + /// Grant id (a lower-case ULID). | ||
| 50 | + pub id: String, | ||
| 51 | + /// Whether the target is a file or a folder. | ||
| 52 | + pub kind: ItemKind, | ||
| 53 | + /// The file or folder shared. | ||
| 54 | + pub target_id: String, | ||
| 55 | + /// The owner of the target, who made the grant. | ||
| 56 | + pub owner: String, | ||
| 57 | + /// The person the target is shared with. | ||
| 58 | + pub grantee: String, | ||
| 59 | + /// Whether the grantee may download (the `Download` level) or only see (`View`). | ||
| 60 | + pub can_download: bool, | ||
| 61 | + /// When the grant was made or last changed its level. | ||
| 62 | + pub created_at: String, | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +/// The reach a person has on one item, computed from the grants on the item and its live ancestors. | ||
| 66 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 67 | +pub struct Access { | ||
| 68 | + /// Whether the item or one of its ancestors is in the trash. Trashed items are never shown to grantees. | ||
| 69 | + pub trashed: bool, | ||
| 70 | + /// The most permissive grant that reaches the item for this person. | ||
| 71 | + pub grant: Grant, | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +/// A grant as its owner sees it: the grant and the name and email of the grantee. | ||
| 75 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 76 | +pub struct ShareEntry { | ||
| 77 | + /// The grant. | ||
| 78 | + pub share: Share, | ||
| 79 | + /// The grantee's display name. | ||
| 80 | + pub grantee_name: String, | ||
| 81 | + /// The grantee's email address. | ||
| 82 | + pub grantee_email: String, | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +/// An item shared with a person at the top level, as the person sees it on the shared page. | ||
| 86 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 87 | +pub struct SharedItem { | ||
| 88 | + /// The grant that reaches the person. | ||
| 89 | + pub share: Share, | ||
| 90 | + /// The item's name. | ||
| 91 | + pub name: String, | ||
| 92 | + /// The item's MIME type; empty for a folder. | ||
| 93 | + pub mime: String, | ||
| 94 | + /// The item's size in bytes; zero for a folder. | ||
| 95 | + pub size: i64, | ||
| 96 | + /// The owner's display name. | ||
| 97 | + pub owner_name: String, | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +/// Maps a row selected with [`SHARE_COLS`] (the first seven columns of a query). | ||
| 101 | +fn map_share(row: &Row) -> Result<Share> { | ||
| 102 | + let kind = kind_from_word(&col_text(row, 1)?) | ||
| 103 | + .ok_or_else(|| Error::Database("grant with an unknown target kind".into()))?; | ||
| 104 | + Ok(Share { | ||
| 105 | + id: col_text(row, 0)?, | ||
| 106 | + kind, | ||
| 107 | + target_id: col_text(row, 2)?, | ||
| 108 | + owner: col_text(row, 3)?, | ||
| 109 | + grantee: col_text(row, 4)?, | ||
| 110 | + can_download: col_int(row, 5)? != 0, | ||
| 111 | + created_at: col_text(row, 6)?, | ||
| 112 | + }) | ||
| 113 | +} | ||
| 114 | + | ||
| 115 | +/// The level a grant flag gives. | ||
| 116 | +fn level(can_download: bool) -> Grant { | ||
| 117 | + if can_download { | ||
| 118 | + Grant::Download | ||
| 119 | + } else { | ||
| 120 | + Grant::View | ||
| 121 | + } | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +/// The state an access check needs: whether the item is trashed (itself or through an ancestor) and the | ||
| 125 | +/// folder it sits in. `None` when no such item exists. | ||
| 126 | +async fn trashed_state( | ||
| 127 | + conn: &Connection, | ||
| 128 | + kind: ItemKind, | ||
| 129 | + id: &str, | ||
| 130 | +) -> Result<Option<(bool, Option<String>)>> { | ||
| 131 | + let own = match kind { | ||
| 132 | + ItemKind::File => file_by_id(conn, id) | ||
| 133 | + .await? | ||
| 134 | + .map(|f: File| (f.trashed_at.is_some(), f.folder_id)), | ||
| 135 | + ItemKind::Folder => folder_by_id(conn, id) | ||
| 136 | + .await? | ||
| 137 | + .map(|f: Folder| (f.trashed_at.is_some(), f.parent_id)), | ||
| 138 | + }; | ||
| 139 | + let Some((own_trashed, parent)) = own else { | ||
| 140 | + return Ok(None); | ||
| 141 | + }; | ||
| 142 | + let trashed = own_trashed || has_trashed_chain(conn, parent.as_deref()).await?; | ||
| 143 | + Ok(Some((trashed, parent))) | ||
| 144 | +} | ||
| 145 | + | ||
| 146 | +/// The folder ids from `start` up to the top level, `start` first. Empty for `None`. | ||
| 147 | +async fn chain_from(conn: &Connection, start: Option<&str>) -> Result<Vec<String>> { | ||
| 148 | + let mut out = Vec::new(); | ||
| 149 | + let mut cur = start.map(str::to_string); | ||
| 150 | + while let Some(id) = cur { | ||
| 151 | + if out.len() >= MAX_DEPTH { | ||
| 152 | + return Err(Error::Database("folder tree is too deep".into())); | ||
| 153 | + } | ||
| 154 | + let Some(folder) = folder_by_id(conn, &id).await? else { | ||
| 155 | + break; | ||
| 156 | + }; | ||
| 157 | + cur = folder.parent_id; | ||
| 158 | + out.push(id); | ||
| 159 | + } | ||
| 160 | + Ok(out) | ||
| 161 | +} | ||
| 162 | + | ||
| 163 | +/// The grant flag `grantee` holds directly on the item, if there is a grant on exactly that item. | ||
| 164 | +async fn direct( | ||
| 165 | + conn: &Connection, | ||
| 166 | + grantee: &str, | ||
| 167 | + kind: ItemKind, | ||
| 168 | + id: &str, | ||
| 169 | +) -> Result<Option<bool>> { | ||
| 170 | + fetch_opt( | ||
| 171 | + conn, | ||
| 172 | + "SELECT can_download FROM grants WHERE target_kind = ?1 AND target_id = ?2 AND grantee = ?3", | ||
| 173 | + ( | ||
| 174 | + kind_word(kind).to_string(), | ||
| 175 | + id.to_string(), | ||
| 176 | + grantee.to_string(), | ||
| 177 | + ), | ||
| 178 | + |row| Ok(col_int(row, 0)? != 0), | ||
| 179 | + ) | ||
| 180 | + .await | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +/// The access `grantee` has to an item: its own grant and the grants on every ancestor folder, the most | ||
| 184 | +/// permissive one wins. `None` when the item does not exist. | ||
| 185 | +pub(crate) async fn access_in( | ||
| 186 | + conn: &Connection, | ||
| 187 | + grantee: &str, | ||
| 188 | + kind: ItemKind, | ||
| 189 | + id: &str, | ||
| 190 | +) -> Result<Option<Access>> { | ||
| 191 | + let Some((trashed, parent)) = trashed_state(conn, kind, id).await? else { | ||
| 192 | + return Ok(None); | ||
| 193 | + }; | ||
| 194 | + let mut grant = Grant::None; | ||
| 195 | + if let Some(can_download) = direct(conn, grantee, kind, id).await? { | ||
| 196 | + grant = grant.max(level(can_download)); | ||
| 197 | + } | ||
| 198 | + for folder in chain_from(conn, parent.as_deref()).await? { | ||
| 199 | + if let Some(can_download) = direct(conn, grantee, ItemKind::Folder, &folder).await? { | ||
| 200 | + grant = grant.max(level(can_download)); | ||
| 201 | + } | ||
| 202 | + } | ||
| 203 | + Ok(Some(Access { trashed, grant })) | ||
| 204 | +} | ||
| 205 | + | ||
| 206 | +/// Whether an ancestor folder of the item (from `parent` up) carries a grant to `grantee`. | ||
| 207 | +async fn granted_above(conn: &Connection, grantee: &str, parent: Option<&str>) -> Result<bool> { | ||
| 208 | + for folder in chain_from(conn, parent).await? { | ||
| 209 | + if direct(conn, grantee, ItemKind::Folder, &folder) | ||
| 210 | + .await? | ||
| 211 | + .is_some() | ||
| 212 | + { | ||
| 213 | + return Ok(true); | ||
| 214 | + } | ||
| 215 | + } | ||
| 216 | + Ok(false) | ||
| 217 | +} | ||
| 218 | + | ||
| 219 | +/// The grant row of `owner` with this id. | ||
| 220 | +async fn share_by_id(conn: &Connection, owner: &str, id: &str) -> Result<Option<Share>> { | ||
| 221 | + fetch_opt( | ||
| 222 | + conn, | ||
| 223 | + &format!("SELECT {SHARE_COLS} FROM grants WHERE id = ?1 AND owner = ?2"), | ||
| 224 | + (id.to_string(), owner.to_string()), | ||
| 225 | + map_share, | ||
| 226 | + ) | ||
| 227 | + .await | ||
| 228 | +} | ||
| 229 | + | ||
| 230 | +impl Store { | ||
| 231 | + /// The access `grantee` has to an item, or `None` when the item does not exist. Authorise with it; | ||
| 232 | + /// a missing item and an item the person cannot reach must both look like "not found". | ||
| 233 | + pub async fn access_of( | ||
| 234 | + &self, | ||
| 235 | + grantee: &str, | ||
| 236 | + kind: ItemKind, | ||
| 237 | + id: &str, | ||
| 238 | + ) -> Result<Option<Access>> { | ||
| 239 | + let conn = self.read_conn().await; | ||
| 240 | + access_in(&conn, grantee, kind, id).await | ||
| 241 | + } | ||
| 242 | + | ||
| 243 | + /// Whether the item is trashed (itself or through an ancestor). `None` when it does not exist. | ||
| 244 | + pub async fn item_trashed(&self, kind: ItemKind, id: &str) -> Result<Option<bool>> { | ||
| 245 | + let conn = self.read_conn().await; | ||
| 246 | + Ok(trashed_state(&conn, kind, id) | ||
| 247 | + .await? | ||
| 248 | + .map(|(trashed, _)| trashed)) | ||
| 249 | + } | ||
| 250 | + | ||
| 251 | + /// Shares a live item of `owner` with `grantee` at the given level. A grant that already exists only | ||
| 252 | + /// changes its level. The grantee must be a current member other than the owner. | ||
| 253 | + pub async fn share_with( | ||
| 254 | + &self, | ||
| 255 | + owner: &str, | ||
| 256 | + kind: ItemKind, | ||
| 257 | + target_id: &str, | ||
| 258 | + grantee: &str, | ||
| 259 | + can_download: bool, | ||
| 260 | + ) -> Result<Share> { | ||
| 261 | + let conn = self.inner.conn.lock().await; | ||
| 262 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 263 | + let outcome: Result<Share> = async { | ||
| 264 | + match kind { | ||
| 265 | + ItemKind::File => { | ||
| 266 | + live_file(&tx, owner, target_id).await?; | ||
| 267 | + } | ||
| 268 | + ItemKind::Folder => { | ||
| 269 | + live_folder(&tx, owner, target_id).await?; | ||
| 270 | + } | ||
| 271 | + } | ||
| 272 | + if owner == grantee { | ||
| 273 | + return Err(Error::Invalid("self_share".into())); | ||
| 274 | + } | ||
| 275 | + let disabled = fetch_opt( | ||
| 276 | + &tx, | ||
| 277 | + "SELECT disabled FROM members WHERE sub = ?1", | ||
| 278 | + (grantee.to_string(),), | ||
| 279 | + |row| col_int(row, 0), | ||
| 280 | + ) | ||
| 281 | + .await?; | ||
| 282 | + if disabled != Some(0) { | ||
| 283 | + return Err(Error::Invalid("no_such_member".into())); | ||
| 284 | + } | ||
| 285 | + tx.execute( | ||
| 286 | + "INSERT INTO grants (id, target_kind, target_id, owner, grantee, can_download, created_at) \ | ||
| 287 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) \ | ||
| 288 | + ON CONFLICT (target_kind, target_id, grantee) DO UPDATE SET can_download = excluded.can_download", | ||
| 289 | + ( | ||
| 290 | + new_id(), | ||
| 291 | + kind_word(kind).to_string(), | ||
| 292 | + target_id.to_string(), | ||
| 293 | + owner.to_string(), | ||
| 294 | + grantee.to_string(), | ||
| 295 | + i64::from(can_download), | ||
| 296 | + now_stamp(), | ||
| 297 | + ), | ||
| 298 | + ) | ||
| 299 | + .await | ||
| 300 | + .map_err(db_err)?; | ||
| 301 | + fetch_opt( | ||
| 302 | + &tx, | ||
| 303 | + &format!( | ||
| 304 | + "SELECT {SHARE_COLS} FROM grants WHERE owner = ?1 AND target_kind = ?2 \ | ||
| 305 | + AND target_id = ?3 AND grantee = ?4" | ||
| 306 | + ), | ||
| 307 | + ( | ||
| 308 | + owner.to_string(), | ||
| 309 | + kind_word(kind).to_string(), | ||
| 310 | + target_id.to_string(), | ||
| 311 | + grantee.to_string(), | ||
| 312 | + ), | ||
| 313 | + map_share, | ||
| 314 | + ) | ||
| 315 | + .await? | ||
| 316 | + .ok_or_else(missing_row) | ||
| 317 | + } | ||
| 318 | + .await; | ||
| 319 | + finish(tx, outcome).await | ||
| 320 | + } | ||
| 321 | + | ||
| 322 | + /// The grant with this id, if `owner` made it. | ||
| 323 | + pub async fn share_of(&self, owner: &str, id: &str) -> Result<Option<Share>> { | ||
| 324 | + let conn = self.read_conn().await; | ||
| 325 | + share_by_id(&conn, owner, id).await | ||
| 326 | + } | ||
| 327 | + | ||
| 328 | + /// Changes the level of a grant that `owner` made. | ||
| 329 | + pub async fn set_share_level( | ||
| 330 | + &self, | ||
| 331 | + owner: &str, | ||
| 332 | + share_id: &str, | ||
| 333 | + can_download: bool, | ||
| 334 | + ) -> Result<Share> { | ||
| 335 | + let conn = self.inner.conn.lock().await; | ||
| 336 | + let changed = conn | ||
| 337 | + .execute( | ||
| 338 | + "UPDATE grants SET can_download = ?3 WHERE id = ?1 AND owner = ?2", | ||
| 339 | + ( | ||
| 340 | + share_id.to_string(), | ||
| 341 | + owner.to_string(), | ||
| 342 | + i64::from(can_download), | ||
| 343 | + ), | ||
| 344 | + ) | ||
| 345 | + .await | ||
| 346 | + .map_err(db_err)?; | ||
| 347 | + if changed == 0 { | ||
| 348 | + return Err(Error::NotFound); | ||
| 349 | + } | ||
| 350 | + share_by_id(&conn, owner, share_id) | ||
| 351 | + .await? | ||
| 352 | + .ok_or(Error::NotFound) | ||
| 353 | + } | ||
| 354 | + | ||
| 355 | + /// Removes a grant that `owner` made and returns it, so the caller can tell the grantee. | ||
| 356 | + pub async fn remove_share(&self, owner: &str, share_id: &str) -> Result<Share> { | ||
| 357 | + let conn = self.inner.conn.lock().await; | ||
| 358 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 359 | + let outcome: Result<Share> = async { | ||
| 360 | + let share = share_by_id(&tx, owner, share_id) | ||
| 361 | + .await? | ||
| 362 | + .ok_or(Error::NotFound)?; | ||
| 363 | + tx.execute( | ||
| 364 | + "DELETE FROM grants WHERE id = ?1 AND owner = ?2", | ||
| 365 | + (share_id.to_string(), owner.to_string()), | ||
| 366 | + ) | ||
| 367 | + .await | ||
| 368 | + .map_err(db_err)?; | ||
| 369 | + Ok(share) | ||
| 370 | + } | ||
| 371 | + .await; | ||
| 372 | + finish(tx, outcome).await | ||
| 373 | + } | ||
| 374 | + | ||
| 375 | + /// Every grant on one item of `owner`, by grantee name. | ||
| 376 | + pub async fn shares_of( | ||
| 377 | + &self, | ||
| 378 | + owner: &str, | ||
| 379 | + kind: ItemKind, | ||
| 380 | + target_id: &str, | ||
| 381 | + ) -> Result<Vec<ShareEntry>> { | ||
| 382 | + let conn = self.read_conn().await; | ||
| 383 | + fetch_all( | ||
| 384 | + &conn, | ||
| 385 | + &format!( | ||
| 386 | + "SELECT {SHARE_COLS}, m.name, m.email FROM grants \ | ||
| 387 | + JOIN members m ON m.sub = grants.grantee \ | ||
| 388 | + WHERE grants.owner = ?1 AND grants.target_kind = ?2 AND grants.target_id = ?3 \ | ||
| 389 | + ORDER BY m.name, grants.id" | ||
| 390 | + ), | ||
| 391 | + ( | ||
| 392 | + owner.to_string(), | ||
| 393 | + kind_word(kind).to_string(), | ||
| 394 | + target_id.to_string(), | ||
| 395 | + ), | ||
| 396 | + |row| { | ||
| 397 | + Ok(ShareEntry { | ||
| 398 | + share: map_share(row)?, | ||
| 399 | + grantee_name: col_text(row, 7)?, | ||
| 400 | + grantee_email: col_text(row, 8)?, | ||
| 401 | + }) | ||
| 402 | + }, | ||
| 403 | + ) | ||
| 404 | + .await | ||
| 405 | + } | ||
| 406 | + | ||
| 407 | + /// The items shared with `grantee` at the top level: live grants whose item is not trashed and that no | ||
| 408 | + /// ancestor folder already carries. Items under a shared folder are reached through that folder. | ||
| 409 | + pub async fn shared_with(&self, grantee: &str) -> Result<Vec<SharedItem>> { | ||
| 410 | + let conn = self.read_conn().await; | ||
| 411 | + let grants = fetch_all( | ||
| 412 | + &conn, | ||
| 413 | + &format!("SELECT {SHARE_COLS} FROM grants WHERE grantee = ?1 ORDER BY created_at, id"), | ||
| 414 | + (grantee.to_string(),), | ||
| 415 | + map_share, | ||
| 416 | + ) | ||
| 417 | + .await?; | ||
| 418 | + let mut out = Vec::new(); | ||
| 419 | + for share in grants { | ||
| 420 | + let Some((trashed, parent)) = | ||
| 421 | + trashed_state(&conn, share.kind, &share.target_id).await? | ||
| 422 | + else { | ||
| 423 | + continue; | ||
| 424 | + }; | ||
| 425 | + if trashed || granted_above(&conn, grantee, parent.as_deref()).await? { | ||
| 426 | + continue; | ||
| 427 | + } | ||
| 428 | + let (name, mime, size) = match share.kind { | ||
| 429 | + ItemKind::File => match file_by_id(&conn, &share.target_id).await? { | ||
| 430 | + Some(file) => (file.name, file.mime, file.size), | ||
| 431 | + None => continue, | ||
| 432 | + }, | ||
| 433 | + ItemKind::Folder => match folder_by_id(&conn, &share.target_id).await? { | ||
| 434 | + Some(folder) => (folder.name, String::new(), 0), | ||
| 435 | + None => continue, | ||
| 436 | + }, | ||
| 437 | + }; | ||
| 438 | + let owner_name = fetch_opt( | ||
| 439 | + &conn, | ||
| 440 | + "SELECT name FROM members WHERE sub = ?1", | ||
| 441 | + (share.owner.clone(),), | ||
| 442 | + |row| col_text(row, 0), | ||
| 443 | + ) | ||
| 444 | + .await? | ||
| 445 | + .unwrap_or_default(); | ||
| 446 | + out.push(SharedItem { | ||
| 447 | + share, | ||
| 448 | + name, | ||
| 449 | + mime, | ||
| 450 | + size, | ||
| 451 | + owner_name, | ||
| 452 | + }); | ||
| 453 | + } | ||
| 454 | + Ok(out) | ||
| 455 | + } | ||
| 456 | + | ||
| 457 | + /// The folders from the topmost ancestor-or-self of `folder` that carries `root` down to `folder`, | ||
| 458 | + /// for breadcrumbs. Empty when `folder` is not inside `root`. Nothing above `root` is returned. | ||
| 459 | + pub async fn folder_trail_to(&self, root: &str, folder: &str) -> Result<Vec<Folder>> { | ||
| 460 | + let conn = self.read_conn().await; | ||
| 461 | + let chain = chain_from(&conn, Some(folder)).await?; | ||
| 462 | + let Some(top) = chain.iter().position(|id| id == root) else { | ||
| 463 | + return Ok(Vec::new()); | ||
| 464 | + }; | ||
| 465 | + let mut trail = Vec::with_capacity(top + 1); | ||
| 466 | + for id in chain[..=top].iter().rev() { | ||
| 467 | + if let Some(row) = folder_by_id(&conn, id).await? { | ||
| 468 | + trail.push(row); | ||
| 469 | + } | ||
| 470 | + } | ||
| 471 | + Ok(trail) | ||
| 472 | + } | ||
| 473 | + | ||
| 474 | + /// The breadcrumbs a grantee sees for `folder`: from the topmost folder of its chain that the grantee | ||
| 475 | + /// has a grant on, down to `folder`. Folders above that grant are never returned. Empty when the | ||
| 476 | + /// grantee has no grant on the folder or any ancestor. | ||
| 477 | + pub async fn shared_trail(&self, grantee: &str, folder: &str) -> Result<Vec<Folder>> { | ||
| 478 | + let root = { | ||
| 479 | + let conn = self.read_conn().await; | ||
| 480 | + let mut top = None; | ||
| 481 | + for id in chain_from(&conn, Some(folder)).await? { | ||
| 482 | + if direct(&conn, grantee, ItemKind::Folder, &id) | ||
| 483 | + .await? | ||
| 484 | + .is_some() | ||
| 485 | + { | ||
| 486 | + top = Some(id); | ||
| 487 | + } | ||
| 488 | + } | ||
| 489 | + top | ||
| 490 | + }; | ||
| 491 | + match root { | ||
| 492 | + Some(root) => self.folder_trail_to(&root, folder).await, | ||
| 493 | + None => Ok(Vec::new()), | ||
| 494 | + } | ||
| 495 | + } | ||
| 496 | + | ||
| 497 | + /// Whether the item lies inside a share root. A file root holds only itself. A folder root holds | ||
| 498 | + /// itself and every folder and file below it. The item's own trash state is not checked here. | ||
| 499 | + pub async fn is_within( | ||
| 500 | + &self, | ||
| 501 | + root_kind: ItemKind, | ||
| 502 | + root_id: &str, | ||
| 503 | + kind: ItemKind, | ||
| 504 | + id: &str, | ||
| 505 | + ) -> Result<bool> { | ||
| 506 | + match root_kind { | ||
| 507 | + ItemKind::File => Ok(kind == ItemKind::File && id == root_id), | ||
| 508 | + ItemKind::Folder => { | ||
| 509 | + if kind == ItemKind::Folder && id == root_id { | ||
| 510 | + return Ok(true); | ||
| 511 | + } | ||
| 512 | + let conn = self.read_conn().await; | ||
| 513 | + let Some((_, parent)) = trashed_state(&conn, kind, id).await? else { | ||
| 514 | + return Ok(false); | ||
| 515 | + }; | ||
| 516 | + Ok(chain_from(&conn, parent.as_deref()) | ||
| 517 | + .await? | ||
| 518 | + .iter() | ||
| 519 | + .any(|folder| folder == root_id)) | ||
| 520 | + } | ||
| 521 | + } | ||
| 522 | + } | ||
| 523 | +} | ||
| 524 | + | ||
| 525 | +#[cfg(test)] | ||
| 526 | +mod tests { | ||
| 527 | + use super::*; | ||
| 528 | + use crate::store::files::NewFile; | ||
| 529 | + use crate::store::test_support::store_with_member; | ||
| 530 | + | ||
| 531 | + async fn member(store: &Store, sub: &str) { | ||
| 532 | + store | ||
| 533 | + .upsert_member_from_claims( | ||
| 534 | + &crate::store::members::MemberFields { | ||
| 535 | + sub: sub.into(), | ||
| 536 | + email: format!("{sub}@example.test"), | ||
| 537 | + name: sub.into(), | ||
| 538 | + is_admin: false, | ||
| 539 | + locale: "en".into(), | ||
| 540 | + zoneinfo: "UTC".into(), | ||
| 541 | + picture_version: 0, | ||
| 542 | + im_updated_at: String::new(), | ||
| 543 | + }, | ||
| 544 | + 1 << 30, | ||
| 545 | + ) | ||
| 546 | + .await | ||
| 547 | + .unwrap(); | ||
| 548 | + } | ||
| 549 | + | ||
| 550 | + #[tokio::test] | ||
| 551 | + async fn a_grant_reaches_the_subtree_until_the_item_leaves_it() { | ||
| 552 | + let (_dir, store) = store_with_member("ann").await; | ||
| 553 | + member(&store, "bob").await; | ||
| 554 | + let trips = store.create_folder("ann", None, "Trips").await.unwrap(); | ||
| 555 | + let other = store.create_folder("ann", None, "Other").await.unwrap(); | ||
| 556 | + let file = store | ||
| 557 | + .insert_file(NewFile { | ||
| 558 | + id: new_id(), | ||
| 559 | + owner: "ann".into(), | ||
| 560 | + folder: Some(trips.id.clone()), | ||
| 561 | + name: "day1.txt".into(), | ||
| 562 | + mime: "text/plain".into(), | ||
| 563 | + size: 1, | ||
| 564 | + sha256: "0".repeat(64), | ||
| 565 | + staged_claims: 0, | ||
| 566 | + }) | ||
| 567 | + .await | ||
| 568 | + .unwrap(); | ||
| 569 | + store | ||
| 570 | + .share_with("ann", ItemKind::Folder, &trips.id, "bob", false) | ||
| 571 | + .await | ||
| 572 | + .unwrap(); | ||
| 573 | + let reach = store | ||
| 574 | + .access_of("bob", ItemKind::File, &file.id) | ||
| 575 | + .await | ||
| 576 | + .unwrap() | ||
| 577 | + .unwrap(); | ||
| 578 | + assert_eq!(reach.grant, Grant::View); | ||
| 579 | + assert!(!reach.trashed); | ||
| 580 | + | ||
| 581 | + store | ||
| 582 | + .move_file("ann", &file.id, Some(&other.id)) | ||
| 583 | + .await | ||
| 584 | + .unwrap(); | ||
| 585 | + let reach = store | ||
| 586 | + .access_of("bob", ItemKind::File, &file.id) | ||
| 587 | + .await | ||
| 588 | + .unwrap() | ||
| 589 | + .unwrap(); | ||
| 590 | + assert_eq!(reach.grant, Grant::None, "the file left the granted folder"); | ||
| 591 | + } | ||
| 592 | + | ||
| 593 | + #[tokio::test] | ||
| 594 | + async fn a_grant_to_the_owner_or_a_stranger_is_refused() { | ||
| 595 | + let (_dir, store) = store_with_member("ann").await; | ||
| 596 | + member(&store, "bob").await; | ||
| 597 | + let folder = store.create_folder("ann", None, "Trips").await.unwrap(); | ||
| 598 | + assert!(matches!( | ||
| 599 | + store | ||
| 600 | + .share_with("ann", ItemKind::Folder, &folder.id, "ann", false) | ||
| 601 | + .await, | ||
| 602 | + Err(Error::Invalid(_)) | ||
| 603 | + )); | ||
| 604 | + assert!(matches!( | ||
| 605 | + store | ||
| 606 | + .share_with("ann", ItemKind::Folder, &folder.id, "nobody", false) | ||
| 607 | + .await, | ||
| 608 | + Err(Error::Invalid(_)) | ||
| 609 | + )); | ||
| 610 | + } | ||
| 611 | +} | ||
crates/in-web/src/boot.rsmodified+3 -0
| @@ -31,6 +31,7 @@ use crate::pages::not_found::NotFoundLayer; | |||
| 31 | use crate::security::{self, SecurityHeaders}; | 31 | use crate::security::{self, SecurityHeaders}; |
| 32 | use crate::state::AppState; | 32 | use crate::state::AppState; |
| 33 | use crate::sweeper; | 33 | use crate::sweeper; |
| 34 | +use crate::throttle::ShareThrottles; | ||
| 34 | use crate::thumbs_worker; | 35 | use crate::thumbs_worker; |
| 35 | 36 | ||
| 36 | /// Name of the instance key file inside the data directory. | 37 | /// Name of the instance key file inside the data directory. |
| @@ -114,6 +115,7 @@ async fn open_state(config: Config) -> Result<AppState> { | |||
| 114 | key: Arc::new(key), | 115 | key: Arc::new(key), |
| 115 | live: Arc::new(LiveHub::default()), | 116 | live: Arc::new(LiveHub::default()), |
| 116 | oidc, | 117 | oidc, |
| 118 | + throttles: Arc::new(ShareThrottles::default()), | ||
| 117 | }) | 119 | }) |
| 118 | } | 120 | } |
| 119 | 121 | ||
| @@ -240,6 +242,7 @@ mod tests { | |||
| 240 | key: Arc::new(key), | 242 | key: Arc::new(key), |
| 241 | live: Arc::new(LiveHub::default()), | 243 | live: Arc::new(LiveHub::default()), |
| 242 | oidc: None, | 244 | oidc: None, |
| 245 | + throttles: Arc::new(ShareThrottles::default()), | ||
| 243 | }; | 246 | }; |
| 244 | (dir, state) | 247 | (dir, state) |
| 245 | } | 248 | } |
crates/in-web/src/i18n/drive.rsmodified+2 -2
| @@ -317,7 +317,7 @@ pub fn notice_text(lang: Lang, word: &str) -> Option<&'static str> { | |||
| 317 | "purged" => d(lang, DK::NoticePurged), | 317 | "purged" => d(lang, DK::NoticePurged), |
| 318 | "emptied" => d(lang, DK::NoticeEmptied), | 318 | "emptied" => d(lang, DK::NoticeEmptied), |
| 319 | "uploaded" => d(lang, DK::NoticeUploaded), | 319 | "uploaded" => d(lang, DK::NoticeUploaded), |
| 320 | - _ => return None, | 320 | + _ => return super::share::notice_text(lang, word), |
| 321 | }) | 321 | }) |
| 322 | } | 322 | } |
| 323 | 323 | ||
| @@ -336,6 +336,6 @@ pub fn refusal_text(lang: Lang, word: &str) -> Option<&'static str> { | |||
| 336 | "too_many_names" => d(lang, DK::RefuseTooManyNames), | 336 | "too_many_names" => d(lang, DK::RefuseTooManyNames), |
| 337 | "no_file" => d(lang, DK::RefuseNoFile), | 337 | "no_file" => d(lang, DK::RefuseNoFile), |
| 338 | "generic" => d(lang, DK::RefuseGeneric), | 338 | "generic" => d(lang, DK::RefuseGeneric), |
| 339 | - _ => return None, | 339 | + _ => return super::share::refusal_text(lang, word), |
| 340 | }) | 340 | }) |
| 341 | } | 341 | } |
crates/in-web/src/i18n/mod.rsmodified+1 -0
| @@ -8,6 +8,7 @@ | |||
| 8 | //! helper functions next to their keys. | 8 | //! helper functions next to their keys. |
| 9 | 9 | ||
| 10 | pub mod drive; | 10 | pub mod drive; |
| 11 | +pub mod share; | ||
| 11 | pub mod shell; | 12 | pub mod shell; |
| 12 | 13 | ||
| 13 | use topcoat::context::Cx; | 14 | use topcoat::context::Cx; |
crates/in-web/src/i18n/share.rsadded+280 -0
| @@ -0,0 +1,280 @@ | |||
| 1 | +//! Strings of sharing: the shared page, the share page of an item, the links page, the public share pages | ||
| 2 | +//! and the notices and refusals that the share forms carry back. The match in [`s`] is exhaustive over | ||
| 3 | +//! `(key, lang)`, so a missing Turkish text does not compile. | ||
| 4 | + | ||
| 5 | +use super::Lang; | ||
| 6 | + | ||
| 7 | +/// One variant per phrase of sharing. | ||
| 8 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 9 | +pub enum SK { | ||
| 10 | + /// Navigation tab: items shared with me. | ||
| 11 | + NavShared, | ||
| 12 | + /// Navigation tab: my share links. | ||
| 13 | + NavLinks, | ||
| 14 | + /// Title of the shared page. | ||
| 15 | + SharedTitle, | ||
| 16 | + /// Heading when nothing is shared with the viewer. | ||
| 17 | + SharedEmpty, | ||
| 18 | + /// Hint under that heading. | ||
| 19 | + SharedEmptyHint, | ||
| 20 | + /// Access label: the grantee may only see the item. | ||
| 21 | + AccessView, | ||
| 22 | + /// Access label: the grantee may download the item. | ||
| 23 | + AccessDownload, | ||
| 24 | + /// Label of the grantee's own view of a shared folder. | ||
| 25 | + SharedWithYou, | ||
| 26 | + /// Heading of the share page of an item. | ||
| 27 | + ShareHeading, | ||
| 28 | + /// Section heading: the people the item is shared with. | ||
| 29 | + ShareWithPeople, | ||
| 30 | + /// Shown when nobody has a grant on the item. | ||
| 31 | + ShareNobody, | ||
| 32 | + /// Label of the person picker. | ||
| 33 | + SharePerson, | ||
| 34 | + /// Placeholder option of the person picker. | ||
| 35 | + SharePickPerson, | ||
| 36 | + /// Label of the access picker. | ||
| 37 | + ShareLevel, | ||
| 38 | + /// Button that adds a grant. | ||
| 39 | + ShareAdd, | ||
| 40 | + /// Button that saves a grant's new level. | ||
| 41 | + ShareSave, | ||
| 42 | + /// Button that removes a grant. | ||
| 43 | + ShareRemove, | ||
| 44 | + /// Hint: only the owner decides who sees an item. | ||
| 45 | + ShareOwnerOnly, | ||
| 46 | + /// Section heading of the links of an item. | ||
| 47 | + ShareLinks, | ||
| 48 | + /// Shown when the item has no links. | ||
| 49 | + ShareNoLinks, | ||
| 50 | + /// Title of the links page. | ||
| 51 | + LinksTitle, | ||
| 52 | + /// Shown on the links page when there are none. | ||
| 53 | + LinksEmpty, | ||
| 54 | + /// Hint under the links page title. | ||
| 55 | + LinksHint, | ||
| 56 | + /// Label of the expiry field. | ||
| 57 | + LinkDays, | ||
| 58 | + /// Label of the optional password field. | ||
| 59 | + LinkPassword, | ||
| 60 | + /// Label of the download checkbox. | ||
| 61 | + LinkAllowDownload, | ||
| 62 | + /// Button that creates a link. | ||
| 63 | + LinkCreate, | ||
| 64 | + /// Label of the link URL. | ||
| 65 | + LinkUrl, | ||
| 66 | + /// Label of the expiry date. | ||
| 67 | + LinkExpires, | ||
| 68 | + /// Shown for an expired link. | ||
| 69 | + LinkExpired, | ||
| 70 | + /// Shown for a link with no password. | ||
| 71 | + LinkNoPassword, | ||
| 72 | + /// Shown for a link with a password. | ||
| 73 | + LinkHasPassword, | ||
| 74 | + /// Label of the access a link gives. | ||
| 75 | + /// Button that revokes a link. | ||
| 76 | + LinkRevoke, | ||
| 77 | + /// Button that replaces a link's URL. | ||
| 78 | + LinkRemint, | ||
| 79 | + /// Label of the visit count. | ||
| 80 | + LinkVisits, | ||
| 81 | + /// Notice: a link was made, so it can be copied. | ||
| 82 | + /// Heading of the public page of a protected link. | ||
| 83 | + PublicGateTitle, | ||
| 84 | + /// Text of the public password page. | ||
| 85 | + PublicGateBody, | ||
| 86 | + /// Label of the public password field. | ||
| 87 | + PublicPassword, | ||
| 88 | + /// Button that opens a protected link. | ||
| 89 | + PublicOpen, | ||
| 90 | + /// Shown after a wrong password. | ||
| 91 | + PublicWrong, | ||
| 92 | + /// Shown in an empty public folder. | ||
| 93 | + PublicEmpty, | ||
| 94 | + /// Link text on a public download. | ||
| 95 | + /// Label of the public breadcrumb trail. | ||
| 96 | + PublicLocation, | ||
| 97 | + /// The root crumb of a shared item on the public page. | ||
| 98 | + PublicRoot, | ||
| 99 | + /// Notice: the grant was made. | ||
| 100 | + NoticeShared, | ||
| 101 | + /// Notice: the grant was changed. | ||
| 102 | + NoticeShareUpdated, | ||
| 103 | + /// Notice: the grant was removed. | ||
| 104 | + NoticeUnshared, | ||
| 105 | + /// Notice: the link was made. | ||
| 106 | + NoticeLinkCreated, | ||
| 107 | + /// Notice: the link was revoked. | ||
| 108 | + NoticeLinkRevoked, | ||
| 109 | + /// Notice: the link was replaced by a new one. | ||
| 110 | + NoticeLinkReminted, | ||
| 111 | + /// Refusal: the person is not an active member. | ||
| 112 | + RefuseNoMember, | ||
| 113 | + /// Refusal: the item is already the viewer's own. | ||
| 114 | + RefuseSelfShare, | ||
| 115 | + /// Refusal: the expiry days are out of range. | ||
| 116 | + RefuseLinkDays, | ||
| 117 | + /// Refusal: the expired link cannot be replaced. | ||
| 118 | + RefuseLinkExpired, | ||
| 119 | + /// Refusal: the password is too long. | ||
| 120 | + RefusePasswordLong, | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +/// The text of a phrase in a language. | ||
| 124 | +pub fn s(lang: Lang, key: SK) -> &'static str { | ||
| 125 | + match (key, lang) { | ||
| 126 | + (SK::NavShared, Lang::En) => "Shared", | ||
| 127 | + (SK::NavShared, Lang::Tr) => "Paylaşılanlar", | ||
| 128 | + (SK::NavLinks, Lang::En) => "Links", | ||
| 129 | + (SK::NavLinks, Lang::Tr) => "Bağlantılar", | ||
| 130 | + (SK::SharedTitle, Lang::En) => "Shared with me", | ||
| 131 | + (SK::SharedTitle, Lang::Tr) => "Benimle paylaşılanlar", | ||
| 132 | + (SK::SharedEmpty, Lang::En) => "Nothing is shared with you yet", | ||
| 133 | + (SK::SharedEmpty, Lang::Tr) => "Sizinle henüz bir şey paylaşılmadı", | ||
| 134 | + (SK::SharedEmptyHint, Lang::En) => { | ||
| 135 | + "When someone in the family shares a file or folder with you, it appears here." | ||
| 136 | + } | ||
| 137 | + (SK::SharedEmptyHint, Lang::Tr) => { | ||
| 138 | + "Bir aile üyesi sizinle bir dosya ya da klasör paylaştığında burada görünür." | ||
| 139 | + } | ||
| 140 | + (SK::AccessView, Lang::En) => "View only", | ||
| 141 | + (SK::AccessView, Lang::Tr) => "Yalnızca görüntüleme", | ||
| 142 | + (SK::AccessDownload, Lang::En) => "May download", | ||
| 143 | + (SK::AccessDownload, Lang::Tr) => "İndirebilir", | ||
| 144 | + (SK::SharedWithYou, Lang::En) => "Shared with you", | ||
| 145 | + (SK::SharedWithYou, Lang::Tr) => "Sizinle paylaşıldı", | ||
| 146 | + (SK::ShareHeading, Lang::En) => "Share", | ||
| 147 | + (SK::ShareHeading, Lang::Tr) => "Paylaş", | ||
| 148 | + (SK::ShareWithPeople, Lang::En) => "People", | ||
| 149 | + (SK::ShareWithPeople, Lang::Tr) => "Kişiler", | ||
| 150 | + (SK::ShareNobody, Lang::En) => "Not shared with anyone yet.", | ||
| 151 | + (SK::ShareNobody, Lang::Tr) => "Henüz kimseyle paylaşılmadı.", | ||
| 152 | + (SK::SharePerson, Lang::En) => "Person", | ||
| 153 | + (SK::SharePerson, Lang::Tr) => "Kişi", | ||
| 154 | + (SK::SharePickPerson, Lang::En) => "Choose a person", | ||
| 155 | + (SK::SharePickPerson, Lang::Tr) => "Bir kişi seçin", | ||
| 156 | + (SK::ShareLevel, Lang::En) => "Access", | ||
| 157 | + (SK::ShareLevel, Lang::Tr) => "Erişim", | ||
| 158 | + (SK::ShareAdd, Lang::En) => "Share", | ||
| 159 | + (SK::ShareAdd, Lang::Tr) => "Paylaş", | ||
| 160 | + (SK::ShareSave, Lang::En) => "Save", | ||
| 161 | + (SK::ShareSave, Lang::Tr) => "Kaydet", | ||
| 162 | + (SK::ShareRemove, Lang::En) => "Remove", | ||
| 163 | + (SK::ShareRemove, Lang::Tr) => "Kaldır", | ||
| 164 | + (SK::ShareOwnerOnly, Lang::En) => "Only the owner can change who sees this item.", | ||
| 165 | + (SK::ShareOwnerOnly, Lang::Tr) => { | ||
| 166 | + "Bu öğeyi kimin göreceğini yalnızca sahibi değiştirebilir." | ||
| 167 | + } | ||
| 168 | + (SK::ShareLinks, Lang::En) => "Share links", | ||
| 169 | + (SK::ShareLinks, Lang::Tr) => "Paylaşım bağlantıları", | ||
| 170 | + (SK::ShareNoLinks, Lang::En) => "No share links for this item.", | ||
| 171 | + (SK::ShareNoLinks, Lang::Tr) => "Bu öğe için paylaşım bağlantısı yok.", | ||
| 172 | + (SK::LinksTitle, Lang::En) => "My share links", | ||
| 173 | + (SK::LinksTitle, Lang::Tr) => "Paylaşım bağlantılarım", | ||
| 174 | + (SK::LinksEmpty, Lang::En) => "You have no share links.", | ||
| 175 | + (SK::LinksEmpty, Lang::Tr) => "Paylaşım bağlantınız yok.", | ||
| 176 | + (SK::LinksHint, Lang::En) => { | ||
| 177 | + "Anyone with a link can open it until it expires or you revoke it." | ||
| 178 | + } | ||
| 179 | + (SK::LinksHint, Lang::Tr) => { | ||
| 180 | + "Bir bağlantıyı, süresi dolana ya da siz iptal edene kadar herkes açabilir." | ||
| 181 | + } | ||
| 182 | + (SK::LinkDays, Lang::En) => "Lasts (days)", | ||
| 183 | + (SK::LinkDays, Lang::Tr) => "Geçerlilik (gün)", | ||
| 184 | + (SK::LinkPassword, Lang::En) => "Password (optional)", | ||
| 185 | + (SK::LinkPassword, Lang::Tr) => "Parola (isteğe bağlı)", | ||
| 186 | + (SK::LinkAllowDownload, Lang::En) => "Allow download", | ||
| 187 | + (SK::LinkAllowDownload, Lang::Tr) => "İndirmeye izin ver", | ||
| 188 | + (SK::LinkCreate, Lang::En) => "Create link", | ||
| 189 | + (SK::LinkCreate, Lang::Tr) => "Bağlantı oluştur", | ||
| 190 | + (SK::LinkUrl, Lang::En) => "Link", | ||
| 191 | + (SK::LinkUrl, Lang::Tr) => "Bağlantı", | ||
| 192 | + (SK::LinkExpires, Lang::En) => "Expires", | ||
| 193 | + (SK::LinkExpires, Lang::Tr) => "Sona erer", | ||
| 194 | + (SK::LinkExpired, Lang::En) => "Expired", | ||
| 195 | + (SK::LinkExpired, Lang::Tr) => "Süresi doldu", | ||
| 196 | + (SK::LinkNoPassword, Lang::En) => "No password", | ||
| 197 | + (SK::LinkNoPassword, Lang::Tr) => "Parola yok", | ||
| 198 | + (SK::LinkHasPassword, Lang::En) => "Password set", | ||
| 199 | + (SK::LinkHasPassword, Lang::Tr) => "Parola var", | ||
| 200 | + (SK::LinkRevoke, Lang::En) => "Revoke", | ||
| 201 | + (SK::LinkRevoke, Lang::Tr) => "İptal et", | ||
| 202 | + (SK::LinkRemint, Lang::En) => "Replace URL", | ||
| 203 | + (SK::LinkRemint, Lang::Tr) => "Adresi değiştir", | ||
| 204 | + (SK::LinkVisits, Lang::En) => "Opened", | ||
| 205 | + (SK::LinkVisits, Lang::Tr) => "Açılma", | ||
| 206 | + (SK::PublicGateTitle, Lang::En) => "This link is protected", | ||
| 207 | + (SK::PublicGateTitle, Lang::Tr) => "Bu bağlantı korumalı", | ||
| 208 | + (SK::PublicGateBody, Lang::En) => "Enter the password to open it.", | ||
| 209 | + (SK::PublicGateBody, Lang::Tr) => "Açmak için parolayı girin.", | ||
| 210 | + (SK::PublicPassword, Lang::En) => "Password", | ||
| 211 | + (SK::PublicPassword, Lang::Tr) => "Parola", | ||
| 212 | + (SK::PublicOpen, Lang::En) => "Open", | ||
| 213 | + (SK::PublicOpen, Lang::Tr) => "Aç", | ||
| 214 | + (SK::PublicWrong, Lang::En) => "Wrong password.", | ||
| 215 | + (SK::PublicWrong, Lang::Tr) => "Parola yanlış.", | ||
| 216 | + (SK::PublicEmpty, Lang::En) => "This folder is empty.", | ||
| 217 | + (SK::PublicEmpty, Lang::Tr) => "Bu klasör boş.", | ||
| 218 | + (SK::PublicLocation, Lang::En) => "Location", | ||
| 219 | + (SK::PublicLocation, Lang::Tr) => "Konum", | ||
| 220 | + (SK::PublicRoot, Lang::En) => "Shared", | ||
| 221 | + (SK::PublicRoot, Lang::Tr) => "Paylaşılan", | ||
| 222 | + (SK::NoticeShared, Lang::En) => "The item is now shared.", | ||
| 223 | + (SK::NoticeShared, Lang::Tr) => "Öğe artık paylaşılıyor.", | ||
| 224 | + (SK::NoticeShareUpdated, Lang::En) => "The access was changed.", | ||
| 225 | + (SK::NoticeShareUpdated, Lang::Tr) => "Erişim değiştirildi.", | ||
| 226 | + (SK::NoticeUnshared, Lang::En) => "The person no longer has access.", | ||
| 227 | + (SK::NoticeUnshared, Lang::Tr) => "Kişinin erişimi kaldırıldı.", | ||
| 228 | + (SK::NoticeLinkCreated, Lang::En) => "The link was created.", | ||
| 229 | + (SK::NoticeLinkCreated, Lang::Tr) => "Bağlantı oluşturuldu.", | ||
| 230 | + (SK::NoticeLinkRevoked, Lang::En) => "The link was revoked.", | ||
| 231 | + (SK::NoticeLinkRevoked, Lang::Tr) => "Bağlantı iptal edildi.", | ||
| 232 | + (SK::NoticeLinkReminted, Lang::En) => { | ||
| 233 | + "The link has a new address. The old one no longer works." | ||
| 234 | + } | ||
| 235 | + (SK::NoticeLinkReminted, Lang::Tr) => { | ||
| 236 | + "Bağlantının yeni bir adresi var. Eskisi artık çalışmıyor." | ||
| 237 | + } | ||
| 238 | + (SK::RefuseNoMember, Lang::En) => "That person is not an active member of the family.", | ||
| 239 | + (SK::RefuseNoMember, Lang::Tr) => "Bu kişi ailede etkin bir üye değil.", | ||
| 240 | + (SK::RefuseSelfShare, Lang::En) => "You already own this item.", | ||
| 241 | + (SK::RefuseSelfShare, Lang::Tr) => "Bu öğenin sahibi zaten sizsiniz.", | ||
| 242 | + (SK::RefuseLinkDays, Lang::En) => { | ||
| 243 | + "The link must last at least one day and no longer than the limit." | ||
| 244 | + } | ||
| 245 | + (SK::RefuseLinkDays, Lang::Tr) => { | ||
| 246 | + "Bağlantı en az bir gün ve sınırı aşmayacak kadar geçerli olmalı." | ||
| 247 | + } | ||
| 248 | + (SK::RefuseLinkExpired, Lang::En) => "This link has expired. Create a new one.", | ||
| 249 | + (SK::RefuseLinkExpired, Lang::Tr) => { | ||
| 250 | + "Bu bağlantının süresi doldu. Yeni bir bağlantı oluşturun." | ||
| 251 | + } | ||
| 252 | + (SK::RefusePasswordLong, Lang::En) => "The password is too long (256 bytes at most).", | ||
| 253 | + (SK::RefusePasswordLong, Lang::Tr) => "Parola çok uzun (en fazla 256 bayt).", | ||
| 254 | + } | ||
| 255 | +} | ||
| 256 | + | ||
| 257 | +/// The notice text of a share word from a redirect, or `None` for a word this build does not know. | ||
| 258 | +pub fn notice_text(lang: Lang, word: &str) -> Option<&'static str> { | ||
| 259 | + Some(match word { | ||
| 260 | + "shared" => s(lang, SK::NoticeShared), | ||
| 261 | + "share_updated" => s(lang, SK::NoticeShareUpdated), | ||
| 262 | + "unshared" => s(lang, SK::NoticeUnshared), | ||
| 263 | + "link_created" => s(lang, SK::NoticeLinkCreated), | ||
| 264 | + "link_revoked" => s(lang, SK::NoticeLinkRevoked), | ||
| 265 | + "link_reminted" => s(lang, SK::NoticeLinkReminted), | ||
| 266 | + _ => return None, | ||
| 267 | + }) | ||
| 268 | +} | ||
| 269 | + | ||
| 270 | +/// The refusal text of a share word from a redirect, or `None` for a word this build does not know. | ||
| 271 | +pub fn refusal_text(lang: Lang, word: &str) -> Option<&'static str> { | ||
| 272 | + Some(match word { | ||
| 273 | + "no_such_member" => s(lang, SK::RefuseNoMember), | ||
| 274 | + "self_share" => s(lang, SK::RefuseSelfShare), | ||
| 275 | + "link_days" => s(lang, SK::RefuseLinkDays), | ||
| 276 | + "link_expired" => s(lang, SK::RefuseLinkExpired), | ||
| 277 | + "password_long" => s(lang, SK::RefusePasswordLong), | ||
| 278 | + _ => return None, | ||
| 279 | + }) | ||
| 280 | +} | ||
crates/in-web/src/main.rsmodified+1 -0
| @@ -18,6 +18,7 @@ mod security; | |||
| 18 | mod serve_bytes; | 18 | mod serve_bytes; |
| 19 | mod state; | 19 | mod state; |
| 20 | mod sweeper; | 20 | mod sweeper; |
| 21 | +mod throttle; | ||
| 21 | mod thumbs_worker; | 22 | mod thumbs_worker; |
| 22 | mod views; | 23 | mod views; |
| 23 | 24 | ||
crates/in-web/src/pages/drive.rsmodified+154 -19
| @@ -17,6 +17,8 @@ use in_core::error::Error as CoreError; | |||
| 17 | use in_core::names::validate_name; | 17 | use in_core::names::validate_name; |
| 18 | use in_core::store::files::File; | 18 | use in_core::store::files::File; |
| 19 | use in_core::store::folders::{Folder, Listing}; | 19 | use in_core::store::folders::{Folder, Listing}; |
| 20 | +use in_core::store::shares::Access; | ||
| 21 | +use in_core::store::trash::ItemKind; | ||
| 20 | use serde::Deserialize; | 22 | use serde::Deserialize; |
| 21 | use topcoat::Result; | 23 | use topcoat::Result; |
| 22 | use topcoat::context::{Cx, app_context}; | 24 | use topcoat::context::{Cx, app_context}; |
| @@ -30,6 +32,7 @@ use crate::auth::{Viewer, require_csrf, require_member, safe_next}; | |||
| 30 | use crate::i18n::Lang; | 32 | use crate::i18n::Lang; |
| 31 | use crate::i18n::drive::{DK, d, refusal_text}; | 33 | use crate::i18n::drive::{DK, d, refusal_text}; |
| 32 | use crate::i18n::lang; | 34 | use crate::i18n::lang; |
| 35 | +use crate::i18n::share::{SK, s as share_s}; | ||
| 33 | use crate::live::{Topic, stream_changes}; | 36 | use crate::live::{Topic, stream_changes}; |
| 34 | use crate::oidc::percent_encode; | 37 | use crate::oidc::percent_encode; |
| 35 | use crate::state::AppState; | 38 | use crate::state::AppState; |
| @@ -119,6 +122,12 @@ pub struct Board { | |||
| 119 | pub live: Option<String>, | 122 | pub live: Option<String>, |
| 120 | /// The start of the sort links: the listing's URL, ending in `?` or `&`. | 123 | /// The start of the sort links: the listing's URL, ending in `?` or `&`. |
| 121 | pub base: String, | 124 | pub base: String, |
| 125 | + /// Whether the viewer owns the listing. Only the owner sees the write forms and row menus. | ||
| 126 | + pub writable: bool, | ||
| 127 | + /// Whether the viewer may download the files listed. | ||
| 128 | + pub downloadable: bool, | ||
| 129 | + /// `Some(can_download)` when the listing is shared with the viewer, which the page says. | ||
| 130 | + pub shared: Option<bool>, | ||
| 122 | } | 131 | } |
| 123 | 132 | ||
| 124 | /// The language of a viewer: the stored override, else the `im` language, else the request. | 133 | /// 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 { | |||
| 136 | } | 145 | } |
| 137 | 146 | ||
| 138 | /// Maps a refusal of the drive's authorization to the HTTP answer. A listing or a view that is refused | 147 | /// Maps a refusal of the drive's authorization to the HTTP answer. A listing or a view that is refused |
| 139 | -/// is always `404`; a change that is refused to someone who can see the item is `403`. | 148 | +/// is always `404`; a change that is refused to someone who can see the item is `403`. `access` is the |
| 140 | -pub fn check(viewer: &Viewer, owner: &str, trashed: bool, action: Action) -> Result<()> { | 149 | +/// reach the viewer has on the item, computed from its grants and its ancestors. |
| 150 | +pub fn check(viewer: &Viewer, owner: &str, access: Access, action: Action) -> Result<()> { | ||
| 141 | let target = Target { | 151 | let target = Target { |
| 142 | owner, | 152 | owner, |
| 143 | - trashed, | 153 | + trashed: access.trashed, |
| 144 | inside_link: false, | 154 | inside_link: false, |
| 145 | }; | 155 | }; |
| 146 | let actor = Actor::Member { | 156 | let actor = Actor::Member { |
| 147 | sub: &viewer.member.sub, | 157 | sub: &viewer.member.sub, |
| 148 | is_admin: viewer.member.is_admin, | 158 | is_admin: viewer.member.is_admin, |
| 149 | }; | 159 | }; |
| 150 | - match authz::authorize(actor, target, Grant::None, action) { | 160 | + match authz::authorize(actor, target, access.grant, action) { |
| 151 | Ok(()) => Ok(()), | 161 | Ok(()) => Ok(()), |
| 152 | Err(Denied::NotFound) => Err(not_found().into()), | 162 | Err(Denied::NotFound) => Err(not_found().into()), |
| 153 | Err(Denied::Forbidden) if matches!(action, Action::List | Action::View) => { | 163 | 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 | |||
| 157 | } | 167 | } |
| 158 | } | 168 | } |
| 159 | 169 | ||
| 160 | -/// A live folder by id, after the authorization for `action`. A missing id is `404`. | 170 | +/// The reach the viewer has on an item. An item that does not exist is `404`. |
| 171 | +pub async fn access_for( | ||
| 172 | + state: &AppState, | ||
| 173 | + viewer: &Viewer, | ||
| 174 | + kind: ItemKind, | ||
| 175 | + id: &str, | ||
| 176 | +) -> Result<Access> { | ||
| 177 | + let access = state | ||
| 178 | + .store | ||
| 179 | + .access_of(&viewer.member.sub, kind, id) | ||
| 180 | + .await? | ||
| 181 | + .ok_or_else(not_found)?; | ||
| 182 | + Ok(access) | ||
| 183 | +} | ||
| 184 | + | ||
| 185 | +/// A folder by id, after the authorization for `action` with the viewer's reach on it. A missing id is `404`. | ||
| 161 | pub async fn folder_for( | 186 | pub async fn folder_for( |
| 162 | state: &AppState, | 187 | state: &AppState, |
| 163 | viewer: &Viewer, | 188 | viewer: &Viewer, |
| @@ -165,7 +190,8 @@ pub async fn folder_for( | |||
| 165 | action: Action, | 190 | action: Action, |
| 166 | ) -> Result<Folder> { | 191 | ) -> Result<Folder> { |
| 167 | let folder = state.store.folder(id).await?.ok_or_else(not_found)?; | 192 | let folder = state.store.folder(id).await?.ok_or_else(not_found)?; |
| 168 | - check(viewer, &folder.owner, folder.trashed_at.is_some(), action)?; | 193 | + let access = access_for(state, viewer, ItemKind::Folder, id).await?; |
| 194 | + check(viewer, &folder.owner, access, action)?; | ||
| 169 | Ok(folder) | 195 | Ok(folder) |
| 170 | } | 196 | } |
| 171 | 197 | ||
| @@ -295,13 +321,38 @@ pub async fn folder_board( | |||
| 295 | query: &ListQuery, | 321 | query: &ListQuery, |
| 296 | lang: Lang, | 322 | lang: Lang, |
| 297 | ) -> Result<Board> { | 323 | ) -> Result<Board> { |
| 298 | - let owner = viewer.member.sub.clone(); | 324 | + let me = viewer.member.sub.clone(); |
| 299 | - let (heading, trail) = match folder.as_deref() { | 325 | + // The listing belongs to the folder's owner, which is the viewer for the drive root and for their own |
| 300 | - None => (d(lang, DK::Drive).to_owned(), Vec::new()), | 326 | + // folders. A grantee sees the owner's folder through the grant, with breadcrumbs that start at the |
| 327 | + // granted folder. | ||
| 328 | + let (heading, trail, owner, writable, downloadable, shared) = match folder.as_deref() { | ||
| 329 | + None => ( | ||
| 330 | + d(lang, DK::Drive).to_owned(), | ||
| 331 | + Vec::new(), | ||
| 332 | + me.clone(), | ||
| 333 | + true, | ||
| 334 | + true, | ||
| 335 | + None, | ||
| 336 | + ), | ||
| 301 | Some(id) => { | 337 | Some(id) => { |
| 302 | let row = folder_for(state, viewer, id, Action::List).await?; | 338 | let row = folder_for(state, viewer, id, Action::List).await?; |
| 303 | - let trail = state.store.folder_path(&owner, id).await?; | 339 | + let access = access_for(state, viewer, ItemKind::Folder, id).await?; |
| 304 | - (row.name.clone(), trail) | 340 | + let mine = row.owner == me; |
| 341 | + let trail = if mine { | ||
| 342 | + state.store.folder_path(&me, id).await? | ||
| 343 | + } else { | ||
| 344 | + state.store.shared_trail(&me, id).await? | ||
| 345 | + }; | ||
| 346 | + let shared = (!mine).then_some(access.grant == Grant::Download); | ||
| 347 | + let downloadable = mine || access.grant == Grant::Download; | ||
| 348 | + ( | ||
| 349 | + row.name.clone(), | ||
| 350 | + trail, | ||
| 351 | + row.owner.clone(), | ||
| 352 | + mine, | ||
| 353 | + downloadable, | ||
| 354 | + shared, | ||
| 355 | + ) | ||
| 305 | } | 356 | } |
| 306 | }; | 357 | }; |
| 307 | let mut listing = state.store.list_children(&owner, folder.as_deref()).await?; | 358 | let mut listing = state.store.list_children(&owner, folder.as_deref()).await?; |
| @@ -335,6 +386,9 @@ pub async fn folder_board( | |||
| 335 | refusal: query.refusal.clone(), | 386 | refusal: query.refusal.clone(), |
| 336 | live: Some(live), | 387 | live: Some(live), |
| 337 | base, | 388 | base, |
| 389 | + writable, | ||
| 390 | + downloadable, | ||
| 391 | + shared, | ||
| 338 | }) | 392 | }) |
| 339 | } | 393 | } |
| 340 | 394 | ||
| @@ -369,6 +423,9 @@ pub async fn search_board( | |||
| 369 | refusal: query.refusal.clone(), | 423 | refusal: query.refusal.clone(), |
| 370 | live: None, | 424 | live: None, |
| 371 | base: format!("{DRIVE_HOME}?q={enc}&"), | 425 | base: format!("{DRIVE_HOME}?q={enc}&"), |
| 426 | + writable: true, | ||
| 427 | + downloadable: true, | ||
| 428 | + shared: None, | ||
| 372 | }) | 429 | }) |
| 373 | } | 430 | } |
| 374 | 431 | ||
| @@ -380,20 +437,36 @@ pub async fn drive_board(lang: Lang, board: &Board) -> Result<impl View> { | |||
| 380 | let in_search = !board.query.is_empty(); | 437 | let in_search = !board.query.is_empty(); |
| 381 | let empty = board.folders.is_empty() && board.files.is_empty(); | 438 | let empty = board.folders.is_empty() && board.files.is_empty(); |
| 382 | let search_value = board.query.clone(); | 439 | let search_value = board.query.clone(); |
| 440 | + let shared_note = match board.shared { | ||
| 441 | + Some(true) => Some(format!( | ||
| 442 | + "{} \u{b7} {}", | ||
| 443 | + share_s(lang, SK::SharedWithYou), | ||
| 444 | + share_s(lang, SK::AccessDownload) | ||
| 445 | + )), | ||
| 446 | + Some(false) => Some(format!( | ||
| 447 | + "{} \u{b7} {}", | ||
| 448 | + share_s(lang, SK::SharedWithYou), | ||
| 449 | + share_s(lang, SK::AccessView) | ||
| 450 | + )), | ||
| 451 | + None => None, | ||
| 452 | + }; | ||
| 383 | Ok(view! { | 453 | Ok(view! { |
| 384 | <section class="drive" data-live=(board.live.as_deref())> | 454 | <section class="drive" data-live=(board.live.as_deref())> |
| 385 | <h1>(board.heading.as_str())</h1> | 455 | <h1>(board.heading.as_str())</h1> |
| 386 | if board.folder.is_some() { | 456 | if board.folder.is_some() { |
| 387 | - crumbs(lang: lang, trail: &board.trail) | 457 | + crumbs(lang: lang, trail: &board.trail, shared: board.shared.is_some()) |
| 458 | + } | ||
| 459 | + if let Some(note) = shared_note { | ||
| 460 | + <p class="muted">(note)</p> | ||
| 388 | } | 461 | } |
| 389 | flash(lang: lang, notice: board.notice.as_str(), refusal: board.refusal.as_str()) | 462 | flash(lang: lang, notice: board.notice.as_str(), refusal: board.refusal.as_str()) |
| 390 | <div class="toolbar"> | 463 | <div class="toolbar"> |
| 391 | - <form method="get" action="/drive" class="inline-form" role="search"> | 464 | + <form method="get" action=(if board.shared.is_some() { "/shared" } else { "/drive" }) class="inline-form" role="search"> |
| 392 | <label class="sr-only" for="drive-search">(d(lang, DK::SearchPlaceholder))</label> | 465 | <label class="sr-only" for="drive-search">(d(lang, DK::SearchPlaceholder))</label> |
| 393 | <input id="drive-search" type="search" name="q" value=(search_value.as_str()) placeholder=(d(lang, DK::SearchPlaceholder))> | 466 | <input id="drive-search" type="search" name="q" value=(search_value.as_str()) placeholder=(d(lang, DK::SearchPlaceholder))> |
| 394 | <button class="button" type="submit">(d(lang, DK::Search))</button> | 467 | <button class="button" type="submit">(d(lang, DK::Search))</button> |
| 395 | </form> | 468 | </form> |
| 396 | - if !in_search { | 469 | + if !in_search && board.writable { |
| 397 | <form method="post" action="/folders" class="inline-form"> | 470 | <form method="post" action="/folders" class="inline-form"> |
| 398 | <input type="hidden" name="csrf" value=(board.csrf.as_str())> | 471 | <input type="hidden" name="csrf" value=(board.csrf.as_str())> |
| 399 | <input type="hidden" name="back" value=(board.back.as_str())> | 472 | <input type="hidden" name="back" value=(board.back.as_str())> |
| @@ -423,7 +496,7 @@ pub async fn drive_board(lang: Lang, board: &Board) -> Result<impl View> { | |||
| 423 | empty_state(title: d(lang, DK::EmptyFolder), <p>(d(lang, DK::EmptyFolderHint))</p>) | 496 | empty_state(title: d(lang, DK::EmptyFolder), <p>(d(lang, DK::EmptyFolderHint))</p>) |
| 424 | } | 497 | } |
| 425 | } else { | 498 | } else { |
| 426 | - 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()) | 499 | + 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) |
| 427 | } | 500 | } |
| 428 | </section> | 501 | </section> |
| 429 | }) | 502 | }) |
| @@ -503,15 +576,19 @@ async fn drive_live(cx: &Cx, query: Option<Form<LiveQuery>>) -> Result<Response> | |||
| 503 | let folder = query | 576 | let folder = query |
| 504 | .map(|Form(query)| query.folder) | 577 | .map(|Form(query)| query.folder) |
| 505 | .filter(|folder| !folder.trim().is_empty()); | 578 | .filter(|folder| !folder.trim().is_empty()); |
| 506 | - if let Some(id) = folder.as_deref() { | 579 | + // The folder's owner is the one whose changes the stream follows: the viewer's own, or the owner of a |
| 507 | - folder_for(state, &viewer, id, Action::List).await?; | 580 | + // folder shared with the viewer. |
| 508 | - } | 581 | + let owner = match folder.as_deref() { |
| 509 | - let owner = viewer.member.sub.clone(); | 582 | + Some(id) => folder_for(state, &viewer, id, Action::List).await?.owner, |
| 583 | + None => viewer.member.sub.clone(), | ||
| 584 | + }; | ||
| 585 | + let me = viewer.member.sub.clone(); | ||
| 510 | let token_hash = viewer.session.token_hash.clone(); | 586 | let token_hash = viewer.session.token_hash.clone(); |
| 511 | let store = state.store.clone(); | 587 | let store = state.store.clone(); |
| 512 | let topics = vec![Topic::Drive(owner.clone())]; | 588 | let topics = vec![Topic::Drive(owner.clone())]; |
| 513 | stream_changes(cx, &state.live, &topics, move || { | 589 | stream_changes(cx, &state.live, &topics, move || { |
| 514 | let store = store.clone(); | 590 | let store = store.clone(); |
| 591 | + let me = me.clone(); | ||
| 515 | let owner = owner.clone(); | 592 | let owner = owner.clone(); |
| 516 | let folder = folder.clone(); | 593 | let folder = folder.clone(); |
| 517 | let token_hash = token_hash.clone(); | 594 | let token_hash = token_hash.clone(); |
| @@ -520,6 +597,16 @@ async fn drive_live(cx: &Cx, query: Option<Form<LiveQuery>>) -> Result<Response> | |||
| 520 | if store.session_by_token_hash(&token_hash).await?.is_none() { | 597 | if store.session_by_token_hash(&token_hash).await?.is_none() { |
| 521 | return Err(not_found().into()); | 598 | return Err(not_found().into()); |
| 522 | } | 599 | } |
| 600 | + // A grant that was taken away ends the stream too, even though the folder still exists. | ||
| 601 | + if let Some(id) = folder.as_deref() { | ||
| 602 | + let access = store | ||
| 603 | + .access_of(&me, ItemKind::Folder, id) | ||
| 604 | + .await? | ||
| 605 | + .ok_or_else(not_found)?; | ||
| 606 | + if access.trashed || access.grant == Grant::None { | ||
| 607 | + return Err(not_found().into()); | ||
| 608 | + } | ||
| 609 | + } | ||
| 523 | let listing = store.list_children(&owner, folder.as_deref()).await?; | 610 | let listing = store.list_children(&owner, folder.as_deref()).await?; |
| 524 | Ok(fingerprint(&listing)) | 611 | Ok(fingerprint(&listing)) |
| 525 | } | 612 | } |
| @@ -712,8 +799,56 @@ mod tests { | |||
| 712 | use http::Request; | 799 | use http::Request; |
| 713 | use http::header::{COOKIE, LOCATION}; | 800 | use http::header::{COOKIE, LOCATION}; |
| 714 | use in_core::quota::DEFAULT_MEMBER_QUOTA; | 801 | use in_core::quota::DEFAULT_MEMBER_QUOTA; |
| 802 | + use in_core::store::trash::ItemKind; | ||
| 715 | use topcoat::router::{Body, to_bytes}; | 803 | use topcoat::router::{Body, to_bytes}; |
| 716 | 804 | ||
| 805 | + /// A grantee who opens a shared folder sees its name and the folders beneath it, never the owner's | ||
| 806 | + /// folders above the grant: the breadcrumb trail stops at the granted folder. | ||
| 807 | + #[tokio::test] | ||
| 808 | + async fn breadcrumbs_of_a_grantee_stop_at_the_granted_folder() { | ||
| 809 | + let (_dir, state) = test_state().await; | ||
| 810 | + let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | ||
| 811 | + let _bob = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await; | ||
| 812 | + let secret = state | ||
| 813 | + .store | ||
| 814 | + .create_folder("ann", None, "Secret plans") | ||
| 815 | + .await | ||
| 816 | + .expect("folder"); | ||
| 817 | + let trips = state | ||
| 818 | + .store | ||
| 819 | + .create_folder("ann", Some(&secret.id), "Trips") | ||
| 820 | + .await | ||
| 821 | + .expect("folder"); | ||
| 822 | + state | ||
| 823 | + .store | ||
| 824 | + .share_with("ann", ItemKind::Folder, &trips.id, "bob", false) | ||
| 825 | + .await | ||
| 826 | + .expect("grant"); | ||
| 827 | + let get = |path: String, token: &str| { | ||
| 828 | + Request::get(path) | ||
| 829 | + .header(COOKIE, format!("{SESSION_COOKIE}={token}")) | ||
| 830 | + .body(Body::empty()) | ||
| 831 | + .expect("request") | ||
| 832 | + }; | ||
| 833 | + let bob = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await; | ||
| 834 | + let response = router(state.clone()) | ||
| 835 | + .handle(get(format!("/drive/{}", trips.id), &bob)) | ||
| 836 | + .await; | ||
| 837 | + assert_eq!(response.status(), 200); | ||
| 838 | + let body = to_bytes(response.into_body(), 1 << 20).await.expect("body"); | ||
| 839 | + let html = String::from_utf8_lossy(&body); | ||
| 840 | + assert!(html.contains("Trips"), "the shared folder is shown"); | ||
| 841 | + assert!( | ||
| 842 | + !html.contains("Secret plans"), | ||
| 843 | + "the owner's parent folder is not revealed" | ||
| 844 | + ); | ||
| 845 | + // The parent itself is not granted, so the grantee cannot open it. | ||
| 846 | + let response = router(state.clone()) | ||
| 847 | + .handle(get(format!("/drive/{}", secret.id), &bob)) | ||
| 848 | + .await; | ||
| 849 | + assert_eq!(response.status(), 404); | ||
| 850 | + } | ||
| 851 | + | ||
| 717 | #[tokio::test] | 852 | #[tokio::test] |
| 718 | async fn the_start_page_goes_to_the_drive_and_the_drive_lists_its_root() { | 853 | async fn the_start_page_goes_to_the_drive_and_the_drive_lists_its_root() { |
| 719 | let (_dir, state) = test_state().await; | 854 | let (_dir, state) = test_state().await; |
crates/in-web/src/pages/files.rsmodified+5 -3
| @@ -15,6 +15,7 @@ use in_core::sniff::sniff; | |||
| 15 | use in_core::staging::{Staged, StagedFile}; | 15 | use in_core::staging::{Staged, StagedFile}; |
| 16 | use in_core::store::files::{File, NewFile, files_blob_key}; | 16 | use in_core::store::files::{File, NewFile, files_blob_key}; |
| 17 | use in_core::store::new_id; | 17 | use in_core::store::new_id; |
| 18 | +use in_core::store::trash::ItemKind; | ||
| 18 | use serde::Deserialize; | 19 | use serde::Deserialize; |
| 19 | use topcoat::Result; | 20 | use topcoat::Result; |
| 20 | use topcoat::context::{Cx, app_context}; | 21 | use topcoat::context::{Cx, app_context}; |
| @@ -29,8 +30,8 @@ use topcoat::view::{View, view}; | |||
| 29 | use crate::auth::{Viewer, require_csrf, require_member}; | 30 | use crate::auth::{Viewer, require_csrf, require_member}; |
| 30 | use crate::i18n::drive::{DK, d}; | 31 | use crate::i18n::drive::{DK, d}; |
| 31 | use crate::pages::drive::{ | 32 | use crate::pages::drive::{ |
| 32 | - DRIVE_HOME, ItemForm, back_or, changed, check, done, optional_folder, pick_body, refusal_word, | 33 | + DRIVE_HOME, ItemForm, access_for, back_or, changed, check, done, optional_folder, pick_body, |
| 33 | - refused, tree_rows, viewer_lang, with_param, | 34 | + refusal_word, refused, tree_rows, viewer_lang, with_param, |
| 34 | }; | 35 | }; |
| 35 | use crate::serve_bytes::{ByteAnswer, ByteSource, Disposition, counts_as_download, serve_bytes}; | 36 | use crate::serve_bytes::{ByteAnswer, ByteSource, Disposition, counts_as_download, serve_bytes}; |
| 36 | use crate::state::AppState; | 37 | use crate::state::AppState; |
| @@ -66,7 +67,8 @@ pub async fn upload_limit(state: &AppState) -> Result<u64> { | |||
| 66 | /// A live or trashed file by id, after the authorization for `action`. A missing id is `404`. | 67 | /// A live or trashed file by id, after the authorization for `action`. A missing id is `404`. |
| 67 | pub async fn file_for(state: &AppState, viewer: &Viewer, id: &str, action: Action) -> Result<File> { | 68 | pub async fn file_for(state: &AppState, viewer: &Viewer, id: &str, action: Action) -> Result<File> { |
| 68 | let file = state.store.file(id).await?.ok_or_else(not_found)?; | 69 | let file = state.store.file(id).await?.ok_or_else(not_found)?; |
| 69 | - check(viewer, &file.owner, file.trashed_at.is_some(), action)?; | 70 | + let access = access_for(state, viewer, ItemKind::File, id).await?; |
| 71 | + check(viewer, &file.owner, access, action)?; | ||
| 70 | Ok(file) | 72 | Ok(file) |
| 71 | } | 73 | } |
| 72 | 74 | ||
crates/in-web/src/pages/links.rsadded+292 -0
| @@ -0,0 +1,292 @@ | |||
| 1 | +//! The owner's share links: the list (`GET /links`), creation (`POST /links`), revoking and reminting. | ||
| 2 | +//! | ||
| 3 | +//! A link is made from the share page of an item, which checks the item is the viewer's and live. Its token | ||
| 4 | +//! is random, shown in full from the sealed copy (so the URL can be copied again), and stored only as its | ||
| 5 | +//! SHA-256. Expiry is at most `link_max_days` (a setting, 365 by default). The password is hashed with | ||
| 6 | +//! argon2id on the blocking pool and is never shown again. Revoking and reminting need the owner; anything | ||
| 7 | +//! else is `404`. | ||
| 8 | + | ||
| 9 | +use std::time::Duration; | ||
| 10 | + | ||
| 11 | +use in_core::error::Error as CoreError; | ||
| 12 | +use in_core::password::hash_password_async; | ||
| 13 | +use in_core::secret; | ||
| 14 | +use in_core::store::links::{Link, NewLink}; | ||
| 15 | +use in_core::store::new_id; | ||
| 16 | +use in_core::store::shares::kind_from_word; | ||
| 17 | +use in_core::store::trash::ItemKind; | ||
| 18 | +use in_core::time::{now_stamp, stamp_after}; | ||
| 19 | +use in_core::token::{generate_token, hash_token}; | ||
| 20 | +use serde::Deserialize; | ||
| 21 | +use topcoat::Result; | ||
| 22 | +use topcoat::context::{Cx, app_context}; | ||
| 23 | +use topcoat::router::content::Form; | ||
| 24 | +use topcoat::router::error::{SeeOther, not_found}; | ||
| 25 | +use topcoat::router::{page, path_param_segment, route}; | ||
| 26 | +use topcoat::view::{View, component, view}; | ||
| 27 | + | ||
| 28 | +use crate::auth::{Viewer, require_csrf, require_member}; | ||
| 29 | +use crate::i18n::Lang; | ||
| 30 | +use crate::i18n::share::{SK, s as share_s}; | ||
| 31 | +use crate::pages::drive::{back_or, done, refused, viewer_lang}; | ||
| 32 | +use crate::pages::share_dialog::shareable; | ||
| 33 | +use crate::state::AppState; | ||
| 34 | +use crate::views::drive::stamp_text; | ||
| 35 | +use crate::views::{ViewerInfo, empty_state, shell}; | ||
| 36 | + | ||
| 37 | +/// The settings key of the longest a link may last, in days. | ||
| 38 | +pub const LINK_MAX_DAYS_SETTING: &str = "link_max_days"; | ||
| 39 | + | ||
| 40 | +/// The longest a link may last when the settings say nothing: a year. | ||
| 41 | +pub const DEFAULT_LINK_MAX_DAYS: u32 = 365; | ||
| 42 | + | ||
| 43 | +/// Longest password accepted, in bytes. Longer ones are refused rather than cut. | ||
| 44 | +pub const MAX_PASSWORD_BYTES: usize = 256; | ||
| 45 | + | ||
| 46 | +/// Seconds in a day, for the expiry arithmetic. | ||
| 47 | +const DAY_SECONDS: u64 = 24 * 60 * 60; | ||
| 48 | + | ||
| 49 | +/// The longest a link may last, from the settings, else the default. Never zero. | ||
| 50 | +pub async fn link_max_days(state: &AppState) -> Result<u32> { | ||
| 51 | + let setting = state.store.get_setting(LINK_MAX_DAYS_SETTING).await?; | ||
| 52 | + Ok(setting | ||
| 53 | + .and_then(|value| value.trim().parse::<u32>().ok()) | ||
| 54 | + .filter(|days| *days >= 1) | ||
| 55 | + .unwrap_or(DEFAULT_LINK_MAX_DAYS)) | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +/// A link as the owner sees it: the link, the name of its target, and the full URL. | ||
| 59 | +#[derive(Debug, Clone)] | ||
| 60 | +pub struct LinkView { | ||
| 61 | + /// The link. | ||
| 62 | + pub link: Link, | ||
| 63 | + /// The target's name, or a dash when the target is gone. | ||
| 64 | + pub name: String, | ||
| 65 | + /// The full address `{base}/s/{token}`, or empty when the sealed token cannot be opened. | ||
| 66 | + pub url: String, | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +/// The URL of a link from its sealed token. Empty when the token cannot be opened. | ||
| 70 | +pub fn public_url(state: &AppState, token_sealed: &str) -> String { | ||
| 71 | + match secret::open(&state.key, token_sealed) | ||
| 72 | + .ok() | ||
| 73 | + .and_then(|bytes| String::from_utf8(bytes).ok()) | ||
| 74 | + { | ||
| 75 | + Some(token) => format!("{}/s/{token}", state.config.base_url.trim_end_matches('/')), | ||
| 76 | + None => String::new(), | ||
| 77 | + } | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +/// The name of a link's target. | ||
| 81 | +async fn target_name(state: &AppState, kind: ItemKind, id: &str) -> Result<String> { | ||
| 82 | + Ok(match kind { | ||
| 83 | + ItemKind::File => state.store.file(id).await?.map(|f| f.name), | ||
| 84 | + ItemKind::Folder => state.store.folder(id).await?.map(|f| f.name), | ||
| 85 | + } | ||
| 86 | + .unwrap_or_else(|| "\u{2014}".to_owned())) | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +/// The views of a viewer's links, in the order the store gives them. | ||
| 90 | +pub async fn link_views(state: &AppState, links: Vec<Link>) -> Result<Vec<LinkView>> { | ||
| 91 | + let mut out = Vec::with_capacity(links.len()); | ||
| 92 | + for link in links { | ||
| 93 | + let name = target_name(state, link.kind, &link.target_id).await?; | ||
| 94 | + let url = public_url(state, &link.token_sealed); | ||
| 95 | + out.push(LinkView { link, name, url }); | ||
| 96 | + } | ||
| 97 | + Ok(out) | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +/// One link in a list: its name and flags, its URL for copying while it works, and the owner's actions. A | ||
| 101 | +/// link past its expiry only offers revoking. | ||
| 102 | +#[component] | ||
| 103 | +pub async fn link_row(lang: Lang, view: &LinkView, csrf: &str, back: &str) -> Result<impl View> { | ||
| 104 | + let link = &view.link; | ||
| 105 | + let id = link.id.as_str(); | ||
| 106 | + let live = link.is_live(&now_stamp()); | ||
| 107 | + let expires = link | ||
| 108 | + .expires_at | ||
| 109 | + .as_deref() | ||
| 110 | + .map(stamp_text) | ||
| 111 | + .unwrap_or_default(); | ||
| 112 | + let access = if link.can_download { | ||
| 113 | + share_s(lang, SK::AccessDownload) | ||
| 114 | + } else { | ||
| 115 | + share_s(lang, SK::AccessView) | ||
| 116 | + }; | ||
| 117 | + let password = if link.password_hash.is_some() { | ||
| 118 | + share_s(lang, SK::LinkHasPassword) | ||
| 119 | + } else { | ||
| 120 | + share_s(lang, SK::LinkNoPassword) | ||
| 121 | + }; | ||
| 122 | + let revoke_action = format!("/links/{id}/revoke"); | ||
| 123 | + let remint_action = format!("/links/{id}/remint"); | ||
| 124 | + let url_id = format!("url-{id}"); | ||
| 125 | + Ok(view! { | ||
| 126 | + <li class="link-row"> | ||
| 127 | + <div class="link-head"><strong>(view.name.as_str())</strong> " " <span class="muted">(access) " \u{b7} " (password)</span></div> | ||
| 128 | + if live { | ||
| 129 | + <label class="sr-only" for=(url_id.as_str())>(share_s(lang, SK::LinkUrl))</label> | ||
| 130 | + <input id=(url_id.as_str()) class="link-url" readonly="" value=(view.url.as_str())> | ||
| 131 | + <p class="muted">(share_s(lang, SK::LinkExpires)) ": " (expires.as_str()) " \u{b7} " (share_s(lang, SK::LinkVisits)) " " (link.use_count.to_string())</p> | ||
| 132 | + <form method="post" action=(remint_action.as_str()) class="inline-form"> | ||
| 133 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 134 | + <input type="hidden" name="back" value=(back)> | ||
| 135 | + <button class="button" type="submit">(share_s(lang, SK::LinkRemint))</button> | ||
| 136 | + </form> | ||
| 137 | + } else { | ||
| 138 | + <p class="muted">(share_s(lang, SK::LinkExpired)) " \u{b7} " (expires.as_str())</p> | ||
| 139 | + } | ||
| 140 | + <form method="post" action=(revoke_action.as_str()) class="inline-form"> | ||
| 141 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 142 | + <input type="hidden" name="back" value=(back)> | ||
| 143 | + <button class="button danger" type="submit">(share_s(lang, SK::LinkRevoke))</button> | ||
| 144 | + </form> | ||
| 145 | + </li> | ||
| 146 | + }) | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +/// The content of the links page: the list of the owner's links, or the empty state. | ||
| 150 | +#[component] | ||
| 151 | +pub async fn links_body(lang: Lang, rows: &[LinkView], csrf: &str) -> Result<impl View> { | ||
| 152 | + Ok(view! { | ||
| 153 | + <section class="drive"> | ||
| 154 | + <h1>(share_s(lang, SK::LinksTitle))</h1> | ||
| 155 | + <p class="muted">(share_s(lang, SK::LinksHint))</p> | ||
| 156 | + if rows.is_empty() { | ||
| 157 | + empty_state(title: share_s(lang, SK::LinksEmpty)) | ||
| 158 | + } else { | ||
| 159 | + <ul class="link-list"> | ||
| 160 | + for row in rows { | ||
| 161 | + link_row(lang: lang, view: row, csrf: csrf, back: "/links") | ||
| 162 | + } | ||
| 163 | + </ul> | ||
| 164 | + } | ||
| 165 | + </section> | ||
| 166 | + }) | ||
| 167 | +} | ||
| 168 | + | ||
| 169 | +/// `GET /links`: every link the viewer has made that is not revoked. | ||
| 170 | +#[page("/links")] | ||
| 171 | +async fn links_page(cx: &Cx) -> Result<impl View> { | ||
| 172 | + let state = app_context::<AppState>(cx); | ||
| 173 | + let viewer = require_member(cx).await?; | ||
| 174 | + let lang = viewer_lang(cx, &viewer); | ||
| 175 | + let links = state.store.links_of(&viewer.member.sub).await?; | ||
| 176 | + let rows = link_views(state, links).await?; | ||
| 177 | + let csrf = viewer.session.csrf_token.clone(); | ||
| 178 | + let info = ViewerInfo::of(&viewer); | ||
| 179 | + let title = share_s(lang, SK::LinksTitle); | ||
| 180 | + Ok(view! { | ||
| 181 | + shell(title: title, lang: lang, viewer: Some(&info), | ||
| 182 | + links_body(lang: lang, rows: &rows, csrf: csrf.as_str()) | ||
| 183 | + ) | ||
| 184 | + }) | ||
| 185 | +} | ||
| 186 | + | ||
| 187 | +/// The form of link writes: the CSRF token, the return page, and for a creation the item, the expiry in | ||
| 188 | +/// days (blank for the maximum), an optional password and the download flag. | ||
| 189 | +#[derive(Debug, Default, Deserialize)] | ||
| 190 | +#[serde(default)] | ||
| 191 | +pub struct LinkForm { | ||
| 192 | + /// The CSRF token of the session. | ||
| 193 | + pub csrf: String, | ||
| 194 | + /// The page to return to. | ||
| 195 | + pub back: String, | ||
| 196 | + /// `file` or `folder`. | ||
| 197 | + pub kind: String, | ||
| 198 | + /// The item the link opens. | ||
| 199 | + pub target_id: String, | ||
| 200 | + /// Days the link lasts; blank means the maximum. | ||
| 201 | + pub days: String, | ||
| 202 | + /// The optional password. Empty means none. | ||
| 203 | + pub password: String, | ||
| 204 | + /// `1` when visitors may download. | ||
| 205 | + pub download: String, | ||
| 206 | +} | ||
| 207 | + | ||
| 208 | +/// Makes a fresh token and its sealed copy: `(token hash, sealed token, token)`. | ||
| 209 | +fn new_token(state: &AppState) -> Result<(String, String, String)> { | ||
| 210 | + let token = generate_token(); | ||
| 211 | + let sealed = secret::seal(&state.key, token.as_bytes())?; | ||
| 212 | + Ok((hash_token(&token), sealed, token)) | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +/// `POST /links`: makes a link to an item the viewer owns and can share. | ||
| 216 | +#[route(POST "/links")] | ||
| 217 | +async fn create_link(cx: &Cx, Form(form): Form<LinkForm>) -> Result<SeeOther> { | ||
| 218 | + let state = app_context::<AppState>(cx); | ||
| 219 | + let viewer: Viewer = require_csrf(cx, &form.csrf).await?; | ||
| 220 | + let kind = kind_from_word(form.kind.trim()).ok_or_else(not_found)?; | ||
| 221 | + let target = form.target_id.trim().to_owned(); | ||
| 222 | + let back = back_or(&form.back, "/links"); | ||
| 223 | + shareable(state, &viewer, kind, &target).await?; | ||
| 224 | + | ||
| 225 | + let max = link_max_days(state).await?; | ||
| 226 | + let raw = form.days.trim(); | ||
| 227 | + let days = if raw.is_empty() { | ||
| 228 | + max | ||
| 229 | + } else { | ||
| 230 | + match raw.parse::<u32>() { | ||
| 231 | + Ok(days) if (1..=max).contains(&days) => days, | ||
| 232 | + _ => return refused(&back, CoreError::Invalid("link_days".into())), | ||
| 233 | + } | ||
| 234 | + }; | ||
| 235 | + let password_hash = if form.password.is_empty() { | ||
| 236 | + None | ||
| 237 | + } else if form.password.len() > MAX_PASSWORD_BYTES { | ||
| 238 | + return refused(&back, CoreError::Invalid("password_long".into())); | ||
| 239 | + } else { | ||
| 240 | + Some(hash_password_async(form.password.clone()).await?) | ||
| 241 | + }; | ||
| 242 | + | ||
| 243 | + let (token_hash, token_sealed, _token) = new_token(state)?; | ||
| 244 | + let new = NewLink { | ||
| 245 | + id: new_id(), | ||
| 246 | + token_hash, | ||
| 247 | + token_sealed, | ||
| 248 | + kind, | ||
| 249 | + target_id: target, | ||
| 250 | + owner: viewer.member.sub.clone(), | ||
| 251 | + can_download: form.download == "1", | ||
| 252 | + password_hash, | ||
| 253 | + expires_at: Some(stamp_after(Duration::from_secs( | ||
| 254 | + u64::from(days) * DAY_SECONDS, | ||
| 255 | + ))), | ||
| 256 | + }; | ||
| 257 | + match state.store.create_link(new).await { | ||
| 258 | + Ok(_) => Ok(done(&back, "link_created")), | ||
| 259 | + Err(error) => refused(&back, error), | ||
| 260 | + } | ||
| 261 | +} | ||
| 262 | + | ||
| 263 | +/// `POST /links/{id}/revoke`: the link stops working at once. | ||
| 264 | +#[route(POST "/links/{id}/revoke")] | ||
| 265 | +async fn revoke_link(cx: &Cx, Form(form): Form<LinkForm>) -> Result<SeeOther> { | ||
| 266 | + let state = app_context::<AppState>(cx); | ||
| 267 | + let viewer = require_csrf(cx, &form.csrf).await?; | ||
| 268 | + let id = path_param_segment(cx, "id").to_owned(); | ||
| 269 | + let back = back_or(&form.back, "/links"); | ||
| 270 | + match state.store.revoke_link(&viewer.member.sub, &id).await { | ||
| 271 | + Ok(()) => Ok(done(&back, "link_revoked")), | ||
| 272 | + Err(error) => refused(&back, error), | ||
| 273 | + } | ||
| 274 | +} | ||
| 275 | + | ||
| 276 | +/// `POST /links/{id}/remint`: a new token for the same link; the old token stops working. | ||
| 277 | +#[route(POST "/links/{id}/remint")] | ||
| 278 | +async fn remint_link(cx: &Cx, Form(form): Form<LinkForm>) -> Result<SeeOther> { | ||
| 279 | + let state = app_context::<AppState>(cx); | ||
| 280 | + let viewer = require_csrf(cx, &form.csrf).await?; | ||
| 281 | + let id = path_param_segment(cx, "id").to_owned(); | ||
| 282 | + let back = back_or(&form.back, "/links"); | ||
| 283 | + let (token_hash, token_sealed, _token) = new_token(state)?; | ||
| 284 | + match state | ||
| 285 | + .store | ||
| 286 | + .remint_link(&viewer.member.sub, &id, &token_hash, &token_sealed) | ||
| 287 | + .await | ||
| 288 | + { | ||
| 289 | + Ok(_) => Ok(done(&back, "link_reminted")), | ||
| 290 | + Err(error) => refused(&back, error), | ||
| 291 | + } | ||
| 292 | +} | ||
crates/in-web/src/pages/mod.rsmodified+4 -0
| @@ -4,8 +4,12 @@ pub mod backchannel; | |||
| 4 | pub mod drive; | 4 | pub mod drive; |
| 5 | pub mod files; | 5 | pub mod files; |
| 6 | pub mod home; | 6 | pub mod home; |
| 7 | +pub mod links; | ||
| 7 | pub mod not_found; | 8 | pub mod not_found; |
| 8 | pub mod photo; | 9 | pub mod photo; |
| 10 | +pub mod public_share; | ||
| 11 | +pub mod share_dialog; | ||
| 12 | +pub mod shared; | ||
| 9 | pub mod sign_in; | 13 | pub mod sign_in; |
| 10 | pub mod thumbs; | 14 | pub mod thumbs; |
| 11 | pub mod trash; | 15 | pub mod trash; |
crates/in-web/src/pages/public_share.rsadded+720 -0
| @@ -0,0 +1,720 @@ | |||
| 1 | +//! The public share pages of a link, anonymous (`/s/{token}`), with their bytes (`/s/{token}/file/{id}`) | ||
| 2 | +//! and thumbnails (`/s/{token}/thumb/{id}`). | ||
| 3 | +//! | ||
| 4 | +//! A link opens one item. A file link shows that file. A folder link lists its folder and browses down | ||
| 5 | +//! inside it; a `?folder=` or `?file=` outside the linked root is `404`, as is any unknown, revoked, | ||
| 6 | +//! expired or trashed link, all alike. A link with a password shows a gate until the visitor posts the | ||
| 7 | +//! right one. The unlock cookie is HMAC-keyed to the link and its password hash, so a changed password | ||
| 8 | +//! locks everyone out again. Wrong passwords are throttled per link and per client address (see | ||
| 9 | +//! `throttle.rs`); the sixth wrong one within the window is `429`. | ||
| 10 | +//! | ||
| 11 | +//! No session is read here and no member's details are shown. The pages send `Referrer-Policy: no-referrer` | ||
| 12 | +//! and `X-Robots-Tag: noindex` (set in `security.rs`). | ||
| 13 | + | ||
| 14 | +use in_core::authz::{Action, Actor, Grant, Target, authorize}; | ||
| 15 | +use in_core::password::verify_password_async; | ||
| 16 | +use in_core::secret::unlock_proof; | ||
| 17 | +use in_core::store::files::File; | ||
| 18 | +use in_core::store::files::thumb_blob_key; | ||
| 19 | +use in_core::store::folders::{Folder, Listing}; | ||
| 20 | +use in_core::store::links::Link; | ||
| 21 | +use in_core::store::trash::ItemKind; | ||
| 22 | +use in_core::time::now_stamp; | ||
| 23 | +use in_core::token::{constant_time_eq, generate_token, hash_token}; | ||
| 24 | +use serde::Deserialize; | ||
| 25 | +use topcoat::Result; | ||
| 26 | +use topcoat::context::{Cx, app_context}; | ||
| 27 | +use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; | ||
| 28 | +use topcoat::router::content::Form; | ||
| 29 | +use topcoat::router::error::{SeeOther, forbidden, not_found, see_other, too_many_requests}; | ||
| 30 | +use topcoat::router::request::{client_ip, headers}; | ||
| 31 | +use topcoat::router::{page, parse_query_params, path_param_segment, route}; | ||
| 32 | +use topcoat::view::{View, component, view}; | ||
| 33 | + | ||
| 34 | +use crate::auth::cookie_value; | ||
| 35 | +use crate::i18n::Lang; | ||
| 36 | +use crate::i18n::drive::{DK, d}; | ||
| 37 | +use crate::i18n::share::{SK, s as share_s}; | ||
| 38 | +use crate::pages::thumbs::thumb_validator; | ||
| 39 | +use crate::serve_bytes::{ | ||
| 40 | + ByteAnswer, ByteSource, Disposition, SHARE_CACHE, counts_as_download, serve_bytes_with, | ||
| 41 | +}; | ||
| 42 | +use crate::state::AppState; | ||
| 43 | +use crate::views::drive::size_text; | ||
| 44 | +use crate::views::{empty_state, shell}; | ||
| 45 | + | ||
| 46 | +/// The cookie that carries the CSRF token of the password gate. `__Host-` makes it host-only, secure and | ||
| 47 | +/// path `/`. | ||
| 48 | +const GATE_CSRF_COOKIE: &str = "__Host-in_precsrf"; | ||
| 49 | + | ||
| 50 | +/// How long a successful password keeps a visitor unlocked: twelve hours. | ||
| 51 | +const UNLOCK_HOURS: i64 = 12; | ||
| 52 | + | ||
| 53 | +/// The unlock cookie name of a link. It is scoped to the link's own path, so the name only needs the id. | ||
| 54 | +fn unlock_cookie_name(link_id: &str) -> String { | ||
| 55 | + format!("in_link_{link_id}") | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +/// The link of a token, when it is live and its target is not in the trash. Every other case is `404`, so | ||
| 59 | +/// an unknown token and a dead one cannot be told apart. | ||
| 60 | +async fn live_link(state: &AppState, token: &str) -> Result<Link> { | ||
| 61 | + let link = state | ||
| 62 | + .store | ||
| 63 | + .link_by_token_hash(&hash_token(token)) | ||
| 64 | + .await? | ||
| 65 | + .ok_or_else(not_found)?; | ||
| 66 | + if !link.is_live(&now_stamp()) { | ||
| 67 | + return Err(not_found().into()); | ||
| 68 | + } | ||
| 69 | + if state.store.item_trashed(link.kind, &link.target_id).await? != Some(false) { | ||
| 70 | + return Err(not_found().into()); | ||
| 71 | + } | ||
| 72 | + Ok(link) | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +/// Checks that the link may show `(kind, id)` for `action`. The item must lie inside the linked root and | ||
| 76 | +/// be live. Anything else is `404`, including a download the link does not allow. | ||
| 77 | +async fn visit( | ||
| 78 | + state: &AppState, | ||
| 79 | + link: &Link, | ||
| 80 | + kind: ItemKind, | ||
| 81 | + id: &str, | ||
| 82 | + action: Action, | ||
| 83 | +) -> Result<()> { | ||
| 84 | + let trashed = state | ||
| 85 | + .store | ||
| 86 | + .item_trashed(kind, id) | ||
| 87 | + .await? | ||
| 88 | + .ok_or_else(not_found)?; | ||
| 89 | + let inside_link = state | ||
| 90 | + .store | ||
| 91 | + .is_within(link.kind, &link.target_id, kind, id) | ||
| 92 | + .await?; | ||
| 93 | + let target = Target { | ||
| 94 | + owner: &link.owner, | ||
| 95 | + trashed, | ||
| 96 | + inside_link, | ||
| 97 | + }; | ||
| 98 | + authorize( | ||
| 99 | + Actor::Link { | ||
| 100 | + can_download: link.can_download, | ||
| 101 | + }, | ||
| 102 | + target, | ||
| 103 | + Grant::None, | ||
| 104 | + action, | ||
| 105 | + ) | ||
| 106 | + .map_err(|_| not_found())?; | ||
| 107 | + Ok(()) | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +/// Whether the visitor holds the unlock cookie of a link that has a password. A link without one is always | ||
| 111 | +/// unlocked. | ||
| 112 | +fn unlocked(cx: &Cx, state: &AppState, link: &Link) -> bool { | ||
| 113 | + let Some(hash) = link.password_hash.as_deref() else { | ||
| 114 | + return true; | ||
| 115 | + }; | ||
| 116 | + let expected = unlock_proof(&state.key, &link.id, hash); | ||
| 117 | + cookie_value(cx, &unlock_cookie_name(&link.id)) | ||
| 118 | + .is_some_and(|given| constant_time_eq(given.as_bytes(), expected.as_bytes())) | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +/// The gate's CSRF token: the one already in the cookie, or a new one, which the response sets. | ||
| 122 | +fn gate_csrf(cx: &Cx) -> String { | ||
| 123 | + if let Some(existing) = cookie_value(cx, GATE_CSRF_COOKIE) { | ||
| 124 | + return existing; | ||
| 125 | + } | ||
| 126 | + let token = generate_token(); | ||
| 127 | + let cookie = Cookie::build((GATE_CSRF_COOKIE, token.clone())) | ||
| 128 | + .path("/") | ||
| 129 | + .http_only(true) | ||
| 130 | + .secure(true) | ||
| 131 | + .same_site(SameSite::Strict) | ||
| 132 | + .build(); | ||
| 133 | + cookies(cx).add(cookie); | ||
| 134 | + token | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +/// The query of the public page: a folder to browse, a file to show, and whether the last password was | ||
| 138 | +/// wrong. | ||
| 139 | +#[derive(Debug, Default, Deserialize)] | ||
| 140 | +#[serde(default)] | ||
| 141 | +pub struct PublicQuery { | ||
| 142 | + /// A folder inside the link's root. | ||
| 143 | + pub folder: String, | ||
| 144 | + /// A file inside the link's root. | ||
| 145 | + pub file: String, | ||
| 146 | + /// `1` after a wrong password. | ||
| 147 | + pub wrong: String, | ||
| 148 | +} | ||
| 149 | + | ||
| 150 | +/// The form of the password gate. | ||
| 151 | +#[derive(Debug, Default, Deserialize)] | ||
| 152 | +#[serde(default)] | ||
| 153 | +pub struct GateForm { | ||
| 154 | + /// The CSRF token that the gate cookie must match. | ||
| 155 | + pub csrf: String, | ||
| 156 | + /// The password the visitor typed. | ||
| 157 | + pub password: String, | ||
| 158 | +} | ||
| 159 | + | ||
| 160 | +/// A folder listing inside a folder link: its breadcrumbs, its current folder, and what it holds. | ||
| 161 | +pub struct FolderPanel { | ||
| 162 | + /// The folders from the link's root down to the current one. | ||
| 163 | + pub trail: Vec<Folder>, | ||
| 164 | + /// The children of the current folder. | ||
| 165 | + pub listing: Listing, | ||
| 166 | + /// Whether the link allows downloads. | ||
| 167 | + pub can_download: bool, | ||
| 168 | +} | ||
| 169 | + | ||
| 170 | +/// One file of a link: its name, size, and the way back to where the visitor came from. | ||
| 171 | +pub struct FilePanel { | ||
| 172 | + /// The file. | ||
| 173 | + pub file: File, | ||
| 174 | + /// The link's path with the query that returns to the folder; empty when there is none. | ||
| 175 | + pub back: String, | ||
| 176 | + /// Whether the link allows downloads. | ||
| 177 | + pub can_download: bool, | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +/// What the public page shows. | ||
| 181 | +pub enum Panel { | ||
| 182 | + /// The password gate, with the wrong-password flag and the CSRF token. | ||
| 183 | + Gate { wrong: bool, csrf: String }, | ||
| 184 | + /// A folder browsing inside its link. | ||
| 185 | + Folder(Box<FolderPanel>), | ||
| 186 | + /// One file. | ||
| 187 | + File(Box<FilePanel>), | ||
| 188 | +} | ||
| 189 | + | ||
| 190 | +/// One row of a public listing: where it leads, its name, its size text and its download link (empty | ||
| 191 | +/// when there is none). | ||
| 192 | +pub struct Entry { | ||
| 193 | + /// Where the row leads. | ||
| 194 | + pub href: String, | ||
| 195 | + /// The name shown. | ||
| 196 | + pub name: String, | ||
| 197 | + /// The size shown, or empty for a folder. | ||
| 198 | + pub size: String, | ||
| 199 | + /// The download link, or empty when the visitor may not download. | ||
| 200 | + pub download: String, | ||
| 201 | +} | ||
| 202 | + | ||
| 203 | +/// The breadcrumb of a public folder: the link's root, then each folder down to the current one. | ||
| 204 | +#[component] | ||
| 205 | +async fn public_crumbs(lang: Lang, token: &str, trail: &[Folder]) -> Result<impl View> { | ||
| 206 | + let root_href = format!("/s/{token}"); | ||
| 207 | + let steps: Vec<Entry> = trail | ||
| 208 | + .iter() | ||
| 209 | + .map(|folder| Entry { | ||
| 210 | + href: format!("/s/{token}?folder={}", folder.id), | ||
| 211 | + name: folder.name.clone(), | ||
| 212 | + size: String::new(), | ||
| 213 | + download: String::new(), | ||
| 214 | + }) | ||
| 215 | + .collect(); | ||
| 216 | + Ok(view! { | ||
| 217 | + <nav class="crumbs" aria-label="breadcrumb"> | ||
| 218 | + <a href=(root_href.as_str())>(share_s(lang, SK::PublicRoot))</a> | ||
| 219 | + for step in &steps { | ||
| 220 | + " / " | ||
| 221 | + <a href=(step.href.as_str())>(step.name.as_str())</a> | ||
| 222 | + } | ||
| 223 | + </nav> | ||
| 224 | + }) | ||
| 225 | +} | ||
| 226 | + | ||
| 227 | +/// The password gate: the notice after a wrong password and the form. | ||
| 228 | +#[component] | ||
| 229 | +async fn gate_panel(lang: Lang, token: &str, wrong: bool, csrf: &str) -> Result<impl View> { | ||
| 230 | + let action = format!("/s/{token}"); | ||
| 231 | + Ok(view! { | ||
| 232 | + <section class="public-gate"> | ||
| 233 | + <h1>(share_s(lang, SK::PublicGateTitle))</h1> | ||
| 234 | + <p class="muted">(share_s(lang, SK::PublicGateBody))</p> | ||
| 235 | + if wrong { | ||
| 236 | + <p class="notice refusal" role="alert">(share_s(lang, SK::PublicWrong))</p> | ||
| 237 | + } | ||
| 238 | + <form method="post" action=(action.as_str()) class="share-form"> | ||
| 239 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 240 | + <label for="public-password">(share_s(lang, SK::PublicPassword))</label> | ||
| 241 | + <input id="public-password" name="password" type="password" required="" autocomplete="off" maxlength="256" autofocus=""> | ||
| 242 | + <button class="button primary" type="submit">(share_s(lang, SK::PublicOpen))</button> | ||
| 243 | + </form> | ||
| 244 | + </section> | ||
| 245 | + }) | ||
| 246 | +} | ||
| 247 | + | ||
| 248 | +/// A folder inside a folder link: its breadcrumbs, its folders, and its files. | ||
| 249 | +#[component] | ||
| 250 | +async fn folder_panel(lang: Lang, token: &str, panel: &FolderPanel) -> Result<impl View> { | ||
| 251 | + let listing = &panel.listing; | ||
| 252 | + let empty = listing.folders.is_empty() && listing.files.is_empty(); | ||
| 253 | + let mut rows: Vec<Entry> = listing | ||
| 254 | + .folders | ||
| 255 | + .iter() | ||
| 256 | + .map(|folder| Entry { | ||
| 257 | + href: format!("/s/{token}?folder={}", folder.id), | ||
| 258 | + name: folder.name.clone(), | ||
| 259 | + size: String::new(), | ||
| 260 | + download: String::new(), | ||
| 261 | + }) | ||
| 262 | + .collect(); | ||
| 263 | + rows.extend(listing.files.iter().map(|file| Entry { | ||
| 264 | + href: format!("/s/{token}?file={}", file.id), | ||
| 265 | + name: file.name.clone(), | ||
| 266 | + size: size_text(file.size), | ||
| 267 | + download: if panel.can_download { | ||
| 268 | + format!("/s/{token}/file/{}?dl=1", file.id) | ||
| 269 | + } else { | ||
| 270 | + String::new() | ||
| 271 | + }, | ||
| 272 | + })); | ||
| 273 | + let download_label = d(lang, DK::Download); | ||
| 274 | + Ok(view! { | ||
| 275 | + <section class="drive public-folder"> | ||
| 276 | + public_crumbs(lang: lang, token: token, trail: &panel.trail) | ||
| 277 | + if empty { | ||
| 278 | + empty_state(title: share_s(lang, SK::PublicEmpty)) | ||
| 279 | + } else { | ||
| 280 | + <div class="table-wrap"> | ||
| 281 | + <table class="table"> | ||
| 282 | + <tbody> | ||
| 283 | + for row in &rows { | ||
| 284 | + <tr> | ||
| 285 | + <td><a href=(row.href.as_str())>(row.name.as_str())</a></td> | ||
| 286 | + <td class="muted">(row.size.as_str())</td> | ||
| 287 | + <td> | ||
| 288 | + if !row.download.is_empty() { | ||
| 289 | + <a class="button ghost" href=(row.download.as_str())>(download_label)</a> | ||
| 290 | + } | ||
| 291 | + </td> | ||
| 292 | + </tr> | ||
| 293 | + } | ||
| 294 | + </tbody> | ||
| 295 | + </table> | ||
| 296 | + </div> | ||
| 297 | + } | ||
| 298 | + </section> | ||
| 299 | + }) | ||
| 300 | +} | ||
| 301 | + | ||
| 302 | +/// One file of a link: a preview for a picture, its size, and the download when the link allows it. | ||
| 303 | +#[component] | ||
| 304 | +async fn file_panel(lang: Lang, token: &str, panel: &FilePanel) -> Result<impl View> { | ||
| 305 | + let file = &panel.file; | ||
| 306 | + let preview = if file.thumb_state == "ready" { | ||
| 307 | + format!("/s/{token}/thumb/{}", file.id) | ||
| 308 | + } else { | ||
| 309 | + String::new() | ||
| 310 | + }; | ||
| 311 | + let download = format!("/s/{token}/file/{}?dl=1", file.id); | ||
| 312 | + Ok(view! { | ||
| 313 | + <section class="drive public-file"> | ||
| 314 | + if !panel.back.is_empty() { | ||
| 315 | + <p><a href=(panel.back.as_str())>"\u{2190} " (share_s(lang, SK::PublicLocation))</a></p> | ||
| 316 | + } | ||
| 317 | + <h1>(file.name.as_str())</h1> | ||
| 318 | + <p class="muted">(size_text(file.size))</p> | ||
| 319 | + if !preview.is_empty() { | ||
| 320 | + <img src=(preview.as_str()) alt=(file.name.as_str()) class="preview"> | ||
| 321 | + } | ||
| 322 | + if panel.can_download { | ||
| 323 | + <p><a class="button primary" href=(download.as_str())>(d(lang, DK::Download))</a></p> | ||
| 324 | + } | ||
| 325 | + </section> | ||
| 326 | + }) | ||
| 327 | +} | ||
| 328 | + | ||
| 329 | +/// The body of the public page: whichever panel the link shows. | ||
| 330 | +#[component] | ||
| 331 | +async fn public_body(lang: Lang, token: &str, panel: &Panel) -> Result<impl View> { | ||
| 332 | + Ok(view! { | ||
| 333 | + if let Panel::Gate { wrong, csrf } = panel { | ||
| 334 | + gate_panel(lang: lang, token: token, wrong: *wrong, csrf: csrf.as_str()) | ||
| 335 | + } | ||
| 336 | + if let Panel::Folder(folder) = panel { | ||
| 337 | + folder_panel(lang: lang, token: token, panel: folder) | ||
| 338 | + } | ||
| 339 | + if let Panel::File(file) = panel { | ||
| 340 | + file_panel(lang: lang, token: token, panel: file) | ||
| 341 | + } | ||
| 342 | + }) | ||
| 343 | +} | ||
| 344 | + | ||
| 345 | +/// Builds the panel of a live, unlocked link from its query. | ||
| 346 | +async fn content_panel( | ||
| 347 | + state: &AppState, | ||
| 348 | + token: &str, | ||
| 349 | + link: &Link, | ||
| 350 | + query: &PublicQuery, | ||
| 351 | +) -> Result<Panel> { | ||
| 352 | + match link.kind { | ||
| 353 | + ItemKind::File => { | ||
| 354 | + visit(state, link, ItemKind::File, &link.target_id, Action::View).await?; | ||
| 355 | + let file = state | ||
| 356 | + .store | ||
| 357 | + .file(&link.target_id) | ||
| 358 | + .await? | ||
| 359 | + .ok_or_else(not_found)?; | ||
| 360 | + Ok(Panel::File(Box::new(FilePanel { | ||
| 361 | + file, | ||
| 362 | + back: String::new(), | ||
| 363 | + can_download: link.can_download, | ||
| 364 | + }))) | ||
| 365 | + } | ||
| 366 | + ItemKind::Folder => { | ||
| 367 | + visit(state, link, ItemKind::Folder, &link.target_id, Action::List).await?; | ||
| 368 | + if !query.file.is_empty() { | ||
| 369 | + visit(state, link, ItemKind::File, &query.file, Action::View).await?; | ||
| 370 | + let file = state.store.file(&query.file).await?.ok_or_else(not_found)?; | ||
| 371 | + let back = match file.folder_id.as_deref() { | ||
| 372 | + Some(folder) => format!("/s/{token}?folder={folder}"), | ||
| 373 | + None => format!("/s/{token}"), | ||
| 374 | + }; | ||
| 375 | + return Ok(Panel::File(Box::new(FilePanel { | ||
| 376 | + file, | ||
| 377 | + back, | ||
| 378 | + can_download: link.can_download, | ||
| 379 | + }))); | ||
| 380 | + } | ||
| 381 | + let current = if query.folder.is_empty() { | ||
| 382 | + link.target_id.clone() | ||
| 383 | + } else { | ||
| 384 | + visit(state, link, ItemKind::Folder, &query.folder, Action::List).await?; | ||
| 385 | + query.folder.clone() | ||
| 386 | + }; | ||
| 387 | + let trail = state | ||
| 388 | + .store | ||
| 389 | + .folder_trail_to(&link.target_id, ¤t) | ||
| 390 | + .await?; | ||
| 391 | + let listing = state | ||
| 392 | + .store | ||
| 393 | + .list_children(&link.owner, Some(¤t)) | ||
| 394 | + .await?; | ||
| 395 | + Ok(Panel::Folder(Box::new(FolderPanel { | ||
| 396 | + trail, | ||
| 397 | + listing, | ||
| 398 | + can_download: link.can_download, | ||
| 399 | + }))) | ||
| 400 | + } | ||
| 401 | + } | ||
| 402 | +} | ||
| 403 | + | ||
| 404 | +/// `GET /s/{token}`: the public page of a link, or its password gate. | ||
| 405 | +#[page("/s/{token}")] | ||
| 406 | +async fn public_page(cx: &Cx) -> Result<impl View> { | ||
| 407 | + let state = app_context::<AppState>(cx); | ||
| 408 | + let token = path_param_segment(cx, "token").to_owned(); | ||
| 409 | + let link = live_link(state, &token).await?; | ||
| 410 | + let query: PublicQuery = parse_query_params(cx).unwrap_or_default(); | ||
| 411 | + let lang = crate::i18n::lang(cx, None); | ||
| 412 | + let title = share_s(lang, SK::PublicGateTitle); | ||
| 413 | + let panel = if link.password_hash.is_some() && !unlocked(cx, state, &link) { | ||
| 414 | + let wrong = query.wrong == "1"; | ||
| 415 | + Panel::Gate { | ||
| 416 | + wrong, | ||
| 417 | + csrf: gate_csrf(cx), | ||
| 418 | + } | ||
| 419 | + } else { | ||
| 420 | + state.store.touch_link(&link.id).await?; | ||
| 421 | + content_panel(state, &token, &link, &query).await? | ||
| 422 | + }; | ||
| 423 | + Ok(view! { | ||
| 424 | + shell(title: title, lang: lang, viewer: None, | ||
| 425 | + public_body(lang: lang, token: token.as_str(), panel: &panel) | ||
| 426 | + ) | ||
| 427 | + }) | ||
| 428 | +} | ||
| 429 | + | ||
| 430 | +/// `POST /s/{token}`: the password of a link. The right one sets the unlock cookie; a wrong one is counted | ||
| 431 | +/// against the link and the client address. Both limits are checked before anything else. | ||
| 432 | +#[route(POST "/s/{token}")] | ||
| 433 | +async fn unlock(cx: &Cx, Form(form): Form<GateForm>) -> Result<SeeOther> { | ||
| 434 | + let state = app_context::<AppState>(cx); | ||
| 435 | + let token = path_param_segment(cx, "token").to_owned(); | ||
| 436 | + let token_hash = hash_token(&token); | ||
| 437 | + let ip = client_ip(cx).map(|ip| ip.to_string()).unwrap_or_default(); | ||
| 438 | + let throttles = &state.throttles; | ||
| 439 | + if let Some(wait) = throttles | ||
| 440 | + .per_link | ||
| 441 | + .blocked(&token_hash) | ||
| 442 | + .or_else(|| throttles.per_ip.blocked(&ip)) | ||
| 443 | + { | ||
| 444 | + return Err(too_many_requests(wait).into()); | ||
| 445 | + } | ||
| 446 | + let expected_csrf = cookie_value(cx, GATE_CSRF_COOKIE).unwrap_or_default(); | ||
| 447 | + if expected_csrf.is_empty() || !constant_time_eq(expected_csrf.as_bytes(), form.csrf.as_bytes()) | ||
| 448 | + { | ||
| 449 | + return Err(forbidden().into()); | ||
| 450 | + } | ||
| 451 | + let link = live_link(state, &token).await?; | ||
| 452 | + let Some(hash) = link.password_hash.clone() else { | ||
| 453 | + return Ok(see_other(format!("/s/{token}"))); | ||
| 454 | + }; | ||
| 455 | + if verify_password_async(form.password, hash.clone()).await? { | ||
| 456 | + let proof = unlock_proof(&state.key, &link.id, &hash); | ||
| 457 | + let cookie = Cookie::build((unlock_cookie_name(&link.id), proof)) | ||
| 458 | + .path(format!("/s/{token}")) | ||
| 459 | + .http_only(true) | ||
| 460 | + .secure(true) | ||
| 461 | + .same_site(SameSite::Lax) | ||
| 462 | + .max_age(time::Duration::hours(UNLOCK_HOURS)) | ||
| 463 | + .build(); | ||
| 464 | + cookies(cx).add(cookie); | ||
| 465 | + return Ok(see_other(format!("/s/{token}"))); | ||
| 466 | + } | ||
| 467 | + throttles.per_link.failure(&token_hash); | ||
| 468 | + throttles.per_ip.failure(&ip); | ||
| 469 | + Ok(see_other(format!("/s/{token}?wrong=1"))) | ||
| 470 | +} | ||
| 471 | + | ||
| 472 | +/// The locked link check of the byte routes: a locked link answers `404`, as if it were not there. | ||
| 473 | +fn require_unlocked(cx: &Cx, state: &AppState, link: &Link) -> Result<()> { | ||
| 474 | + if unlocked(cx, state, link) { | ||
| 475 | + Ok(()) | ||
| 476 | + } else { | ||
| 477 | + Err(not_found().into()) | ||
| 478 | + } | ||
| 479 | +} | ||
| 480 | + | ||
| 481 | +/// The query of a byte route: `dl=1` asks for a download. | ||
| 482 | +#[derive(Debug, Default, Deserialize)] | ||
| 483 | +#[serde(default)] | ||
| 484 | +pub struct PublicBytesQuery { | ||
| 485 | + /// `1` for a download. | ||
| 486 | + pub dl: String, | ||
| 487 | +} | ||
| 488 | + | ||
| 489 | +/// `GET /s/{token}/file/{id}`: the bytes of a file inside the link. | ||
| 490 | +#[route(GET "/s/{token}/file/{id}")] | ||
| 491 | +async fn public_file_bytes(cx: &Cx) -> Result<ByteAnswer> { | ||
| 492 | + let state = app_context::<AppState>(cx); | ||
| 493 | + let token = path_param_segment(cx, "token").to_owned(); | ||
| 494 | + let id = path_param_segment(cx, "id").to_owned(); | ||
| 495 | + let link = live_link(state, &token).await?; | ||
| 496 | + require_unlocked(cx, state, &link)?; | ||
| 497 | + let query: PublicBytesQuery = parse_query_params(cx).unwrap_or_default(); | ||
| 498 | + let download = query.dl == "1"; | ||
| 499 | + let action = if download { | ||
| 500 | + Action::Download | ||
| 501 | + } else { | ||
| 502 | + Action::View | ||
| 503 | + }; | ||
| 504 | + visit(state, &link, ItemKind::File, &id, action).await?; | ||
| 505 | + let file = state.store.file(&id).await?.ok_or_else(not_found)?; | ||
| 506 | + let size = u64::try_from(file.size).unwrap_or(0); | ||
| 507 | + if download && counts_as_download(headers(cx), &file.sha256, size) { | ||
| 508 | + state.store.record_download(&file.id).await?; | ||
| 509 | + } | ||
| 510 | + let source = ByteSource { | ||
| 511 | + blob_key: &file.blob_key, | ||
| 512 | + size, | ||
| 513 | + sha256: &file.sha256, | ||
| 514 | + mime: &file.mime, | ||
| 515 | + name: &file.name, | ||
| 516 | + }; | ||
| 517 | + let disposition = if download { | ||
| 518 | + Disposition::Attachment | ||
| 519 | + } else { | ||
| 520 | + Disposition::Inline | ||
| 521 | + }; | ||
| 522 | + serve_bytes_with(cx, state.blobs.as_ref(), &source, disposition, SHARE_CACHE).await | ||
| 523 | +} | ||
| 524 | + | ||
| 525 | +/// `GET /s/{token}/thumb/{id}`: the thumbnail of a picture inside the link. | ||
| 526 | +#[route(GET "/s/{token}/thumb/{id}")] | ||
| 527 | +async fn public_thumb(cx: &Cx) -> Result<ByteAnswer> { | ||
| 528 | + let state = app_context::<AppState>(cx); | ||
| 529 | + let token = path_param_segment(cx, "token").to_owned(); | ||
| 530 | + let id = path_param_segment(cx, "id").to_owned(); | ||
| 531 | + let link = live_link(state, &token).await?; | ||
| 532 | + require_unlocked(cx, state, &link)?; | ||
| 533 | + visit(state, &link, ItemKind::File, &id, Action::View).await?; | ||
| 534 | + let file = state.store.file(&id).await?.ok_or_else(not_found)?; | ||
| 535 | + if file.thumb_state != "ready" { | ||
| 536 | + return Err(not_found().into()); | ||
| 537 | + } | ||
| 538 | + let key = thumb_blob_key(&file.id); | ||
| 539 | + let size = state.blobs.size(&key).await?.ok_or_else(not_found)?; | ||
| 540 | + let validator = thumb_validator(&file.sha256); | ||
| 541 | + let source = ByteSource { | ||
| 542 | + blob_key: &key, | ||
| 543 | + size, | ||
| 544 | + sha256: &validator, | ||
| 545 | + mime: "image/webp", | ||
| 546 | + name: &file.name, | ||
| 547 | + }; | ||
| 548 | + serve_bytes_with( | ||
| 549 | + cx, | ||
| 550 | + state.blobs.as_ref(), | ||
| 551 | + &source, | ||
| 552 | + Disposition::Inline, | ||
| 553 | + SHARE_CACHE, | ||
| 554 | + ) | ||
| 555 | + .await | ||
| 556 | +} | ||
| 557 | + | ||
| 558 | +#[cfg(test)] | ||
| 559 | +mod tests { | ||
| 560 | + use super::*; | ||
| 561 | + use crate::auth::test_support::signed_in; | ||
| 562 | + use crate::boot::{router, test_state}; | ||
| 563 | + use http::Request; | ||
| 564 | + use http::header::{CONTENT_TYPE, COOKIE}; | ||
| 565 | + use in_core::password::hash_password_async; | ||
| 566 | + use in_core::quota::DEFAULT_MEMBER_QUOTA; | ||
| 567 | + use in_core::secret; | ||
| 568 | + use in_core::store::links::NewLink; | ||
| 569 | + use in_core::store::new_id; | ||
| 570 | + use topcoat::router::Body; | ||
| 571 | + | ||
| 572 | + /// Makes a link owned by `ann` on `target`, with an optional password. Returns `(token, link id)`. | ||
| 573 | + async fn link_to( | ||
| 574 | + state: &AppState, | ||
| 575 | + kind: ItemKind, | ||
| 576 | + target: &str, | ||
| 577 | + password: Option<&str>, | ||
| 578 | + ) -> (String, String) { | ||
| 579 | + let token = generate_token(); | ||
| 580 | + let password_hash = match password { | ||
| 581 | + Some(text) => Some(hash_password_async(text.to_owned()).await.expect("hash")), | ||
| 582 | + None => None, | ||
| 583 | + }; | ||
| 584 | + let link = state | ||
| 585 | + .store | ||
| 586 | + .create_link(NewLink { | ||
| 587 | + id: new_id(), | ||
| 588 | + token_hash: hash_token(&token), | ||
| 589 | + token_sealed: secret::seal(&state.key, token.as_bytes()).expect("seal"), | ||
| 590 | + kind, | ||
| 591 | + target_id: target.to_owned(), | ||
| 592 | + owner: "ann".to_owned(), | ||
| 593 | + can_download: true, | ||
| 594 | + password_hash, | ||
| 595 | + expires_at: Some("9999-12-31T23:59:59.000Z".to_owned()), | ||
| 596 | + }) | ||
| 597 | + .await | ||
| 598 | + .expect("link"); | ||
| 599 | + (token, link.id) | ||
| 600 | + } | ||
| 601 | + | ||
| 602 | + async fn get(state: &AppState, path: &str) -> u16 { | ||
| 603 | + let request = Request::get(path).body(Body::empty()).expect("request"); | ||
| 604 | + router(state.clone()) | ||
| 605 | + .handle(request) | ||
| 606 | + .await | ||
| 607 | + .status() | ||
| 608 | + .as_u16() | ||
| 609 | + } | ||
| 610 | + | ||
| 611 | + /// A link to a folder shows its subfolders; a folder outside the root is `404`. | ||
| 612 | + #[tokio::test] | ||
| 613 | + async fn a_folder_link_does_not_reach_outside_its_root() { | ||
| 614 | + let (_dir, state) = test_state().await; | ||
| 615 | + let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | ||
| 616 | + let trips = state | ||
| 617 | + .store | ||
| 618 | + .create_folder("ann", None, "Trips") | ||
| 619 | + .await | ||
| 620 | + .expect("folder"); | ||
| 621 | + let sub = state | ||
| 622 | + .store | ||
| 623 | + .create_folder("ann", Some(&trips.id), "Sub") | ||
| 624 | + .await | ||
| 625 | + .expect("folder"); | ||
| 626 | + let other = state | ||
| 627 | + .store | ||
| 628 | + .create_folder("ann", None, "Other") | ||
| 629 | + .await | ||
| 630 | + .expect("folder"); | ||
| 631 | + let (token, _) = link_to(&state, ItemKind::Folder, &trips.id, None).await; | ||
| 632 | + assert_eq!( | ||
| 633 | + get(&state, &format!("/s/{token}?folder={}", sub.id)).await, | ||
| 634 | + 200 | ||
| 635 | + ); | ||
| 636 | + assert_eq!( | ||
| 637 | + get(&state, &format!("/s/{token}?folder={}", other.id)).await, | ||
| 638 | + 404 | ||
| 639 | + ); | ||
| 640 | + } | ||
| 641 | + | ||
| 642 | + /// A revoked link is `404`, and so is a link whose target is in the trash. | ||
| 643 | + #[tokio::test] | ||
| 644 | + async fn a_revoked_or_trashed_link_is_not_found() { | ||
| 645 | + let (_dir, state) = test_state().await; | ||
| 646 | + let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | ||
| 647 | + let trips = state | ||
| 648 | + .store | ||
| 649 | + .create_folder("ann", None, "Trips") | ||
| 650 | + .await | ||
| 651 | + .expect("folder"); | ||
| 652 | + let (token, link_id) = link_to(&state, ItemKind::Folder, &trips.id, None).await; | ||
| 653 | + assert_eq!(get(&state, &format!("/s/{token}")).await, 200); | ||
| 654 | + state | ||
| 655 | + .store | ||
| 656 | + .revoke_link("ann", &link_id) | ||
| 657 | + .await | ||
| 658 | + .expect("revoke"); | ||
| 659 | + assert_eq!(get(&state, &format!("/s/{token}")).await, 404); | ||
| 660 | + | ||
| 661 | + let (token, _) = link_to(&state, ItemKind::Folder, &trips.id, None).await; | ||
| 662 | + state | ||
| 663 | + .store | ||
| 664 | + .trash_folder("ann", &trips.id) | ||
| 665 | + .await | ||
| 666 | + .expect("trash"); | ||
| 667 | + assert_eq!(get(&state, &format!("/s/{token}")).await, 404); | ||
| 668 | + } | ||
| 669 | + | ||
| 670 | + /// Five wrong passwords are answered with a redirect; the sixth within the window is `429`. | ||
| 671 | + #[tokio::test] | ||
| 672 | + async fn the_sixth_wrong_password_is_throttled() { | ||
| 673 | + let (_dir, state) = test_state().await; | ||
| 674 | + let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | ||
| 675 | + let trips = state | ||
| 676 | + .store | ||
| 677 | + .create_folder("ann", None, "Trips") | ||
| 678 | + .await | ||
| 679 | + .expect("folder"); | ||
| 680 | + let (token, _) = link_to(&state, ItemKind::Folder, &trips.id, Some("right")).await; | ||
| 681 | + let path = format!("/s/{token}"); | ||
| 682 | + let mut statuses = Vec::new(); | ||
| 683 | + for _ in 0..6 { | ||
| 684 | + let request = Request::post(path.as_str()) | ||
| 685 | + .header(CONTENT_TYPE, "application/x-www-form-urlencoded") | ||
| 686 | + .header(COOKIE, format!("{GATE_CSRF_COOKIE}=tok")) | ||
| 687 | + .body(Body::from("csrf=tok&password=wrong")) | ||
| 688 | + .expect("request"); | ||
| 689 | + let response = router(state.clone()).handle(request).await; | ||
| 690 | + statuses.push(response.status().as_u16()); | ||
| 691 | + } | ||
| 692 | + assert_eq!(statuses, vec![303, 303, 303, 303, 303, 429]); | ||
| 693 | + } | ||
| 694 | + | ||
| 695 | + /// A file link answers the file's bytes only with the unlock cookie of a password-protected link. | ||
| 696 | + #[tokio::test] | ||
| 697 | + async fn a_locked_link_gives_no_bytes_without_the_password() { | ||
| 698 | + let (_dir, state) = test_state().await; | ||
| 699 | + let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | ||
| 700 | + let file = state | ||
| 701 | + .store | ||
| 702 | + .insert_file(in_core::store::files::NewFile { | ||
| 703 | + id: new_id(), | ||
| 704 | + owner: "ann".into(), | ||
| 705 | + folder: None, | ||
| 706 | + name: "note.bin".into(), | ||
| 707 | + mime: "application/octet-stream".into(), | ||
| 708 | + size: 0, | ||
| 709 | + sha256: "0".repeat(64), | ||
| 710 | + staged_claims: 0, | ||
| 711 | + }) | ||
| 712 | + .await | ||
| 713 | + .expect("file"); | ||
| 714 | + let (token, _) = link_to(&state, ItemKind::File, &file.id, Some("right")).await; | ||
| 715 | + assert_eq!( | ||
| 716 | + get(&state, &format!("/s/{token}/file/{}", file.id)).await, | ||
| 717 | + 404 | ||
| 718 | + ); | ||
| 719 | + } | ||
| 720 | +} | ||
crates/in-web/src/pages/share_dialog.rsadded+484 -0
| @@ -0,0 +1,484 @@ | |||
| 1 | +//! The share page of one item (`GET /share/{kind}/{id}`, linked from the row menu and the viewer) and the | ||
| 2 | +//! writes of its grants: `POST /grants` (a new grant, or the level of an existing one), `POST | ||
| 3 | +//! /grants/{id}/update` and `POST /grants/{id}/remove`. The page also makes the item's share links. | ||
| 4 | +//! | ||
| 5 | +//! Only the owner of a live item may share it (`authz` `Share`). A grantee is `403` on it, and anyone else | ||
| 6 | +//! is `404`. The grantee of a grant is chosen from the family's members, active ones other than the owner | ||
| 7 | +//! only, and the store checks that again. Each change tells the grantee's open shared page. | ||
| 8 | + | ||
| 9 | +use in_core::authz::Action; | ||
| 10 | +use in_core::store::members::Member; | ||
| 11 | +use in_core::store::shares::{Share, ShareEntry, kind_from_word, kind_word}; | ||
| 12 | +use in_core::store::trash::ItemKind; | ||
| 13 | +use serde::Deserialize; | ||
| 14 | +use topcoat::Result; | ||
| 15 | +use topcoat::context::{Cx, app_context}; | ||
| 16 | +use topcoat::router::content::Form; | ||
| 17 | +use topcoat::router::error::{SeeOther, not_found}; | ||
| 18 | +use topcoat::router::{page, path_param_segment, route}; | ||
| 19 | +use topcoat::view::{View, component, view}; | ||
| 20 | + | ||
| 21 | +use crate::auth::{Viewer, require_csrf, require_member}; | ||
| 22 | +use crate::i18n::Lang; | ||
| 23 | +use crate::i18n::share::{SK, s as share_s}; | ||
| 24 | +use crate::live::Topic; | ||
| 25 | +use crate::pages::drive::{ListQuery, access_for, back_or, check, done, refused, viewer_lang}; | ||
| 26 | +use crate::pages::links::{LinkView, link_max_days, link_row, link_views}; | ||
| 27 | +use crate::state::AppState; | ||
| 28 | +use crate::views::drive::flash; | ||
| 29 | +use crate::views::{ViewerInfo, shell}; | ||
| 30 | + | ||
| 31 | +/// The form of the share writes. Every field is optional; each write reads what it needs. | ||
| 32 | +#[derive(Debug, Default, Deserialize)] | ||
| 33 | +#[serde(default)] | ||
| 34 | +pub struct GrantForm { | ||
| 35 | + /// The CSRF token of the session. | ||
| 36 | + pub csrf: String, | ||
| 37 | + /// The page to return to. | ||
| 38 | + pub back: String, | ||
| 39 | + /// `file` or `folder`, for a new grant. | ||
| 40 | + pub kind: String, | ||
| 41 | + /// The item, for a new grant. | ||
| 42 | + pub target_id: String, | ||
| 43 | + /// The grantee's subject, for a new grant. | ||
| 44 | + pub grantee: String, | ||
| 45 | + /// `download` or `view`. | ||
| 46 | + pub level: String, | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +/// The name and owner of an item, for the share checks. A missing item is `404`. | ||
| 50 | +async fn item_head(state: &AppState, kind: ItemKind, id: &str) -> Result<(String, String)> { | ||
| 51 | + Ok(match kind { | ||
| 52 | + ItemKind::File => { | ||
| 53 | + let file = state.store.file(id).await?.ok_or_else(not_found)?; | ||
| 54 | + (file.owner, file.name) | ||
| 55 | + } | ||
| 56 | + ItemKind::Folder => { | ||
| 57 | + let folder = state.store.folder(id).await?.ok_or_else(not_found)?; | ||
| 58 | + (folder.owner, folder.name) | ||
| 59 | + } | ||
| 60 | + }) | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +/// The name of an item the viewer may share: it must be theirs and live. A grantee is refused with `403` | ||
| 64 | +/// and anyone else sees `404`. | ||
| 65 | +pub async fn shareable( | ||
| 66 | + state: &AppState, | ||
| 67 | + viewer: &Viewer, | ||
| 68 | + kind: ItemKind, | ||
| 69 | + id: &str, | ||
| 70 | +) -> Result<String> { | ||
| 71 | + let (owner, name) = item_head(state, kind, id).await?; | ||
| 72 | + let access = access_for(state, viewer, kind, id).await?; | ||
| 73 | + check(viewer, &owner, access, Action::Share)?; | ||
| 74 | + Ok(name) | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +/// Tells the grantee's open shared page that its list changed. | ||
| 78 | +fn notify(state: &AppState, grantee: &str) { | ||
| 79 | + state.live.bump(&Topic::Shared(grantee.to_owned())); | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +/// The level picker of a grant: `view` or `download`, with the current one selected. | ||
| 83 | +#[component] | ||
| 84 | +pub async fn level_select(lang: Lang, name: &str, id: &str, download: bool) -> Result<impl View> { | ||
| 85 | + let view_label = share_s(lang, SK::AccessView); | ||
| 86 | + let download_label = share_s(lang, SK::AccessDownload); | ||
| 87 | + Ok(view! { | ||
| 88 | + <label class="sr-only" for=(id)>(share_s(lang, SK::ShareLevel))</label> | ||
| 89 | + <select id=(id) name=(name)> | ||
| 90 | + if download { | ||
| 91 | + <option value="view">(view_label)</option> | ||
| 92 | + <option value="download" selected="">(download_label)</option> | ||
| 93 | + } else { | ||
| 94 | + <option value="view" selected="">(view_label)</option> | ||
| 95 | + <option value="download">(download_label)</option> | ||
| 96 | + } | ||
| 97 | + </select> | ||
| 98 | + }) | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +/// The people in one grant: the name, the email, the level, and the forms that change or remove it. | ||
| 102 | +#[component] | ||
| 103 | +pub async fn grant_row( | ||
| 104 | + lang: Lang, | ||
| 105 | + entry: &ShareEntry, | ||
| 106 | + csrf: &str, | ||
| 107 | + back: &str, | ||
| 108 | +) -> Result<impl View> { | ||
| 109 | + let id = entry.share.id.as_str(); | ||
| 110 | + let update_action = format!("/grants/{id}/update"); | ||
| 111 | + let remove_action = format!("/grants/{id}/remove"); | ||
| 112 | + let select_id = format!("level-{id}"); | ||
| 113 | + let access = if entry.share.can_download { | ||
| 114 | + share_s(lang, SK::AccessDownload) | ||
| 115 | + } else { | ||
| 116 | + share_s(lang, SK::AccessView) | ||
| 117 | + }; | ||
| 118 | + Ok(view! { | ||
| 119 | + <li class="grant-row"> | ||
| 120 | + <div><strong>(entry.grantee_name.as_str())</strong> " " <span class="muted">(entry.grantee_email.as_str())</span> " \u{b7} " (access)</div> | ||
| 121 | + <form method="post" action=(update_action.as_str()) class="inline-form"> | ||
| 122 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 123 | + <input type="hidden" name="back" value=(back)> | ||
| 124 | + level_select(lang: lang, name: "level", id: select_id.as_str(), download: entry.share.can_download) | ||
| 125 | + <button class="button" type="submit">(share_s(lang, SK::ShareSave))</button> | ||
| 126 | + </form> | ||
| 127 | + <form method="post" action=(remove_action.as_str()) class="inline-form"> | ||
| 128 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 129 | + <input type="hidden" name="back" value=(back)> | ||
| 130 | + <button class="button danger" type="submit">(share_s(lang, SK::ShareRemove))</button> | ||
| 131 | + </form> | ||
| 132 | + </li> | ||
| 133 | + }) | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +/// The share page's content: the people the item is shared with, the form that adds one, the links of the | ||
| 137 | +/// item and the form that makes one. | ||
| 138 | +#[component] | ||
| 139 | +pub async fn share_body( | ||
| 140 | + lang: Lang, | ||
| 141 | + name: &str, | ||
| 142 | + kind: &str, | ||
| 143 | + id: &str, | ||
| 144 | + entries: &[ShareEntry], | ||
| 145 | + people: &[Member], | ||
| 146 | + links: &[LinkView], | ||
| 147 | + csrf: &str, | ||
| 148 | + back: &str, | ||
| 149 | + item_page: &str, | ||
| 150 | + max_days: u32, | ||
| 151 | + notice: &str, | ||
| 152 | + refusal: &str, | ||
| 153 | +) -> Result<impl View> { | ||
| 154 | + let max_days_text = max_days.to_string(); | ||
| 155 | + Ok(view! { | ||
| 156 | + <section class="drive share-page"> | ||
| 157 | + <p><a href=(item_page)>"\u{2190} " (name)</a></p> | ||
| 158 | + flash(lang: lang, notice: notice, refusal: refusal) | ||
| 159 | + <h1>(share_s(lang, SK::ShareHeading)) " \u{b7} " (name)</h1> | ||
| 160 | + <h2>(share_s(lang, SK::ShareWithPeople))</h2> | ||
| 161 | + if entries.is_empty() { | ||
| 162 | + <p class="muted">(share_s(lang, SK::ShareNobody))</p> | ||
| 163 | + } else { | ||
| 164 | + <ul class="grant-list"> | ||
| 165 | + for entry in entries { | ||
| 166 | + grant_row(lang: lang, entry: entry, csrf: csrf, back: back) | ||
| 167 | + } | ||
| 168 | + </ul> | ||
| 169 | + } | ||
| 170 | + if !people.is_empty() { | ||
| 171 | + <form method="post" action="/grants" class="share-form"> | ||
| 172 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 173 | + <input type="hidden" name="back" value=(back)> | ||
| 174 | + <input type="hidden" name="kind" value=(kind)> | ||
| 175 | + <input type="hidden" name="target_id" value=(id)> | ||
| 176 | + <label class="sr-only" for="grantee">(share_s(lang, SK::SharePerson))</label> | ||
| 177 | + <select id="grantee" name="grantee" required=""> | ||
| 178 | + <option value="" selected="">(share_s(lang, SK::SharePickPerson))</option> | ||
| 179 | + for person in people { | ||
| 180 | + <option value=(person.sub.as_str())>(person.name.as_str()) " (" (person.email.as_str()) ")"</option> | ||
| 181 | + } | ||
| 182 | + </select> | ||
| 183 | + level_select(lang: lang, name: "level", id: "new-level", download: false) | ||
| 184 | + <button class="button primary" type="submit">(share_s(lang, SK::ShareAdd))</button> | ||
| 185 | + </form> | ||
| 186 | + } | ||
| 187 | + <p class="muted">(share_s(lang, SK::ShareOwnerOnly))</p> | ||
| 188 | + <h2>(share_s(lang, SK::ShareLinks))</h2> | ||
| 189 | + <form method="post" action="/links" class="share-form"> | ||
| 190 | + <input type="hidden" name="csrf" value=(csrf)> | ||
| 191 | + <input type="hidden" name="back" value=(back)> | ||
| 192 | + <input type="hidden" name="kind" value=(kind)> | ||
| 193 | + <input type="hidden" name="target_id" value=(id)> | ||
| 194 | + <label for="link-days">(share_s(lang, SK::LinkDays))</label> | ||
| 195 | + <input id="link-days" name="days" type="number" min="1" max=(max_days_text.as_str()) placeholder=(max_days_text.as_str())> | ||
| 196 | + <label for="link-password">(share_s(lang, SK::LinkPassword))</label> | ||
| 197 | + <input id="link-password" name="password" type="password" autocomplete="new-password" maxlength="256"> | ||
| 198 | + <label><input type="checkbox" name="download" value="1"> (share_s(lang, SK::LinkAllowDownload))</label> | ||
| 199 | + <button class="button primary" type="submit">(share_s(lang, SK::LinkCreate))</button> | ||
| 200 | + </form> | ||
| 201 | + if links.is_empty() { | ||
| 202 | + <p class="muted">(share_s(lang, SK::ShareNoLinks))</p> | ||
| 203 | + } else { | ||
| 204 | + <ul class="link-list"> | ||
| 205 | + for link in links { | ||
| 206 | + link_row(lang: lang, view: link, csrf: csrf, back: back) | ||
| 207 | + } | ||
| 208 | + </ul> | ||
| 209 | + } | ||
| 210 | + </section> | ||
| 211 | + }) | ||
| 212 | +} | ||
| 213 | + | ||
| 214 | +/// `GET /share/{kind}/{id}`: the share page of an item the viewer owns. | ||
| 215 | +#[page("/share/{kind}/{id}")] | ||
| 216 | +async fn share_page(cx: &Cx) -> Result<impl View> { | ||
| 217 | + let state = app_context::<AppState>(cx); | ||
| 218 | + let viewer = require_member(cx).await?; | ||
| 219 | + let lang = viewer_lang(cx, &viewer); | ||
| 220 | + let kind = kind_from_word(path_param_segment(cx, "kind")).ok_or_else(not_found)?; | ||
| 221 | + let id = path_param_segment(cx, "id").to_owned(); | ||
| 222 | + let name = shareable(state, &viewer, kind, &id).await?; | ||
| 223 | + let me = viewer.member.sub.clone(); | ||
| 224 | + let entries = state.store.shares_of(&me, kind, &id).await?; | ||
| 225 | + let people: Vec<Member> = state | ||
| 226 | + .store | ||
| 227 | + .list_members() | ||
| 228 | + .await? | ||
| 229 | + .into_iter() | ||
| 230 | + .filter(|member| !member.disabled && member.sub != me) | ||
| 231 | + .collect(); | ||
| 232 | + let mine = state | ||
| 233 | + .store | ||
| 234 | + .links_of(&me) | ||
| 235 | + .await? | ||
| 236 | + .into_iter() | ||
| 237 | + .filter(|link| link.target_id == id) | ||
| 238 | + .collect(); | ||
| 239 | + let links = link_views(state, mine).await?; | ||
| 240 | + let max_days = link_max_days(state).await?; | ||
| 241 | + let query: ListQuery = topcoat::router::parse_query_params(cx).unwrap_or_default(); | ||
| 242 | + let back = format!("/share/{}/{id}", kind_word(kind)); | ||
| 243 | + let item_page = match kind { | ||
| 244 | + ItemKind::File => format!("/view/{id}"), | ||
| 245 | + ItemKind::Folder => format!("/drive/{id}"), | ||
| 246 | + }; | ||
| 247 | + let csrf = viewer.session.csrf_token.clone(); | ||
| 248 | + let info = ViewerInfo::of(&viewer); | ||
| 249 | + Ok(view! { | ||
| 250 | + shell(title: name.as_str(), lang: lang, viewer: Some(&info), | ||
| 251 | + share_body(lang: lang, name: name.as_str(), kind: kind_word(kind), id: id.as_str(), | ||
| 252 | + entries: &entries, people: &people, links: &links, csrf: csrf.as_str(), | ||
| 253 | + back: back.as_str(), item_page: item_page.as_str(), max_days: max_days, | ||
| 254 | + notice: query.notice.as_str(), refusal: query.refusal.as_str()) | ||
| 255 | + ) | ||
| 256 | + }) | ||
| 257 | +} | ||
| 258 | + | ||
| 259 | +/// `POST /grants`: shares an item with a person at a level, or changes the level of the grant they already | ||
| 260 | +/// have. | ||
| 261 | +#[route(POST "/grants")] | ||
| 262 | +async fn create_grant(cx: &Cx, Form(form): Form<GrantForm>) -> Result<SeeOther> { | ||
| 263 | + let state = app_context::<AppState>(cx); | ||
| 264 | + let viewer = require_csrf(cx, &form.csrf).await?; | ||
| 265 | + let kind = kind_from_word(form.kind.trim()).ok_or_else(not_found)?; | ||
| 266 | + let target = form.target_id.trim().to_owned(); | ||
| 267 | + let default_back = format!("/share/{}/{target}", kind_word(kind)); | ||
| 268 | + let back = back_or(&form.back, &default_back); | ||
| 269 | + shareable(state, &viewer, kind, &target).await?; | ||
| 270 | + let result = state | ||
| 271 | + .store | ||
| 272 | + .share_with( | ||
| 273 | + &viewer.member.sub, | ||
| 274 | + kind, | ||
| 275 | + &target, | ||
| 276 | + form.grantee.trim(), | ||
| 277 | + form.level == "download", | ||
| 278 | + ) | ||
| 279 | + .await; | ||
| 280 | + match result { | ||
| 281 | + Ok(share) => { | ||
| 282 | + notify(state, &share.grantee); | ||
| 283 | + Ok(done(&back, "shared")) | ||
| 284 | + } | ||
| 285 | + Err(error) => refused(&back, error), | ||
| 286 | + } | ||
| 287 | +} | ||
| 288 | + | ||
| 289 | +/// The grant a write names, if the viewer owns it. A grant of someone else's item is `404`. | ||
| 290 | +async fn owned_share(state: &AppState, viewer: &Viewer, id: &str) -> Result<Share> { | ||
| 291 | + Ok(state | ||
| 292 | + .store | ||
| 293 | + .share_of(&viewer.member.sub, id) | ||
| 294 | + .await? | ||
| 295 | + .ok_or_else(not_found)?) | ||
| 296 | +} | ||
| 297 | + | ||
| 298 | +/// `POST /grants/{id}/update`: changes a grant's level between view only and download. | ||
| 299 | +#[route(POST "/grants/{id}/update")] | ||
| 300 | +async fn update_grant(cx: &Cx, Form(form): Form<GrantForm>) -> Result<SeeOther> { | ||
| 301 | + let state = app_context::<AppState>(cx); | ||
| 302 | + let viewer = require_csrf(cx, &form.csrf).await?; | ||
| 303 | + let id = path_param_segment(cx, "id").to_owned(); | ||
| 304 | + let share = owned_share(state, &viewer, &id).await?; | ||
| 305 | + let default_back = format!("/share/{}/{}", kind_word(share.kind), share.target_id); | ||
| 306 | + let back = back_or(&form.back, &default_back); | ||
| 307 | + shareable(state, &viewer, share.kind, &share.target_id).await?; | ||
| 308 | + match state | ||
| 309 | + .store | ||
| 310 | + .set_share_level(&viewer.member.sub, &id, form.level == "download") | ||
| 311 | + .await | ||
| 312 | + { | ||
| 313 | + Ok(changed) => { | ||
| 314 | + notify(state, &changed.grantee); | ||
| 315 | + Ok(done(&back, "share_updated")) | ||
| 316 | + } | ||
| 317 | + Err(error) => refused(&back, error), | ||
| 318 | + } | ||
| 319 | +} | ||
| 320 | + | ||
| 321 | +/// `POST /grants/{id}/remove`: ends a grant. The grantee loses the item at once, and so does everything | ||
| 322 | +/// below it that they reached through this grant. | ||
| 323 | +#[route(POST "/grants/{id}/remove")] | ||
| 324 | +async fn remove_grant(cx: &Cx, Form(form): Form<GrantForm>) -> Result<SeeOther> { | ||
| 325 | + let state = app_context::<AppState>(cx); | ||
| 326 | + let viewer = require_csrf(cx, &form.csrf).await?; | ||
| 327 | + let id = path_param_segment(cx, "id").to_owned(); | ||
| 328 | + let share = owned_share(state, &viewer, &id).await?; | ||
| 329 | + let default_back = format!("/share/{}/{}", kind_word(share.kind), share.target_id); | ||
| 330 | + let back = back_or(&form.back, &default_back); | ||
| 331 | + shareable(state, &viewer, share.kind, &share.target_id).await?; | ||
| 332 | + match state.store.remove_share(&viewer.member.sub, &id).await { | ||
| 333 | + Ok(removed) => { | ||
| 334 | + notify(state, &removed.grantee); | ||
| 335 | + Ok(done(&back, "unshared")) | ||
| 336 | + } | ||
| 337 | + Err(error) => refused(&back, error), | ||
| 338 | + } | ||
| 339 | +} | ||
| 340 | + | ||
| 341 | +#[cfg(test)] | ||
| 342 | +mod tests { | ||
| 343 | + use super::*; | ||
| 344 | + use crate::auth::SESSION_COOKIE; | ||
| 345 | + use crate::auth::test_support::signed_in; | ||
| 346 | + use crate::boot::{router, test_state}; | ||
| 347 | + use http::Request; | ||
| 348 | + use http::header::COOKIE; | ||
| 349 | + use in_core::quota::DEFAULT_MEMBER_QUOTA; | ||
| 350 | + use in_core::store::files::NewFile; | ||
| 351 | + use in_core::store::new_id; | ||
| 352 | + use topcoat::router::Body; | ||
| 353 | + | ||
| 354 | + /// A file of `owner` in `folder` (or the top level), with a type that the viewer does not read. | ||
| 355 | + async fn file_in(state: &AppState, owner: &str, folder: Option<&str>, name: &str) -> String { | ||
| 356 | + state | ||
| 357 | + .store | ||
| 358 | + .insert_file(NewFile { | ||
| 359 | + id: new_id(), | ||
| 360 | + owner: owner.into(), | ||
| 361 | + folder: folder.map(str::to_owned), | ||
| 362 | + name: name.into(), | ||
| 363 | + mime: "application/octet-stream".into(), | ||
| 364 | + size: 0, | ||
| 365 | + sha256: "0".repeat(64), | ||
| 366 | + staged_claims: 0, | ||
| 367 | + }) | ||
| 368 | + .await | ||
| 369 | + .expect("file") | ||
| 370 | + .id | ||
| 371 | + } | ||
| 372 | + | ||
| 373 | + async fn status_as(state: &AppState, path: &str, token: &str) -> u16 { | ||
| 374 | + let request = Request::get(path) | ||
| 375 | + .header(COOKIE, format!("{SESSION_COOKIE}={token}")) | ||
| 376 | + .body(Body::empty()) | ||
| 377 | + .expect("request"); | ||
| 378 | + router(state.clone()) | ||
| 379 | + .handle(request) | ||
| 380 | + .await | ||
| 381 | + .status() | ||
| 382 | + .as_u16() | ||
| 383 | + } | ||
| 384 | + | ||
| 385 | + /// A grantee reaches a file through its folder's grant until the file is moved out of that folder; then | ||
| 386 | + /// the access is gone, with nothing copied or cleaned up. | ||
| 387 | + #[tokio::test] | ||
| 388 | + async fn grantee_loses_access_when_the_file_leaves_the_granted_folder() { | ||
| 389 | + let (_dir, state) = test_state().await; | ||
| 390 | + let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | ||
| 391 | + let bob = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await; | ||
| 392 | + let trips = state | ||
| 393 | + .store | ||
| 394 | + .create_folder("ann", None, "Trips") | ||
| 395 | + .await | ||
| 396 | + .expect("folder"); | ||
| 397 | + let other = state | ||
| 398 | + .store | ||
| 399 | + .create_folder("ann", None, "Other") | ||
| 400 | + .await | ||
| 401 | + .expect("folder"); | ||
| 402 | + let file = file_in(&state, "ann", Some(&trips.id), "day1.bin").await; | ||
| 403 | + state | ||
| 404 | + .store | ||
| 405 | + .share_with("ann", ItemKind::Folder, &trips.id, "bob", false) | ||
| 406 | + .await | ||
| 407 | + .expect("grant"); | ||
| 408 | + let path = format!("/view/{file}"); | ||
| 409 | + assert_eq!(status_as(&state, &path, &bob).await, 200); | ||
| 410 | + | ||
| 411 | + state | ||
| 412 | + .store | ||
| 413 | + .move_file("ann", &file, Some(&other.id)) | ||
| 414 | + .await | ||
| 415 | + .expect("move"); | ||
| 416 | + assert_eq!(status_as(&state, &path, &bob).await, 404); | ||
| 417 | + assert_eq!( | ||
| 418 | + status_as(&state, &format!("/drive/{}", trips.id), &bob).await, | ||
| 419 | + 200, | ||
| 420 | + "the folder itself is still granted" | ||
| 421 | + ); | ||
| 422 | + } | ||
| 423 | + | ||
| 424 | + /// A trashed item under a grant is invisible to the grantee: the file itself, and the folder it was in. | ||
| 425 | + #[tokio::test] | ||
| 426 | + async fn a_trashed_item_under_a_grant_is_not_found_to_the_grantee() { | ||
| 427 | + let (_dir, state) = test_state().await; | ||
| 428 | + let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | ||
| 429 | + let bob = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await; | ||
| 430 | + let trips = state | ||
| 431 | + .store | ||
| 432 | + .create_folder("ann", None, "Trips") | ||
| 433 | + .await | ||
| 434 | + .expect("folder"); | ||
| 435 | + let file = file_in(&state, "ann", Some(&trips.id), "day1.bin").await; | ||
| 436 | + state | ||
| 437 | + .store | ||
| 438 | + .share_with("ann", ItemKind::Folder, &trips.id, "bob", true) | ||
| 439 | + .await | ||
| 440 | + .expect("grant"); | ||
| 441 | + state | ||
| 442 | + .store | ||
| 443 | + .trash_folder("ann", &trips.id) | ||
| 444 | + .await | ||
| 445 | + .expect("trash"); | ||
| 446 | + assert_eq!(status_as(&state, &format!("/view/{file}"), &bob).await, 404); | ||
| 447 | + assert_eq!( | ||
| 448 | + status_as(&state, &format!("/file/{file}?dl=1"), &bob).await, | ||
| 449 | + 404 | ||
| 450 | + ); | ||
| 451 | + assert_eq!( | ||
| 452 | + status_as(&state, &format!("/drive/{}", trips.id), &bob).await, | ||
| 453 | + 404 | ||
| 454 | + ); | ||
| 455 | + } | ||
| 456 | + | ||
| 457 | + /// Only the owner of a live item may share it: a grantee is refused with `403`, a stranger sees `404`. | ||
| 458 | + #[tokio::test] | ||
| 459 | + async fn a_grantee_cannot_share_further() { | ||
| 460 | + let (_dir, state) = test_state().await; | ||
| 461 | + let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | ||
| 462 | + let bob = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await; | ||
| 463 | + let _cy = signed_in(&state, "cy", DEFAULT_MEMBER_QUOTA).await; | ||
| 464 | + let trips = state | ||
| 465 | + .store | ||
| 466 | + .create_folder("ann", None, "Trips") | ||
| 467 | + .await | ||
| 468 | + .expect("folder"); | ||
| 469 | + state | ||
| 470 | + .store | ||
| 471 | + .share_with("ann", ItemKind::Folder, &trips.id, "bob", true) | ||
| 472 | + .await | ||
| 473 | + .expect("grant"); | ||
| 474 | + let cy = signed_in(&state, "cy", DEFAULT_MEMBER_QUOTA).await; | ||
| 475 | + assert_eq!( | ||
| 476 | + status_as(&state, &format!("/share/folder/{}", trips.id), &bob).await, | ||
| 477 | + 403 | ||
| 478 | + ); | ||
| 479 | + assert_eq!( | ||
| 480 | + status_as(&state, &format!("/share/folder/{}", trips.id), &cy).await, | ||
| 481 | + 404 | ||
| 482 | + ); | ||
| 483 | + } | ||
| 484 | +} | ||
crates/in-web/src/pages/shared.rsadded+152 -0
| @@ -0,0 +1,152 @@ | |||
| 1 | +//! Items shared with the viewer (`GET /shared`) and the stream that refreshes it (`GET /live/shared`). | ||
| 2 | +//! | ||
| 3 | +//! The page lists the top-level grants only: an item that lies under a folder shared with the viewer is | ||
| 4 | +//! reached through that folder, not listed twice. Trashed items and items under a trashed folder are left | ||
| 5 | +//! out by the store. Folders open in the drive (`/drive/{id}`), files in the viewer (`/view/{id}`), and the | ||
| 6 | +//! download link appears only with a download grant. The owner's name is shown; no owner's folder is. | ||
| 7 | + | ||
| 8 | +use in_core::store::shares::SharedItem; | ||
| 9 | +use topcoat::Result; | ||
| 10 | +use topcoat::context::{Cx, app_context}; | ||
| 11 | +use topcoat::router::error::not_found; | ||
| 12 | +use topcoat::router::response::Response; | ||
| 13 | +use topcoat::router::{page, route}; | ||
| 14 | +use topcoat::view::{View, component, view}; | ||
| 15 | + | ||
| 16 | +use crate::auth::require_member; | ||
| 17 | +use crate::i18n::Lang; | ||
| 18 | +use crate::i18n::drive::{DK, d}; | ||
| 19 | +use crate::i18n::share::{SK, s as share_s}; | ||
| 20 | +use crate::live::{Topic, stream_changes}; | ||
| 21 | +use crate::pages::drive::viewer_lang; | ||
| 22 | +use crate::state::AppState; | ||
| 23 | +use crate::views::drive::size_text; | ||
| 24 | +use crate::views::{ViewerInfo, empty_state, shell}; | ||
| 25 | + | ||
| 26 | +/// The fingerprint of the shared page: every row's grant, name, level, size and owner. Equal text means the | ||
| 27 | +/// page would look the same, so the stream stays quiet. | ||
| 28 | +fn fingerprint(items: &[SharedItem]) -> String { | ||
| 29 | + let mut text = String::new(); | ||
| 30 | + for item in items { | ||
| 31 | + text.push_str(&format!( | ||
| 32 | + "{}|{}|{}|{}|{}|{}\n", | ||
| 33 | + item.share.id, | ||
| 34 | + item.name, | ||
| 35 | + item.share.can_download, | ||
| 36 | + item.size, | ||
| 37 | + item.owner_name, | ||
| 38 | + item.share.created_at | ||
| 39 | + )); | ||
| 40 | + } | ||
| 41 | + text | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +/// The shared page's content: a table of the items, folders first, each group by name. | ||
| 45 | +#[component] | ||
| 46 | +pub async fn shared_body(lang: Lang, items: &[SharedItem]) -> Result<impl View> { | ||
| 47 | + let mut sorted: Vec<&SharedItem> = items.iter().collect(); | ||
| 48 | + sorted.sort_by(|a, b| { | ||
| 49 | + let a_folder = a.share.kind == in_core::store::trash::ItemKind::Folder; | ||
| 50 | + let b_folder = b.share.kind == in_core::store::trash::ItemKind::Folder; | ||
| 51 | + b_folder | ||
| 52 | + .cmp(&a_folder) | ||
| 53 | + .then_with(|| a.name.cmp(&b.name)) | ||
| 54 | + .then_with(|| a.share.id.cmp(&b.share.id)) | ||
| 55 | + }); | ||
| 56 | + Ok(view! { | ||
| 57 | + <section class="drive" data-live="/live/shared"> | ||
| 58 | + <h1>(share_s(lang, SK::SharedTitle))</h1> | ||
| 59 | + if sorted.is_empty() { | ||
| 60 | + empty_state(title: share_s(lang, SK::SharedEmpty), <p>(share_s(lang, SK::SharedEmptyHint))</p>) | ||
| 61 | + } else { | ||
| 62 | + <div class="table-wrap"> | ||
| 63 | + <table class="table"> | ||
| 64 | + <thead> | ||
| 65 | + <tr> | ||
| 66 | + <th scope="col">(d(lang, DK::Name))</th> | ||
| 67 | + <th scope="col">(share_s(lang, SK::SharePerson))</th> | ||
| 68 | + <th scope="col">(share_s(lang, SK::ShareLevel))</th> | ||
| 69 | + <th scope="col">(d(lang, DK::Size))</th> | ||
| 70 | + <th scope="col">(d(lang, DK::Actions))</th> | ||
| 71 | + </tr> | ||
| 72 | + </thead> | ||
| 73 | + <tbody> | ||
| 74 | + for item in sorted { | ||
| 75 | + <tr> | ||
| 76 | + <td> | ||
| 77 | + if item.share.kind == in_core::store::trash::ItemKind::Folder { | ||
| 78 | + <a href=(format!("/drive/{}", item.share.target_id))>(item.name.as_str())</a> | ||
| 79 | + } else { | ||
| 80 | + <a href=(format!("/view/{}", item.share.target_id))>(item.name.as_str())</a> | ||
| 81 | + } | ||
| 82 | + </td> | ||
| 83 | + <td class="muted">(item.owner_name.as_str())</td> | ||
| 84 | + <td> | ||
| 85 | + if item.share.can_download { | ||
| 86 | + (share_s(lang, SK::AccessDownload)) | ||
| 87 | + } else { | ||
| 88 | + (share_s(lang, SK::AccessView)) | ||
| 89 | + } | ||
| 90 | + </td> | ||
| 91 | + <td> | ||
| 92 | + if item.share.kind == in_core::store::trash::ItemKind::File { | ||
| 93 | + (size_text(item.size)) | ||
| 94 | + } else { | ||
| 95 | + "\u{2014}" | ||
| 96 | + } | ||
| 97 | + </td> | ||
| 98 | + <td> | ||
| 99 | + if item.share.kind == in_core::store::trash::ItemKind::File && item.share.can_download { | ||
| 100 | + <a class="button ghost" href=(format!("/file/{}?dl=1", item.share.target_id))>(d(lang, DK::Download))</a> | ||
| 101 | + } | ||
| 102 | + </td> | ||
| 103 | + </tr> | ||
| 104 | + } | ||
| 105 | + </tbody> | ||
| 106 | + </table> | ||
| 107 | + </div> | ||
| 108 | + } | ||
| 109 | + </section> | ||
| 110 | + }) | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +/// `GET /shared`: the items shared with the signed-in person. | ||
| 114 | +#[page("/shared")] | ||
| 115 | +async fn shared_page(cx: &Cx) -> Result<impl View> { | ||
| 116 | + let state = app_context::<AppState>(cx); | ||
| 117 | + let viewer = require_member(cx).await?; | ||
| 118 | + let lang = viewer_lang(cx, &viewer); | ||
| 119 | + let items = state.store.shared_with(&viewer.member.sub).await?; | ||
| 120 | + let info = ViewerInfo::of(&viewer); | ||
| 121 | + let title = share_s(lang, SK::SharedTitle); | ||
| 122 | + Ok(view! { | ||
| 123 | + shell(title: title, lang: lang, viewer: Some(&info), | ||
| 124 | + shared_body(lang: lang, items: &items) | ||
| 125 | + ) | ||
| 126 | + }) | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +/// `GET /live/shared`: a data-less `changed` event whenever the viewer's shared items change. It ends when | ||
| 130 | +/// the session is gone. | ||
| 131 | +#[route(GET "/live/shared")] | ||
| 132 | +async fn shared_live(cx: &Cx) -> Result<Response> { | ||
| 133 | + let state = app_context::<AppState>(cx); | ||
| 134 | + let viewer = require_member(cx).await?; | ||
| 135 | + let me = viewer.member.sub.clone(); | ||
| 136 | + let token_hash = viewer.session.token_hash.clone(); | ||
| 137 | + let store = state.store.clone(); | ||
| 138 | + let topics = vec![Topic::Shared(me.clone())]; | ||
| 139 | + stream_changes(cx, &state.live, &topics, move || { | ||
| 140 | + let store = store.clone(); | ||
| 141 | + let me = me.clone(); | ||
| 142 | + let token_hash = token_hash.clone(); | ||
| 143 | + async move { | ||
| 144 | + if store.session_by_token_hash(&token_hash).await?.is_none() { | ||
| 145 | + return Err(not_found().into()); | ||
| 146 | + } | ||
| 147 | + let items = store.shared_with(&me).await?; | ||
| 148 | + Ok(fingerprint(&items)) | ||
| 149 | + } | ||
| 150 | + }) | ||
| 151 | + .await | ||
| 152 | +} | ||
crates/in-web/src/pages/view.rsmodified+55 -15
| @@ -12,19 +12,21 @@ | |||
| 12 | //! both, which allows the same-origin bytes this page embeds. The bytes keep their own sandboxed CSP. | 12 | //! both, which allows the same-origin bytes this page embeds. The bytes keep their own sandboxed CSP. |
| 13 | 13 | ||
| 14 | use futures_util::StreamExt; | 14 | use futures_util::StreamExt; |
| 15 | -use in_core::authz::Action; | 15 | +use in_core::authz::{Action, Grant}; |
| 16 | use in_core::store::files::File; | 16 | use in_core::store::files::File; |
| 17 | use in_core::store::folders::Listing; | 17 | use in_core::store::folders::Listing; |
| 18 | +use in_core::store::trash::ItemKind; | ||
| 18 | use topcoat::Result; | 19 | use topcoat::Result; |
| 19 | use topcoat::context::{Cx, app_context}; | 20 | use topcoat::context::{Cx, app_context}; |
| 20 | use topcoat::router::page; | 21 | use topcoat::router::page; |
| 21 | use topcoat::router::{parse_query_params, path_param_segment}; | 22 | use topcoat::router::{parse_query_params, path_param_segment}; |
| 22 | use topcoat::view::{View, component, view}; | 23 | use topcoat::view::{View, component, view}; |
| 23 | 24 | ||
| 24 | -use crate::auth::require_member; | 25 | +use crate::auth::{Viewer, require_member}; |
| 25 | use crate::i18n::Lang; | 26 | use crate::i18n::Lang; |
| 26 | use crate::i18n::drive::{DK, d}; | 27 | use crate::i18n::drive::{DK, d}; |
| 27 | -use crate::pages::drive::{ListQuery, SortKey, sort_listing, viewer_lang}; | 28 | +use crate::i18n::share::{SK, s as share_s}; |
| 29 | +use crate::pages::drive::{ListQuery, SortKey, access_for, sort_listing, viewer_lang}; | ||
| 28 | use crate::pages::files::file_for; | 30 | use crate::pages::files::file_for; |
| 29 | use crate::serve_bytes::inline_safe; | 31 | use crate::serve_bytes::inline_safe; |
| 30 | use crate::state::AppState; | 32 | use crate::state::AppState; |
| @@ -76,14 +78,26 @@ async fn text_head(state: &AppState, file: &File) -> Result<(String, bool)> { | |||
| 76 | )) | 78 | )) |
| 77 | } | 79 | } |
| 78 | 80 | ||
| 81 | +/// Whether the viewer may see the folder a file sits in: it is their own, or a grant reaches it. The top | ||
| 82 | +/// level is the owner's alone. A grantee's neighbours come from a listing they may see, so the folder must | ||
| 83 | +/// be visible to them, not only the file. | ||
| 84 | +async fn folder_visible(state: &AppState, viewer: &Viewer, file: &File) -> Result<bool> { | ||
| 85 | + let Some(folder) = file.folder_id.as_deref() else { | ||
| 86 | + return Ok(file.owner == viewer.member.sub); | ||
| 87 | + }; | ||
| 88 | + if file.owner == viewer.member.sub { | ||
| 89 | + return Ok(true); | ||
| 90 | + } | ||
| 91 | + let access = state | ||
| 92 | + .store | ||
| 93 | + .access_of(&viewer.member.sub, ItemKind::Folder, folder) | ||
| 94 | + .await?; | ||
| 95 | + Ok(access.is_some_and(|a| !a.trashed && a.grant != Grant::None)) | ||
| 96 | +} | ||
| 97 | + | ||
| 79 | /// The viewer links of the files before and after `file` in its folder, in the listing's sort order. Each is a | 98 | /// The viewer links of the files before and after `file` in its folder, in the listing's sort order. Each is a |
| 80 | /// `/view` link that carries the sort, so stepping through keeps the order. Empty when there is none. | 99 | /// `/view` link that carries the sort, so stepping through keeps the order. Empty when there is none. |
| 81 | -async fn neighbours( | 100 | +async fn neighbours(state: &AppState, file: &File, query: &ListQuery) -> Result<(String, String)> { |
| 82 | - state: &AppState, | ||
| 83 | - owner: &str, | ||
| 84 | - file: &File, | ||
| 85 | - query: &ListQuery, | ||
| 86 | -) -> Result<(String, String)> { | ||
| 87 | if file.trashed_at.is_some() { | 101 | if file.trashed_at.is_some() { |
| 88 | return Ok((String::new(), String::new())); | 102 | return Ok((String::new(), String::new())); |
| 89 | } | 103 | } |
| @@ -91,7 +105,7 @@ async fn neighbours( | |||
| 91 | let descending = query.dir == "desc"; | 105 | let descending = query.dir == "desc"; |
| 92 | let mut listing: Listing = state | 106 | let mut listing: Listing = state |
| 93 | .store | 107 | .store |
| 94 | - .list_children(owner, file.folder_id.as_deref()) | 108 | + .list_children(&file.owner, file.folder_id.as_deref()) |
| 95 | .await?; | 109 | .await?; |
| 96 | sort_listing(&mut listing, key, descending); | 110 | sort_listing(&mut listing, key, descending); |
| 97 | let Some(at) = listing.files.iter().position(|f| f.id == file.id) else { | 111 | let Some(at) = listing.files.iter().position(|f| f.id == file.id) else { |
| @@ -183,6 +197,8 @@ pub async fn viewer_body( | |||
| 183 | next: &str, | 197 | next: &str, |
| 184 | notice: &str, | 198 | notice: &str, |
| 185 | refusal: &str, | 199 | refusal: &str, |
| 200 | + writable: bool, | ||
| 201 | + downloadable: bool, | ||
| 186 | ) -> Result<impl View> { | 202 | ) -> Result<impl View> { |
| 187 | let download = format!("/file/{}?dl=1", file.id); | 203 | let download = format!("/file/{}?dl=1", file.id); |
| 188 | let open = format!("/file/{}", file.id); | 204 | let open = format!("/file/{}", file.id); |
| @@ -193,12 +209,19 @@ pub async fn viewer_body( | |||
| 193 | flash(lang: lang, notice: notice, refusal: refusal) | 209 | flash(lang: lang, notice: notice, refusal: refusal) |
| 194 | <h1>(file.name.as_str())</h1> | 210 | <h1>(file.name.as_str())</h1> |
| 195 | <p class="muted">(file.mime.as_str()) " \u{b7} " (size_text(file.size)) " \u{b7} " (stamp_text(&file.updated_at))</p> | 211 | <p class="muted">(file.mime.as_str()) " \u{b7} " (size_text(file.size)) " \u{b7} " (stamp_text(&file.updated_at))</p> |
| 212 | + if !writable && !downloadable { | ||
| 213 | + <p class="muted">(share_s(lang, SK::AccessView))</p> | ||
| 214 | + } | ||
| 196 | viewer_nav(lang: lang, prev: prev, next: next) | 215 | viewer_nav(lang: lang, prev: prev, next: next) |
| 197 | viewer_stage(lang: lang, file: file, kind: kind, text: text, truncated: truncated) | 216 | viewer_stage(lang: lang, file: file, kind: kind, text: text, truncated: truncated) |
| 198 | <div class="actions"> | 217 | <div class="actions"> |
| 199 | - <a class="button primary" href=(download.as_str())>(d(lang, DK::Download))</a> | 218 | + if downloadable { |
| 219 | + <a class="button primary" href=(download.as_str())>(d(lang, DK::Download))</a> | ||
| 220 | + } | ||
| 200 | <a class="button" href=(open.as_str())>(d(lang, DK::OpenRaw))</a> | 221 | <a class="button" href=(open.as_str())>(d(lang, DK::OpenRaw))</a> |
| 201 | - row_menu(lang: lang, csrf: csrf, back: here.as_str(), kind: "file", id: file.id.as_str(), name: file.name.as_str()) | 222 | + if writable { |
| 223 | + row_menu(lang: lang, csrf: csrf, back: here.as_str(), kind: "file", id: file.id.as_str(), name: file.name.as_str()) | ||
| 224 | + } | ||
| 202 | </div> | 225 | </div> |
| 203 | </section> | 226 | </section> |
| 204 | }) | 227 | }) |
| @@ -213,20 +236,36 @@ async fn view_page(cx: &Cx) -> Result<impl View> { | |||
| 213 | let id = path_param_segment(cx, "id").to_owned(); | 236 | let id = path_param_segment(cx, "id").to_owned(); |
| 214 | let query: ListQuery = parse_query_params(cx).unwrap_or_default(); | 237 | let query: ListQuery = parse_query_params(cx).unwrap_or_default(); |
| 215 | let file = file_for(state, &viewer, &id, Action::View).await?; | 238 | let file = file_for(state, &viewer, &id, Action::View).await?; |
| 239 | + let access = access_for(state, &viewer, ItemKind::File, &id).await?; | ||
| 240 | + let owned = file.owner == viewer.member.sub; | ||
| 241 | + let writable = owned && file.trashed_at.is_none(); | ||
| 242 | + let downloadable = owned || access.grant == Grant::Download; | ||
| 216 | let kind = viewer_kind(&file.mime); | 243 | let kind = viewer_kind(&file.mime); |
| 217 | let (text, truncated) = if kind == "text" { | 244 | let (text, truncated) = if kind == "text" { |
| 218 | text_head(state, &file).await? | 245 | text_head(state, &file).await? |
| 219 | } else { | 246 | } else { |
| 220 | (String::new(), false) | 247 | (String::new(), false) |
| 221 | }; | 248 | }; |
| 222 | - let (prev, next) = neighbours(state, &viewer.member.sub, &file, &query).await?; | 249 | + let visible = folder_visible(state, &viewer, &file).await?; |
| 250 | + let (prev, next) = if owned || visible { | ||
| 251 | + neighbours(state, &file, &query).await? | ||
| 252 | + } else { | ||
| 253 | + (String::new(), String::new()) | ||
| 254 | + }; | ||
| 255 | + // Back goes to the owner's listing, the shared page, or the trash, and never to a folder the viewer | ||
| 256 | + // cannot see. | ||
| 223 | let back = if file.trashed_at.is_some() { | 257 | let back = if file.trashed_at.is_some() { |
| 224 | "/trash".to_owned() | 258 | "/trash".to_owned() |
| 225 | - } else { | 259 | + } else if owned { |
| 226 | match file.folder_id.as_deref() { | 260 | match file.folder_id.as_deref() { |
| 227 | Some(folder) => format!("/drive/{folder}"), | 261 | Some(folder) => format!("/drive/{folder}"), |
| 228 | None => "/drive".to_owned(), | 262 | None => "/drive".to_owned(), |
| 229 | } | 263 | } |
| 264 | + } else { | ||
| 265 | + match (visible, file.folder_id.as_deref()) { | ||
| 266 | + (true, Some(folder)) => format!("/drive/{folder}"), | ||
| 267 | + _ => "/shared".to_owned(), | ||
| 268 | + } | ||
| 230 | }; | 269 | }; |
| 231 | let csrf = viewer.session.csrf_token.clone(); | 270 | let csrf = viewer.session.csrf_token.clone(); |
| 232 | let info = ViewerInfo::of(&viewer); | 271 | let info = ViewerInfo::of(&viewer); |
| @@ -235,7 +274,8 @@ async fn view_page(cx: &Cx) -> Result<impl View> { | |||
| 235 | shell(title: title.as_str(), lang: lang, viewer: Some(&info), | 274 | shell(title: title.as_str(), lang: lang, viewer: Some(&info), |
| 236 | viewer_body(lang: lang, file: &file, back: back.as_str(), csrf: csrf.as_str(), kind: kind, | 275 | viewer_body(lang: lang, file: &file, back: back.as_str(), csrf: csrf.as_str(), kind: kind, |
| 237 | text: text.as_str(), truncated: truncated, prev: prev.as_str(), next: next.as_str(), | 276 | text: text.as_str(), truncated: truncated, prev: prev.as_str(), next: next.as_str(), |
| 238 | - notice: query.notice.as_str(), refusal: query.refusal.as_str()) | 277 | + notice: query.notice.as_str(), refusal: query.refusal.as_str(), |
| 278 | + writable: writable, downloadable: downloadable) | ||
| 239 | ) | 279 | ) |
| 240 | }) | 280 | }) |
| 241 | } | 281 | } |
crates/in-web/src/security.rsmodified+49 -6
| @@ -6,13 +6,43 @@ | |||
| 6 | //! `docs/conventions.md` section 5. | 6 | //! `docs/conventions.md` section 5. |
| 7 | 7 | ||
| 8 | use topcoat::context::Cx; | 8 | use topcoat::context::Cx; |
| 9 | +use topcoat::router::request::uri; | ||
| 9 | use topcoat::router::response::response_headers; | 10 | use topcoat::router::response::response_headers; |
| 10 | -use topcoat::router::{Body, HeaderMap, HeaderValue, Layer, LayerFuture, Next, Path, header}; | 11 | +use topcoat::router::{ |
| 12 | + Body, HeaderMap, HeaderName, HeaderValue, Layer, LayerFuture, Next, Path, header, | ||
| 13 | +}; | ||
| 11 | 14 | ||
| 12 | /// The Content-Security-Policy of every response. | 15 | /// The Content-Security-Policy of every response. |
| 13 | pub const CSP: &str = "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; \ | 16 | pub const CSP: &str = "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; \ |
| 14 | form-action 'self'; frame-ancestors 'none'; base-uri 'none'"; | 17 | form-action 'self'; frame-ancestors 'none'; base-uri 'none'"; |
| 15 | 18 | ||
| 19 | +/// Path prefix of the public share pages and their bytes. The token is in the path, so these pages send no | ||
| 20 | +/// referrer and ask search engines not to index them (architecture section 8). | ||
| 21 | +pub const SHARE_PREFIX: &str = "/s/"; | ||
| 22 | + | ||
| 23 | +/// `Referrer-Policy` of the public share pages: the token in the URL must never reach another site. | ||
| 24 | +const SHARE_REFERRER: &str = "no-referrer"; | ||
| 25 | + | ||
| 26 | +/// `X-Robots-Tag` of the public share pages. | ||
| 27 | +const SHARE_ROBOTS: &str = "noindex"; | ||
| 28 | + | ||
| 29 | +/// The headers of `base` as they apply to a request for `path`: on a public share path the referrer and | ||
| 30 | +/// robots headers are replaced, everywhere else `base` is used as it is. | ||
| 31 | +fn for_path(base: &HeaderMap, path: &str) -> HeaderMap { | ||
| 32 | + let mut headers = base.clone(); | ||
| 33 | + if path.starts_with(SHARE_PREFIX) { | ||
| 34 | + headers.insert( | ||
| 35 | + header::REFERRER_POLICY, | ||
| 36 | + HeaderValue::from_static(SHARE_REFERRER), | ||
| 37 | + ); | ||
| 38 | + headers.insert( | ||
| 39 | + HeaderName::from_static("x-robots-tag"), | ||
| 40 | + HeaderValue::from_static(SHARE_ROBOTS), | ||
| 41 | + ); | ||
| 42 | + } | ||
| 43 | + headers | ||
| 44 | +} | ||
| 45 | + | ||
| 16 | /// One year, in seconds. Sent only when the public origin is https. | 46 | /// One year, in seconds. Sent only when the public origin is https. |
| 17 | const HSTS: &str = "max-age=31536000"; | 47 | const HSTS: &str = "max-age=31536000"; |
| 18 | 48 | ||
| @@ -63,14 +93,16 @@ impl Layer for SecurityHeaders { | |||
| 63 | 93 | ||
| 64 | fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { | 94 | fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { |
| 65 | Box::pin(async move { | 95 | Box::pin(async move { |
| 96 | + let path = uri(cx).path().to_owned(); | ||
| 97 | + let headers = for_path(&self.headers, &path); | ||
| 66 | match next.run(cx, body).await { | 98 | match next.run(cx, body).await { |
| 67 | // A header the route set itself wins: byte responses carry their own sandboxed | 99 | // A header the route set itself wins: byte responses carry their own sandboxed |
| 68 | // policy, and two policies would apply both (the page one forbids framing). | 100 | // policy, and two policies would apply both (the page one forbids framing). |
| 69 | Ok(mut response) => { | 101 | Ok(mut response) => { |
| 70 | - let headers = response.headers_mut(); | 102 | + let response_map = response.headers_mut(); |
| 71 | - for (name, value) in &self.headers { | 103 | + for (name, value) in &headers { |
| 72 | - if !headers.contains_key(name) { | 104 | + if !response_map.contains_key(name) { |
| 73 | - headers.insert(name.clone(), value.clone()); | 105 | + response_map.insert(name.clone(), value.clone()); |
| 74 | } | 106 | } |
| 75 | } | 107 | } |
| 76 | Ok(response) | 108 | Ok(response) |
| @@ -78,7 +110,7 @@ impl Layer for SecurityHeaders { | |||
| 78 | // Errors become responses after the layers have run; the per-request slot gives | 110 | // Errors become responses after the layers have run; the per-request slot gives |
| 79 | // them the headers too. | 111 | // them the headers too. |
| 80 | Err(error) => { | 112 | Err(error) => { |
| 81 | - response_headers(cx).extend(self.headers.clone()); | 113 | + response_headers(cx).extend(headers); |
| 82 | Err(error) | 114 | Err(error) |
| 83 | } | 115 | } |
| 84 | } | 116 | } |
| @@ -90,6 +122,17 @@ impl Layer for SecurityHeaders { | |||
| 90 | mod tests { | 122 | mod tests { |
| 91 | use super::*; | 123 | use super::*; |
| 92 | 124 | ||
| 125 | + #[test] | ||
| 126 | + fn share_paths_send_no_referrer_and_no_index() { | ||
| 127 | + let base = headers_for("https://in.example.com"); | ||
| 128 | + let share = for_path(&base, "/s/abc"); | ||
| 129 | + assert_eq!(share[header::REFERRER_POLICY], "no-referrer"); | ||
| 130 | + assert_eq!(share["x-robots-tag"], "noindex"); | ||
| 131 | + let drive = for_path(&base, "/drive"); | ||
| 132 | + assert_eq!(drive[header::REFERRER_POLICY], "same-origin"); | ||
| 133 | + assert!(!drive.contains_key("x-robots-tag")); | ||
| 134 | + } | ||
| 135 | + | ||
| 93 | #[test] | 136 | #[test] |
| 94 | fn hsts_only_for_https_origins() { | 137 | fn hsts_only_for_https_origins() { |
| 95 | assert!( | 138 | assert!( |
crates/in-web/src/serve_bytes.rsmodified+22 -6
| @@ -69,6 +69,10 @@ pub const PDF_CSP: &str = "default-src 'none'; img-src 'self'; media-src 'self'; | |||
| 69 | /// Cache policy of content addressed by id and hash: the bytes behind a URL never change. | 69 | /// Cache policy of content addressed by id and hash: the bytes behind a URL never change. |
| 70 | const BYTES_CACHE: &str = "private, max-age=31536000, immutable"; | 70 | const BYTES_CACHE: &str = "private, max-age=31536000, immutable"; |
| 71 | 71 | ||
| 72 | +/// Cache policy of bytes behind a public share link. The link can be revoked or its password changed, so | ||
| 73 | +/// a cached copy must not outlive the check: the browser asks again every time. | ||
| 74 | +pub const SHARE_CACHE: &str = "private, no-cache"; | ||
| 75 | + | ||
| 72 | /// The outcome of reading a `Range` header against a length. | 76 | /// The outcome of reading a `Range` header against a length. |
| 73 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] | 77 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 74 | pub enum Ranged { | 78 | pub enum Ranged { |
| @@ -264,7 +268,7 @@ pub fn content_disposition(kind: Disposition, name: &str) -> String { | |||
| 264 | } | 268 | } |
| 265 | 269 | ||
| 266 | /// The headers every byte response carries, whatever its status. | 270 | /// The headers every byte response carries, whatever its status. |
| 267 | -fn common_headers(etag: &str, mime: &str) -> HeaderMap { | 271 | +fn common_headers(etag: &str, mime: &str, cache: &str) -> HeaderMap { |
| 268 | let mut headers = HeaderMap::new(); | 272 | let mut headers = HeaderMap::new(); |
| 269 | insert(&mut headers, ETAG, etag); | 273 | insert(&mut headers, ETAG, etag); |
| 270 | headers.insert(ACCEPT_RANGES, HeaderValue::from_static("bytes")); | 274 | headers.insert(ACCEPT_RANGES, HeaderValue::from_static("bytes")); |
| @@ -280,7 +284,7 @@ fn common_headers(etag: &str, mime: &str) -> HeaderMap { | |||
| 280 | HeaderName::from_static("cross-origin-resource-policy"), | 284 | HeaderName::from_static("cross-origin-resource-policy"), |
| 281 | HeaderValue::from_static("same-origin"), | 285 | HeaderValue::from_static("same-origin"), |
| 282 | ); | 286 | ); |
| 283 | - headers.insert(CACHE_CONTROL, HeaderValue::from_static(BYTES_CACHE)); | 287 | + insert(&mut headers, CACHE_CONTROL, cache); |
| 284 | headers | 288 | headers |
| 285 | } | 289 | } |
| 286 | 290 | ||
| @@ -293,8 +297,8 @@ fn insert(headers: &mut HeaderMap, name: http::HeaderName, value: &str) { | |||
| 293 | } | 297 | } |
| 294 | 298 | ||
| 295 | /// The `416` answer: no body, and the length the client may ask again within. | 299 | /// The `416` answer: no body, and the length the client may ask again within. |
| 296 | -fn unsatisfiable(etag: &str, len: u64) -> ByteAnswer { | 300 | +fn unsatisfiable(etag: &str, len: u64, cache: &str) -> ByteAnswer { |
| 297 | - let mut headers = common_headers(etag, ""); | 301 | + let mut headers = common_headers(etag, "", cache); |
| 298 | insert(&mut headers, CONTENT_RANGE, &format!("bytes */{len}")); | 302 | insert(&mut headers, CONTENT_RANGE, &format!("bytes */{len}")); |
| 299 | (StatusCode::RANGE_NOT_SATISFIABLE, headers, Body::empty()) | 303 | (StatusCode::RANGE_NOT_SATISFIABLE, headers, Body::empty()) |
| 300 | } | 304 | } |
| @@ -310,6 +314,18 @@ pub async fn serve_bytes( | |||
| 310 | blobs: &dyn BlobStore, | 314 | blobs: &dyn BlobStore, |
| 311 | source: &ByteSource<'_>, | 315 | source: &ByteSource<'_>, |
| 312 | disposition: Disposition, | 316 | disposition: Disposition, |
| 317 | +) -> Result<ByteAnswer> { | ||
| 318 | + serve_bytes_with(cx, blobs, source, disposition, BYTES_CACHE).await | ||
| 319 | +} | ||
| 320 | + | ||
| 321 | +/// [`serve_bytes`] with the cache policy given: the owner's bytes use [`BYTES_CACHE`], share-link bytes | ||
| 322 | +/// use [`SHARE_CACHE`]. Everything else is the same. | ||
| 323 | +pub async fn serve_bytes_with( | ||
| 324 | + cx: &Cx, | ||
| 325 | + blobs: &dyn BlobStore, | ||
| 326 | + source: &ByteSource<'_>, | ||
| 327 | + disposition: Disposition, | ||
| 328 | + cache: &str, | ||
| 313 | ) -> Result<ByteAnswer> { | 329 | ) -> Result<ByteAnswer> { |
| 314 | let request = headers(cx); | 330 | let request = headers(cx); |
| 315 | let etag = format!("\"{}\"", source.sha256); | 331 | let etag = format!("\"{}\"", source.sha256); |
| @@ -317,7 +333,7 @@ pub async fn serve_bytes( | |||
| 317 | Disposition::Inline if inline_safe(source.mime) => Disposition::Inline, | 333 | Disposition::Inline if inline_safe(source.mime) => Disposition::Inline, |
| 318 | _ => Disposition::Attachment, | 334 | _ => Disposition::Attachment, |
| 319 | }; | 335 | }; |
| 320 | - let mut answer_headers = common_headers(&etag, source.mime); | 336 | + let mut answer_headers = common_headers(&etag, source.mime, cache); |
| 321 | insert( | 337 | insert( |
| 322 | &mut answer_headers, | 338 | &mut answer_headers, |
| 323 | CONTENT_DISPOSITION, | 339 | CONTENT_DISPOSITION, |
| @@ -334,7 +350,7 @@ pub async fn serve_bytes( | |||
| 334 | } | 350 | } |
| 335 | 351 | ||
| 336 | match requested_range(request, &etag, source.size) { | 352 | match requested_range(request, &etag, source.size) { |
| 337 | - Ranged::Unsatisfiable => Ok(unsatisfiable(&etag, source.size)), | 353 | + Ranged::Unsatisfiable => Ok(unsatisfiable(&etag, source.size, cache)), |
| 338 | Ranged::Full => { | 354 | Ranged::Full => { |
| 339 | insert( | 355 | insert( |
| 340 | &mut answer_headers, | 356 | &mut answer_headers, |
crates/in-web/src/state.rsmodified+3 -0
| @@ -8,6 +8,7 @@ use in_core::store::Store; | |||
| 8 | 8 | ||
| 9 | use crate::live::LiveHub; | 9 | use crate::live::LiveHub; |
| 10 | use crate::oidc::OidcClient; | 10 | use crate::oidc::OidcClient; |
| 11 | +use crate::throttle::ShareThrottles; | ||
| 11 | 12 | ||
| 12 | /// Everything a request handler reaches through the app context. Every field is cheap to clone. | 13 | /// Everything a request handler reaches through the app context. Every field is cheap to clone. |
| 13 | #[allow(dead_code)] // The live hub is read by the live pages, which come after sign-in. | 14 | #[allow(dead_code)] // The live hub is read by the live pages, which come after sign-in. |
| @@ -26,4 +27,6 @@ pub struct AppState { | |||
| 26 | /// The OpenID Connect client of `im`. `None` when the configuration has no `[oidc]` table, in which | 27 | /// The OpenID Connect client of `im`. `None` when the configuration has no `[oidc]` table, in which |
| 27 | /// case nobody can sign in and the sign-in routes say so. | 28 | /// case nobody can sign in and the sign-in routes say so. |
| 28 | pub oidc: Option<Arc<OidcClient>>, | 29 | pub oidc: Option<Arc<OidcClient>>, |
| 30 | + /// The failure windows of share-link passwords. | ||
| 31 | + pub throttles: Arc<ShareThrottles>, | ||
| 29 | } | 32 | } |
crates/in-web/src/throttle.rsadded+115 -0
| @@ -0,0 +1,115 @@ | |||
| 1 | +//! Failure throttling in memory: a sliding window of failures per key, with a bounded number of keys. | ||
| 2 | +//! | ||
| 3 | +//! A check asks [`Throttle::blocked`] before any lookup and answers `429` with `Retry-After` when the key | ||
| 4 | +//! has reached its limit. A failure is recorded with [`Throttle::failure`]. Nothing is persisted, so a | ||
| 5 | +//! restart forgets the failures; that is accepted for a family instance and documented in the backlog. | ||
| 6 | +//! | ||
| 7 | +//! The key count is capped. When a new key would exceed the cap, the windows that have expired are | ||
| 8 | +//! dropped first, and then the key whose last failure is oldest. So an attacker who spreads guesses over | ||
| 9 | +//! many keys can only evict other keys, never grow the memory. | ||
| 10 | + | ||
| 11 | +use std::collections::HashMap; | ||
| 12 | +use std::sync::{Mutex, MutexGuard, PoisonError}; | ||
| 13 | +use std::time::{Duration, Instant}; | ||
| 14 | + | ||
| 15 | +/// Length of the sliding window for share-link passwords: 15 minutes. | ||
| 16 | +pub const PASSWORD_WINDOW: Duration = Duration::from_secs(15 * 60); | ||
| 17 | + | ||
| 18 | +/// Failed password attempts allowed against one link in a window. The sixth is refused with `429`. | ||
| 19 | +pub const LINK_PASSWORD_LIMIT: usize = 5; | ||
| 20 | + | ||
| 21 | +/// Failed password attempts allowed from one client address in a window, across all links. | ||
| 22 | +pub const IP_PASSWORD_LIMIT: usize = 10; | ||
| 23 | + | ||
| 24 | +/// Most keys held at once. Each key is a short string and a short list of instants. | ||
| 25 | +pub const MAX_KEYS: usize = 10_000; | ||
| 26 | + | ||
| 27 | +/// Failures per key within a sliding window, with a cap on the number of keys. | ||
| 28 | +pub struct Throttle { | ||
| 29 | + failures: Mutex<HashMap<String, Vec<Instant>>>, | ||
| 30 | + window: Duration, | ||
| 31 | + limit: usize, | ||
| 32 | + max_keys: usize, | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +impl Throttle { | ||
| 36 | + /// A throttle that blocks a key after `limit` failures within `window`. | ||
| 37 | + pub fn new(window: Duration, limit: usize, max_keys: usize) -> Self { | ||
| 38 | + Self { | ||
| 39 | + failures: Mutex::new(HashMap::new()), | ||
| 40 | + window, | ||
| 41 | + limit, | ||
| 42 | + max_keys, | ||
| 43 | + } | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + /// Locks the map. A poisoned lock is used as it is: a panic elsewhere must not open the throttle. | ||
| 47 | + fn map(&self) -> MutexGuard<'_, HashMap<String, Vec<Instant>>> { | ||
| 48 | + self.failures.lock().unwrap_or_else(PoisonError::into_inner) | ||
| 49 | + } | ||
| 50 | + | ||
| 51 | + /// The seconds `key` must wait before it may try again, or `None` when it may try now. Only failures | ||
| 52 | + /// inside the window count. | ||
| 53 | + pub fn blocked(&self, key: &str) -> Option<u64> { | ||
| 54 | + let now = Instant::now(); | ||
| 55 | + let mut map = self.map(); | ||
| 56 | + let stamps = map.get_mut(key)?; | ||
| 57 | + stamps.retain(|at| now.duration_since(*at) < self.window); | ||
| 58 | + if stamps.len() < self.limit { | ||
| 59 | + return None; | ||
| 60 | + } | ||
| 61 | + // The key may try again once enough failures have left the window: the one at this index is the | ||
| 62 | + // last to leave before the count drops below the limit. | ||
| 63 | + let index = stamps.len() - self.limit; | ||
| 64 | + let free_at = stamps[index] + self.window; | ||
| 65 | + let wait = free_at.saturating_duration_since(now); | ||
| 66 | + // Rounded up, and at least one second, so `Retry-After` is never zero for a blocked key. | ||
| 67 | + let seconds = wait.as_secs() + u64::from(wait.subsec_nanos() > 0); | ||
| 68 | + Some(seconds.max(1)) | ||
| 69 | + } | ||
| 70 | + | ||
| 71 | + /// Records one failure of `key` now. | ||
| 72 | + pub fn failure(&self, key: &str) { | ||
| 73 | + let now = Instant::now(); | ||
| 74 | + let mut map = self.map(); | ||
| 75 | + if !map.contains_key(key) && map.len() >= self.max_keys { | ||
| 76 | + self.make_room(&mut map, now); | ||
| 77 | + } | ||
| 78 | + map.entry(key.to_owned()).or_default().push(now); | ||
| 79 | + } | ||
| 80 | + | ||
| 81 | + /// Frees one slot: expired windows go first, then the key with the oldest last failure. | ||
| 82 | + fn make_room(&self, map: &mut HashMap<String, Vec<Instant>>, now: Instant) { | ||
| 83 | + let window = self.window; | ||
| 84 | + map.retain(|_, stamps| { | ||
| 85 | + stamps.retain(|at| now.duration_since(*at) < window); | ||
| 86 | + !stamps.is_empty() | ||
| 87 | + }); | ||
| 88 | + if map.len() >= self.max_keys { | ||
| 89 | + let oldest = map | ||
| 90 | + .iter() | ||
| 91 | + .min_by_key(|(_, stamps)| stamps.last().copied()) | ||
| 92 | + .map(|(key, _)| key.clone()); | ||
| 93 | + if let Some(key) = oldest { | ||
| 94 | + map.remove(&key); | ||
| 95 | + } | ||
| 96 | + } | ||
| 97 | + } | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +/// The two throttles of share-link passwords: one per link (by token hash) and one per client address. | ||
| 101 | +pub struct ShareThrottles { | ||
| 102 | + /// Failures per link. | ||
| 103 | + pub per_link: Throttle, | ||
| 104 | + /// Failures per client address. | ||
| 105 | + pub per_ip: Throttle, | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +impl Default for ShareThrottles { | ||
| 109 | + fn default() -> Self { | ||
| 110 | + Self { | ||
| 111 | + per_link: Throttle::new(PASSWORD_WINDOW, LINK_PASSWORD_LIMIT, MAX_KEYS), | ||
| 112 | + per_ip: Throttle::new(PASSWORD_WINDOW, IP_PASSWORD_LIMIT, MAX_KEYS), | ||
| 113 | + } | ||
| 114 | + } | ||
| 115 | +} | ||
crates/in-web/src/views/drive.rsmodified+45 -15
| @@ -10,6 +10,7 @@ use topcoat::view::{View, component, view}; | |||
| 10 | 10 | ||
| 11 | use crate::i18n::Lang; | 11 | use crate::i18n::Lang; |
| 12 | use crate::i18n::drive::{DK, d, notice_text, quota_text, refusal_text}; | 12 | use crate::i18n::drive::{DK, d, notice_text, quota_text, refusal_text}; |
| 13 | +use crate::i18n::share::{SK, s as share_s}; | ||
| 13 | use in_core::store::files::File; | 14 | use in_core::store::files::File; |
| 14 | use in_core::store::folders::Folder; | 15 | use in_core::store::folders::Folder; |
| 15 | 16 | ||
| @@ -81,13 +82,20 @@ pub fn kind_glyph(mime: &str) -> &'static str { | |||
| 81 | } | 82 | } |
| 82 | } | 83 | } |
| 83 | 84 | ||
| 84 | -/// The breadcrumb trail, top level first. Empty for the top level, which needs no trail. | 85 | +/// The breadcrumb trail, top level first. Empty for the top level, which needs no trail. The first crumb is |
| 86 | +/// the viewer's drive, or the shared page when the listing is shared with the viewer. A shared trail starts | ||
| 87 | +/// at the granted folder, so nothing above it is named. | ||
| 85 | #[component] | 88 | #[component] |
| 86 | -pub async fn crumbs(lang: Lang, trail: &[Folder]) -> Result<impl View> { | 89 | +pub async fn crumbs(lang: Lang, trail: &[Folder], shared: bool) -> Result<impl View> { |
| 90 | + let (root_href, root_label) = if shared { | ||
| 91 | + ("/shared", share_s(lang, SK::SharedTitle)) | ||
| 92 | + } else { | ||
| 93 | + ("/drive", d(lang, DK::Drive)) | ||
| 94 | + }; | ||
| 87 | Ok(view! { | 95 | Ok(view! { |
| 88 | <nav class="crumbs" aria-label=(d(lang, DK::Location2))> | 96 | <nav class="crumbs" aria-label=(d(lang, DK::Location2))> |
| 89 | <ol> | 97 | <ol> |
| 90 | - <li><a href="/drive">(d(lang, DK::Drive))</a></li> | 98 | + <li><a href=(root_href)>(root_label)</a></li> |
| 91 | for folder in trail { | 99 | for folder in trail { |
| 92 | <li><a href=(format!("/drive/{}", folder.id))>(folder.name.as_str())</a></li> | 100 | <li><a href=(format!("/drive/{}", folder.id))>(folder.name.as_str())</a></li> |
| 93 | } | 101 | } |
| @@ -137,10 +145,12 @@ pub async fn row_menu( | |||
| 137 | let rename_action = format!("/{kind}s/{id}/rename"); | 145 | let rename_action = format!("/{kind}s/{id}/rename"); |
| 138 | let move_page = format!("/{kind}s/{id}/pick"); | 146 | let move_page = format!("/{kind}s/{id}/pick"); |
| 139 | let trash_action = format!("/{kind}s/{id}/trash"); | 147 | let trash_action = format!("/{kind}s/{id}/trash"); |
| 148 | + let share_page = format!("/share/{kind}/{id}"); | ||
| 140 | Ok(view! { | 149 | Ok(view! { |
| 141 | <details class="row-menu"> | 150 | <details class="row-menu"> |
| 142 | <summary>(d(lang, DK::Actions))</summary> | 151 | <summary>(d(lang, DK::Actions))</summary> |
| 143 | <div class="row-menu-body"> | 152 | <div class="row-menu-body"> |
| 153 | + <a class="button" href=(share_page)>(share_s(lang, SK::ShareHeading))</a> | ||
| 144 | <form method="post" action=(rename_action) class="inline-form"> | 154 | <form method="post" action=(rename_action) class="inline-form"> |
| 145 | <input type="hidden" name="csrf" value=(csrf)> | 155 | <input type="hidden" name="csrf" value=(csrf)> |
| 146 | <input type="hidden" name="back" value=(back)> | 156 | <input type="hidden" name="back" value=(back)> |
| @@ -160,7 +170,9 @@ pub async fn row_menu( | |||
| 160 | } | 170 | } |
| 161 | 171 | ||
| 162 | /// A table of folders and files: the rows, their selection box for the bulk trash, and the row menus. | 172 | /// A table of folders and files: the rows, their selection box for the bulk trash, and the row menus. |
| 163 | -/// `base` is the listing's own URL without a query, and `query` the sort part already in it. | 173 | +/// `base` is the listing's own URL without a query, and `query` the sort part already in it. A listing |
| 174 | +/// the viewer does not own (`writable` false) has no selection boxes, menus or trash form; its files have a | ||
| 175 | +/// download link only when `downloadable` is set. | ||
| 164 | #[component] | 176 | #[component] |
| 165 | pub async fn listing_table( | 177 | pub async fn listing_table( |
| 166 | lang: Lang, | 178 | lang: Lang, |
| @@ -171,6 +183,8 @@ pub async fn listing_table( | |||
| 171 | sort: &str, | 183 | sort: &str, |
| 172 | dir: &str, | 184 | dir: &str, |
| 173 | base: &str, | 185 | base: &str, |
| 186 | + writable: bool, | ||
| 187 | + downloadable: bool, | ||
| 174 | ) -> Result<impl View> { | 188 | ) -> Result<impl View> { |
| 175 | let descending = dir == "desc"; | 189 | let descending = dir == "desc"; |
| 176 | let name_sort = sort == "name"; | 190 | let name_sort = sort == "name"; |
| @@ -181,7 +195,9 @@ pub async fn listing_table( | |||
| 181 | <table class="table"> | 195 | <table class="table"> |
| 182 | <thead> | 196 | <thead> |
| 183 | <tr> | 197 | <tr> |
| 184 | - <th scope="col"><span class="sr-only">"\u{2713}"</span></th> | 198 | + if writable { |
| 199 | + <th scope="col"><span class="sr-only">"\u{2713}"</span></th> | ||
| 200 | + } | ||
| 185 | <th scope="col"> | 201 | <th scope="col"> |
| 186 | sort_link(base: base, key: "name", label: d(lang, DK::Name), current: name_sort, descending: descending) | 202 | sort_link(base: base, key: "name", label: d(lang, DK::Name), current: name_sort, descending: descending) |
| 187 | </th> | 203 | </th> |
| @@ -198,17 +214,25 @@ pub async fn listing_table( | |||
| 198 | <tbody> | 214 | <tbody> |
| 199 | for folder in folders { | 215 | for folder in folders { |
| 200 | <tr> | 216 | <tr> |
| 201 | - <td><input type="checkbox" name="item" value=(format!("folder:{}", folder.id)) form="bulk-trash" aria-label=(folder.name.as_str())></td> | 217 | + if writable { |
| 218 | + <td><input type="checkbox" name="item" value=(format!("folder:{}", folder.id)) form="bulk-trash" aria-label=(folder.name.as_str())></td> | ||
| 219 | + } | ||
| 202 | <td><a href=(format!("/drive/{}", folder.id))>(folder.name.as_str())</a></td> | 220 | <td><a href=(format!("/drive/{}", folder.id))>(folder.name.as_str())</a></td> |
| 203 | <td class="muted">"\u{2014}"</td> | 221 | <td class="muted">"\u{2014}"</td> |
| 204 | <td class="muted">(stamp_text(&folder.updated_at))</td> | 222 | <td class="muted">(stamp_text(&folder.updated_at))</td> |
| 205 | <td>(d(lang, DK::FolderKind))</td> | 223 | <td>(d(lang, DK::FolderKind))</td> |
| 206 | - <td>row_menu(lang: lang, csrf: csrf, back: back, kind: "folder", id: folder.id.as_str(), name: folder.name.as_str())</td> | 224 | + <td> |
| 225 | + if writable { | ||
| 226 | + row_menu(lang: lang, csrf: csrf, back: back, kind: "folder", id: folder.id.as_str(), name: folder.name.as_str()) | ||
| 227 | + } | ||
| 228 | + </td> | ||
| 207 | </tr> | 229 | </tr> |
| 208 | } | 230 | } |
| 209 | for file in files { | 231 | for file in files { |
| 210 | <tr> | 232 | <tr> |
| 211 | - <td><input type="checkbox" name="item" value=(format!("file:{}", file.id)) form="bulk-trash" aria-label=(file.name.as_str())></td> | 233 | + if writable { |
| 234 | + <td><input type="checkbox" name="item" value=(format!("file:{}", file.id)) form="bulk-trash" aria-label=(file.name.as_str())></td> | ||
| 235 | + } | ||
| 212 | <td class="name-cell"> | 236 | <td class="name-cell"> |
| 213 | if file.thumb_state == "ready" { | 237 | if file.thumb_state == "ready" { |
| 214 | <img class="thumb" src=(format!("/thumb/{}", file.id)) alt="" loading="lazy" width="40" height="40"> | 238 | <img class="thumb" src=(format!("/thumb/{}", file.id)) alt="" loading="lazy" width="40" height="40"> |
| @@ -221,18 +245,24 @@ pub async fn listing_table( | |||
| 221 | <td class="muted">(stamp_text(&file.updated_at))</td> | 245 | <td class="muted">(stamp_text(&file.updated_at))</td> |
| 222 | <td>(d(lang, DK::FileKind))</td> | 246 | <td>(d(lang, DK::FileKind))</td> |
| 223 | <td> | 247 | <td> |
| 224 | - <a class="button ghost" href=(format!("/file/{}?dl=1", file.id))>(d(lang, DK::Download))</a> | 248 | + if downloadable { |
| 225 | - row_menu(lang: lang, csrf: csrf, back: back, kind: "file", id: file.id.as_str(), name: file.name.as_str()) | 249 | + <a class="button ghost" href=(format!("/file/{}?dl=1", file.id))>(d(lang, DK::Download))</a> |
| 250 | + } | ||
| 251 | + if writable { | ||
| 252 | + row_menu(lang: lang, csrf: csrf, back: back, kind: "file", id: file.id.as_str(), name: file.name.as_str()) | ||
| 253 | + } | ||
| 226 | </td> | 254 | </td> |
| 227 | </tr> | 255 | </tr> |
| 228 | } | 256 | } |
| 229 | </tbody> | 257 | </tbody> |
| 230 | </table> | 258 | </table> |
| 231 | </div> | 259 | </div> |
| 232 | - <form id="bulk-trash" method="post" action="/items/trash" class="bulk"> | 260 | + if writable { |
| 233 | - <input type="hidden" name="csrf" value=(csrf)> | 261 | + <form id="bulk-trash" method="post" action="/items/trash" class="bulk"> |
| 234 | - <input type="hidden" name="back" value=(back)> | 262 | + <input type="hidden" name="csrf" value=(csrf)> |
| 235 | - <button class="button danger" type="submit">(d(lang, DK::TrashSelected))</button> | 263 | + <input type="hidden" name="back" value=(back)> |
| 236 | - </form> | 264 | + <button class="button danger" type="submit">(d(lang, DK::TrashSelected))</button> |
| 265 | + </form> | ||
| 266 | + } | ||
| 237 | }) | 267 | }) |
| 238 | } | 268 | } |
crates/in-web/src/views/mod.rsmodified+3 -0
| @@ -10,6 +10,7 @@ use crate::assets::{DRIVE_JS_HREF, MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF, VI | |||
| 10 | use crate::auth::Viewer; | 10 | use crate::auth::Viewer; |
| 11 | use crate::i18n::Lang; | 11 | use crate::i18n::Lang; |
| 12 | use crate::i18n::drive::{DK, d}; | 12 | use crate::i18n::drive::{DK, d}; |
| 13 | +use crate::i18n::share::{SK, s as share_s}; | ||
| 13 | use crate::i18n::shell::{K, t}; | 14 | use crate::i18n::shell::{K, t}; |
| 14 | use crate::views::drive::quota_bar; | 15 | use crate::views::drive::quota_bar; |
| 15 | 16 | ||
| @@ -81,6 +82,8 @@ pub async fn shell( | |||
| 81 | <nav class="switcher" aria-label=(t(lang, K::Services))> | 82 | <nav class="switcher" aria-label=(t(lang, K::Services))> |
| 82 | if viewer.is_some() { | 83 | if viewer.is_some() { |
| 83 | <a href="/drive">(d(lang, DK::Drive))</a> | 84 | <a href="/drive">(d(lang, DK::Drive))</a> |
| 85 | + <a href="/shared">(share_s(lang, SK::NavShared))</a> | ||
| 86 | + <a href="/links">(share_s(lang, SK::NavLinks))</a> | ||
| 84 | <a href="/trash">(d(lang, DK::Trash))</a> | 87 | <a href="/trash">(d(lang, DK::Trash))</a> |
| 85 | } | 88 | } |
| 86 | </nav> | 89 | </nav> |