Public links may carry a password
Browse files at this commitc36b77cb0d54d78a81c748cd37231745169e53dbParent: 83f47c5- feat
- public links may carry a password
13 changed files +599 -24
- Cargo.lock +33 -0
- Cargo.toml +1 -0
- crates/in-core/Cargo.toml +2 -0
- crates/in-core/migrations/0005_link_password.sql +11 -0
- crates/in-core/src/lib.rs +2 -1
- crates/in-core/src/store/mod.rs +13 -3
- crates/in-core/src/store/reconcile.rs +25 -12
- crates/in-core/src/store/schema.rs +1 -0
- crates/in-core/src/store/turso_store.rs +64 -5
- crates/in-core/tests/store.rs +156 -1
- crates/in-web/src/i18n.rs +19 -0
- crates/in-web/src/share.rs +144 -1
- crates/in-web/tests/http.rs +128 -1
Cargo.lockmodified+33 -0
| @@ -197,6 +197,18 @@ dependencies = [ | |||
| 197 | "rustversion", | 197 | "rustversion", |
| 198 | ] | 198 | ] |
| 199 | 199 | ||
| 200 | +[[package]] | ||
| 201 | +name = "argon2" | ||
| 202 | +version = "0.5.3" | ||
| 203 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 204 | +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" | ||
| 205 | +dependencies = [ | ||
| 206 | + "base64ct", | ||
| 207 | + "blake2", | ||
| 208 | + "cpufeatures 0.2.17", | ||
| 209 | + "password-hash", | ||
| 210 | +] | ||
| 211 | + | ||
| 200 | [[package]] | 212 | [[package]] |
| 201 | name = "aristo" | 213 | name = "aristo" |
| 202 | version = "0.4.1" | 214 | version = "0.4.1" |
| @@ -362,6 +374,15 @@ dependencies = [ | |||
| 362 | "wyz", | 374 | "wyz", |
| 363 | ] | 375 | ] |
| 364 | 376 | ||
| 377 | +[[package]] | ||
| 378 | +name = "blake2" | ||
| 379 | +version = "0.10.6" | ||
| 380 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 381 | +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" | ||
| 382 | +dependencies = [ | ||
| 383 | + "digest 0.10.7", | ||
| 384 | +] | ||
| 385 | + | ||
| 365 | [[package]] | 386 | [[package]] |
| 366 | name = "block-buffer" | 387 | name = "block-buffer" |
| 367 | version = "0.10.4" | 388 | version = "0.10.4" |
| @@ -1797,6 +1818,7 @@ dependencies = [ | |||
| 1797 | name = "in-core" | 1818 | name = "in-core" |
| 1798 | version = "0.1.0" | 1819 | version = "0.1.0" |
| 1799 | dependencies = [ | 1820 | dependencies = [ |
| 1821 | + "argon2", | ||
| 1800 | "async-trait", | 1822 | "async-trait", |
| 1801 | "base64 0.22.1", | 1823 | "base64 0.22.1", |
| 1802 | "bytes", | 1824 | "bytes", |
| @@ -2491,6 +2513,17 @@ dependencies = [ | |||
| 2491 | "windows-link", | 2513 | "windows-link", |
| 2492 | ] | 2514 | ] |
| 2493 | 2515 | ||
| 2516 | +[[package]] | ||
| 2517 | +name = "password-hash" | ||
| 2518 | +version = "0.5.0" | ||
| 2519 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2520 | +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" | ||
| 2521 | +dependencies = [ | ||
| 2522 | + "base64ct", | ||
| 2523 | + "rand_core 0.6.4", | ||
| 2524 | + "subtle", | ||
| 2525 | +] | ||
| 2526 | + | ||
| 2494 | [[package]] | 2527 | [[package]] |
| 2495 | name = "pastey" | 2528 | name = "pastey" |
| 2496 | version = "0.2.3" | 2529 | version = "0.2.3" |
Cargo.tomlmodified+1 -0
| @@ -21,6 +21,7 @@ turso = "=0.8.0-pre.8" | |||
| 21 | rand = "0.10.2" | 21 | rand = "0.10.2" |
| 22 | sha2 = "0.11.0" | 22 | sha2 = "0.11.0" |
| 23 | subtle = "2.6.1" | 23 | subtle = "2.6.1" |
| 24 | +argon2 = "0.5" | ||
| 24 | chacha20poly1305 = "0.10.1" | 25 | chacha20poly1305 = "0.10.1" |
| 25 | base64 = "0.22.1" | 26 | base64 = "0.22.1" |
| 26 | toml = "1" | 27 | toml = "1" |
crates/in-core/Cargo.tomlmodified+2 -0
| @@ -17,6 +17,7 @@ server = [ | |||
| 17 | "dep:futures-core", | 17 | "dep:futures-core", |
| 18 | "dep:tokio-util", | 18 | "dep:tokio-util", |
| 19 | "dep:base64", | 19 | "dep:base64", |
| 20 | + "dep:argon2", | ||
| 20 | "dep:chacha20poly1305", | 21 | "dep:chacha20poly1305", |
| 21 | "dep:image", | 22 | "dep:image", |
| 22 | "dep:rand", | 23 | "dep:rand", |
| @@ -33,6 +34,7 @@ bytes = { version = "1", optional = true } | |||
| 33 | futures-core = { version = "0.3", optional = true } | 34 | futures-core = { version = "0.3", optional = true } |
| 34 | tokio-util = { version = "0.7", features = ["io"], optional = true } | 35 | tokio-util = { version = "0.7", features = ["io"], optional = true } |
| 35 | base64 = { workspace = true, optional = true } | 36 | base64 = { workspace = true, optional = true } |
| 37 | +argon2 = { workspace = true, optional = true } | ||
| 36 | chacha20poly1305 = { workspace = true, optional = true } | 38 | chacha20poly1305 = { workspace = true, optional = true } |
| 37 | image = { workspace = true, optional = true } | 39 | image = { workspace = true, optional = true } |
| 38 | rand = { workspace = true, optional = true } | 40 | rand = { workspace = true, optional = true } |
crates/in-core/migrations/0005_link_password.sqladded+11 -0
| @@ -0,0 +1,11 @@ | |||
| 1 | +-- Optional passwords on public share links. | ||
| 2 | +-- | ||
| 3 | +-- `share_link.password_hash` holds an Argon2id PHC string when the owner | ||
| 4 | +-- gave the link a password, and NULL when the link opens like any other. | ||
| 5 | +-- A visitor who answers the gate keeps their proof in a cookie named for | ||
| 6 | +-- the link's own id — the row needs no session of its own, and a link | ||
| 7 | +-- without a password behaves exactly as it did before this column. | ||
| 8 | +-- Databases already carrying the column never see this file applied | ||
| 9 | +-- piecemeal — they reach the declared shape through `in reconcile`, whose | ||
| 10 | +-- copy map carries the column across. | ||
| 11 | +ALTER TABLE share_link ADD COLUMN password_hash TEXT; | ||
crates/in-core/src/lib.rsmodified+2 -1
| @@ -25,5 +25,6 @@ pub use config::{Config, ConfigError, OidcConfig}; | |||
| 25 | pub use live::{Change, Topic, next_seq}; | 25 | pub use live::{Change, Topic, next_seq}; |
| 26 | #[cfg(feature = "server")] | 26 | #[cfg(feature = "server")] |
| 27 | pub use store::{ | 27 | pub use store::{ |
| 28 | - ReconcileOptions, Result, Store, StoreError, TursoStore, hash_share_token, reconcile, | 28 | + ReconcileOptions, Result, Store, StoreError, TursoStore, hash_link_password, hash_share_token, |
| 29 | + link_password_matches, link_unlock_proof, reconcile, | ||
| 29 | }; | 30 | }; |
crates/in-core/src/store/mod.rsmodified+13 -3
| @@ -26,7 +26,9 @@ pub mod turso_store; | |||
| 26 | #[cfg(feature = "server")] | 26 | #[cfg(feature = "server")] |
| 27 | pub use reconcile::{ReconcileOptions, reconcile}; | 27 | pub use reconcile::{ReconcileOptions, reconcile}; |
| 28 | #[cfg(feature = "server")] | 28 | #[cfg(feature = "server")] |
| 29 | -pub use turso_store::{TursoStore, hash_share_token}; | 29 | +pub use turso_store::{ |
| 30 | + TursoStore, hash_link_password, hash_share_token, link_password_matches, link_unlock_proof, | ||
| 31 | +}; | ||
| 30 | 32 | ||
| 31 | /// What the store can fail with. A caller that needs to distinguish "no such | 33 | /// What the store can fail with. A caller that needs to distinguish "no such |
| 32 | /// row" from "someone else's row" gets [`StoreError::NotFound`] for the | 34 | /// row" from "someone else's row" gets [`StoreError::NotFound`] for the |
| @@ -216,7 +218,10 @@ impl ShareKind { | |||
| 216 | } | 218 | } |
| 217 | 219 | ||
| 218 | /// A public share link. The row holds only the token's hash; the plaintext | 220 | /// A public share link. The row holds only the token's hash; the plaintext |
| 219 | -/// is shown once at creation and never again. | 221 | +/// is shown once at creation and never again. An owner may also give the |
| 222 | +/// link a password: the row then keeps the password's Argon2id PHC string, | ||
| 223 | +/// and a visitor answers the gate once per browser — the proof lives in a | ||
| 224 | +/// cookie, never in a server-side session. | ||
| 220 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | 225 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 221 | pub struct ShareLink { | 226 | pub struct ShareLink { |
| 222 | pub id: String, | 227 | pub id: String, |
| @@ -228,6 +233,7 @@ pub struct ShareLink { | |||
| 228 | pub created_at: OffsetDateTime, | 233 | pub created_at: OffsetDateTime, |
| 229 | pub expires_at: Option<OffsetDateTime>, | 234 | pub expires_at: Option<OffsetDateTime>, |
| 230 | pub revoked_at: Option<OffsetDateTime>, | 235 | pub revoked_at: Option<OffsetDateTime>, |
| 236 | + pub password_hash: Option<String>, | ||
| 231 | } | 237 | } |
| 232 | 238 | ||
| 233 | impl ShareLink { | 239 | impl ShareLink { |
| @@ -528,7 +534,10 @@ pub trait Store: 'static + Send + Sync { | |||
| 528 | 534 | ||
| 529 | /// Creates a public link onto one file or folder. Returns the row and the | 535 | /// Creates a public link onto one file or folder. Returns the row and the |
| 530 | /// plaintext token — the only moment the token exists outside its hash. | 536 | /// plaintext token — the only moment the token exists outside its hash. |
| 531 | - /// A target of another owner is [`StoreError::CrossOwner`]. | 537 | + /// `password_hash` is stored as given: the caller hashes the password |
| 538 | + /// with [`hash_link_password`], because Argon2id is CPU-slow on | ||
| 539 | + /// purpose and only the caller knows whether the hash belongs off the | ||
| 540 | + /// async path. A target of another owner is [`StoreError::CrossOwner`]. | ||
| 532 | async fn create_share_link( | 541 | async fn create_share_link( |
| 533 | &self, | 542 | &self, |
| 534 | created_by: &str, | 543 | created_by: &str, |
| @@ -536,6 +545,7 @@ pub trait Store: 'static + Send + Sync { | |||
| 536 | target_id: &str, | 545 | target_id: &str, |
| 537 | can_download: bool, | 546 | can_download: bool, |
| 538 | expires_at: Option<OffsetDateTime>, | 547 | expires_at: Option<OffsetDateTime>, |
| 548 | + password_hash: Option<String>, | ||
| 539 | ) -> Result<CreatedLink>; | 549 | ) -> Result<CreatedLink>; |
| 540 | 550 | ||
| 541 | /// Revokes a link. The row stays, so a dead link reads as revoked rather | 551 | /// Revokes a link. The row stays, so a dead link reads as revoked rather |
crates/in-core/src/store/reconcile.rsmodified+25 -12
| @@ -207,7 +207,9 @@ struct TableMap { | |||
| 207 | /// `ui`, `theme` and `language`, and the file table one for | 207 | /// `ui`, `theme` and `language`, and the file table one for |
| 208 | /// `download_count`: a database old enough to predate a column starts on the | 208 | /// `download_count`: a database old enough to predate a column starts on the |
| 209 | /// schema's own default rather than on an empty string, which no writer | 209 | /// schema's own default rather than on an empty string, which no writer |
| 210 | -/// would ever store and no reader would ever honour. Tables the old database | 210 | +/// would ever store and no reader would ever honour. The share-link table |
| 211 | +/// carries `password_hash` the same way, backfilled with NULL — a link from | ||
| 212 | +/// before passwords opens like it always did. Tables the old database | ||
| 211 | /// predates entirely (today: `setting`) map column-for-column and are | 213 | /// predates entirely (today: `setting`) map column-for-column and are |
| 212 | /// skipped at copy time, starting empty. | 214 | /// skipped at copy time, starting empty. |
| 213 | fn build_maps( | 215 | fn build_maps( |
| @@ -215,6 +217,7 @@ fn build_maps( | |||
| 215 | old_has_theme: bool, | 217 | old_has_theme: bool, |
| 216 | old_has_language: bool, | 218 | old_has_language: bool, |
| 217 | old_has_download_count: bool, | 219 | old_has_download_count: bool, |
| 220 | + old_has_password_hash: bool, | ||
| 218 | ) -> Vec<TableMap> { | 221 | ) -> Vec<TableMap> { |
| 219 | vec![ | 222 | vec![ |
| 220 | TableMap { | 223 | TableMap { |
| @@ -285,17 +288,25 @@ fn build_maps( | |||
| 285 | }, | 288 | }, |
| 286 | TableMap { | 289 | TableMap { |
| 287 | name: "share_link", | 290 | name: "share_link", |
| 288 | - columns: old_cols(&[ | 291 | + columns: { |
| 289 | - "id", | 292 | + let mut columns = old_cols(&[ |
| 290 | - "token_hash", | 293 | + "id", |
| 291 | - "kind", | 294 | + "token_hash", |
| 292 | - "target_id", | 295 | + "kind", |
| 293 | - "created_by", | 296 | + "target_id", |
| 294 | - "can_download", | 297 | + "created_by", |
| 295 | - "created_at", | 298 | + "can_download", |
| 296 | - "expires_at", | 299 | + "created_at", |
| 297 | - "revoked_at", | 300 | + "expires_at", |
| 298 | - ]), | 301 | + "revoked_at", |
| 302 | + ]); | ||
| 303 | + columns.push(if old_has_password_hash { | ||
| 304 | + ("password_hash", "old.password_hash".into()) | ||
| 305 | + } else { | ||
| 306 | + ("password_hash", "NULL".into()) | ||
| 307 | + }); | ||
| 308 | + columns | ||
| 309 | + }, | ||
| 299 | }, | 310 | }, |
| 300 | TableMap { | 311 | TableMap { |
| 301 | name: "share_user", | 312 | name: "share_user", |
| @@ -412,11 +423,13 @@ async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) -> | |||
| 412 | let old_has_theme = old_has_column(old_conn, "user", "theme").await?; | 423 | let old_has_theme = old_has_column(old_conn, "user", "theme").await?; |
| 413 | let old_has_language = old_has_column(old_conn, "user", "language").await?; | 424 | let old_has_language = old_has_column(old_conn, "user", "language").await?; |
| 414 | let old_has_download_count = old_has_column(old_conn, "file", "download_count").await?; | 425 | let old_has_download_count = old_has_column(old_conn, "file", "download_count").await?; |
| 426 | + let old_has_password_hash = old_has_column(old_conn, "share_link", "password_hash").await?; | ||
| 415 | let maps = build_maps( | 427 | let maps = build_maps( |
| 416 | old_has_ui, | 428 | old_has_ui, |
| 417 | old_has_theme, | 429 | old_has_theme, |
| 418 | old_has_language, | 430 | old_has_language, |
| 419 | old_has_download_count, | 431 | old_has_download_count, |
| 432 | + old_has_password_hash, | ||
| 420 | ); | 433 | ); |
| 421 | validate_maps(new_conn, &maps).await?; | 434 | validate_maps(new_conn, &maps).await?; |
| 422 | 435 | ||
crates/in-core/src/store/schema.rsmodified+1 -0
| @@ -18,6 +18,7 @@ pub(crate) const MIGRATIONS: &[&str] = &[ | |||
| 18 | include_str!("../../migrations/0002_ui.sql"), | 18 | include_str!("../../migrations/0002_ui.sql"), |
| 19 | include_str!("../../migrations/0003_preferences.sql"), | 19 | include_str!("../../migrations/0003_preferences.sql"), |
| 20 | include_str!("../../migrations/0004_downloads_settings.sql"), | 20 | include_str!("../../migrations/0004_downloads_settings.sql"), |
| 21 | + include_str!("../../migrations/0005_link_password.sql"), | ||
| 21 | ]; | 22 | ]; |
| 22 | 23 | ||
| 23 | /// The whole declared schema — every migration applied in order — as one | 24 | /// The whole declared schema — every migration applied in order — as one |
crates/in-core/src/store/turso_store.rsmodified+64 -5
| @@ -38,8 +38,7 @@ const THUMB_SOURCE_CAP: u64 = 64 * 1024 * 1024; | |||
| 38 | const USER_COLUMNS: &str = "id, oidc_sub, email, display_name, admin, disabled, quota_bytes, used_bytes, ui, created_at, last_seen_at, theme, language"; | 38 | const USER_COLUMNS: &str = "id, oidc_sub, email, display_name, admin, disabled, quota_bytes, used_bytes, ui, created_at, last_seen_at, theme, language"; |
| 39 | const FOLDER_COLUMNS: &str = "id, owner_id, parent_id, name, created_at, deleted_at"; | 39 | const FOLDER_COLUMNS: &str = "id, owner_id, parent_id, name, created_at, deleted_at"; |
| 40 | const FILE_COLUMNS: &str = "id, owner_id, folder_id, name, mime, size_bytes, thumb_state, created_at, updated_at, deleted_at, download_count"; | 40 | const FILE_COLUMNS: &str = "id, owner_id, folder_id, name, mime, size_bytes, thumb_state, created_at, updated_at, deleted_at, download_count"; |
| 41 | -const LINK_COLUMNS: &str = | 41 | +const LINK_COLUMNS: &str = "id, token_hash, kind, target_id, created_by, can_download, created_at, expires_at, revoked_at, password_hash"; |
| 42 | - "id, token_hash, kind, target_id, created_by, can_download, created_at, expires_at, revoked_at"; | ||
| 43 | const SESSION_COLUMNS: &str = "id, owner_id, folder_id, name, size_bytes, chunk_size, received_bytes, state, created_at, expires_at"; | 42 | const SESSION_COLUMNS: &str = "id, owner_id, folder_id, name, size_bytes, chunk_size, received_bytes, state, created_at, expires_at"; |
| 44 | 43 | ||
| 45 | pub struct TursoStore { | 44 | pub struct TursoStore { |
| @@ -544,6 +543,63 @@ pub fn hash_share_token(token: &str) -> String { | |||
| 544 | use sha2::Digest as _; | 543 | use sha2::Digest as _; |
| 545 | base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sha2::Sha256::digest(token.as_bytes())) | 544 | base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sha2::Sha256::digest(token.as_bytes())) |
| 546 | } | 545 | } |
| 546 | + | ||
| 547 | +/// Argon2id's cost, mirrored from im's account hasher: 19 MiB of memory, | ||
| 548 | +/// two iterations, one lane. Slow enough that a guess costs real work, | ||
| 549 | +/// cheap enough that unlocking a link never reads as an outage. | ||
| 550 | +pub const ARGON2_MEMORY_KIB: u32 = 19 * 1024; | ||
| 551 | +pub const ARGON2_ITERATIONS: u32 = 2; | ||
| 552 | +pub const ARGON2_PARALLELISM: u32 = 1; | ||
| 553 | + | ||
| 554 | +fn link_argon2() -> argon2::Argon2<'static> { | ||
| 555 | + let params = argon2::Params::new( | ||
| 556 | + ARGON2_MEMORY_KIB, | ||
| 557 | + ARGON2_ITERATIONS, | ||
| 558 | + ARGON2_PARALLELISM, | ||
| 559 | + None, | ||
| 560 | + ) | ||
| 561 | + .expect("argon2 parameters are constants and are in range"); | ||
| 562 | + argon2::Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, params) | ||
| 563 | +} | ||
| 564 | + | ||
| 565 | +/// Hashes a link password into a PHC string, salt included. The parameters | ||
| 566 | +/// ride in the string itself, so raising the cost later does not lock | ||
| 567 | +/// holders of the link out. | ||
| 568 | +/// | ||
| 569 | +/// CPU-slow on purpose: the caller owns the async boundary and runs this | ||
| 570 | +/// under `tokio::task::spawn_blocking`. | ||
| 571 | +pub fn hash_link_password(password: &str) -> Result<String> { | ||
| 572 | + use argon2::password_hash::{PasswordHasher, SaltString, rand_core::OsRng}; | ||
| 573 | + let salt = SaltString::generate(&mut OsRng); | ||
| 574 | + link_argon2() | ||
| 575 | + .hash_password(password.as_bytes(), &salt) | ||
| 576 | + .map(|hash| hash.to_string()) | ||
| 577 | + .map_err(|e| StoreError::Backend(format!("password hashing failed: {e}"))) | ||
| 578 | +} | ||
| 579 | + | ||
| 580 | +/// Checks a candidate password against a stored PHC string. A malformed | ||
| 581 | +/// hash answers false — a gate that could panic would be a gate an attacker | ||
| 582 | +/// could aim. | ||
| 583 | +pub fn link_password_matches(phc: &str, candidate: &str) -> bool { | ||
| 584 | + use argon2::password_hash::{PasswordHash, PasswordVerifier}; | ||
| 585 | + match PasswordHash::new(phc) { | ||
| 586 | + Ok(parsed) => link_argon2() | ||
| 587 | + .verify_password(candidate.as_bytes(), &parsed) | ||
| 588 | + .is_ok(), | ||
| 589 | + Err(_) => false, | ||
| 590 | + } | ||
| 591 | +} | ||
| 592 | + | ||
| 593 | +/// The unlock proof a visitor's browser carries as `in_link_{id}`: the | ||
| 594 | +/// token and the stored hash bound together, so a proof stolen from one | ||
| 595 | +/// link is worthless on another and a re-keyed password voids every cookie | ||
| 596 | +/// minted before. Same encode as [`hash_share_token`]. | ||
| 597 | +pub fn link_unlock_proof(token: &str, password_hash: &str) -> String { | ||
| 598 | + use base64::Engine as _; | ||
| 599 | + use sha2::Digest as _; | ||
| 600 | + let bound = format!("{token}:{password_hash}"); | ||
| 601 | + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sha2::Sha256::digest(bound.as_bytes())) | ||
| 602 | +} | ||
| 547 | /// zero-byte upload has no chunks; its finish assembles the empty file. | 603 | /// zero-byte upload has no chunks; its finish assembles the empty file. |
| 548 | fn chunk_count(size_bytes: u64) -> u64 { | 604 | fn chunk_count(size_bytes: u64) -> u64 { |
| 549 | if size_bytes == 0 { | 605 | if size_bytes == 0 { |
| @@ -807,6 +863,7 @@ fn link_from(row: &Row) -> Result<ShareLink> { | |||
| 807 | created_at: parse_stamp(&text(row, 6)?)?, | 863 | created_at: parse_stamp(&text(row, 6)?)?, |
| 808 | expires_at: opt_stamp(row, 7)?, | 864 | expires_at: opt_stamp(row, 7)?, |
| 809 | revoked_at: opt_stamp(row, 8)?, | 865 | revoked_at: opt_stamp(row, 8)?, |
| 866 | + password_hash: opt_text(row, 9)?, | ||
| 810 | }) | 867 | }) |
| 811 | } | 868 | } |
| 812 | 869 | ||
| @@ -1951,6 +2008,7 @@ impl Store for TursoStore { | |||
| 1951 | target_id: &str, | 2008 | target_id: &str, |
| 1952 | can_download: bool, | 2009 | can_download: bool, |
| 1953 | expires_at: Option<OffsetDateTime>, | 2010 | expires_at: Option<OffsetDateTime>, |
| 2011 | + password_hash: Option<String>, | ||
| 1954 | ) -> Result<CreatedLink> { | 2012 | ) -> Result<CreatedLink> { |
| 1955 | // The sharer must own a live target: a stranger's, a missing, or a | 2013 | // The sharer must own a live target: a stranger's, a missing, or a |
| 1956 | // trashed target refuses before any token exists to leak. | 2014 | // trashed target refuses before any token exists to leak. |
| @@ -1967,8 +2025,8 @@ impl Store for TursoStore { | |||
| 1967 | let conn = self.conn.lock().await; | 2025 | let conn = self.conn.lock().await; |
| 1968 | conn.execute( | 2026 | conn.execute( |
| 1969 | "INSERT INTO share_link (id, token_hash, kind, target_id, created_by, \ | 2027 | "INSERT INTO share_link (id, token_hash, kind, target_id, created_by, \ |
| 1970 | - can_download, created_at, expires_at, revoked_at) \ | 2028 | + can_download, created_at, expires_at, revoked_at, password_hash) \ |
| 1971 | - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, NULL)", | 2029 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, NULL, ?9)", |
| 1972 | params![ | 2030 | params![ |
| 1973 | id.clone(), | 2031 | id.clone(), |
| 1974 | token_hash, | 2032 | token_hash, |
| @@ -1977,7 +2035,8 @@ impl Store for TursoStore { | |||
| 1977 | created_by, | 2035 | created_by, |
| 1978 | if can_download { 1 } else { 0 }, | 2036 | if can_download { 1 } else { 0 }, |
| 1979 | now, | 2037 | now, |
| 1980 | - expires | 2038 | + expires, |
| 2039 | + password_hash, | ||
| 1981 | ], | 2040 | ], |
| 1982 | ) | 2041 | ) |
| 1983 | .await | 2042 | .await |
crates/in-core/tests/store.rsmodified+156 -1
| @@ -636,7 +636,7 @@ async fn share_links_open_until_revoked_or_expired() { | |||
| 636 | 636 | ||
| 637 | let created = scratch | 637 | let created = scratch |
| 638 | .store | 638 | .store |
| 639 | - .create_share_link(&user.id, ShareKind::File, &file.id, true, None) | 639 | + .create_share_link(&user.id, ShareKind::File, &file.id, true, None, None) |
| 640 | .await | 640 | .await |
| 641 | .unwrap(); | 641 | .unwrap(); |
| 642 | // The token is shown once; the row keeps only the hash. | 642 | // The token is shown once; the row keeps only the hash. |
| @@ -669,6 +669,7 @@ async fn share_links_open_until_revoked_or_expired() { | |||
| 669 | &file.id, | 669 | &file.id, |
| 670 | false, | 670 | false, |
| 671 | Some(now - Duration::hours(1)), | 671 | Some(now - Duration::hours(1)), |
| 672 | + None, | ||
| 672 | ) | 673 | ) |
| 673 | .await | 674 | .await |
| 674 | .unwrap(); | 675 | .unwrap(); |
| @@ -677,6 +678,160 @@ async fn share_links_open_until_revoked_or_expired() { | |||
| 677 | assert_eq!(scratch.store.share_links(&user.id).await.unwrap().len(), 2); | 678 | assert_eq!(scratch.store.share_links(&user.id).await.unwrap().len(), 2); |
| 678 | } | 679 | } |
| 679 | 680 | ||
| 681 | +#[tokio::test] | ||
| 682 | +async fn a_password_link_round_trips_its_hash() { | ||
| 683 | + let scratch = Scratch::open().await; | ||
| 684 | + let user = alice(&scratch.store).await; | ||
| 685 | + let file = scratch | ||
| 686 | + .store | ||
| 687 | + .insert_file(&user.id, None, "locked", b"data") | ||
| 688 | + .await | ||
| 689 | + .unwrap(); | ||
| 690 | + let now = OffsetDateTime::now_utc(); | ||
| 691 | + | ||
| 692 | + let hash = in_core::hash_link_password("open sesame").unwrap(); | ||
| 693 | + let created = scratch | ||
| 694 | + .store | ||
| 695 | + .create_share_link( | ||
| 696 | + &user.id, | ||
| 697 | + ShareKind::File, | ||
| 698 | + &file.id, | ||
| 699 | + true, | ||
| 700 | + None, | ||
| 701 | + Some(hash.clone()), | ||
| 702 | + ) | ||
| 703 | + .await | ||
| 704 | + .unwrap(); | ||
| 705 | + | ||
| 706 | + // The hash is really on disk: a fresh database carries the column, and | ||
| 707 | + // the row reads back through a second connection the way it sits. | ||
| 708 | + let raw = raw_conn(&scratch).await; | ||
| 709 | + let mut rows = raw | ||
| 710 | + .query( | ||
| 711 | + "SELECT password_hash FROM share_link WHERE id = ?1", | ||
| 712 | + turso::params![created.link.id.as_str()], | ||
| 713 | + ) | ||
| 714 | + .await | ||
| 715 | + .unwrap(); | ||
| 716 | + let stored = rows.next().await.unwrap().unwrap(); | ||
| 717 | + assert_eq!(stored.get::<String>(0).unwrap(), hash); | ||
| 718 | + | ||
| 719 | + // Resolving hands the hash back, so the route can mint the proof | ||
| 720 | + // without a second read. | ||
| 721 | + let resolved = scratch | ||
| 722 | + .store | ||
| 723 | + .resolve_share_link(&created.link.token_hash, now) | ||
| 724 | + .await | ||
| 725 | + .unwrap() | ||
| 726 | + .unwrap(); | ||
| 727 | + assert_eq!(resolved.password_hash.as_deref(), Some(hash.as_str())); | ||
| 728 | + | ||
| 729 | + // The check answers the right password and refuses the rest — and a | ||
| 730 | + // malformed hash refuses without panicking, the way a gate must. | ||
| 731 | + assert!(in_core::link_password_matches(&hash, "open sesame")); | ||
| 732 | + assert!(!in_core::link_password_matches(&hash, "Open Sesame")); | ||
| 733 | + assert!(!in_core::link_password_matches(&hash, "")); | ||
| 734 | + assert!(!in_core::link_password_matches( | ||
| 735 | + "not a phc string", | ||
| 736 | + "open sesame" | ||
| 737 | + )); | ||
| 738 | + | ||
| 739 | + // The proof binds the token to the stored hash: same pair, same proof; | ||
| 740 | + // any other pair — another link's, or a re-keyed hash — answers | ||
| 741 | + // differently. | ||
| 742 | + assert_eq!( | ||
| 743 | + in_core::link_unlock_proof(&created.token, &hash), | ||
| 744 | + in_core::link_unlock_proof(&created.token, &hash) | ||
| 745 | + ); | ||
| 746 | + assert_ne!( | ||
| 747 | + in_core::link_unlock_proof(&created.token, &hash), | ||
| 748 | + in_core::link_unlock_proof("another-token", &hash) | ||
| 749 | + ); | ||
| 750 | +} | ||
| 751 | +#[tokio::test] | ||
| 752 | +async fn a_pre_password_link_reconciles_to_no_password_and_a_new_one_survives_reopen() { | ||
| 753 | + // A database built from 0001+0004 — the shape In ran with before links | ||
| 754 | + // could carry passwords — has a share_link table with no | ||
| 755 | + // `password_hash` column. Opening it with the current code reconciles | ||
| 756 | + // it onto the declared schema: the link row is carried across and wears | ||
| 757 | + // NULL, opening like it always did, and a password minted after the | ||
| 758 | + // rebuild survives the next boot whole. | ||
| 759 | + let dir = std::env::temp_dir().join(format!("in-test-{}", Ulid::new())); | ||
| 760 | + std::fs::create_dir_all(&dir).unwrap(); | ||
| 761 | + let path = dir.join("in.db").to_string_lossy().into_owned(); | ||
| 762 | + { | ||
| 763 | + let db = turso::Builder::new_local(&path).build().await.unwrap(); | ||
| 764 | + let conn = db.connect().unwrap(); | ||
| 765 | + conn.execute_batch(include_str!("../migrations/0001_init.sql")) | ||
| 766 | + .await | ||
| 767 | + .unwrap(); | ||
| 768 | + conn.execute_batch(include_str!("../migrations/0002_ui.sql")) | ||
| 769 | + .await | ||
| 770 | + .unwrap(); | ||
| 771 | + conn.execute_batch(include_str!("../migrations/0003_preferences.sql")) | ||
| 772 | + .await | ||
| 773 | + .unwrap(); | ||
| 774 | + conn.execute_batch(include_str!("../migrations/0004_downloads_settings.sql")) | ||
| 775 | + .await | ||
| 776 | + .unwrap(); | ||
| 777 | + conn.execute( | ||
| 778 | + "INSERT INTO user (id, oidc_sub, email, display_name, admin, disabled, \ | ||
| 779 | + quota_bytes, used_bytes, created_at, last_seen_at) \ | ||
| 780 | + VALUES ('u-old', 'sub-old', 'old@example.com', 'Old', 1, 0, 100, 0, \ | ||
| 781 | + '2026-08-01T00:00:00Z', '2026-08-01T00:00:00Z')", | ||
| 782 | + (), | ||
| 783 | + ) | ||
| 784 | + .await | ||
| 785 | + .unwrap(); | ||
| 786 | + conn.execute( | ||
| 787 | + "INSERT INTO file (id, owner_id, folder_id, name, mime, size_bytes, \ | ||
| 788 | + thumb_state, created_at, updated_at, deleted_at) \ | ||
| 789 | + VALUES ('f-old', 'u-old', NULL, 'old.txt', 'text/plain', 3, 'none', \ | ||
| 790 | + '2026-08-01T00:00:00Z', '2026-08-01T00:00:00Z', NULL)", | ||
| 791 | + (), | ||
| 792 | + ) | ||
| 793 | + .await | ||
| 794 | + .unwrap(); | ||
| 795 | + conn.execute( | ||
| 796 | + "INSERT INTO share_link (id, token_hash, kind, target_id, created_by, \ | ||
| 797 | + can_download, created_at, expires_at, revoked_at) \ | ||
| 798 | + VALUES ('l-old', 'hash-old', 'file', 'f-old', 'u-old', 1, \ | ||
| 799 | + '2026-08-01T00:00:00Z', NULL, NULL)", | ||
| 800 | + (), | ||
| 801 | + ) | ||
| 802 | + .await | ||
| 803 | + .unwrap(); | ||
| 804 | + } | ||
| 805 | + let storage = dir.join("storage"); | ||
| 806 | + let store = TursoStore::open(&path, Some(&storage)).await.unwrap(); | ||
| 807 | + let links = store.share_links("u-old").await.unwrap(); | ||
| 808 | + assert_eq!(links.len(), 1); | ||
| 809 | + assert_eq!(links[0].id, "l-old"); | ||
| 810 | + assert_eq!(links[0].password_hash, None); | ||
| 811 | + | ||
| 812 | + // A password minted after the rebuild is an ordinary row: the next open | ||
| 813 | + // sees the declared shape, changes nothing, and the hash survives. | ||
| 814 | + let hash = in_core::hash_link_password("open sesame").unwrap(); | ||
| 815 | + store | ||
| 816 | + .create_share_link( | ||
| 817 | + "u-old", | ||
| 818 | + ShareKind::File, | ||
| 819 | + "f-old", | ||
| 820 | + true, | ||
| 821 | + None, | ||
| 822 | + Some(hash.clone()), | ||
| 823 | + ) | ||
| 824 | + .await | ||
| 825 | + .unwrap(); | ||
| 826 | + drop(store); | ||
| 827 | + let store = TursoStore::open(&path, Some(&storage)).await.unwrap(); | ||
| 828 | + let links = store.share_links("u-old").await.unwrap(); | ||
| 829 | + assert_eq!(links.len(), 2); | ||
| 830 | + let carried = links.iter().find(|link| link.id != "l-old").unwrap(); | ||
| 831 | + assert_eq!(carried.password_hash.as_deref(), Some(hash.as_str())); | ||
| 832 | + drop(store); | ||
| 833 | + let _ = std::fs::remove_dir_all(&dir); | ||
| 834 | +} | ||
| 680 | #[tokio::test] | 835 | #[tokio::test] |
| 681 | async fn per_person_shares_gate_visibility() { | 836 | async fn per_person_shares_gate_visibility() { |
| 682 | let scratch = Scratch::open().await; | 837 | let scratch = Scratch::open().await; |
crates/in-web/src/i18n.rsmodified+19 -0
| @@ -220,6 +220,13 @@ pub enum Key { | |||
| 220 | PublicLinkLabel, | 220 | PublicLinkLabel, |
| 221 | AnyoneWithLink, | 221 | AnyoneWithLink, |
| 222 | NotActive, | 222 | NotActive, |
| 223 | + // Link passwords (LinkPassword owns this block). | ||
| 224 | + PasswordOptional, | ||
| 225 | + PasswordProtected, | ||
| 226 | + PasswordPrompt, | ||
| 227 | + PasswordLabel, | ||
| 228 | + WrongPassword, | ||
| 229 | + Unlock, | ||
| 223 | } | 230 | } |
| 224 | 231 | ||
| 225 | pub fn t(lang: Lang, key: Key) -> &'static str { | 232 | pub fn t(lang: Lang, key: Key) -> &'static str { |
| @@ -366,6 +373,12 @@ pub fn t(lang: Lang, key: Key) -> &'static str { | |||
| 366 | CreateLink => "Create link", | 373 | CreateLink => "Create link", |
| 367 | ExpiresInDays => "Expires in days", | 374 | ExpiresInDays => "Expires in days", |
| 368 | NoShares => "Not shared with anyone yet.", | 375 | NoShares => "Not shared with anyone yet.", |
| 376 | + PasswordOptional => "Password (optional)", | ||
| 377 | + PasswordProtected => "This link is locked", | ||
| 378 | + PasswordPrompt => "Enter the password to open this link.", | ||
| 379 | + PasswordLabel => "Password", | ||
| 380 | + WrongPassword => "Wrong password.", | ||
| 381 | + Unlock => "Unlock", | ||
| 369 | }, | 382 | }, |
| 370 | Lang::Tr => match key { | 383 | Lang::Tr => match key { |
| 371 | Cancel => "Vazgeç", | 384 | Cancel => "Vazgeç", |
| @@ -508,6 +521,12 @@ pub fn t(lang: Lang, key: Key) -> &'static str { | |||
| 508 | NotActive => "Etkin değil", | 521 | NotActive => "Etkin değil", |
| 509 | ExpiresInDays => "Bitiş (gün)", | 522 | ExpiresInDays => "Bitiş (gün)", |
| 510 | NoShares => "Henüz kimseyle paylaşılmadı.", | 523 | NoShares => "Henüz kimseyle paylaşılmadı.", |
| 524 | + PasswordOptional => "Parola (isteğe bağlı)", | ||
| 525 | + PasswordProtected => "Bu bağlantı kilitli", | ||
| 526 | + PasswordPrompt => "Bağlantıyı açmak için parolayı girin.", | ||
| 527 | + PasswordLabel => "Parola", | ||
| 528 | + WrongPassword => "Parola hatalı.", | ||
| 529 | + Unlock => "Kilidi aç", | ||
| 511 | }, | 530 | }, |
| 512 | } | 531 | } |
| 513 | } | 532 | } |
crates/in-web/src/share.rsmodified+144 -1
| @@ -16,12 +16,13 @@ | |||
| 16 | //! a browser without script can copy it, and the drive and settings pages | 16 | //! a browser without script can copy it, and the drive and settings pages |
| 17 | //! render the copy-once banner off that pair. | 17 | //! render the copy-once banner off that pair. |
| 18 | 18 | ||
| 19 | -use in_core::hash_share_token; | ||
| 20 | use in_core::store::{File, ShareKind, Store, StoreError, ThumbState, User}; | 19 | use in_core::store::{File, ShareKind, Store, StoreError, ThumbState, User}; |
| 20 | +use in_core::{hash_link_password, hash_share_token, link_password_matches, link_unlock_proof}; | ||
| 21 | use serde::Deserialize; | 21 | use serde::Deserialize; |
| 22 | use time::OffsetDateTime; | 22 | use time::OffsetDateTime; |
| 23 | use topcoat::Result; | 23 | use topcoat::Result; |
| 24 | use topcoat::context::Cx; | 24 | use topcoat::context::Cx; |
| 25 | +use topcoat::cookie::{Cookies, cookie, cookies}; | ||
| 25 | use topcoat::router::content::Form; | 26 | use topcoat::router::content::Form; |
| 26 | use topcoat::router::request::{headers as request_headers, uri}; | 27 | use topcoat::router::request::{headers as request_headers, uri}; |
| 27 | use topcoat::router::response::IntoResponse; | 28 | use topcoat::router::response::IntoResponse; |
| @@ -134,6 +135,15 @@ fn parse_expiry(raw: Option<&str>) -> std::result::Result<Option<OffsetDateTime> | |||
| 134 | .ok_or(Refusal::Forbidden) | 135 | .ok_or(Refusal::Forbidden) |
| 135 | } | 136 | } |
| 136 | 137 | ||
| 138 | +/// The link password off the form: absent, blank, or all whitespace is no | ||
| 139 | +/// password — the field is optional, and a blank string nobody typed is | ||
| 140 | +/// never a secret worth keeping. | ||
| 141 | +fn form_password(raw: Option<&str>) -> Option<String> { | ||
| 142 | + raw.map(str::trim) | ||
| 143 | + .filter(|password| !password.is_empty()) | ||
| 144 | + .map(str::to_string) | ||
| 145 | +} | ||
| 146 | + | ||
| 137 | /// The target the caller must own: present, untrashed, and theirs. Anything | 147 | /// The target the caller must own: present, untrashed, and theirs. Anything |
| 138 | /// else is not-found — a stranger learns nothing about whose it is. | 148 | /// else is not-found — a stranger learns nothing about whose it is. |
| 139 | async fn owned_target( | 149 | async fn owned_target( |
| @@ -196,6 +206,8 @@ struct CreateLinkForm { | |||
| 196 | can_download: Option<String>, | 206 | can_download: Option<String>, |
| 197 | #[serde(default)] | 207 | #[serde(default)] |
| 198 | expires_in_days: Option<String>, | 208 | expires_in_days: Option<String>, |
| 209 | + #[serde(default)] | ||
| 210 | + password: Option<String>, | ||
| 199 | } | 211 | } |
| 200 | 212 | ||
| 201 | /// Mints a bearer link. The token is shown once — in the redirect's | 213 | /// Mints a bearer link. The token is shown once — in the redirect's |
| @@ -218,6 +230,19 @@ async fn create_link(cx: &Cx, Form(input): Form<CreateLinkForm>) -> Redirect { | |||
| 218 | Ok(expires_at) => expires_at, | 230 | Ok(expires_at) => expires_at, |
| 219 | Err(refusal) => return redirect_back(cx, "/settings", "create", Some(refusal)), | 231 | Err(refusal) => return redirect_back(cx, "/settings", "create", Some(refusal)), |
| 220 | }; | 232 | }; |
| 233 | + // An optional password on the link: a trimmed empty field is no | ||
| 234 | + // password at all. Argon2id is CPU-slow on purpose, so the hash runs | ||
| 235 | + // off the async path — a hash this cheap would be a hash worth | ||
| 236 | + // guessing. | ||
| 237 | + let password_hash = match form_password(input.password.as_deref()) { | ||
| 238 | + Some(password) => { | ||
| 239 | + match tokio::task::spawn_blocking(move || hash_link_password(&password)).await { | ||
| 240 | + Ok(Ok(hash)) => Some(hash), | ||
| 241 | + _ => return redirect_back(cx, "/settings", "create", Some(Refusal::Unavailable)), | ||
| 242 | + } | ||
| 243 | + } | ||
| 244 | + None => None, | ||
| 245 | + }; | ||
| 221 | let created = app(cx) | 246 | let created = app(cx) |
| 222 | .store | 247 | .store |
| 223 | .create_share_link( | 248 | .create_share_link( |
| @@ -228,6 +253,7 @@ async fn create_link(cx: &Cx, Form(input): Form<CreateLinkForm>) -> Redirect { | |||
| 228 | // box posts `1`; nothing posted must never mint a download. | 253 | // box posts `1`; nothing posted must never mint a download. |
| 229 | parse_flag(input.can_download.as_deref(), false), | 254 | parse_flag(input.can_download.as_deref(), false), |
| 230 | expires_at, | 255 | expires_at, |
| 256 | + password_hash, | ||
| 231 | ) | 257 | ) |
| 232 | .await; | 258 | .await; |
| 233 | match created { | 259 | match created { |
| @@ -439,6 +465,19 @@ async fn shared_link(cx: &Cx) -> topcoat::Result<topcoat::router::response::Resp | |||
| 439 | let Some(link) = link else { | 465 | let Some(link) = link else { |
| 440 | return dead_link(cx).await.into_response(cx); | 466 | return dead_link(cx).await.into_response(cx); |
| 441 | }; | 467 | }; |
| 468 | + // A password-protected link answers nothing — card, bytes or thumbnail — | ||
| 469 | + // until this browser carries the unlock proof. One check up front gates | ||
| 470 | + // every branch below, which is the point: a gate the download route | ||
| 471 | + // forgot would not be a gate. | ||
| 472 | + if let Some(password_hash) = &link.password_hash { | ||
| 473 | + let proof = link_unlock_proof(token, password_hash); | ||
| 474 | + let presented = cookies(cx) | ||
| 475 | + .get(&link_cookie_name(&link.id)) | ||
| 476 | + .map(|cookie| cookie.value().to_string()); | ||
| 477 | + if presented.as_deref() != Some(proof.as_str()) { | ||
| 478 | + return password_gate(cx).await.into_response(cx); | ||
| 479 | + } | ||
| 480 | + } | ||
| 442 | let query = shared_query(cx); | 481 | let query = shared_query(cx); |
| 443 | match link.kind { | 482 | match link.kind { |
| 444 | ShareKind::File => { | 483 | ShareKind::File => { |
| @@ -530,6 +569,106 @@ async fn shared_link(cx: &Cx) -> topcoat::Result<topcoat::router::response::Resp | |||
| 530 | } | 569 | } |
| 531 | } | 570 | } |
| 532 | 571 | ||
| 572 | +/// The cookie a unlocked browser carries for one link, named for the link's | ||
| 573 | +/// own id: two protected links are two gates, not one. | ||
| 574 | +fn link_cookie_name(link_id: &str) -> String { | ||
| 575 | + format!("in_link_{link_id}") | ||
| 576 | +} | ||
| 577 | + | ||
| 578 | +/// The gate a password-protected link shows until the browser carries the | ||
| 579 | +/// proof. Same public chrome as the cards — no hint of what waits behind | ||
| 580 | +/// the gate, not even the file's name. | ||
| 581 | +async fn password_gate(cx: &Cx) -> Result { | ||
| 582 | + let language = lang(cx).await; | ||
| 583 | + let action = current_path(cx); | ||
| 584 | + let wrong = has_flag(uri(cx).query().unwrap_or(""), "wrong"); | ||
| 585 | + view! { | ||
| 586 | + cx => | ||
| 587 | + <main class="scaffold-note"> | ||
| 588 | + (wordmark(cx).await?) | ||
| 589 | + <h1 class="settings-title">(t(language, Key::PasswordProtected))</h1> | ||
| 590 | + <p class="field-note">(t(language, Key::PasswordPrompt))</p> | ||
| 591 | + if wrong { | ||
| 592 | + <p class="field-error" role="alert">(t(language, Key::WrongPassword))</p> | ||
| 593 | + } | ||
| 594 | + <form class="pop-row-form" method="post" action=(action)> | ||
| 595 | + <input class="field-input" type="password" name="password" required="" autocomplete="off" placeholder=(t(language, Key::PasswordLabel)) aria-label=(t(language, Key::PasswordLabel))> | ||
| 596 | + <button class="quiet" type="submit">(t(language, Key::Unlock))</button> | ||
| 597 | + </form> | ||
| 598 | + </main> | ||
| 599 | + } | ||
| 600 | +} | ||
| 601 | + | ||
| 602 | +#[derive(Deserialize)] | ||
| 603 | +struct UnlockForm { | ||
| 604 | + #[serde(default)] | ||
| 605 | + password: Option<String>, | ||
| 606 | +} | ||
| 607 | + | ||
| 608 | +/// Unlocks a password-protected link: the right password mints the proof | ||
| 609 | +/// cookie and the visitor is sent on to the page as if the gate had never | ||
| 610 | +/// been there; anything else is the gate again, the error riding `?wrong=1`. | ||
| 611 | +/// The whole surface answers a 303 either way, so the response says nothing | ||
| 612 | +/// about whether the guess was close. | ||
| 613 | +#[route(POST "/s/{token}")] | ||
| 614 | +async fn unlock_link( | ||
| 615 | + cx: &Cx, | ||
| 616 | + Form(input): Form<UnlockForm>, | ||
| 617 | +) -> topcoat::Result<topcoat::router::response::Response> { | ||
| 618 | + let token: &str = path_param::<Token>(cx); | ||
| 619 | + let store = app(cx).store; | ||
| 620 | + let now = OffsetDateTime::now_utc(); | ||
| 621 | + let link = store | ||
| 622 | + .resolve_share_link(&hash_share_token(token), now) | ||
| 623 | + .await | ||
| 624 | + .ok() | ||
| 625 | + .flatten(); | ||
| 626 | + let Some(link) = link else { | ||
| 627 | + return dead_link(cx).await.into_response(cx); | ||
| 628 | + }; | ||
| 629 | + let Some(password_hash) = link.password_hash else { | ||
| 630 | + // Nothing to unlock: the form has no business here. Back to the page. | ||
| 631 | + return ( | ||
| 632 | + StatusCode::SEE_OTHER, | ||
| 633 | + [(header::LOCATION, format!("/s/{token}"))], | ||
| 634 | + ) | ||
| 635 | + .into_response(cx); | ||
| 636 | + }; | ||
| 637 | + let candidate = input.password.unwrap_or_default(); | ||
| 638 | + // The proof needs the hash after the verify, so the verify gets a copy. | ||
| 639 | + let hash_for_verify = password_hash.clone(); | ||
| 640 | + let matches = | ||
| 641 | + tokio::task::spawn_blocking(move || link_password_matches(&hash_for_verify, &candidate)) | ||
| 642 | + .await | ||
| 643 | + .unwrap_or(false); | ||
| 644 | + if matches { | ||
| 645 | + let proof = link_unlock_proof(token, &password_hash); | ||
| 646 | + // Secure mirrors the session cookie: on when the identity provider | ||
| 647 | + // itself is reached over https, so a plain-http rehearsal stays | ||
| 648 | + // plain. | ||
| 649 | + let secure = app(cx).config.oidc.issuer.starts_with("https://"); | ||
| 650 | + let name = link_cookie_name(&link.id); | ||
| 651 | + cookies(cx).add(cookie! { | ||
| 652 | + name = proof; | ||
| 653 | + Path = "/s"; | ||
| 654 | + HttpOnly; | ||
| 655 | + SameSite = Lax; | ||
| 656 | + Secure = secure | ||
| 657 | + }); | ||
| 658 | + ( | ||
| 659 | + StatusCode::SEE_OTHER, | ||
| 660 | + [(header::LOCATION, format!("/s/{token}"))], | ||
| 661 | + ) | ||
| 662 | + .into_response(cx) | ||
| 663 | + } else { | ||
| 664 | + ( | ||
| 665 | + StatusCode::SEE_OTHER, | ||
| 666 | + [(header::LOCATION, format!("/s/{token}?wrong=1"))], | ||
| 667 | + ) | ||
| 668 | + .into_response(cx) | ||
| 669 | + } | ||
| 670 | +} | ||
| 671 | + | ||
| 533 | /// The bytes behind a public link. A view-only link answers the dead card | 672 | /// The bytes behind a public link. A view-only link answers the dead card |
| 534 | /// here — the same answer as a spent token — so the surface never says which | 673 | /// here — the same answer as a spent token — so the surface never says which |
| 535 | /// tokens exist. The body streams off disk through | 674 | /// tokens exist. The body streams off disk through |
| @@ -1241,6 +1380,7 @@ pub(crate) async fn share_modal( | |||
| 1241 | <option value="0">(t(language, Key::ViewOnly))</option> | 1380 | <option value="0">(t(language, Key::ViewOnly))</option> |
| 1242 | </select> | 1381 | </select> |
| 1243 | <input class="field-input share-expiry" type="number" name="expires_in_days" min="1" step="1" placeholder=(t(language, Key::ExpiresInDays)) aria-label=(t(language, Key::ExpiresInDays))> | 1382 | <input class="field-input share-expiry" type="number" name="expires_in_days" min="1" step="1" placeholder=(t(language, Key::ExpiresInDays)) aria-label=(t(language, Key::ExpiresInDays))> |
| 1383 | + <input class="field-input share-expiry" type="password" name="password" autocomplete="new-password" placeholder=(t(language, Key::PasswordOptional)) aria-label=(t(language, Key::PasswordOptional))> | ||
| 1244 | <button class="quiet" type="submit">(t(language, Key::CreateLink))</button> | 1384 | <button class="quiet" type="submit">(t(language, Key::CreateLink))</button> |
| 1245 | </form> | 1385 | </form> |
| 1246 | } | 1386 | } |
| @@ -1249,6 +1389,9 @@ pub(crate) async fn share_modal( | |||
| 1249 | <span class="member-name">(t(language, Key::AnyoneWithLink))</span> | 1389 | <span class="member-name">(t(language, Key::AnyoneWithLink))</span> |
| 1250 | <div class="spacer"></div> | 1390 | <div class="spacer"></div> |
| 1251 | <span class="field-note">(expiry_line(language, link.expires_at))</span> | 1391 | <span class="field-note">(expiry_line(language, link.expires_at))</span> |
| 1392 | + if link.password_hash.is_some() { | ||
| 1393 | + <span class="field-note">"▪ "(t(language, Key::PasswordLabel))</span> | ||
| 1394 | + } | ||
| 1252 | <span class="field-note">(access_chip(language, link.can_download))</span> | 1395 | <span class="field-note">(access_chip(language, link.can_download))</span> |
| 1253 | </div> | 1396 | </div> |
| 1254 | <div class="share-link-row"> | 1397 | <div class="share-link-row"> |
crates/in-web/tests/http.rsmodified+128 -1
| @@ -591,6 +591,7 @@ struct Answer { | |||
| 591 | status: StatusCode, | 591 | status: StatusCode, |
| 592 | body: String, | 592 | body: String, |
| 593 | location: Option<String>, | 593 | location: Option<String>, |
| 594 | + set_cookie: Option<String>, | ||
| 594 | } | 595 | } |
| 595 | 596 | ||
| 596 | impl Answer { | 597 | impl Answer { |
| @@ -601,10 +602,16 @@ impl Answer { | |||
| 601 | .get(header::LOCATION) | 602 | .get(header::LOCATION) |
| 602 | .and_then(|value| value.to_str().ok()) | 603 | .and_then(|value| value.to_str().ok()) |
| 603 | .map(str::to_string); | 604 | .map(str::to_string); |
| 605 | + let set_cookie = response | ||
| 606 | + .headers() | ||
| 607 | + .get(header::SET_COOKIE) | ||
| 608 | + .and_then(|value| value.to_str().ok()) | ||
| 609 | + .map(str::to_string); | ||
| 604 | let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap(); | 610 | let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap(); |
| 605 | Answer { | 611 | Answer { |
| 606 | status, | 612 | status, |
| 607 | location, | 613 | location, |
| 614 | + set_cookie, | ||
| 608 | body: String::from_utf8(bytes.to_vec()).unwrap(), | 615 | body: String::from_utf8(bytes.to_vec()).unwrap(), |
| 609 | } | 616 | } |
| 610 | } | 617 | } |
| @@ -1518,7 +1525,7 @@ async fn expired_link_is_dead() { | |||
| 1518 | let past = time::OffsetDateTime::now_utc() - time::Duration::days(1); | 1525 | let past = time::OffsetDateTime::now_utc() - time::Duration::days(1); |
| 1519 | let created = app | 1526 | let created = app |
| 1520 | .store | 1527 | .store |
| 1521 | - .create_share_link(&owner, ShareKind::File, &file, true, Some(past)) | 1528 | + .create_share_link(&owner, ShareKind::File, &file, true, Some(past), None) |
| 1522 | .await | 1529 | .await |
| 1523 | .unwrap(); | 1530 | .unwrap(); |
| 1524 | let page = app.get(&format!("/s/{}", created.token), None).await; | 1531 | let page = app.get(&format!("/s/{}", created.token), None).await; |
| @@ -1563,6 +1570,126 @@ async fn view_only_link_download_is_dead_card() { | |||
| 1563 | ); | 1570 | ); |
| 1564 | } | 1571 | } |
| 1565 | 1572 | ||
| 1573 | +/// A password-protected link gates everything — card, download bytes — | ||
| 1574 | +/// until the browser answers the gate once; the proof then lives in the | ||
| 1575 | +/// link's own cookie. A wrong password answers the gate with the error and | ||
| 1576 | +/// mints no cookie, a revoked link dead-ends even an unlocked browser, and | ||
| 1577 | +/// none of the gate pages ever name the file. | ||
| 1578 | +#[tokio::test] | ||
| 1579 | +async fn password_link_gates_until_unlocked() { | ||
| 1580 | + let app = TestApp::build().await; | ||
| 1581 | + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; | ||
| 1582 | + let owner = owner_of(&app, "sub-admin").await; | ||
| 1583 | + let file = file_id(&app, &owner, "private.txt", b"behind the gate").await; | ||
| 1584 | + let answer = app | ||
| 1585 | + .post( | ||
| 1586 | + "/api/share/link/create", | ||
| 1587 | + Some(&admin), | ||
| 1588 | + &[ | ||
| 1589 | + ("kind", "file"), | ||
| 1590 | + ("target_id", &file), | ||
| 1591 | + ("can_download", "1"), | ||
| 1592 | + ("password", "open sesame"), | ||
| 1593 | + ], | ||
| 1594 | + ) | ||
| 1595 | + .await; | ||
| 1596 | + assert!(answer.accepted(), "create refused: {:?}", answer.location); | ||
| 1597 | + let token = created_token(answer.location.as_deref().unwrap()); | ||
| 1598 | + let link = &app.store.share_links(&owner).await.unwrap()[0]; | ||
| 1599 | + assert!(link.password_hash.is_some()); | ||
| 1600 | + | ||
| 1601 | + // The gate: no cookie, no name, no bytes — on the card and on `?dl=1` | ||
| 1602 | + // both. | ||
| 1603 | + let gate = app.get(&format!("/s/{token}"), None).await; | ||
| 1604 | + assert_eq!(gate.status, StatusCode::OK, "{}", gate.text()); | ||
| 1605 | + assert!( | ||
| 1606 | + !gate.text().contains("private.txt"), | ||
| 1607 | + "gate leaked the file name: {}", | ||
| 1608 | + gate.text() | ||
| 1609 | + ); | ||
| 1610 | + assert!(gate.text().contains("type=\"password\""), "{}", gate.text()); | ||
| 1611 | + let gated_bytes = app.get(&format!("/s/{token}?dl=1"), None).await; | ||
| 1612 | + assert_eq!(gated_bytes.status, StatusCode::OK); | ||
| 1613 | + assert!( | ||
| 1614 | + !gated_bytes.text().contains("behind the gate"), | ||
| 1615 | + "gate leaked the bytes: {}", | ||
| 1616 | + gated_bytes.text() | ||
| 1617 | + ); | ||
| 1618 | + | ||
| 1619 | + // A wrong password: back to the gate with the error on the query, and | ||
| 1620 | + // no cookie minted. | ||
| 1621 | + let wrong = app | ||
| 1622 | + .post(&format!("/s/{token}"), None, &[("password", "wrong one")]) | ||
| 1623 | + .await; | ||
| 1624 | + assert_eq!(wrong.status, StatusCode::SEE_OTHER); | ||
| 1625 | + assert_eq!( | ||
| 1626 | + wrong.location.as_deref(), | ||
| 1627 | + Some(&format!("/s/{token}?wrong=1")[..]) | ||
| 1628 | + ); | ||
| 1629 | + assert!( | ||
| 1630 | + wrong.set_cookie.is_none(), | ||
| 1631 | + "a wrong password minted a cookie: {:?}", | ||
| 1632 | + wrong.set_cookie | ||
| 1633 | + ); | ||
| 1634 | + let wrong_gate = app.get(&format!("/s/{token}?wrong=1"), None).await; | ||
| 1635 | + assert_eq!(wrong_gate.status, StatusCode::OK); | ||
| 1636 | + assert!( | ||
| 1637 | + wrong_gate.text().contains("Wrong password."), | ||
| 1638 | + "the gate did not say what went wrong: {}", | ||
| 1639 | + wrong_gate.text() | ||
| 1640 | + ); | ||
| 1641 | + | ||
| 1642 | + // The right password: a 303 back to the page, carrying the proof cookie | ||
| 1643 | + // named for the link, scoped to /s, not marked Secure on a plain-http | ||
| 1644 | + // rehearsal. | ||
| 1645 | + let right = app | ||
| 1646 | + .post(&format!("/s/{token}"), None, &[("password", "open sesame")]) | ||
| 1647 | + .await; | ||
| 1648 | + assert_eq!(right.status, StatusCode::SEE_OTHER); | ||
| 1649 | + assert_eq!( | ||
| 1650 | + right.location.as_deref(), | ||
| 1651 | + Some(format!("/s/{token}").as_str()) | ||
| 1652 | + ); | ||
| 1653 | + let proof = in_core::link_unlock_proof(&token, link.password_hash.as_deref().unwrap()); | ||
| 1654 | + let cookie_pair = format!("in_link_{}={proof}", link.id); | ||
| 1655 | + let set_cookie = right.set_cookie.as_deref().expect("unlock set no cookie"); | ||
| 1656 | + assert!( | ||
| 1657 | + set_cookie.contains(&cookie_pair), | ||
| 1658 | + "cookie did not carry the proof: {set_cookie}" | ||
| 1659 | + ); | ||
| 1660 | + assert!(set_cookie.contains("Path=/s"), "{set_cookie}"); | ||
| 1661 | + assert!(set_cookie.contains("HttpOnly"), "{set_cookie}"); | ||
| 1662 | + assert!(set_cookie.contains("SameSite=Lax"), "{set_cookie}"); | ||
| 1663 | + assert!(!set_cookie.contains("Secure"), "{set_cookie}"); | ||
| 1664 | + | ||
| 1665 | + // The unlocked browser sees the card, and the download serves bytes. | ||
| 1666 | + let unlocked = app.get(&format!("/s/{token}"), Some(&cookie_pair)).await; | ||
| 1667 | + assert_eq!(unlocked.status, StatusCode::OK, "{}", unlocked.text()); | ||
| 1668 | + assert!( | ||
| 1669 | + unlocked.text().contains("private.txt"), | ||
| 1670 | + "unlocked card showed nothing: {}", | ||
| 1671 | + unlocked.text() | ||
| 1672 | + ); | ||
| 1673 | + let served = app | ||
| 1674 | + .get(&format!("/s/{token}?dl=1"), Some(&cookie_pair)) | ||
| 1675 | + .await; | ||
| 1676 | + assert_eq!(served.bytes, b"behind the gate"); | ||
| 1677 | + | ||
| 1678 | + // Revocation dead-ends even the unlocked browser. | ||
| 1679 | + let id = link.id.clone(); | ||
| 1680 | + let answer = app | ||
| 1681 | + .post("/api/share/link/revoke", Some(&admin), &[("id", &id)]) | ||
| 1682 | + .await; | ||
| 1683 | + assert!(answer.accepted(), "revoke refused: {:?}", answer.location); | ||
| 1684 | + let gone = app.get(&format!("/s/{token}"), Some(&cookie_pair)).await; | ||
| 1685 | + assert_eq!(gone.status, StatusCode::OK); | ||
| 1686 | + assert!( | ||
| 1687 | + gone.text().contains("no longer works"), | ||
| 1688 | + "revoked link showed: {}", | ||
| 1689 | + gone.text() | ||
| 1690 | + ); | ||
| 1691 | +} | ||
| 1692 | + | ||
| 1566 | /// An unchecked `can_download` box posts nothing at all, and nothing posted | 1693 | /// An unchecked `can_download` box posts nothing at all, and nothing posted |
| 1567 | /// must never mint a download: the absent flag reads view-only, the way an | 1694 | /// must never mint a download: the absent flag reads view-only, the way an |
| 1568 | /// explicitly refused one does — while the checked box still opens the bytes. | 1695 | /// explicitly refused one does — while the checked box still opens the bytes. |