The server plumbing crosses over
Browse files at this commitc321eeeef12269903b06a660cc80b872b070ff60Parent: 4deb90c- feat
- the server plumbing crosses over
5 changed files +677 -1
- Cargo.lock +2 -0
- crates/izlek-topcoat/Cargo.toml +4 -0
- crates/izlek-topcoat/src/lib.rs +1 -0
- crates/izlek-topcoat/src/main.rs +1 -1
- crates/izlek-topcoat/src/server.rs +669 -0
Cargo.lockmodified+2 -0
| @@ -2136,9 +2136,11 @@ version = "0.1.0" | |||
| 2136 | dependencies = [ | 2136 | dependencies = [ |
| 2137 | "async-trait", | 2137 | "async-trait", |
| 2138 | "grass", | 2138 | "grass", |
| 2139 | + "http", | ||
| 2139 | "izlek-core", | 2140 | "izlek-core", |
| 2140 | "lettre", | 2141 | "lettre", |
| 2141 | "serde", | 2142 | "serde", |
| 2143 | + "serde_json", | ||
| 2142 | "thiserror", | 2144 | "thiserror", |
| 2143 | "time", | 2145 | "time", |
| 2144 | "tokio", | 2146 | "tokio", |
crates/izlek-topcoat/Cargo.tomlmodified+4 -0
| @@ -20,6 +20,7 @@ topcoat = { version = "0.6.2", default-features = false, features = [ | |||
| 20 | ] } | 20 | ] } |
| 21 | izlek-core = { workspace = true, features = ["server"] } | 21 | izlek-core = { workspace = true, features = ["server"] } |
| 22 | serde.workspace = true | 22 | serde.workspace = true |
| 23 | +serde_json.workspace = true | ||
| 23 | time.workspace = true | 24 | time.workspace = true |
| 24 | thiserror.workspace = true | 25 | thiserror.workspace = true |
| 25 | tokio = { workspace = true } | 26 | tokio = { workspace = true } |
| @@ -37,3 +38,6 @@ lettre = { version = "0.11.23", default-features = false, features = [ | |||
| 37 | 38 | ||
| 38 | [build-dependencies] | 39 | [build-dependencies] |
| 39 | grass = "0.13" | 40 | grass = "0.13" |
| 41 | + | ||
| 42 | +[dev-dependencies] | ||
| 43 | +http = "1.5" | ||
crates/izlek-topcoat/src/lib.rsmodified+1 -0
| @@ -4,4 +4,5 @@ | |||
| 4 | #![recursion_limit = "256"] | 4 | #![recursion_limit = "256"] |
| 5 | 5 | ||
| 6 | pub mod layout; | 6 | pub mod layout; |
| 7 | +pub mod server; | ||
| 7 | pub mod smtp; | 8 | pub mod smtp; |
crates/izlek-topcoat/src/main.rsmodified+1 -1
| @@ -56,7 +56,7 @@ async fn main() { | |||
| 56 | .cookies() | 56 | .cookies() |
| 57 | .assets(AssetBundle::load().expect("failed to load the asset bundle")) | 57 | .assets(AssetBundle::load().expect("failed to load the asset bundle")) |
| 58 | .app_context(accounts) | 58 | .app_context(accounts) |
| 59 | - .app_context(engine) | 59 | + .app_context(izlek_topcoat::server::Mail::sending(engine.clone())) |
| 60 | .build(); | 60 | .build(); |
| 61 | 61 | ||
| 62 | topcoat::start(router).await.expect("server error"); | 62 | topcoat::start(router).await.expect("server error"); |
crates/izlek-topcoat/src/server.rsadded+669 -0
| @@ -0,0 +1,669 @@ | |||
| 1 | +//! Server-side plumbing for the auth surface: the session cookie, the person | ||
| 2 | +//! behind the current request, and the role guards. | ||
| 3 | +//! | ||
| 4 | +//! Every guard here is the real one. The UI hides what a role may not do, but | ||
| 5 | +//! the answer that matters is the one given in this module, on the server. | ||
| 6 | +//! | ||
| 7 | +//! Ported from `izlek-web/src/server.rs` and the `Refusal`/`call_id` pieces of | ||
| 8 | +//! `izlek-web/src/auth.rs`, onto topcoat's context/cookie/layer primitives. | ||
| 9 | + | ||
| 10 | +use izlek_core::accounts::{AccountError, Accounts}; | ||
| 11 | +use izlek_core::board::Transition; | ||
| 12 | +use izlek_core::mail::Engine; | ||
| 13 | +use izlek_core::store::{Freeing, User}; | ||
| 14 | +use serde::{Deserialize, Serialize}; | ||
| 15 | +use topcoat::context::{Cx, app_context, memoize, try_app_context}; | ||
| 16 | +use topcoat::cookie::{Cookie, Cookies, SameSite, cookie, cookies}; | ||
| 17 | +use topcoat::router::request::headers; | ||
| 18 | +use topcoat::router::{Body, HeaderValue, Next, StatusCode, header, response::Response, to_bytes}; | ||
| 19 | + | ||
| 20 | +/// The session cookie's name. One cookie, one browser, one session row. | ||
| 21 | +pub const SESSION_COOKIE: &str = "izlek_session"; | ||
| 22 | + | ||
| 23 | +/// The workspace's account service, put into context by the router. | ||
| 24 | +pub fn accounts(cx: &Cx) -> Accounts { | ||
| 25 | + app_context::<Accounts>(cx).clone() | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +/// The mail engine, or the fact that there is nobody to hand a crossing to. | ||
| 29 | +/// | ||
| 30 | +/// The running server always has an engine: the sender is workspace settings | ||
| 31 | +/// now, so it can appear at any moment and the engine reads it per send. The | ||
| 32 | +/// `None` is for tests, which drive the router without one and assert on the | ||
| 33 | +/// ledger rather than on a mail server. | ||
| 34 | +#[derive(Clone)] | ||
| 35 | +pub struct Mail(Option<std::sync::Arc<Engine>>); | ||
| 36 | + | ||
| 37 | +impl Mail { | ||
| 38 | + /// No engine at all. Crossings are recorded and nothing is handed on. | ||
| 39 | + pub fn silent() -> Self { | ||
| 40 | + Self(None) | ||
| 41 | + } | ||
| 42 | + | ||
| 43 | + pub fn sending(engine: std::sync::Arc<Engine>) -> Self { | ||
| 44 | + Self(Some(engine)) | ||
| 45 | + } | ||
| 46 | + | ||
| 47 | + /// Hands a committed crossing to the engine, off the request. | ||
| 48 | + /// | ||
| 49 | + /// The move is already written by the time this is called and the response | ||
| 50 | + /// does not wait for it: a card that took thirty seconds to drop because | ||
| 51 | + /// somebody's SMTP host was slow would be a board broken by its own mail | ||
| 52 | + /// feature. What the send is owed is in the ledger, so a process that dies | ||
| 53 | + /// mid-send loses nothing — the sweep picks it up. | ||
| 54 | + pub fn after(&self, transition: Transition) { | ||
| 55 | + let Some(engine) = self.0.clone() else { | ||
| 56 | + return; | ||
| 57 | + }; | ||
| 58 | + tokio::spawn(async move { | ||
| 59 | + let report = engine.on_transition(&transition).await; | ||
| 60 | + Self::log(report); | ||
| 61 | + }); | ||
| 62 | + } | ||
| 63 | + | ||
| 64 | + /// Kicks the engine to send an invite mail now rather than on the next | ||
| 65 | + /// sweep, off the request the same way `after` is. | ||
| 66 | + /// | ||
| 67 | + /// The invite is already on the ledger by the time this is called — this | ||
| 68 | + /// only makes the wait before it leaves as short as the request itself, | ||
| 69 | + /// so the admin does not sit wondering whether the mail is coming. | ||
| 70 | + pub fn after_invite(&self) { | ||
| 71 | + let Some(engine) = self.0.clone() else { | ||
| 72 | + return; | ||
| 73 | + }; | ||
| 74 | + tokio::spawn(async move { | ||
| 75 | + let report = engine | ||
| 76 | + .deliver_owed(time::OffsetDateTime::now_utc(), 8) | ||
| 77 | + .await; | ||
| 78 | + Self::log(report); | ||
| 79 | + }); | ||
| 80 | + } | ||
| 81 | + | ||
| 82 | + /// Hands a recorded activity to the engine, off the request, the same way | ||
| 83 | + /// `after` hands a transition. | ||
| 84 | + /// | ||
| 85 | + /// The activity row is already written by the time this is called; this | ||
| 86 | + /// rehydrates it and lets the engine decide whether any rule owes a mail. | ||
| 87 | + /// `store` is the same store the request already wrote through — the | ||
| 88 | + /// engine has no public handle back to it, so the caller carries it. | ||
| 89 | + pub fn after_activity(&self, store: std::sync::Arc<dyn izlek_core::store::Store>, activity_id: String) { | ||
| 90 | + let Some(engine) = self.0.clone() else { | ||
| 91 | + return; | ||
| 92 | + }; | ||
| 93 | + tokio::spawn(async move { | ||
| 94 | + let report = match store.event(&activity_id).await { | ||
| 95 | + Ok(Some(izlek_core::store::Event::Happened(ev))) => { | ||
| 96 | + match engine.on_activity(&ev).await { | ||
| 97 | + Ok(_) => { | ||
| 98 | + engine | ||
| 99 | + .deliver_owed(time::OffsetDateTime::now_utc(), 8) | ||
| 100 | + .await | ||
| 101 | + } | ||
| 102 | + Err(problem) => Err(problem), | ||
| 103 | + } | ||
| 104 | + } | ||
| 105 | + Ok(_) => return, | ||
| 106 | + Err(problem) => Err(problem), | ||
| 107 | + }; | ||
| 108 | + Self::log(report); | ||
| 109 | + }); | ||
| 110 | + } | ||
| 111 | + | ||
| 112 | + /// Hands a committed delete to the engine, off the request, the same way. | ||
| 113 | + /// | ||
| 114 | + /// A blocker being deleted frees the tasks that were waiting on it just as | ||
| 115 | + /// finishing it would, so the unblocked rule fires on both. The freeing is | ||
| 116 | + /// already written; this only reads it. | ||
| 117 | + pub fn after_freeing(&self, freeing: Freeing, freed: Vec<String>) { | ||
| 118 | + let Some(engine) = self.0.clone() else { | ||
| 119 | + return; | ||
| 120 | + }; | ||
| 121 | + tokio::spawn(async move { | ||
| 122 | + let report = engine.on_freeing(&freeing, &freed).await; | ||
| 123 | + Self::log(report); | ||
| 124 | + }); | ||
| 125 | + } | ||
| 126 | + | ||
| 127 | + /// Sends one test mail and waits for the answer, because the answer is the | ||
| 128 | + /// whole point of pressing the button. `None` means this process has no | ||
| 129 | + /// engine at all, which happens only in tests. | ||
| 130 | + pub async fn test(&self, to: &str) -> Option<Result<time::Duration, izlek_core::MailError>> { | ||
| 131 | + let engine = self.0.clone()?; | ||
| 132 | + Some(engine.send_test(to).await) | ||
| 133 | + } | ||
| 134 | + | ||
| 135 | + fn log(report: izlek_core::store::Result<izlek_core::mail::Report>) { | ||
| 136 | + match report { | ||
| 137 | + Ok(report) if report.sent + report.failed + report.abandoned > 0 => { | ||
| 138 | + println!( | ||
| 139 | + "izlek mail {} sent, {} to retry, {} given up on", | ||
| 140 | + report.sent, report.failed, report.abandoned | ||
| 141 | + ); | ||
| 142 | + } | ||
| 143 | + Ok(_) => {} | ||
| 144 | + Err(problem) => eprintln!("izlek mail the ledger could not be read: {problem}"), | ||
| 145 | + } | ||
| 146 | + } | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +/// The engine for this request, or a silent one when the router was built | ||
| 150 | +/// without an engine at all. | ||
| 151 | +pub fn mail(cx: &Cx) -> Mail { | ||
| 152 | + try_app_context::<Mail>(cx).cloned().unwrap_or_else(Mail::silent) | ||
| 153 | +} | ||
| 154 | + | ||
| 155 | +/// The application cookie jar, with the attributes every Izlek cookie wants. | ||
| 156 | +fn app_cookies(cx: &Cx) -> impl Cookies { | ||
| 157 | + cookies(cx) | ||
| 158 | + .default_secure(true) | ||
| 159 | + .default_http_only(true) | ||
| 160 | + .default_same_site(SameSite::Lax) | ||
| 161 | + .default_path("/") | ||
| 162 | +} | ||
| 163 | + | ||
| 164 | +/// The cookie value this request presented, if it presented one. | ||
| 165 | +pub fn presented_session(cx: &Cx) -> Option<String> { | ||
| 166 | + cookies(cx).get(SESSION_COOKIE).map(|c| c.value().to_string()) | ||
| 167 | +} | ||
| 168 | + | ||
| 169 | +/// A stable-enough label for the client, for rate limiting. A proxy header is | ||
| 170 | +/// only trusted because Izlek is meant to sit behind one; the address bucket is | ||
| 171 | +/// the limit that actually protects the Argon2 work either way. | ||
| 172 | +/// | ||
| 173 | +/// topcoat 0.6.2 exposes no peer address; x-forwarded-for or nothing. | ||
| 174 | +pub fn client_label(cx: &Cx) -> String { | ||
| 175 | + let Some(forwarded) = headers(cx).get("x-forwarded-for") else { | ||
| 176 | + return "unknown".to_string(); | ||
| 177 | + }; | ||
| 178 | + let Ok(raw) = forwarded.to_str() else { | ||
| 179 | + return "unknown".to_string(); | ||
| 180 | + }; | ||
| 181 | + match raw.split(',').next() { | ||
| 182 | + Some(first) if !first.trim().is_empty() => first.trim().to_string(), | ||
| 183 | + _ => "unknown".to_string(), | ||
| 184 | + } | ||
| 185 | +} | ||
| 186 | + | ||
| 187 | +/// Writes the session cookie. `HttpOnly` so script cannot read it, `Secure` so | ||
| 188 | +/// it never crosses plain HTTP, `SameSite=Lax` so another site's form cannot | ||
| 189 | +/// post with it. | ||
| 190 | +pub fn set_session_cookie(cx: &Cx, token: &str, lifetime: time::Duration) { | ||
| 191 | + app_cookies(cx).add(cookie! { | ||
| 192 | + SESSION_COOKIE = token.to_owned(); | ||
| 193 | + Path = "/"; | ||
| 194 | + Secure; | ||
| 195 | + HttpOnly; | ||
| 196 | + SameSite = Lax; | ||
| 197 | + MaxAge = lifetime | ||
| 198 | + }); | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +/// Removes the session cookie from this browser. The server-side revocation is | ||
| 202 | +/// what actually ends the session; this only tidies the client. | ||
| 203 | +pub fn clear_session_cookie(cx: &Cx) { | ||
| 204 | + app_cookies(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/").build()); | ||
| 205 | +} | ||
| 206 | + | ||
| 207 | +/// The person behind this request, or nobody, or the store failing to say. | ||
| 208 | +/// | ||
| 209 | +/// A store error is not "nobody" — a busy database mid-drag is a fact about | ||
| 210 | +/// the database, not about whether this browser is signed in, and a caller | ||
| 211 | +/// that folded the two together would send a signed-in person to a sign-in | ||
| 212 | +/// screen because a write elsewhere held a lock for a moment. | ||
| 213 | +#[memoize(as_ref)] | ||
| 214 | +pub async fn current_user(cx: &Cx) -> Result<Option<User>, AccountError> { | ||
| 215 | + let Some(presented) = presented_session(cx) else { | ||
| 216 | + return Ok(None); | ||
| 217 | + }; | ||
| 218 | + accounts(cx).authenticate(&presented).await | ||
| 219 | +} | ||
| 220 | + | ||
| 221 | +/// The person behind this request, or a refusal the caller can return as-is. | ||
| 222 | +/// | ||
| 223 | +/// A store error becomes `Refusal::Unavailable` — the same place every other | ||
| 224 | +/// account error already lands, via `refusal_for` below — rather than | ||
| 225 | +/// `SignInFirst`, which would tell a signed-in person to sign in again over | ||
| 226 | +/// what was only a database hiccup. | ||
| 227 | +pub async fn require_user(cx: &Cx) -> Result<User, Refusal> { | ||
| 228 | + match current_user(cx).await { | ||
| 229 | + Ok(Some(user)) => Ok(user.clone()), | ||
| 230 | + Ok(None) => Err(Refusal::SignInFirst), | ||
| 231 | + Err(error) => Err(refusal_for(error)), | ||
| 232 | + } | ||
| 233 | +} | ||
| 234 | + | ||
| 235 | +/// The admin behind this request. A member or a viewer is refused *here*, not | ||
| 236 | +/// merely hidden from in the UI. | ||
| 237 | +pub async fn require_admin(cx: &Cx) -> Result<User, Refusal> { | ||
| 238 | + let user = require_user(cx).await?; | ||
| 239 | + if user.role.can_administer() { | ||
| 240 | + Ok(user) | ||
| 241 | + } else { | ||
| 242 | + Err(Refusal::Forbidden) | ||
| 243 | + } | ||
| 244 | +} | ||
| 245 | + | ||
| 246 | +/// The person behind this request if they may change the board. | ||
| 247 | +pub async fn require_writer(cx: &Cx) -> Result<User, Refusal> { | ||
| 248 | + let user = require_user(cx).await?; | ||
| 249 | + if user.role.can_write_tasks() { | ||
| 250 | + Ok(user) | ||
| 251 | + } else { | ||
| 252 | + Err(Refusal::Forbidden) | ||
| 253 | + } | ||
| 254 | +} | ||
| 255 | + | ||
| 256 | +/// Shared by `From<AccountError>` and the `&AccountError` `current_user` | ||
| 257 | +/// hands back once memoized, so both paths land on the exact same wording. | ||
| 258 | +fn refusal_for(error: &AccountError) -> Refusal { | ||
| 259 | + match error { | ||
| 260 | + AccountError::Rejected => Refusal::Rejected, | ||
| 261 | + AccountError::RateLimited => Refusal::RateLimited, | ||
| 262 | + AccountError::Password(problem) => Refusal::Password(problem.to_string()), | ||
| 263 | + AccountError::Forbidden => Refusal::Forbidden, | ||
| 264 | + AccountError::AlreadyClaimed => Refusal::AlreadyClaimed, | ||
| 265 | + AccountError::AddressTaken => Refusal::AddressTaken, | ||
| 266 | + AccountError::Store(error) => { | ||
| 267 | + eprintln!("store error: {error}"); | ||
| 268 | + Refusal::Unavailable | ||
| 269 | + } | ||
| 270 | + AccountError::Auth(error) => { | ||
| 271 | + eprintln!("auth error: {error}"); | ||
| 272 | + Refusal::Unavailable | ||
| 273 | + } | ||
| 274 | + } | ||
| 275 | +} | ||
| 276 | + | ||
| 277 | +impl From<AccountError> for Refusal { | ||
| 278 | + fn from(error: AccountError) -> Self { | ||
| 279 | + refusal_for(&error) | ||
| 280 | + } | ||
| 281 | +} | ||
| 282 | + | ||
| 283 | +/// Everything a refused call is allowed to say. | ||
| 284 | +/// | ||
| 285 | +/// Ported from `izlek-web/src/auth.rs`; the auth pages that construct most of | ||
| 286 | +/// these variants land in a later slice, but the server plumbing above needs | ||
| 287 | +/// the type now. | ||
| 288 | +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] | ||
| 289 | +pub enum Refusal { | ||
| 290 | + /// Wrong address, wrong password, or no account at all — deliberately one | ||
| 291 | + /// answer for all three. | ||
| 292 | + Rejected, | ||
| 293 | + RateLimited, | ||
| 294 | + /// A password broke a stated rule. Only reachable once we know who the | ||
| 295 | + /// person is, so it gives nothing away. | ||
| 296 | + Password(String), | ||
| 297 | + Forbidden, | ||
| 298 | + SignInFirst, | ||
| 299 | + AlreadyClaimed, | ||
| 300 | + /// Admin-side wording, shown on the member list and nowhere public. | ||
| 301 | + AddressTaken, | ||
| 302 | + /// The link is spent, expired, or was never real. | ||
| 303 | + LinkNotUsable, | ||
| 304 | + /// A card with no title is not a card. | ||
| 305 | + EmptyTitle, | ||
| 306 | + /// A person with no name is not a person the board can show. | ||
| 307 | + EmptyName, | ||
| 308 | + /// A limit of nothing, or a limit wider than the disk should promise. | ||
| 309 | + BadLimit, | ||
| 310 | + /// Something in the allowed-types list is not a file extension. | ||
| 311 | + BadFileType, | ||
| 312 | + /// The sender panel was saved with a field it cannot work without, or with | ||
| 313 | + /// one that is not what it claims to be. The message names the field: this | ||
| 314 | + /// is a form somebody is filling in, not an attacker probing, and "that did | ||
| 315 | + /// not work" would send them round the panel guessing. | ||
| 316 | + BadSender(String), | ||
| 317 | + /// A comment with nothing in it. | ||
| 318 | + EmptyComment, | ||
| 319 | + /// The upload arrived without a file in it. | ||
| 320 | + NoFile, | ||
| 321 | + /// The bytes kept coming past what this workspace allows per file. | ||
| 322 | + FileTooBig, | ||
| 323 | + /// The name does not end in one of the extensions the admin allows. | ||
| 324 | + FileTypeNotAllowed, | ||
| 325 | + /// A rule with no subject line: the mail it sends would arrive blank. | ||
| 326 | + EmptySubject, | ||
| 327 | + /// The date field did not hold a date. | ||
| 328 | + BadDeadline, | ||
| 329 | + /// The link asked for would put a task behind itself. | ||
| 330 | + Cycle, | ||
| 331 | + /// The card was already moved out of the column this request thought it | ||
| 332 | + /// was in, by somebody else, while this person was deciding. | ||
| 333 | + MovedAlready, | ||
| 334 | + /// No such task — or none this account may see. Deliberately one answer for | ||
| 335 | + /// both. | ||
| 336 | + NotFound, | ||
| 337 | + Unavailable, | ||
| 338 | +} | ||
| 339 | + | ||
| 340 | +impl Refusal { | ||
| 341 | + /// The refusal as a short word, for the address bar. | ||
| 342 | + /// | ||
| 343 | + /// A browser without script never sees a call's return value: it posts the | ||
| 344 | + /// form, follows the redirect, and the page it lands on has to be told what | ||
| 345 | + /// happened. That telling goes through the query, so every refusal needs a | ||
| 346 | + /// name that survives a round trip through a URL. | ||
| 347 | + pub fn code(&self) -> &'static str { | ||
| 348 | + match self { | ||
| 349 | + Refusal::Rejected => "rejected", | ||
| 350 | + Refusal::RateLimited => "rate-limited", | ||
| 351 | + // The problem itself, not the wording, so the sentence is built | ||
| 352 | + // here on the way back rather than reflected out of the address. | ||
| 353 | + Refusal::Password(problem) => { | ||
| 354 | + if problem == "at least 10 characters" { | ||
| 355 | + "password-short" | ||
| 356 | + } else if problem == "not your address or your name" { | ||
| 357 | + "password-you" | ||
| 358 | + } else { | ||
| 359 | + "rejected" | ||
| 360 | + } | ||
| 361 | + } | ||
| 362 | + Refusal::Forbidden => "forbidden", | ||
| 363 | + Refusal::SignInFirst => "sign-in-first", | ||
| 364 | + Refusal::AlreadyClaimed => "already-claimed", | ||
| 365 | + Refusal::AddressTaken => "address-taken", | ||
| 366 | + Refusal::LinkNotUsable => "link-not-usable", | ||
| 367 | + Refusal::EmptyTitle => "empty-title", | ||
| 368 | + Refusal::EmptyName => "empty-name", | ||
| 369 | + Refusal::BadLimit => "bad-limit", | ||
| 370 | + Refusal::BadFileType => "bad-file-type", | ||
| 371 | + Refusal::BadSender(_) => "bad-sender", | ||
| 372 | + Refusal::EmptyComment => "empty-comment", | ||
| 373 | + Refusal::NoFile => "no-file", | ||
| 374 | + Refusal::FileTooBig => "file-too-big", | ||
| 375 | + Refusal::FileTypeNotAllowed => "file-type", | ||
| 376 | + Refusal::EmptySubject => "empty-subject", | ||
| 377 | + Refusal::BadDeadline => "bad-deadline", | ||
| 378 | + Refusal::Cycle => "cycle", | ||
| 379 | + Refusal::MovedAlready => "moved-already", | ||
| 380 | + Refusal::NotFound => "not-found", | ||
| 381 | + Refusal::Unavailable => "unavailable", | ||
| 382 | + } | ||
| 383 | + } | ||
| 384 | +} | ||
| 385 | + | ||
| 386 | +/// Which call a carried refusal belongs to. Two forms on one page must not both | ||
| 387 | +/// claim the same sentence, so the redirect names the call and this is the name: | ||
| 388 | +/// the last piece of the server function's path, with anything that is not a | ||
| 389 | +/// plain word dropped so it can only ever be compared, never rendered. | ||
| 390 | +pub fn call_id(path: &str) -> String { | ||
| 391 | + path.rsplit('/') | ||
| 392 | + .next() | ||
| 393 | + .unwrap_or(path) | ||
| 394 | + .chars() | ||
| 395 | + .filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-') | ||
| 396 | + .collect() | ||
| 397 | +} | ||
| 398 | + | ||
| 399 | +/// Puts a refusal on the redirect a browser without script follows. | ||
| 400 | +/// | ||
| 401 | +/// A hydrated page reads the call's return value straight off the action. A | ||
| 402 | +/// browser without script has no such thing: it posts the form, the server | ||
| 403 | +/// function handler answers with a redirect back to the page it came from, and | ||
| 404 | +/// the value — the whole refusal — sits in a body nobody will ever look at. | ||
| 405 | +/// The click then looks like nothing happening, which is the worst answer | ||
| 406 | +/// Izlek can give. | ||
| 407 | +/// | ||
| 408 | +/// So the refusal is copied onto the `Location`, as `?refusal=<code>&on=<call>`, | ||
| 409 | +/// and the page renders it from the query. This is one place rather than | ||
| 410 | +/// thirty-eight because the shape is the same for every refusing call, present | ||
| 411 | +/// and future: nothing here knows what any of them do. | ||
| 412 | +/// | ||
| 413 | +/// Requests carrying script are untouched — they are answered with the value | ||
| 414 | +/// itself and never see a redirect. | ||
| 415 | +/// | ||
| 416 | +/// Ported from axum's `middleware::from_fn` onto a topcoat `#[layer]`. topcoat's | ||
| 417 | +/// Post/Redirect/Get helper (`error::see_other`) answers with `303 See Other`, | ||
| 418 | +/// not the `302 Found` axum's server-function redirect used, so the status this | ||
| 419 | +/// checks for is `SEE_OTHER` — the guard's three conditions are otherwise | ||
| 420 | +/// unchanged. | ||
| 421 | +#[topcoat::router::layer("/api")] | ||
| 422 | +async fn carry_refusal_on_redirect(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result<Response> { | ||
| 423 | + // A form post from a browser asks for a page back. A server-function call | ||
| 424 | + // from the hydrated bundle does not. | ||
| 425 | + let wants_page = headers(cx) | ||
| 426 | + .get(header::ACCEPT) | ||
| 427 | + .and_then(|value| value.to_str().ok()) | ||
| 428 | + .is_some_and(|value| value.contains("text/html")); | ||
| 429 | + let called = call_id(topcoat::router::request::uri(cx).path()); | ||
| 430 | + let has_referer = headers(cx).contains_key(header::REFERER); | ||
| 431 | + let response = next.run(cx, body).await?; | ||
| 432 | + if !wants_page || !has_referer || response.status() != StatusCode::SEE_OTHER { | ||
| 433 | + return Ok(response); | ||
| 434 | + } | ||
| 435 | + | ||
| 436 | + let (mut parts, body) = response.into_parts(); | ||
| 437 | + // The body of one of these redirects is a serialised `Option<Refusal>` and | ||
| 438 | + // nothing else; the cap is there so a response that is something else | ||
| 439 | + // entirely cannot be read into memory whole. | ||
| 440 | + let Ok(bytes) = to_bytes(body, 64 * 1024).await else { | ||
| 441 | + return Ok(Response::from_parts(parts, Body::empty())); | ||
| 442 | + }; | ||
| 443 | + if let Ok(Some(refusal)) = serde_json::from_slice::<Option<Refusal>>(&bytes) | ||
| 444 | + && let Some(location) = parts.headers.get(header::LOCATION).and_then(|v| v.to_str().ok()) | ||
| 445 | + && let Some(carried) = carrying(location, refusal.code(), &called) | ||
| 446 | + && let Ok(value) = HeaderValue::from_str(&carried) | ||
| 447 | + { | ||
| 448 | + parts.headers.insert(header::LOCATION, value); | ||
| 449 | + } | ||
| 450 | + Ok(Response::from_parts(parts, Body::from(bytes))) | ||
| 451 | +} | ||
| 452 | + | ||
| 453 | +/// `location` with the refusal in its query. | ||
| 454 | +/// | ||
| 455 | +/// The redirect goes back to the page the form was posted from, and that page | ||
| 456 | +/// may already carry a query — `?task=DZ-01` is how a browser without script | ||
| 457 | +/// opens the modal at all — so the two pairs are merged in, and the pair from | ||
| 458 | +/// any earlier refusal is dropped rather than stacked on top of. | ||
| 459 | +fn carrying(location: &str, code: &str, called: &str) -> Option<String> { | ||
| 460 | + if called.is_empty() { | ||
| 461 | + return None; | ||
| 462 | + } | ||
| 463 | + // The Location we are rewriting came from the form post's Referer, and on a | ||
| 464 | + // cross-origin post the Referer is whatever the other site is. Sending the | ||
| 465 | + // browser back there would make Izlek an open redirect, so the address is | ||
| 466 | + // rebuilt from its path and query alone and anything that is not a plain | ||
| 467 | + // absolute path is answered with the board. | ||
| 468 | + let here = same_origin(location); | ||
| 469 | + let (path, query) = match here.split_once('?') { | ||
| 470 | + Some((path, query)) => (path, query), | ||
| 471 | + None => (here, ""), | ||
| 472 | + }; | ||
| 473 | + let mut pairs: Vec<String> = query | ||
| 474 | + .split('&') | ||
| 475 | + .filter(|pair| { | ||
| 476 | + !pair.is_empty() && !pair.starts_with("refusal=") && !pair.starts_with("on=") | ||
| 477 | + }) | ||
| 478 | + .map(str::to_string) | ||
| 479 | + .collect(); | ||
| 480 | + pairs.push(format!("refusal={code}&on={called}")); | ||
| 481 | + Some(format!("{path}?{}", pairs.join("&"))) | ||
| 482 | +} | ||
| 483 | + | ||
| 484 | +/// The path and query of `location`, with scheme and authority dropped. A | ||
| 485 | +/// protocol-relative address (`//elsewhere.example/`) is another host wearing a | ||
| 486 | +/// path's clothes, and a browser reads a backslash there as a slash, so both | ||
| 487 | +/// are answered with the board rather than trusted. | ||
| 488 | +fn same_origin(location: &str) -> &str { | ||
| 489 | + let rest = match location.split_once("://") { | ||
| 490 | + Some((_scheme, rest)) => match rest.find(['/', '?']) { | ||
| 491 | + Some(at) => &rest[at..], | ||
| 492 | + None => "/", | ||
| 493 | + }, | ||
| 494 | + None => location, | ||
| 495 | + }; | ||
| 496 | + let mut characters = rest.chars(); | ||
| 497 | + match (characters.next(), characters.next()) { | ||
| 498 | + (Some('/'), Some('/' | '\\')) => "/", | ||
| 499 | + (Some('/'), _) => rest, | ||
| 500 | + _ => "/", | ||
| 501 | + } | ||
| 502 | +} | ||
| 503 | + | ||
| 504 | +#[cfg(test)] | ||
| 505 | +mod refusal_redirect_tests { | ||
| 506 | + use super::carrying; | ||
| 507 | + | ||
| 508 | + #[test] | ||
| 509 | + fn a_bare_address_gains_a_query() { | ||
| 510 | + assert_eq!( | ||
| 511 | + carrying("http://izlek.sh/", "cycle", "link_tasks").as_deref(), | ||
| 512 | + Some("/?refusal=cycle&on=link_tasks") | ||
| 513 | + ); | ||
| 514 | + } | ||
| 515 | + | ||
| 516 | + #[test] | ||
| 517 | + fn an_open_modal_stays_open() { | ||
| 518 | + assert_eq!( | ||
| 519 | + carrying("http://izlek.sh/?task=DZ-01", "cycle", "link_tasks").as_deref(), | ||
| 520 | + Some("/?task=DZ-01&refusal=cycle&on=link_tasks") | ||
| 521 | + ); | ||
| 522 | + } | ||
| 523 | + | ||
| 524 | + #[test] | ||
| 525 | + fn a_second_refusal_replaces_the_first() { | ||
| 526 | + assert_eq!( | ||
| 527 | + carrying( | ||
| 528 | + "http://izlek.sh/?task=DZ-01&refusal=cycle&on=link_tasks", | ||
| 529 | + "not-found", | ||
| 530 | + "link_tasks" | ||
| 531 | + ) | ||
| 532 | + .as_deref(), | ||
| 533 | + Some("/?task=DZ-01&refusal=not-found&on=link_tasks") | ||
| 534 | + ); | ||
| 535 | + } | ||
| 536 | + | ||
| 537 | + // The Referer of a cross-origin post is the other site's address, and it | ||
| 538 | + // reaches this function as the Location. Izlek answers on its own ground or | ||
| 539 | + // not at all. | ||
| 540 | + #[test] | ||
| 541 | + fn another_site_cannot_be_redirected_to() { | ||
| 542 | + for elsewhere in [ | ||
| 543 | + "https://elsewhere.example", | ||
| 544 | + "//elsewhere.example/steal", | ||
| 545 | + "/\\elsewhere.example/steal", | ||
| 546 | + "javascript:alert(1)", | ||
| 547 | + "", | ||
| 548 | + ] { | ||
| 549 | + assert_eq!( | ||
| 550 | + carrying(elsewhere, "cycle", "link_tasks").as_deref(), | ||
| 551 | + Some("/?refusal=cycle&on=link_tasks"), | ||
| 552 | + "{elsewhere} was not brought home" | ||
| 553 | + ); | ||
| 554 | + } | ||
| 555 | + // An address with a path keeps the path — it is read as a path on this | ||
| 556 | + // site, which is the point: whatever the Referer claimed, the browser | ||
| 557 | + // is sent somewhere on Izlek. | ||
| 558 | + let carried = carrying( | ||
| 559 | + "http://elsewhere.example/steal?task=DZ-01", | ||
| 560 | + "cycle", | ||
| 561 | + "link_tasks", | ||
| 562 | + ); | ||
| 563 | + assert_eq!( | ||
| 564 | + carried.as_deref(), | ||
| 565 | + Some("/steal?task=DZ-01&refusal=cycle&on=link_tasks") | ||
| 566 | + ); | ||
| 567 | + } | ||
| 568 | + | ||
| 569 | + #[test] | ||
| 570 | + fn a_path_on_this_site_is_kept() { | ||
| 571 | + assert_eq!( | ||
| 572 | + carrying("/board?task=DZ-01", "cycle", "link_tasks").as_deref(), | ||
| 573 | + Some("/board?task=DZ-01&refusal=cycle&on=link_tasks") | ||
| 574 | + ); | ||
| 575 | + } | ||
| 576 | + | ||
| 577 | + #[test] | ||
| 578 | + fn a_call_with_no_name_carries_nothing() { | ||
| 579 | + assert_eq!(carrying("http://izlek.sh/", "cycle", ""), None); | ||
| 580 | + } | ||
| 581 | +} | ||
| 582 | + | ||
| 583 | +#[cfg(test)] | ||
| 584 | +mod call_id_tests { | ||
| 585 | + use super::call_id; | ||
| 586 | + | ||
| 587 | + #[test] | ||
| 588 | + fn a_call_is_named_by_its_last_path_piece() { | ||
| 589 | + assert_eq!(call_id("/api/link_tasks"), "link_tasks"); | ||
| 590 | + assert_eq!(call_id("/api/link_tasks?x=1"), "link_tasksx1"); | ||
| 591 | + } | ||
| 592 | +} | ||
| 593 | + | ||
| 594 | +#[cfg(test)] | ||
| 595 | +mod session_cookie_tests { | ||
| 596 | + use super::{SESSION_COOKIE, clear_session_cookie, presented_session, set_session_cookie}; | ||
| 597 | + use topcoat::context::{Cx, CxTestBuilder}; | ||
| 598 | + use topcoat::cookie::{CookieJarCell, write_cookies}; | ||
| 599 | + | ||
| 600 | + /// A `Cx` whose request carried the given `Cookie` header, ready for | ||
| 601 | + /// `set_session_cookie`/`presented_session`/`clear_session_cookie` to read | ||
| 602 | + /// and write through. | ||
| 603 | + fn cx_with(cookie_header: Option<&str>) -> Cx { | ||
| 604 | + let mut builder = http::Request::builder(); | ||
| 605 | + if let Some(value) = cookie_header { | ||
| 606 | + builder = builder.header(http::header::COOKIE, value); | ||
| 607 | + } | ||
| 608 | + let (parts, ()) = builder.body(()).unwrap().into_parts(); | ||
| 609 | + CxTestBuilder::new() | ||
| 610 | + .request_context(parts) | ||
| 611 | + .request_context(CookieJarCell::new()) | ||
| 612 | + .build() | ||
| 613 | + } | ||
| 614 | + | ||
| 615 | + fn set_cookie_headers(cx: &Cx) -> Vec<String> { | ||
| 616 | + let mut headers = http::HeaderMap::new(); | ||
| 617 | + write_cookies(cx, &mut headers); | ||
| 618 | + headers | ||
| 619 | + .get_all(http::header::SET_COOKIE) | ||
| 620 | + .iter() | ||
| 621 | + .map(|v| v.to_str().unwrap().to_owned()) | ||
| 622 | + .collect() | ||
| 623 | + } | ||
| 624 | + | ||
| 625 | + /// The cookie name is a wire contract: every existing browser's `Cookie` | ||
| 626 | + /// header still says "izlek_session", and it must stay byte-identical or | ||
| 627 | + /// every one of them is signed out at once. | ||
| 628 | + #[test] | ||
| 629 | + fn the_cookie_name_stayed_byte_identical() { | ||
| 630 | + assert_eq!(SESSION_COOKIE, "izlek_session"); | ||
| 631 | + } | ||
| 632 | + | ||
| 633 | + #[test] | ||
| 634 | + fn setting_writes_the_session_cookie_with_the_right_attributes() { | ||
| 635 | + let cx = cx_with(None); | ||
| 636 | + set_session_cookie(&cx, "tok123", time::Duration::days(14)); | ||
| 637 | + | ||
| 638 | + let set = set_cookie_headers(&cx); | ||
| 639 | + assert_eq!(set.len(), 1); | ||
| 640 | + assert!(set[0].starts_with("izlek_session=tok123;"), "{}", set[0]); | ||
| 641 | + for attr in ["Path=/", "Secure", "HttpOnly", "SameSite=Lax", "Max-Age=1209600"] { | ||
| 642 | + assert!(set[0].contains(attr), "{} missing {attr}", set[0]); | ||
| 643 | + } | ||
| 644 | + } | ||
| 645 | + | ||
| 646 | + #[test] | ||
| 647 | + fn presented_session_reads_the_cookie_the_browser_sent() { | ||
| 648 | + let cx = cx_with(Some("izlek_session=tok123")); | ||
| 649 | + assert_eq!(presented_session(&cx).as_deref(), Some("tok123")); | ||
| 650 | + } | ||
| 651 | + | ||
| 652 | + #[test] | ||
| 653 | + fn absent_cookie_presents_nothing() { | ||
| 654 | + let cx = cx_with(None); | ||
| 655 | + assert_eq!(presented_session(&cx), None); | ||
| 656 | + } | ||
| 657 | + | ||
| 658 | + #[test] | ||
| 659 | + fn clearing_expires_the_cookie_at_the_same_path() { | ||
| 660 | + let cx = cx_with(Some("izlek_session=tok123")); | ||
| 661 | + clear_session_cookie(&cx); | ||
| 662 | + | ||
| 663 | + let set = set_cookie_headers(&cx); | ||
| 664 | + assert_eq!(set.len(), 1); | ||
| 665 | + assert!(set[0].starts_with("izlek_session="), "{}", set[0]); | ||
| 666 | + assert!(set[0].contains("Max-Age=0"), "{}", set[0]); | ||
| 667 | + assert!(set[0].contains("Path=/"), "{}", set[0]); | ||
| 668 | + } | ||
| 669 | +} | ||