diff --git a/crates/in-core/src/config.rs b/crates/in-core/src/config.rs index 7759ae8..0640b9e 100644 --- a/crates/in-core/src/config.rs +++ b/crates/in-core/src/config.rs @@ -360,22 +360,10 @@ impl Config { // like every key here. let base_url = value(toml.base_url); if let Some(base) = &base_url { - if !base.starts_with("http://") && !base.starts_with("https://") { - return Err(ConfigError::Invalid { - key: "base_url", - why: format!( - "{base:?} names no scheme — an origin like https://files.example.com is what links are built from" - ), - }); - } - if base.ends_with('/') { - return Err(ConfigError::Invalid { - key: "base_url", - why: format!( - "{base:?} ends in a slash — set the bare origin; In joins the /s/ path itself" - ), - }); - } + Config::validate_base_url(base).map_err(|why| ConfigError::Invalid { + key: "base_url", + why, + })?; } let oidc_toml = toml.oidc.ok_or(ConfigError::Missing("[oidc]"))?; @@ -472,6 +460,26 @@ fn listen_url_of(listen: &SocketAddr) -> String { } } +impl Config { + /// Whether a base URL is an origin a public link can be built on: an + /// `http` or `https` scheme and no trailing slash. Shared by the file's + /// own parse and the admin's server-address form, so a value the boot + /// refuses is refused by the form for exactly the same reason. + pub fn validate_base_url(value: &str) -> Result<(), String> { + if !value.starts_with("http://") && !value.starts_with("https://") { + return Err(format!( + "{value:?} names no scheme — an origin like https://files.example.com is what links are built from" + )); + } + if value.ends_with('/') { + return Err(format!( + "{value:?} ends in a slash — set the bare origin; In joins the /s/ path itself" + )); + } + Ok(()) + } +} + /// Adds the top-level keys the file does not mention, each with its own /// comment and the default already in effect. The file is how a reader learns /// what can be changed, so a key that is silently defaulted is a key nobody diff --git a/crates/in-web/src/drive.rs b/crates/in-web/src/drive.rs index 0b6da35..1050e93 100644 --- a/crates/in-web/src/drive.rs +++ b/crates/in-web/src/drive.rs @@ -25,7 +25,7 @@ use topcoat::view::view; use crate::i18n::{Key, lang, t}; use crate::layout::{NavPage, topbar}; -use crate::server::{Refusal, app, back_to, refusal_of, require_user}; +use crate::server::{Refusal, app, back_to, refusal_of, require_user, share_origin}; /// A [`StoreError`] in the drive's own words. Cross-owner reads and writes /// alike answer [`Refusal::NotFound`]: telling a stranger which ids exist is @@ -505,7 +505,7 @@ async fn drive(cx: &Cx) -> Result { // A link minted from this surface redirects back here with the plaintext // token on `?created=` — rendered once, like the settings page does. let created = created_token(uri(cx).query().unwrap_or("")); - let origin = app(cx).config.public_origin(); + let origin = share_origin(cx).await; let current_id = current .as_ref() diff --git a/crates/in-web/src/i18n.rs b/crates/in-web/src/i18n.rs index 6c7e8b9..859fd09 100644 --- a/crates/in-web/src/i18n.rs +++ b/crates/in-web/src/i18n.rs @@ -227,6 +227,11 @@ pub enum Key { PasswordLabel, WrongPassword, Unlock, + // Server address (SettingsPaging owns this block). + ServerAddress, + EffectiveOrigin, + BaseUrlLabel, + BaseUrlNote, } pub fn t(lang: Lang, key: Key) -> &'static str { @@ -379,6 +384,10 @@ pub fn t(lang: Lang, key: Key) -> &'static str { PasswordLabel => "Password", WrongPassword => "Wrong password.", Unlock => "Unlock", + ServerAddress => "Server address", + EffectiveOrigin => "Effective origin", + BaseUrlLabel => "Public base URL", + BaseUrlNote => "The origin share links carry: a saved value wins, an empty one falls back to the configured base_url, then the bind address.", }, Lang::Tr => match key { Cancel => "Vazgeç", @@ -527,6 +536,10 @@ pub fn t(lang: Lang, key: Key) -> &'static str { PasswordLabel => "Parola", WrongPassword => "Parola hatalı.", Unlock => "Kilidi aç", + ServerAddress => "Sunucu adresi", + EffectiveOrigin => "Etkin kök adres", + BaseUrlLabel => "Herkese açık kök adres", + BaseUrlNote => "Paylaşım bağlantılarının taşıdığı kök adres: kaydedilen değer önceliklidir, boş bırakılırsa yapılandırılmış base_url'e, sonra bağlanılan adrese dönülür.", }, } } diff --git a/crates/in-web/src/server.rs b/crates/in-web/src/server.rs index 144fc75..c0981ff 100644 --- a/crates/in-web/src/server.rs +++ b/crates/in-web/src/server.rs @@ -42,6 +42,18 @@ pub fn app(cx: &Cx) -> App { app_context::(cx).clone() } +/// The origin the public links carry: the `base_url` an admin saved on the +/// running install when one is set, else the config chain — the file's +/// `base_url`, else the address bound. Every public URL construction (the +/// share links and their copy-once banners) asks this; the settings +/// server-address panel is what edits the setting the lookup reads. +pub async fn share_origin(cx: &Cx) -> String { + match app(cx).store.get_setting("base_url").await { + Ok(Some(base)) if !base.trim().is_empty() => base.trim().to_string(), + _ => app(cx).config.public_origin(), + } +} + /// A stable-enough label for the client, for rate limiting. A proxy header is /// only trusted because In is meant to sit behind one; the address bucket is /// the limit that actually protects the login round-trip either way. @@ -219,6 +231,9 @@ pub enum Refusal { /// The admin's quota form named something unusable — unparseable, or a /// unit the form does not offer. BadLimit, + /// The admin's server-address form named something no public link can + /// be built on — no `http`/`https` scheme, or a trailing slash. + BadBaseUrl, } impl Refusal { @@ -242,6 +257,7 @@ impl Refusal { Refusal::BadTheme => "That is not a theme.".to_string(), Refusal::BadLanguage => "That is not a language.".to_string(), Refusal::BadLimit => "That limit is not usable.".to_string(), + Refusal::BadBaseUrl => "That address is not an origin links can be built on.".to_string(), } } @@ -267,6 +283,7 @@ impl Refusal { Refusal::BadTheme => "Bu bir tema değil.".to_string(), Refusal::BadLanguage => "Bu bir dil değil.".to_string(), Refusal::BadLimit => "Bu sınır kullanılamaz.".to_string(), + Refusal::BadBaseUrl => "Bu adres, bağlantı kurulabilecek bir kök adres değil.".to_string(), } } @@ -290,6 +307,7 @@ impl Refusal { "bad-theme" => Refusal::BadTheme, "bad-language" => Refusal::BadLanguage, "bad-limit" => Refusal::BadLimit, + "bad-base-url" => Refusal::BadBaseUrl, _ => return None, }) } @@ -317,6 +335,7 @@ impl Refusal { Refusal::BadTheme => "bad-theme", Refusal::BadLanguage => "bad-language", Refusal::BadLimit => "bad-limit", + Refusal::BadBaseUrl => "bad-base-url", } } } diff --git a/crates/in-web/src/settings.rs b/crates/in-web/src/settings.rs index cada358..218ab13 100644 --- a/crates/in-web/src/settings.rs +++ b/crates/in-web/src/settings.rs @@ -1,14 +1,17 @@ //! Settings: the reader's profile and quota, plus the admin's user panel. //! -//! `GET /settings` shows the profile im vouches for (name, address) with the -//! quota usage bar beside it, and the reader's own live share links with -//! their revoke buttons — including the copy-once banner after a creation -//! (`?created=` on the query, rendered once and never stored). -//! Admins additionally see every account with its quota and disabled flag in -//! the Everyone panel. `POST /api/settings/quota|disable` are admin-only: -//! the first sets a user's byte quota, the second disables or re-enables -//! them (a disabled account reads as signed-out everywhere, the im session -//! untouched, and disabling yourself is refused). +//! `GET /settings` renders one rail section at a time (`?section=`, the +//! profile when the pair is missing or unknown): the profile with the quota +//! usage bar; the reader's own live share links with their revoke buttons — +//! including the copy-once banner after a creation (`?created=` on +//! the query, rendered once and never stored); and, for an admin, the +//! Everyone panel of every account with its quota and disabled flag, plus +//! the server address the public links carry. `POST +//! /api/settings/quota|disable|base_url` are admin-only: the first sets a +//! user's byte quota, the second disables or re-enables them (a disabled +//! account reads as signed-out everywhere, the im session untouched, and +//! disabling yourself is refused), the third stores the origin share links +//! are built from. use in_core::store::{ShareKind, User}; use serde::Deserialize; @@ -21,7 +24,7 @@ use topcoat::view::view; use crate::i18n::{Key, lang, t}; use crate::layout::{NavPage, topbar}; -use crate::server::{Refusal, app, back_to, require_admin, require_user}; +use crate::server::{Refusal, app, back_to, require_admin, require_user, share_origin}; use crate::share::{refusal_banner, refusal_of}; /// Bytes in human units: `512 B`, `1.5 KiB`, `2.0 GiB`. One decimal past @@ -93,11 +96,13 @@ fn unit_bytes(amount: &str, unit: &str) -> Option { type Redirect = Result<(StatusCode, [(HeaderName, String); 1])>; -/// Back to settings, the refusal (if any) on the query — or `saved=` -/// when there was nothing to refuse, the way iz's `saved_or_refused` marks -/// a save the page should chip. -fn redirect_back(cx: &Cx, call: &str, refusal: Option) -> Redirect { - let back = back_to(cx, "/settings"); +/// Back to the posting page's section, the refusal (if any) on the query — +/// or `saved=` when there was nothing to refuse, the way iz's +/// `saved_or_refused` marks a save the page should chip. `nowhere` names +/// the section the call is answered on, for a post that arrives without a +/// `Referer` to go back to. +fn redirect_back(cx: &Cx, nowhere: &str, call: &str, refusal: Option) -> Redirect { + let back = back_to(cx, nowhere); let separator = if back.contains('?') { '&' } else { '?' }; let location = match refusal { Some(refusal) => format!("{back}{separator}refusal={}&on={call}", refusal.code()), @@ -122,7 +127,7 @@ struct QuotaForm { #[route(POST "/api/settings/quota")] async fn set_quota(cx: &Cx, Form(input): Form) -> Redirect { if let Err(refusal) = require_admin(cx).await { - return redirect_back(cx, "quota", Some(refusal)); + return redirect_back(cx, "/settings?section=everyone", "quota", Some(refusal)); } match unit_bytes(&input.quota, &input.quota_unit) { Some(quota_bytes) => match app(cx) @@ -130,10 +135,10 @@ async fn set_quota(cx: &Cx, Form(input): Form) -> Redirect { .set_user_quota(&input.user_id, quota_bytes) .await { - Ok(()) => redirect_back(cx, "quota", None), - Err(error) => redirect_back(cx, "quota", Some(refusal_of(error))), + Ok(()) => redirect_back(cx, "/settings?section=everyone", "quota", None), + Err(error) => redirect_back(cx, "/settings?section=everyone", "quota", Some(refusal_of(error))), }, - None => redirect_back(cx, "quota", Some(Refusal::BadLimit)), + None => redirect_back(cx, "/settings?section=everyone", "quota", Some(Refusal::BadLimit)), } } @@ -150,10 +155,10 @@ struct DisableForm { async fn set_disabled(cx: &Cx, Form(input): Form) -> Redirect { let admin = match require_admin(cx).await { Ok(admin) => admin, - Err(refusal) => return redirect_back(cx, "disable", Some(refusal)), + Err(refusal) => return redirect_back(cx, "/settings?section=everyone", "disable", Some(refusal)), }; if input.user_id == admin.id { - return redirect_back(cx, "disable", Some(Refusal::Forbidden)); + return redirect_back(cx, "/settings?section=everyone", "disable", Some(Refusal::Forbidden)); } let disabled = match input.disabled.as_deref() { None => true, @@ -167,8 +172,8 @@ async fn set_disabled(cx: &Cx, Form(input): Form) -> Redirect { .set_user_disabled(&input.user_id, disabled) .await { - Ok(()) => redirect_back(cx, "disable", None), - Err(error) => redirect_back(cx, "disable", Some(refusal_of(error))), + Ok(()) => redirect_back(cx, "/settings?section=everyone", "disable", None), + Err(error) => redirect_back(cx, "/settings?section=everyone", "disable", Some(refusal_of(error))), } } @@ -196,29 +201,89 @@ const LANGUAGE_OPTIONS: [&str; 2] = ["en", "tr"]; async fn set_preferences(cx: &Cx, Form(input): Form) -> Redirect { let user = match require_user(cx).await { Ok(user) => user, - Err(refusal) => return redirect_back(cx, "preferences", Some(refusal)), + Err(refusal) => return redirect_back(cx, "/settings?section=profile", "preferences", Some(refusal)), }; if !UI_OPTIONS.contains(&input.ui.as_str()) { - return redirect_back(cx, "preferences", Some(Refusal::BadUi)); + return redirect_back(cx, "/settings?section=profile", "preferences", Some(Refusal::BadUi)); } if !THEME_OPTIONS.contains(&input.theme.as_str()) { - return redirect_back(cx, "preferences", Some(Refusal::BadTheme)); + return redirect_back(cx, "/settings?section=profile", "preferences", Some(Refusal::BadTheme)); } if !LANGUAGE_OPTIONS.contains(&input.language.as_str()) { - return redirect_back(cx, "preferences", Some(Refusal::BadLanguage)); + return redirect_back(cx, "/settings?section=profile", "preferences", Some(Refusal::BadLanguage)); } match app(cx) .store .set_preferences(&user.id, &input.theme, &input.language, &input.ui) .await { - Ok(()) => redirect_back(cx, "preferences", None), - Err(error) => redirect_back(cx, "preferences", Some(refusal_of(error))), + Ok(()) => redirect_back(cx, "/settings?section=profile", "preferences", None), + Err(error) => redirect_back(cx, "/settings?section=profile", "preferences", Some(refusal_of(error))), } } -/// The reader's profile and quota, their live share links, and — for an -/// admin — every account with its quota and kill switch. +#[derive(Deserialize)] +struct BaseUrlForm { + #[serde(default)] + base_url: String, +} + +/// Stores the origin the public links are built from, in the instance +/// `setting` store under `base_url`. While a non-empty value sits there it +/// is what [`crate::server::share_origin`] hands every link builder; +/// saving empty clears it, and the origin falls back to the config chain. +/// A value the boot would refuse is refused here for the same reason — +/// [`in_core::Config::validate_base_url`], the very check `parse` runs — +/// and the stored setting is left untouched. +#[route(POST "/api/settings/base_url")] +async fn set_base_url(cx: &Cx, Form(input): Form) -> Redirect { + if let Err(refusal) = require_admin(cx).await { + return redirect_back(cx, "/settings?section=server", "base_url", Some(refusal)); + } + let trimmed = input.base_url.trim().to_string(); + if !trimmed.is_empty() && in_core::Config::validate_base_url(&trimmed).is_err() { + return redirect_back(cx, "/settings?section=server", "base_url", Some(Refusal::BadBaseUrl)); + } + match app(cx).store.set_setting("base_url", &trimmed).await { + Ok(()) => redirect_back(cx, "/settings?section=server", "base_url", None), + Err(error) => redirect_back(cx, "/settings?section=server", "base_url", Some(refusal_of(error))), + } +} + +/// Which rail section the page renders. Only one is drawn at a time; an +/// admin-only value asked for by anyone else falls back to `Profile`, same +/// as a section name it does not recognize at all. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Section { + Profile, + Links, + Everyone, + Server, +} + +/// The class a rail link wears: `active` on the section it points to when +/// that is the one showing, plain otherwise. +fn rail_class(current: Section, target: Section) -> &'static str { + if current == target { + "settings-section-link active" + } else { + "settings-section-link" + } +} + +/// The value of one query pair, if present. +fn query_value(query: &str, key: &str) -> Option { + query.split('&').find_map(|pair| { + let (name, value) = pair.split_once('=')?; + (name == key).then(|| value.to_string()) + }) +} + +/// The settings screen, one rail section at a time: the reader's profile +/// and quota, their live share links, and — for an admin — every account +/// with its quota and kill switch, plus the server address the public +/// links are built from. An admin section asked for by anyone else renders +/// the profile, the way an unknown section name does. #[page("/settings")] async fn settings(cx: &Cx) -> Result { let user = match require_user(cx).await { @@ -238,131 +303,174 @@ async fn settings(cx: &Cx) -> Result { let store = app(cx).store; // Re-read the row so the quota bar never shows a stale number. let fresh = store.user(&user.id).await?.unwrap_or_else(|| user.clone()); - let links = store.share_links(&user.id).await?; - let live_links: Vec<_> = links - .iter() - .filter(|link| link.revoked_at.is_none()) - .collect(); - // The display name per live link's target: the row carries only the id. - // A missing or trashed target keeps its id — the grant row outlives the - // trash, and the panel still revokes it. Enrichment never fails the - // page: an unreadable target reads as its id, the way the shared list - // degrades per row. + let administers = fresh.admin; + let query = uri(cx).query().unwrap_or(""); + let section = match query_value(query, "section").as_deref() { + Some("links") => Section::Links, + Some("everyone") if administers => Section::Everyone, + Some("server") if administers => Section::Server, + _ => Section::Profile, + }; + let created = created_token(query); + // Only the section on show pays for its rows: the links panel names + // each live link's target, Everyone lists the accounts, and the server + // panel needs the origin — nothing else reads them. let mut link_names: Vec<(&in_core::store::ShareLink, String)> = Vec::new(); - for link in &live_links { - let name = match link.kind { - ShareKind::File => store - .file(&link.target_id) - .await - .ok() - .flatten() - .map(|file| file.name), - ShareKind::Folder => store - .folder(&link.target_id) - .await - .ok() - .flatten() - .map(|folder| folder.name), + let links = if section == Section::Links { + store.share_links(&user.id).await? + } else { + Vec::new() + }; + if section == Section::Links { + // The display name per live link's target: the row carries only + // the id. A missing or trashed target keeps its id — the grant row + // outlives the trash, and the panel still revokes it. Enrichment + // never fails the page: an unreadable target reads as its id, the + // way the shared list degrades per row. + for link in links.iter().filter(|link| link.revoked_at.is_none()) { + let name = match link.kind { + ShareKind::File => store + .file(&link.target_id) + .await + .ok() + .flatten() + .map(|file| file.name), + ShareKind::Folder => store + .folder(&link.target_id) + .await + .ok() + .flatten() + .map(|folder| folder.name), + } + .unwrap_or_else(|| link.target_id.clone()); + link_names.push((link, name)); } - .unwrap_or_else(|| link.target_id.clone()); - link_names.push((*link, name)); } - let users = if fresh.admin { + let users = if administers && section == Section::Everyone { store.users().await? } else { Vec::new() }; - let created = created_token(uri(cx).query().unwrap_or("")); - let origin = app(cx).config.public_origin(); + // The origin the copy-once banner and the server panel show: the + // stored setting when an admin set one, the config chain otherwise. + let origin = if matches!(section, Section::Links | Section::Server) { + share_origin(cx).await + } else { + String::new() + }; + // What the server form's field holds: the stored setting alone. An + // empty field is not an invented value — the effective line above it + // shows what an empty save falls back to. + let stored_base_url = if section == Section::Server { + store + .get_setting("base_url") + .await? + .filter(|value| !value.trim().is_empty()) + .unwrap_or_default() + } else { + String::new() + }; view! { cx => (topbar(cx, NavPage::Settings, &fresh, language).await?)
+

(t(language, Key::Settings))

- (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "preferences"]).await?) - if let Some(token) = created { + (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "preferences", "base_url"]).await?) + if section == Section::Profile {
-

(t(language, Key::LinkCreated))

+

(t(language, Key::Profile))

-

(t(language, Key::CopyLinkOnce))

- -
-
- } -
-
-

(t(language, Key::Profile))

-
-
- - -
- (t(language, Key::QuotaUsage)) - (format!("{} {} {}", human_bytes(fresh.used_bytes), t(language, Key::QuotaOf), human_bytes(fresh.quota_bytes))) -
-
-
-
-
- -
- +
+ (t(language, Key::QuotaUsage)) + (format!("{} {} {}", human_bytes(fresh.used_bytes), t(language, Key::QuotaOf), human_bytes(fresh.quota_bytes))) +
+
+
- -
-
-
-
-

(t(language, Key::ManageLinks))

-
-
- if live_links.is_empty() { -

(t(language, Key::NoLinks))

- } - for (link, target_name) in &link_names { -
- (format!("{} · {}", link.kind.as_str(), target_name.clone())) - (expiry_line(language, link.expires_at)) -
- (if link.can_download { t(language, Key::CanDownload) } else { t(language, Key::ViewOnly) }) -
- - -
+
+ + + +
+ +
+
+
+
+ } + if section == Section::Links { + if let Some(token) = created { +
+
+

(t(language, Key::LinkCreated))

- } -
- - if fresh.admin { +
+

(t(language, Key::CopyLinkOnce))

+ +
+ + } +
+
+

(t(language, Key::ManageLinks))

+
+
+ if link_names.is_empty() { +

(t(language, Key::NoLinks))

+ } + for (link, target_name) in &link_names { +
+ (format!("{} · {}", link.kind.as_str(), target_name.clone())) + (expiry_line(language, link.expires_at)) +
+ (if link.can_download { t(language, Key::CanDownload) } else { t(language, Key::ViewOnly) }) +
+ + +
+
+ } +
+
+ } + if section == Section::Everyone {

(t(language, Key::AdminPanel))

@@ -427,6 +535,29 @@ async fn settings(cx: &Cx) -> Result {
} + if section == Section::Server { +
+
+

(t(language, Key::ServerAddress))

+
+
+ +
+ +

(t(language, Key::BaseUrlNote))

+
+ +
+
+
+
+ } (crate::dropdown::dropdown_script(cx).await?) @@ -435,10 +566,7 @@ async fn settings(cx: &Cx) -> Result { /// The just-minted token off the redirect's `?created=` pair, if present. fn created_token(query: &str) -> Option { - query.split('&').find_map(|pair| { - let (name, value) = pair.split_once('=')?; - (name == "created" && !value.is_empty()).then(|| value.to_string()) - }) + query_value(query, "created").filter(|value| !value.is_empty()) } /// When the link stops opening, or never on its own. diff --git a/crates/in-web/src/share.rs b/crates/in-web/src/share.rs index c2f8575..93c4afc 100644 --- a/crates/in-web/src/share.rs +++ b/crates/in-web/src/share.rs @@ -34,7 +34,7 @@ use topcoat::view::view; use crate::files::{ViewerKind, entry_chip, media_player, media_player_script, viewer_kind}; use crate::i18n::{Key, Lang, lang, t}; use crate::layout::{NavPage, document_shell, topbar, wordmark}; -use crate::server::{Refusal, app, back_to, require_user}; +use crate::server::{Refusal, app, back_to, require_user, share_origin}; path_param!(token); path_param!(kind); @@ -219,18 +219,18 @@ struct CreateLinkForm { async fn create_link(cx: &Cx, Form(input): Form) -> Redirect { let user = match require_user(cx).await { Ok(user) => user, - Err(refusal) => return redirect_back(cx, "/settings", "create", Some(refusal)), + Err(refusal) => return redirect_back(cx, "/settings?section=links", "create", Some(refusal)), }; let Some(kind) = parse_kind(&input.kind) else { - return redirect_back(cx, "/settings", "create", Some(Refusal::NotFound)); + return redirect_back(cx, "/settings?section=links", "create", Some(Refusal::NotFound)); }; if let Err(refusal) = owned_target(app(cx).store.as_ref(), &user, kind, &input.target_id).await { - return redirect_back(cx, "/settings", "create", Some(refusal)); + return redirect_back(cx, "/settings?section=links", "create", Some(refusal)); } let expires_at = match parse_expiry(input.expires_in_days.as_deref()) { Ok(expires_at) => expires_at, - Err(refusal) => return redirect_back(cx, "/settings", "create", Some(refusal)), + Err(refusal) => return redirect_back(cx, "/settings?section=links", "create", Some(refusal)), }; // An optional password on the link: a trimmed empty field is no // password at all. Argon2id is CPU-slow on purpose, so the hash runs @@ -240,7 +240,7 @@ async fn create_link(cx: &Cx, Form(input): Form) -> Redirect { Some(password) => { match tokio::task::spawn_blocking(move || hash_link_password(&password)).await { Ok(Ok(hash)) => Some(hash), - _ => return redirect_back(cx, "/settings", "create", Some(Refusal::Unavailable)), + _ => return redirect_back(cx, "/settings?section=links", "create", Some(Refusal::Unavailable)), } } None => None, @@ -260,12 +260,12 @@ async fn create_link(cx: &Cx, Form(input): Form) -> Redirect { .await; match created { Ok(link) => { - let back = back_to(cx, "/settings"); + let back = back_to(cx, "/settings?section=links"); let separator = if back.contains('?') { '&' } else { '?' }; let location = format!("{back}{separator}created={}", link.token); Ok((StatusCode::SEE_OTHER, [(header::LOCATION, location)])) } - Err(error) => redirect_back(cx, "/settings", "create", Some(refusal_of(error))), + Err(error) => redirect_back(cx, "/settings?section=links", "create", Some(refusal_of(error))), } } @@ -280,7 +280,7 @@ struct RevokeLinkForm { async fn revoke_link(cx: &Cx, Form(input): Form) -> Redirect { let user = match require_user(cx).await { Ok(user) => user, - Err(refusal) => return redirect_back(cx, "/settings", "revoke", Some(refusal)), + Err(refusal) => return redirect_back(cx, "/settings?section=links", "revoke", Some(refusal)), }; let store = app(cx).store; let mine = store @@ -288,17 +288,17 @@ async fn revoke_link(cx: &Cx, Form(input): Form) -> Redirect { .await .map_err(|_| Refusal::Unavailable); let Ok(links) = mine else { - return redirect_back(cx, "/settings", "revoke", Some(Refusal::Unavailable)); + return redirect_back(cx, "/settings?section=links", "revoke", Some(Refusal::Unavailable)); }; if !links .iter() .any(|link| link.id == input.id && link.created_by == user.id) { - return redirect_back(cx, "/settings", "revoke", Some(Refusal::NotFound)); + return redirect_back(cx, "/settings?section=links", "revoke", Some(Refusal::NotFound)); } match store.revoke_share_link(&input.id).await { - Ok(()) => redirect_back(cx, "/settings", "revoke", None), - Err(error) => redirect_back(cx, "/settings", "revoke", Some(refusal_of(error))), + Ok(()) => redirect_back(cx, "/settings?section=links", "revoke", None), + Err(error) => redirect_back(cx, "/settings?section=links", "revoke", Some(refusal_of(error))), } } @@ -1350,9 +1350,10 @@ pub(crate) async fn share_modal( Err(_) => return Ok(None), }; let language = lang(cx).await; - // The links this modal shows carry the public origin — the configured - // `base_url` when the deployment names one, the bound address otherwise. - let origin = app(cx).config.public_origin(); + // The links this modal shows carry the public origin — the admin-set + // `base_url` setting when one is stored, else the config chain: the + // file's `base_url`, else the bound address. + let origin = share_origin(cx).await; let store = app(cx).store.clone(); // The owned, live target: present, untrashed, and theirs. Anything else // opens nothing — a stranger learns not even whose it is. diff --git a/crates/in-web/tests/http.rs b/crates/in-web/tests/http.rs index b681de6..9ac2b2e 100644 --- a/crates/in-web/tests/http.rs +++ b/crates/in-web/tests/http.rs @@ -1736,7 +1736,7 @@ async fn link_create_without_the_flag_is_view_only() { "share modal showed no name: {}", named.text() ); - let settings = app.get("/settings", Some(&admin)).await; + let settings = app.get("/settings?section=links", Some(&admin)).await; assert_eq!(settings.status, StatusCode::OK, "{}", settings.text()); assert!( settings.text().contains("file · plain.txt"), @@ -2407,6 +2407,14 @@ async fn settings_quota_and_disable_guards() { ) .await; assert!(answer.accepted(), "quota refused: {:?}", answer.location); + assert!( + answer + .location + .as_deref() + .is_some_and(|location| location.contains("section=everyone")), + "quota left the Everyone section: {:?}", + answer.location + ); assert_eq!( app.store.user(&bob_id).await.unwrap().unwrap().quota_bytes, 2147483648 @@ -2452,6 +2460,14 @@ async fn settings_quota_and_disable_guards() { ) .await; assert!(answer.accepted(), "disable refused: {:?}", answer.location); + assert!( + answer + .location + .as_deref() + .is_some_and(|location| location.contains("section=everyone")), + "disable left the Everyone section: {:?}", + answer.location + ); let page = app.get("/settings", Some(&bob)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!( @@ -2487,7 +2503,7 @@ async fn share_links_carry_the_configured_base_url() { // The banner the mint redirects back to. let page = app - .get(&format!("/settings?created={token}"), Some(&admin)) + .get(&format!("/settings?section=links&created={token}"), Some(&admin)) .await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!( @@ -2548,7 +2564,7 @@ async fn share_links_follow_the_bind_without_a_base_url() { // No `base_url`: the links say the address bound, as they always // have. let page = app - .get(&format!("/settings?created={token}"), Some(&admin)) + .get(&format!("/settings?section=links&created={token}"), Some(&admin)) .await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!( @@ -2559,6 +2575,289 @@ async fn share_links_follow_the_bind_without_a_base_url() { ); } +/// Mints one link over `file` and returns the plaintext token — and the +/// mint must land back on the links section that renders its banner. +async fn minted_token(app: &TestApp, cookie: &str, file: &str) -> String { + let answer = app + .post( + "/api/share/link/create", + Some(cookie), + &[("kind", "file"), ("target_id", file), ("can_download", "1")], + ) + .await; + assert!(answer.accepted(), "create refused: {:?}", answer.location); + assert!( + answer + .location + .as_deref() + .is_some_and(|location| location.contains("section=links")), + "create left the links section: {:?}", + answer.location + ); + created_token(answer.location.as_deref().unwrap()) +} + +/// The rail splits the page: every signed-in reader sees Profile and Share +/// links, an admin additionally Everyone and Server — and an admin URL a +/// non-admin pastes renders the profile, leaking no rows and no form. +#[tokio::test] +async fn settings_rail_gates_the_admin_sections() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await; + + // An admin's rail carries all four sections, and the default page is + // the profile alone. + let page = app.get("/settings", Some(&admin)).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + let body = page.text(); + for section in ["profile", "links", "everyone", "server"] { + assert!( + body.contains(&format!("/settings?section={section}")), + "admin rail lacks {section}: {body}" + ); + } + assert!(body.contains("name=\"ui\""), "{}", body); + assert!(!body.contains("member-table"), "{}", body); + assert!(!body.contains("/api/settings/base_url"), "{}", body); + + // A non-admin's rail stops at the reader sections. + let page = app.get("/settings", Some(&bob)).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + let body = page.text(); + assert!(body.contains("/settings?section=profile"), "{}", body); + assert!(body.contains("/settings?section=links"), "{}", body); + assert!(!body.contains("/settings?section=everyone"), "{}", body); + assert!(!body.contains("/settings?section=server"), "{}", body); + + // An admin URL pasted by a non-admin answers the profile: no account + // rows, no address form, no origin. + for asked in ["everyone", "server"] { + let page = app + .get(&format!("/settings?section={asked}"), Some(&bob)) + .await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + let body = page.text(); + assert!(body.contains("name=\"ui\""), "not the profile: {body}"); + assert!(!body.contains("member-table"), "{body}"); + assert!(!body.contains("/api/settings/base_url"), "{body}"); + } +} + +/// Each section renders alone on its own `?section=` pair — the profile's +/// preferences form, the links panel, the Everyone register, the server +/// address form — and never a row or form belonging to another. +#[tokio::test] +async fn admin_settings_sections_render_alone() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let owner = owner_of(&app, "sub-admin").await; + let file = file_id(&app, &owner, "notes.txt", b"hello in").await; + app.store + .create_share_link(&owner, ShareKind::File, &file, true, None, None) + .await + .unwrap(); + + let body = app.get("/settings?section=profile", Some(&admin)).await.text(); + assert!(body.contains("name=\"ui\""), "{body}"); + assert!(!body.contains("/api/share/link/revoke"), "{body}"); + assert!(!body.contains("member-table"), "{body}"); + assert!(!body.contains("/api/settings/base_url"), "{body}"); + + let body = app.get("/settings?section=links", Some(&admin)).await.text(); + assert!(body.contains("action=\"/api/share/link/revoke\""), "{body}"); + assert!(!body.contains("name=\"ui\""), "{body}"); + assert!(!body.contains("member-table"), "{body}"); + assert!(!body.contains("/api/settings/base_url"), "{body}"); + + let body = app.get("/settings?section=everyone", Some(&admin)).await.text(); + assert!(body.contains("member-table"), "{body}"); + assert!(body.contains("ada@in.test"), "{body}"); + assert!(!body.contains("name=\"ui\""), "{body}"); + assert!(!body.contains("/api/share/link/revoke"), "{body}"); + assert!(!body.contains("/api/settings/base_url"), "{body}"); + + let body = app.get("/settings?section=server", Some(&admin)).await.text(); + assert!(body.contains("action=\"/api/settings/base_url\""), "{body}"); + // The effective origin shows before anything is stored: the bind. + assert!(body.contains("http://127.0.0.1:7655"), "{body}"); + assert!(!body.contains("name=\"ui\""), "{body}"); + assert!(!body.contains("member-table"), "{body}"); + assert!(!body.contains("/api/share/link/revoke"), "{body}"); +} + +/// The admin's server-address form: a valid origin stores the `base_url` +/// setting and every newly minted link carries it; a value with no scheme +/// or a trailing slash is refused with the setting untouched; saving empty +/// clears it and the links fall back to the address bound. A non-admin is +/// refused before anything is read. +#[tokio::test] +async fn server_address_setting_drives_share_links() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await; + let owner = owner_of(&app, "sub-admin").await; + let file = file_id(&app, &owner, "notes.txt", b"hello in").await; + + let answer = app + .post( + "/api/settings/base_url", + Some(&bob), + &[("base_url", "https://bob.example.net")], + ) + .await; + assert!( + answer.refused("forbidden", "base_url"), + "{:?}", + answer.location + ); + assert_eq!(app.store.get_setting("base_url").await.unwrap(), None); + + let answer = app + .post( + "/api/settings/base_url", + Some(&admin), + &[("base_url", "https://files.example.com")], + ) + .await; + assert!(answer.accepted(), "save refused: {:?}", answer.location); + assert!( + answer.location.as_deref().is_some_and(|location| { + location.contains("section=server") && location.contains("saved=base_url") + }), + "{:?}", + answer.location + ); + assert_eq!( + app.store.get_setting("base_url").await.unwrap().as_deref(), + Some("https://files.example.com") + ); + let token = minted_token(&app, &admin, &file).await; + let page = app + .get( + &format!("/settings?section=links&created={token}"), + Some(&admin), + ) + .await; + assert!( + page + .text() + .contains(&format!("https://files.example.com/s/{token}")), + "{}", + page.text() + ); + + // No scheme, or a trailing slash: refused, the stored value untouched. + for bad in ["files.example.com", "https://files.example.com/"] { + let answer = app + .post("/api/settings/base_url", Some(&admin), &[("base_url", bad)]) + .await; + assert!( + answer.refused("bad-base-url", "base_url"), + "{bad}: {:?}", + answer.location + ); + } + assert_eq!( + app.store.get_setting("base_url").await.unwrap().as_deref(), + Some("https://files.example.com"), + "a refused save changed the setting" + ); + + // Empty clears: the links fall back to the address bound. + let answer = app + .post("/api/settings/base_url", Some(&admin), &[("base_url", "")]) + .await; + assert!(answer.accepted(), "clear refused: {:?}", answer.location); + assert_eq!( + app.store.get_setting("base_url").await.unwrap().as_deref(), + Some("") + ); + let token = minted_token(&app, &admin, &file).await; + let page = app + .get( + &format!("/settings?section=links&created={token}"), + Some(&admin), + ) + .await; + let body = page.text(); + assert!( + body.contains(&format!("http://127.0.0.1:7655/s/{token}")), + "{body}" + ); + assert!(!body.contains("https://files.example.com"), "{body}"); +} + +/// Clearing a stored origin falls back to the config's `base_url` when the +/// file sets one: the setting wins only while it is non-empty. +#[tokio::test] +async fn cleared_setting_falls_back_to_the_configured_base_url() { + let app = TestApp::build_with(Some("https://cfg.example.com")).await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let owner = owner_of(&app, "sub-admin").await; + let file = file_id(&app, &owner, "notes.txt", b"hello in").await; + + let answer = app + .post( + "/api/settings/base_url", + Some(&admin), + &[("base_url", "https://override.example.com")], + ) + .await; + assert!(answer.accepted(), "save refused: {:?}", answer.location); + let token = minted_token(&app, &admin, &file).await; + let page = app + .get( + &format!("/settings?section=links&created={token}"), + Some(&admin), + ) + .await; + assert!( + page + .text() + .contains(&format!("https://override.example.com/s/{token}")), + "{}", + page.text() + ); + + let answer = app + .post("/api/settings/base_url", Some(&admin), &[("base_url", "")]) + .await; + assert!(answer.accepted(), "clear refused: {:?}", answer.location); + let token = minted_token(&app, &admin, &file).await; + let page = app + .get( + &format!("/settings?section=links&created={token}"), + Some(&admin), + ) + .await; + let body = page.text(); + assert!( + body.contains(&format!("https://cfg.example.com/s/{token}")), + "{body}" + ); + assert!(!body.contains("override.example.com"), "{body}"); +} + +/// A revoke lands back on the links section that hosts its rows, even for +/// a post arriving without a `Referer` to return to. +#[tokio::test] +async fn revoke_redirects_land_on_the_links_section() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let answer = app + .post("/api/share/link/revoke", Some(&admin), &[("id", "never-real")]) + .await; + assert!( + answer + .location + .as_deref() + .is_some_and(|location| location.contains("/settings?section=links")), + "{:?}", + answer.location + ); +} + /// The revoke control is one inline quiet button at the row's end, like /// the modal's remove-access rows — not a full-width block of its own. #[tokio::test] @@ -2572,7 +2871,7 @@ async fn the_settings_revoke_button_sits_inline_in_its_row() { .await .unwrap(); - let body = app.get("/settings", Some(&admin)).await.text(); + let body = app.get("/settings?section=links", Some(&admin)).await.text(); let row_at = body .find("
") .expect("no share-link row"); @@ -3529,11 +3828,20 @@ async fn settings_panels_nest_inside_the_stage() { .find("
").expect("no main close"); - for marker in ["panel-head", "member-table", "name=\"ui\""] { + for marker in ["panel-head", "name=\"ui\""] { let at = body.find(marker).unwrap_or_else(|| panic!("no {marker}")); assert!(stage < at && at < close, "{marker} escapes the stage"); } - // The admin register is a table now: one named column per fact. + // The admin register keeps its named columns, on its own section. + let page = app.get("/settings?section=everyone", Some(&admin)).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + let body = page.text(); + let stage = body + .find("
").expect("no main close"); + let at = body.find("member-table").expect("no member-table"); + assert!(stage < at && at < close, "member-table escapes the stage"); assert!(body.contains("