forge
Explore
Log in

Don't you dare go Hollow

iz_old

Clone
★ 0

0 watching0 forksRustGPL-3.02.2 MiB4c154b4Tahinli2 months ago301 commits

server.rs1129 lines, 46.4 KiBHistoryRawDownload
1//! Server-side plumbing: the application context, the person behind the
2//! 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//! There are no local passwords — im holds the central session over OIDC and
8//! `iz-client` (vendored from `im-client` via `in-client`) holds this app's
9//! side of it. This module's `current_user` maps im's claims onto the local
10//! user row, provisioning it on first sight.
11
12use std::sync::Arc;
13
14use iz_core::board::Transition;
15use iz_core::mail::Engine;
16use iz_core::store::{Freeing, Store, StoreError, User};
17use serde::{Deserialize, Serialize};
18use sha2::Digest;
19use topcoat::asset::AssetBundle;
20use topcoat::context::{Cx, app_context, memoize, try_app_context};
21use topcoat::cookie::{Cookies, cookies};
22use topcoat::router::request::{client_ip, headers};
23use topcoat::router::{
24 route, Body, HeaderValue, Next, StatusCode, header, response::IntoResponse, response::Response,
25 to_bytes,
26};
27
28/// The workspace store, put into context by the router.
29pub fn store(cx: &Cx) -> Arc<dyn Store> {
30 app_context::<Arc<dyn Store>>(cx).clone()
31}
32
33/// The loaded `config/iz.toml`, put into context by `main.rs`.
34pub fn config(cx: &Cx) -> iz_core::Config {
35 app_context::<iz_core::Config>(cx).clone()
36}
37
38/// One proxy hop in front of the process. `iz` is reached through that hop,
39/// so [`client_ip`] reads the address it appended rather than the hop's own.
40/// A direct connection, with no hop in front, is its own address.
41pub fn trusted_proxies() -> topcoat::router::TrustedProxies {
42 topcoat::router::TrustedProxies::new().nearest(1)
43}
44
45/// A stable-enough label for the client.
46///
47/// [`client_ip`] under [`trusted_proxies`]: the address the one trusted hop
48/// reported, or the peer when the request did not come through it. `unknown`
49/// when neither is there. A client-supplied `x-forwarded-for` is not read
50/// unless that hop appended it.
51pub fn client_label(cx: &Cx) -> String {
52 client_ip(cx)
53 .map(|ip| ip.to_string())
54 .unwrap_or_else(|| "unknown".to_string())
55}
56
57/// The app-level `setting` key the background beat in `main.rs` stores
58/// im's family list under, and `layout.rs`'s switcher renders from. The
59/// value is a JSON array of `{key, name, url}` — exactly what im's
60/// `/family` served.
61pub const FAMILY_KEY: &str = "family";
62/// The app-level `setting` key the storage mode form writes: which surface
63/// keeps the attachment bytes, `"local"` or `"in"`. The store's
64/// `set_storage_backend` owns the write and the announcement; the constant
65/// is named here beside `FAMILY_KEY` because tests read the row directly.
66pub const STORAGE_BACKEND_KEY: &str = "storage_backend";
67
68/// The app-level `setting` key the public-address field on Settings
69/// writes: where a sign-out that started here sends the browser. Saving
70/// empty clears the row rather than storing an empty string, so what the
71/// fallback chain sits under is always either a usable address or nothing.
72pub const PUBLIC_URL_KEY: &str = "public_url";
73
74/// Resolves where a sign-out that started here sends the browser, per
75/// request: the public address an admin stored wins; a missing or
76/// unreadable one is no opinion, and iz-client falls back to the
77/// configured chain — `base_url`, else the address bound. Registered as
78/// an app context in `main.rs`; this function is the shape that
79/// registration wants.
80pub fn logout_back(cx: &Cx) -> iz_client::BackAnswer<'_> {
81 Box::pin(async move {
82 match store(cx).get_setting(PUBLIC_URL_KEY).await {
83 Ok(Some(value)) if !value.trim().is_empty() => Some(value),
84 _ => None,
85 }
86 })
87}
88
89/// The mail engine, or the fact that there is nobody to hand a crossing to.
90///
91/// The running server always has an engine: the sender is workspace settings
92/// now, so it can appear at any moment and the engine reads it per send. The
93/// `None` is for tests, which drive the router without one and assert on the
94/// ledger rather than on a mail server.
95#[derive(Clone)]
96pub struct Mail(Option<std::sync::Arc<Engine>>);
97
98impl Mail {
99 /// No engine at all. Crossings are recorded and nothing is handed on.
100 pub fn silent() -> Self {
101 Self(None)
102 }
103
104 pub fn sending(engine: std::sync::Arc<Engine>) -> Self {
105 Self(Some(engine))
106 }
107
108 /// Hands a committed crossing to the engine, off the request.
109 ///
110 /// The move is already written by the time this is called and the response
111 /// does not wait for it: a card that took thirty seconds to drop because
112 /// somebody's SMTP host was slow would be a board broken by its own mail
113 /// feature. What the send is owed is in the ledger, so a process that dies
114 /// mid-send loses nothing — the sweep picks it up.
115 pub fn after(&self, transition: Transition) {
116 let Some(engine) = self.0.clone() else {
117 return;
118 };
119 tokio::spawn(async move {
120 let report = engine.on_transition(&transition).await;
121 Self::log(report);
122 });
123 }
124
125 /// Kicks the engine to send an invite mail now rather than on the next
126 /// sweep, off the request the same way `after` is.
127 ///
128 /// The invite is already on the ledger by the time this is called — this
129 /// only makes the wait before it leaves as short as the request itself,
130 /// so the admin does not sit wondering whether the mail is coming.
131 pub fn after_invite(&self) {
132 let Some(engine) = self.0.clone() else {
133 return;
134 };
135 tokio::spawn(async move {
136 let report = engine
137 .deliver_owed(time::OffsetDateTime::now_utc(), 8)
138 .await;
139 Self::log(report);
140 });
141 }
142
143 /// Hands a recorded activity to the engine, off the request, the same way
144 /// `after` hands a transition.
145 ///
146 /// The activity row is already written by the time this is called; this
147 /// rehydrates it and lets the engine decide whether any rule owes a mail.
148 /// `store` is the same store the request already wrote through — the
149 /// engine has no public handle back to it, so the caller carries it.
150 pub fn after_activity(
151 &self,
152 store: std::sync::Arc<dyn iz_core::store::Store>,
153 activity_id: String,
154 ) {
155 let Some(engine) = self.0.clone() else {
156 return;
157 };
158 tokio::spawn(async move {
159 let ev = store.event(&activity_id).await;
160 let report = match ev {
161 Ok(Some(iz_core::store::Event::Happened(ev))) => {
162 match engine.on_activity(&ev).await {
163 Ok(_) => {
164 engine
165 .deliver_owed(time::OffsetDateTime::now_utc(), 8)
166 .await
167 }
168 Err(problem) => Err(problem),
169 }
170 }
171 Ok(_) => return,
172 Err(problem) => Err(problem),
173 };
174 Self::log(report);
175 });
176 }
177
178 /// Hands a committed delete to the engine, off the request, the same way.
179 ///
180 /// A blocker being deleted frees the tasks that were waiting on it just as
181 /// finishing it would, so the unblocked rule fires on both. The freeing is
182 /// already written; this only reads it.
183 pub fn after_freeing(&self, freeing: Freeing, freed: Vec<String>) {
184 let Some(engine) = self.0.clone() else {
185 return;
186 };
187 tokio::spawn(async move {
188 let report = engine.on_freeing(&freeing, &freed).await;
189 Self::log(report);
190 });
191 }
192
193 /// Sends one test mail and waits for the answer, because the answer is the
194 /// whole point of pressing the button. `None` means this process has no
195 /// engine at all, which happens only in tests.
196 pub async fn test(&self, to: &str) -> Option<Result<time::Duration, iz_core::MailError>> {
197 let engine = self.0.clone()?;
198 Some(engine.send_test(to).await)
199 }
200
201 /// Asks the mail server whether it would have us, sending nothing.
202 pub async fn check(&self) -> Option<Result<time::Duration, iz_core::MailError>> {
203 let engine = self.0.clone()?;
204 Some(engine.check_sender().await)
205 }
206
207 fn log(report: iz_core::store::Result<iz_core::mail::Report>) {
208 match report {
209 Ok(report) if report.sent + report.failed + report.abandoned > 0 => {
210 println!(
211 "iz mail {} sent, {} to retry, {} given up on",
212 report.sent, report.failed, report.abandoned
213 );
214 }
215 Ok(_) => {}
216 Err(problem) => eprintln!("iz mail the ledger could not be read: {problem}"),
217 }
218 }
219}
220
221/// The engine for this request, or a silent one when the router was built
222/// without an engine at all.
223pub fn mail(cx: &Cx) -> Mail {
224 try_app_context::<Mail>(cx)
225 .cloned()
226 .unwrap_or_else(Mail::silent)
227}
228
229/// Any cookie the request presented, by name — the client-set, non-`HttpOnly`
230/// ones (e.g. `iz_rows_<section>`) that JS reads and writes on its own.
231pub fn presented_cookie(cx: &Cx, name: &str) -> Option<String> {
232 cookies(cx).get(name).map(|c| c.value().to_string())
233}
234
235/// The stylesheet this binary serves must be the one compiled into it.
236///
237/// `asset!` embeds an asset's declaration — its id and source path — into
238/// the binary, but the served bytes live in the bundle directory beside the
239/// executable, and topcoat loads whatever manifest it finds there. A bundle
240/// left behind by another deploy sits beside a newer binary without a word
241/// of complaint, and the pages then reference a stylesheet whose bytes are
242/// from another generation — the mixed generation a browser once caught on
243/// production. `build.rs` stamps the compiled stylesheet's SHA-256 into the
244/// binary; this hashes the bundle's bytes against it, so a foreign bundle
245/// refuses the boot instead of serving under it.
246///
247/// Returns the startup log line naming the served fingerprint, or the
248/// reason the boot must not proceed.
249pub fn stylesheet_guard(bundle: &AssetBundle) -> Result<String, String> {
250 let expected = env!("IZ_STYLE_FINGERPRINT");
251 let stylesheet = bundle
252 .catalog()
253 .assets()
254 .find(|asset| {
255 let name = asset.name();
256 name.starts_with("main-") && name.ends_with(".css")
257 })
258 .ok_or_else(|| {
259 format!(
260 "the asset bundle at {} carries no stylesheet",
261 bundle.dir().display()
262 )
263 })?;
264 let bytes = std::fs::read(bundle.dir().join(stylesheet.name())).map_err(|err| {
265 format!(
266 "the bundled stylesheet {} could not be read: {err}",
267 stylesheet.name()
268 )
269 })?;
270 let digest = sha2::Sha256::digest(&bytes);
271 let actual = format!(
272 "sha256:{}",
273 digest.as_slice().iter().map(|b| format!("{b:02x}")).collect::<String>()
274 );
275 if actual != expected {
276 return Err(format!(
277 "the asset bundle at {} is from another build: stylesheet {} is {actual} but this binary was compiled against {expected}; run `topcoat asset bundle` and redeploy",
278 bundle.dir().display(),
279 stylesheet.name()
280 ));
281 }
282 Ok(format!(
283 "assets stylesheet {} ({actual})",
284 stylesheet.name()
285 ))
286}
287
288/// The person behind this request, or nobody, or the store failing to say.
289///
290/// im is asked on every request — the cookie holds an opaque session token,
291/// introspected per call — so an admin revoking the person in im signs them
292/// out here at once. The first sight of a `sub` inserts the local row (open
293/// provisioning: any im user who completes SSO gets one; a legacy row with
294/// the same address is claimed onto the new `sub`); every later sight
295/// refreshes the address and name, syncs the admin role from im's flag, and
296/// stamps the last sign-in time.
297///
298/// A store error is not "nobody" — a busy database mid-drag is a fact about
299/// the database, not about whether this browser is signed in, and a caller
300/// that folded the two together would send a signed-in person to a sign-in
301/// screen because a write elsewhere held a lock for a moment.
302///
303/// A disabled account reads as nobody: the cookie is im's business and is
304/// left untouched, but every guard below refuses as if signed out.
305#[memoize(as_ref)]
306pub async fn current_user(cx: &Cx) -> Result<Option<User>, StoreError> {
307 let Some(claims) = iz_client::current_user(cx).await else {
308 return Ok(None);
309 };
310 let user = store(cx)
311 .provision_user(&claims.sub, &claims.email, &claims.name, claims.admin)
312 .await?;
313 if user.disabled {
314 return Ok(None);
315 }
316 Ok(Some(user))
317}
318
319/// The person behind this request, or a refusal the caller can return as-is.
320///
321/// A store error becomes `Refusal::Unavailable` rather than `SignInFirst`,
322/// which would tell a signed-in person to sign in again over what was only
323/// a database hiccup.
324pub async fn require_user(cx: &Cx) -> Result<User, Refusal> {
325 match current_user(cx).await {
326 Ok(Some(user)) => Ok(user.clone()),
327 Ok(None) => Err(Refusal::SignInFirst),
328 Err(error) => Err(error.clone().into()),
329 }
330}
331
332/// The admin behind this request. A member or a viewer is refused *here*, not
333/// merely hidden from in the UI.
334pub async fn require_admin(cx: &Cx) -> Result<User, Refusal> {
335 let user = require_user(cx).await?;
336 if user.role.can_administer() {
337 Ok(user)
338 } else {
339 Err(Refusal::Forbidden)
340 }
341}
342
343/// The person behind this request if they may change the board.
344pub async fn require_writer(cx: &Cx) -> Result<User, Refusal> {
345 let user = require_user(cx).await?;
346 if user.role.can_write_tasks() {
347 Ok(user)
348 } else {
349 Err(Refusal::Forbidden)
350 }
351}
352
353/// The lightweight am-I-signed-in probe the live script's error path asks:
354/// `204` with no body when the caller carries a live session, `401` when
355/// anything about the caller — no cookie, a revoked or disabled one, a
356/// store that cannot answer — says otherwise. It exists so a dropped live
357/// stream can tell "the server restarted" from "I was signed out" without
358/// fetching a page of HTML to learn it.
359#[route(GET "/api/me")]
360async fn me(cx: &Cx) -> topcoat::Result<Response> {
361 match current_user(cx).await {
362 Ok(Some(_)) => StatusCode::NO_CONTENT.into_response(cx),
363 _ => (StatusCode::UNAUTHORIZED, "").into_response(cx),
364 }
365}
366
367impl From<StoreError> for Refusal {
368 fn from(error: StoreError) -> Self {
369 eprintln!("store error: {error}");
370 Refusal::Unavailable
371 }
372}
373
374/// Everything a refused call is allowed to say.
375///
376/// The codes are the contract's: a browser without script only ever sees
377/// them through the address bar, so each one has a short word form
378/// ([`Refusal::code`]) beside its sentence.
379#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
380pub enum Refusal {
381 /// Signed in, but refused here rather than merely hidden in the UI.
382 Forbidden,
383 /// No session, a revoked one, or a disabled account — deliberately one
384 /// answer for all three.
385 SignInFirst,
386 /// A card with no title is not a card.
387 EmptyTitle,
388 /// A person with no name is not a person the board can show.
389 EmptyName,
390 /// A limit of nothing, or a limit wider than the disk should promise.
391 BadLimit,
392 /// A security number below its floor or past its ceiling. Not `BadLimit`:
393 /// that sentence is about megabytes, and these knobs are counts, minutes
394 /// and days.
395 BadPolicy,
396 /// The timezone field was not one of the offsets the form offers.
397 /// The theme field was not one of the values the form offers.
398 BadTheme,
399 /// The ui field was not one of the values the form offers.
400 BadUi,
401 /// The language field was not one of the values the form offers.
402 BadLanguage,
403 /// The email field did not look like an address.
404 BadEmail,
405 /// Something in the allowed-types list is not a file extension.
406 BadFileType,
407 /// A public address that is not an http:// or https:// origin.
408 BadOrigin,
409 /// The sender panel was saved with a field it cannot work without, or with
410 /// one that is not what it claims to be. The message names the field: this
411 /// is a form somebody is filling in, not an attacker probing, and "that did
412 /// not work" would send them round the panel guessing.
413 BadSender(String),
414 /// A comment with nothing in it.
415 EmptyComment,
416 /// The upload arrived without a file in it.
417 NoFile,
418 /// The bytes kept coming past what this workspace allows per file.
419 FileTooBig,
420 /// The name does not end in one of the extensions the admin allows.
421 FileTypeNotAllowed,
422 /// The bytes uploaded as a profile photo do not sniff as an image.
423 NotAnImage,
424 /// A rule with no subject line: the mail it sends would arrive blank.
425 EmptySubject,
426 /// A tag with no name is not a tag the board can show.
427 EmptyTag,
428 /// A tag with cards on it stays. Emptying it is the admin's job, and it
429 /// is one they can see the size of.
430 TagInUse,
431 /// A message with no body: there is nothing for the recipient to read.
432 EmptyBody,
433 /// The date field did not hold a date.
434 BadDeadline,
435 /// The moment field's time box did not hold a 24h `HH:MM`, or a time
436 /// arrived with no day to sit on.
437 BadClock,
438 /// The link asked for would put a task behind itself.
439 Cycle,
440 /// The card was already moved out of the column this request thought it
441 /// was in, by somebody else, while this person was deciding.
442 MovedAlready,
443 /// A task headed for a done column while its subtasks are not done. The
444 /// count is deliberately not in the sentence: the parent's card already
445 /// carries it, and a number cannot survive the round trip through the
446 /// address bar that a browser without script makes.
447 SubtasksOpen,
448 /// Subtasks go one level deep: the task named as a parent is itself a
449 /// part, or the task being filed already has parts of its own.
450 NotNestable,
451 /// No such task — or none this account may see. Deliberately one answer for
452 /// both.
453 NotFound,
454 /// A recipient id that names nobody in this workspace.
455 NoSuchMember,
456 /// The address typed into the add-member form already has a row here.
457 AlreadyMember,
458 /// in refused the push: the bytes iz holds have spent the limit im set.
459 StorageQuota,
460 /// Storage through the Files service was asked for while `[storage.in]`
461 /// holds no token — there is no key to speak with.
462 StorageNotConfigured,
463 /// The Files service is not in the family mirror, so there is no URL to
464 /// push to. im's panel puts it there; iz does not guess.
465 StorageNotListed,
466 /// The Files service did not answer — down, mid-deploy, or the wire
467 /// between. An upload is not queued for later; it is refused now.
468 StorageUnavailable,
469 Unavailable,
470}
471
472impl Refusal {
473 /// The refusal in words.
474 pub fn message(&self) -> String {
475 match self {
476 Refusal::Forbidden => "Not permitted.".to_string(),
477 Refusal::SignInFirst => "Sign in first.".to_string(),
478 Refusal::EmptyTitle => "Give the task a title.".to_string(),
479 Refusal::EmptyName => "Give yourself a name.".to_string(),
480 Refusal::BadLimit => {
481 "A limit has to be at least 1 MB, and no wider than 500 MB per file.".to_string()
482 }
483 Refusal::BadPolicy => "A security number is out of range.".to_string(),
484 Refusal::BadTheme => "That is not a theme.".to_string(),
485 Refusal::BadUi => "That is not an interface.".to_string(),
486 Refusal::BadLanguage => "That is not a language.".to_string(),
487 Refusal::BadEmail => "That is not an address.".to_string(),
488 Refusal::BadFileType => {
489 "File types are extensions — png, pdf, zip — separated by commas.".to_string()
490 }
491 Refusal::BadOrigin => "Not an http:// or https:// address.".to_string(),
492 Refusal::BadSender(problem) => problem.clone(),
493 Refusal::EmptyComment => "Write something first.".to_string(),
494 Refusal::NoFile => "Choose a file first.".to_string(),
495 Refusal::FileTooBig => "Too big for this workspace.".to_string(),
496 Refusal::FileTypeNotAllowed => {
497 "That kind of file is not on this workspace's allowed list.".to_string()
498 }
499 Refusal::NotAnImage => "That is not an image.".to_string(),
500 Refusal::EmptySubject => "Give the rule a subject line.".to_string(),
501 Refusal::EmptyTag => "Give the tag a name.".to_string(),
502 Refusal::TagInUse => "This tag still has cards.".to_string(),
503 Refusal::EmptyBody => "Write something first.".to_string(),
504 Refusal::BadDeadline => "That is not a date.".to_string(),
505 Refusal::BadClock => "That is not a time.".to_string(),
506 Refusal::Cycle => "That link would put this task behind itself.".to_string(),
507 Refusal::MovedAlready => "Somebody moved this card first.".to_string(),
508 Refusal::SubtasksOpen => "Subtasks are still open.".to_string(),
509 Refusal::NotNestable => "Subtasks go one level deep.".to_string(),
510 Refusal::NotFound => "No such task.".to_string(),
511 Refusal::NoSuchMember => "No such member.".to_string(),
512 Refusal::AlreadyMember => "Already a member.".to_string(),
513 Refusal::StorageNotConfigured => "The Files service has no key.".to_string(),
514 Refusal::StorageNotListed => "The Files service is not in the family.".to_string(),
515 Refusal::StorageUnavailable => "The Files service is unreachable.".to_string(),
516 Refusal::StorageQuota => "The Files service is full.".to_string(),
517 Refusal::Unavailable => "Something went wrong.".to_string(),
518 }
519 }
520
521 /// `message()`, in a user's language. English is the canonical
522 /// sentence; the Turkish match arms every variant — the compiler holds
523 /// it exhaustive, so a refusal cannot land untranslated — and
524 /// `BadSender` falls back to English because its sentence is built
525 /// where the complaint is decided, already in the caller's language.
526 pub fn message_in(&self, lang: crate::i18n::Lang) -> String {
527 use crate::i18n::Lang::Tr;
528 if lang != Tr {
529 return self.message();
530 }
531 match self {
532 Refusal::Forbidden => "İzin verilmiyor.".to_string(),
533 Refusal::SignInFirst => "Önce oturum aç.".to_string(),
534 Refusal::EmptyTitle => "Göreve bir başlık ver.".to_string(),
535 Refusal::EmptyComment => "Önce bir şey yaz.".to_string(),
536 Refusal::NoFile => "Önce bir dosya seç.".to_string(),
537 Refusal::FileTooBig => "Bu çalışma alanı için çok büyük.".to_string(),
538 Refusal::FileTypeNotAllowed => {
539 "Bu dosya türü bu çalışma alanının izin verdiği listede değil.".to_string()
540 }
541 Refusal::NotAnImage => "Bu bir resim değil.".to_string(),
542 Refusal::BadDeadline => "Bu bir tarih değil.".to_string(),
543 Refusal::BadClock => "Bu bir saat değil.".to_string(),
544 Refusal::Cycle => "Bu bağlantı görevi kendi arkasına koyar.".to_string(),
545 Refusal::MovedAlready => "Bu kartı başka biri zaten taşıdı.".to_string(),
546 Refusal::SubtasksOpen => "Alt görevler hâlâ açık.".to_string(),
547 Refusal::NotNestable => "Alt görevler tek seviyedir.".to_string(),
548 Refusal::NotFound => "Böyle bir görev yok.".to_string(),
549 Refusal::NoSuchMember => "Böyle bir üye yok.".to_string(),
550 Refusal::AlreadyMember => "Zaten üye.".to_string(),
551 Refusal::StorageNotConfigured => "Dosyalar hizmetinin anahtarı yok.".to_string(),
552 Refusal::StorageNotListed => "Dosyalar hizmeti ailede değil.".to_string(),
553 Refusal::StorageUnavailable => "Dosyalar hizmetine erişilemiyor.".to_string(),
554 Refusal::StorageQuota => "Dosyalar hizmeti dolu.".to_string(),
555 Refusal::Unavailable => "Bir şeyler ters gitti.".to_string(),
556 Refusal::BadLimit => {
557 "Limit en az 1 MB, dosya başına en çok 500 MB olabilir.".to_string()
558 }
559 Refusal::BadPolicy => "Güvenlik sayısı aralığın dışında.".to_string(),
560 Refusal::BadTheme => "Bu bir tema değil.".to_string(),
561 Refusal::BadUi => "Bu bir arayüz değil.".to_string(),
562 Refusal::BadLanguage => "Bu bir dil değil.".to_string(),
563 Refusal::BadEmail => "Bu bir adres değil.".to_string(),
564 Refusal::BadFileType => {
565 "Dosya türleri virgülle ayrılmış uzantılardır — png, pdf, zip.".to_string()
566 }
567 Refusal::BadOrigin => "http:// veya https:// adresi değil.".to_string(),
568 // `BadSender`'s sentence is built where the complaint is
569 // decided (`settings.rs`), already in the caller's language —
570 // this is only reached for a request with no admin to read a
571 // language off of, so it falls back to English like the rest.
572 Refusal::BadSender(_) => self.message(),
573 Refusal::EmptySubject => "Kurala bir konu ver.".to_string(),
574 Refusal::EmptyTag => "Etikete bir ad ver.".to_string(),
575 Refusal::TagInUse => "Bu etikette kartlar var.".to_string(),
576 Refusal::EmptyBody => "Önce bir şey yaz.".to_string(),
577 Refusal::EmptyName => "Kendine bir isim ver.".to_string(),
578 }
579 }
580
581 /// The refusal a `code` names, or nothing. Nothing for an unknown word: the
582 /// query is whatever the address bar holds, so a code that is not one of
583 /// ours says nothing at all rather than something invented.
584 pub fn from_code(code: &str) -> Option<Refusal> {
585 Some(match code {
586 "forbidden" => Refusal::Forbidden,
587 "sign-in-first" => Refusal::SignInFirst,
588 "empty-title" => Refusal::EmptyTitle,
589 "empty-name" => Refusal::EmptyName,
590 "bad-limit" => Refusal::BadLimit,
591 "bad-policy" => Refusal::BadPolicy,
592 "bad-theme" => Refusal::BadTheme,
593 "bad-ui" => Refusal::BadUi,
594 "bad-language" => Refusal::BadLanguage,
595 "bad-email" => Refusal::BadEmail,
596 "bad-file-type" => Refusal::BadFileType,
597 "bad-origin" => Refusal::BadOrigin,
598 // The specific complaint (which field, and why) lives only in the
599 // response the save itself returned; a code that survived a round
600 // trip through the address bar carries no more than this.
601 "bad-sender" => Refusal::BadSender("That sender setting will not work.".to_string()),
602 "empty-comment" => Refusal::EmptyComment,
603 "no-file" => Refusal::NoFile,
604 "file-too-big" => Refusal::FileTooBig,
605 "file-type" => Refusal::FileTypeNotAllowed,
606 "not-an-image" => Refusal::NotAnImage,
607 "empty-subject" => Refusal::EmptySubject,
608 "empty-tag" => Refusal::EmptyTag,
609 "tag-in-use" => Refusal::TagInUse,
610 "empty-body" => Refusal::EmptyBody,
611 "bad-deadline" => Refusal::BadDeadline,
612 "bad-clock" => Refusal::BadClock,
613 "cycle" => Refusal::Cycle,
614 "moved-already" => Refusal::MovedAlready,
615 "subtasks-open" => Refusal::SubtasksOpen,
616 "not-nestable" => Refusal::NotNestable,
617 "not-found" => Refusal::NotFound,
618 "no-such-member" => Refusal::NoSuchMember,
619 "already-member" => Refusal::AlreadyMember,
620 "storage-quota" => Refusal::StorageQuota,
621 "storage-not-configured" => Refusal::StorageNotConfigured,
622 "storage-not-listed" => Refusal::StorageNotListed,
623 "storage-unavailable" => Refusal::StorageUnavailable,
624 "unavailable" => Refusal::Unavailable,
625 _ => return None,
626 })
627 }
628
629 /// The refusal as a short word, for the address bar.
630 ///
631 /// A browser without script never sees a call's return value: it posts the
632 /// form, follows the redirect, and the page it lands on has to be told what
633 /// happened. That telling goes through the query, so every refusal needs a
634 /// name that survives a round trip through a URL.
635 pub fn code(&self) -> &'static str {
636 match self {
637 Refusal::Forbidden => "forbidden",
638 Refusal::SignInFirst => "sign-in-first",
639 Refusal::EmptyTitle => "empty-title",
640 Refusal::EmptyName => "empty-name",
641 Refusal::BadLimit => "bad-limit",
642 Refusal::BadPolicy => "bad-policy",
643 Refusal::BadTheme => "bad-theme",
644 Refusal::BadUi => "bad-ui",
645 Refusal::BadLanguage => "bad-language",
646 Refusal::BadEmail => "bad-email",
647 Refusal::BadFileType => "bad-file-type",
648 Refusal::BadOrigin => "bad-origin",
649 Refusal::BadSender(_) => "bad-sender",
650 Refusal::EmptyComment => "empty-comment",
651 Refusal::NoFile => "no-file",
652 Refusal::FileTooBig => "file-too-big",
653 Refusal::FileTypeNotAllowed => "file-type",
654 Refusal::NotAnImage => "not-an-image",
655 Refusal::EmptySubject => "empty-subject",
656 Refusal::EmptyTag => "empty-tag",
657 Refusal::TagInUse => "tag-in-use",
658 Refusal::EmptyBody => "empty-body",
659 Refusal::BadDeadline => "bad-deadline",
660 Refusal::BadClock => "bad-clock",
661 Refusal::Cycle => "cycle",
662 Refusal::MovedAlready => "moved-already",
663 Refusal::SubtasksOpen => "subtasks-open",
664 Refusal::NotNestable => "not-nestable",
665 Refusal::NotFound => "not-found",
666 Refusal::NoSuchMember => "no-such-member",
667 Refusal::AlreadyMember => "already-member",
668 Refusal::StorageNotConfigured => "storage-not-configured",
669 Refusal::StorageNotListed => "storage-not-listed",
670 Refusal::StorageUnavailable => "storage-unavailable",
671 Refusal::StorageQuota => "storage-quota",
672 Refusal::Unavailable => "unavailable",
673 }
674 }
675}
676
677/// Which call a carried refusal belongs to. Two forms on one page must not both
678/// claim the same sentence, so the redirect names the call and this is the name:
679/// the last piece of the server function's path, with anything that is not a
680/// plain word dropped so it can only ever be compared, never rendered.
681pub fn call_id(path: &str) -> String {
682 path.rsplit('/')
683 .next()
684 .unwrap_or(path)
685 .chars()
686 .filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
687 .collect()
688}
689
690/// What a call refused with, however the browser without script carried it
691/// back — read straight off the query, since there is no client-side action
692/// value to check first the way a hydrated page in the old UI had.
693///
694/// Every topcoat page is rendered server-side on every request, so there is
695/// only ever the query to read.
696pub fn refusal_of(cx: &Cx, call: &str) -> Option<Refusal> {
697 let query = topcoat::router::request::uri(cx).query()?;
698 let mut code = None;
699 let mut on = None;
700 for pair in query.split('&') {
701 if let Some((key, value)) = pair.split_once('=') {
702 match key {
703 "refusal" => code = Some(value),
704 "on" => on = Some(value),
705 _ => {}
706 }
707 }
708 }
709 if on? != call {
710 return None;
711 }
712 Refusal::from_code(code?)
713}
714
715/// The page a form was posted from: the `Referer`, with the answer any
716/// earlier post left on its query dropped, or `nowhere` when no `Referer`
717/// came with the request.
718///
719/// The feedback pairs — `refusal=`, `on=`, `why=`, `saved=` — are how a page
720/// renders what the last post did. Sending the browser back with them still
721/// on the query re-renders that old answer under the new post's own: a change
722/// that succeeded right after one that was refused announces the refusal
723/// again, and reads as having failed. The answer this redirect carries — the
724/// pairs it was built with, or the body [`carry_refusal_on_redirect`] copies
725/// onto the query — is the one that shows; an earlier one never survives the
726/// trip.
727pub fn back_to(cx: &Cx, nowhere: &str) -> String {
728 let referer = headers(cx)
729 .get(header::REFERER)
730 .and_then(|value| value.to_str().ok())
731 .unwrap_or(nowhere);
732 let (path, query) = referer.split_once('?').unwrap_or((referer, ""));
733 let pairs: Vec<&str> = query
734 .split('&')
735 .filter(|pair| {
736 !pair.is_empty()
737 && !["refusal", "on", "why", "saved"].iter().any(|key| {
738 pair.strip_prefix(*key)
739 .is_some_and(|rest| rest.starts_with('='))
740 })
741 })
742 .collect();
743 if pairs.is_empty() {
744 return path.to_string();
745 }
746 format!("{path}?{}", pairs.join("&"))
747}
748
749/// Puts a refusal on the redirect a browser without script follows.
750///
751/// A hydrated page reads the call's return value straight off the action. A
752/// browser without script has no such thing: it posts the form, the server
753/// function handler answers with a redirect back to the page it came from, and
754/// the value — the whole refusal — sits in a body nobody will ever look at.
755/// The click then looks like nothing happening, which is the worst answer
756/// iz can give.
757///
758/// So the refusal is copied onto the `Location`, as `?refusal=<code>&on=<call>`,
759/// and the page renders it from the query. This is one place rather than
760/// thirty-eight because the shape is the same for every refusing call, present
761/// and future: nothing here knows what any of them do.
762///
763/// Requests carrying script are untouched — they are answered with the value
764/// itself and never see a redirect.
765///
766/// Ported from axum's `middleware::from_fn` onto a topcoat `#[layer]`. topcoat's
767/// Post/Redirect/Get helper (`error::see_other`) answers with `303 See Other`,
768/// not the `302 Found` axum's server-function redirect used, so the status this
769/// checks for is `SEE_OTHER` — the guard's three conditions are otherwise
770/// unchanged.
771#[topcoat::router::layer("/api")]
772async fn carry_refusal_on_redirect(
773 cx: &Cx,
774 body: Body,
775 next: Next<'_>,
776) -> topcoat::Result<Response> {
777 // A form post from a browser asks for a page back. A server-function call
778 // from the hydrated bundle does not.
779 let wants_page = headers(cx)
780 .get(header::ACCEPT)
781 .and_then(|value| value.to_str().ok())
782 .is_some_and(|value| value.contains("text/html"));
783 let called = call_id(topcoat::router::request::uri(cx).path());
784 let has_referer = headers(cx).contains_key(header::REFERER);
785 let response = next.run(cx, body).await?;
786 if !wants_page || !has_referer || response.status() != StatusCode::SEE_OTHER {
787 return Ok(response);
788 }
789
790 let (mut parts, body) = response.into_parts();
791 // The body of one of these redirects is a serialised `Option<Refusal>` and
792 // nothing else; the cap is there so a response that is something else
793 // entirely cannot be read into memory whole. A body that fails to parse —
794 // an empty one included, the shape a route with nothing to say back sends
795 // — is read as "no refusal", never as "leave the Location alone": the
796 // Referer sanitization below has to run on every redirect this layer
797 // sees, not only the ones that happen to carry a refusal.
798 let Ok(bytes) = to_bytes(body, 64 * 1024).await else {
799 return Ok(Response::from_parts(parts, Body::empty()));
800 };
801 let refusal = serde_json::from_slice::<Option<Refusal>>(&bytes)
802 .ok()
803 .flatten();
804 if let Some(location) = parts
805 .headers
806 .get(header::LOCATION)
807 .and_then(|v| v.to_str().ok())
808 {
809 let rewritten = match refusal {
810 Some(refusal) => carrying(location, refusal.code(), &called),
811 None => Some(same_origin(location).to_string()),
812 };
813 if let Some(carried) = rewritten
814 && let Ok(value) = HeaderValue::from_str(&carried)
815 {
816 parts.headers.insert(header::LOCATION, value);
817 }
818 }
819 Ok(Response::from_parts(parts, Body::from(bytes)))
820}
821
822/// `location` with the refusal in its query.
823///
824/// The redirect goes back to the page the form was posted from, and that page
825/// may already carry a query — `?task=DZ-01` is how a browser without script
826/// opens the modal at all — so the two pairs are merged in, and the pair from
827/// any earlier refusal is dropped rather than stacked on top of.
828fn carrying(location: &str, code: &str, called: &str) -> Option<String> {
829 if called.is_empty() {
830 return None;
831 }
832 // The Location we are rewriting came from the form post's Referer, and on a
833 // cross-origin post the Referer is whatever the other site is. Sending the
834 // browser back there would make iz an open redirect, so the address is
835 // rebuilt from its path and query alone and anything that is not a plain
836 // absolute path is answered with the board.
837 let here = same_origin(location);
838 let (path, query) = match here.split_once('?') {
839 Some((path, query)) => (path, query),
840 None => (here, ""),
841 };
842 let mut pairs: Vec<String> = query
843 .split('&')
844 .filter(|pair| {
845 !pair.is_empty() && !pair.starts_with("refusal=") && !pair.starts_with("on=")
846 })
847 .map(str::to_string)
848 .collect();
849 pairs.push(format!("refusal={code}&on={called}"));
850 Some(format!("{path}?{}", pairs.join("&")))
851}
852
853/// The path and query of `location`, with scheme and authority dropped. A
854/// protocol-relative address (`//elsewhere.example/`) is another host wearing a
855/// path's clothes, and a browser reads a backslash there as a slash, so both
856/// are answered with the board rather than trusted.
857fn same_origin(location: &str) -> &str {
858 let rest = match location.split_once("://") {
859 Some((_scheme, rest)) => match rest.find(['/', '?']) {
860 Some(at) => &rest[at..],
861 None => "/",
862 },
863 None => location,
864 };
865 let mut characters = rest.chars();
866 match (characters.next(), characters.next()) {
867 (Some('/'), Some('/' | '\\')) => "/",
868 (Some('/'), _) => rest,
869 _ => "/",
870 }
871}
872
873/// The cache directives a response cannot choose for itself.
874///
875/// HTML is revalidated on every load: a page the browser kept from before a
876/// deploy is the old app answering under the new one's address, which is how a
877/// fixed bug once came back after shipping. So every response whose body is a
878/// document gets `no-cache`. Responses that already carry a directive keep it —
879/// topcoat stamps the fingerprinted assets under `/_topcoat/assets` with a year
880/// of `immutable` and the live stream with `no-cache`, and the photo and
881/// attachment handlers stamp their own — and everything else (redirects, JSON
882/// answers) ships none, the idiom they already ride on: no directive, nothing
883/// cached. One layer at `/`, because the decision is about what the bytes are,
884/// not which route built them.
885#[topcoat::router::layer("/")]
886async fn cache_directives(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result<Response> {
887 let response = next.run(cx, body).await?;
888 let (mut parts, body) = response.into_parts();
889 let is_html = parts
890 .headers
891 .get(header::CONTENT_TYPE)
892 .and_then(|value| value.to_str().ok())
893 .is_some_and(|value| value.starts_with("text/html"));
894 if !is_html || parts.headers.contains_key(header::CACHE_CONTROL) {
895 return Ok(Response::from_parts(parts, body));
896 }
897 parts
898 .headers
899 .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
900 Ok(Response::from_parts(parts, body))
901}
902
903#[cfg(test)]
904mod refusal_redirect_tests {
905 use super::carrying;
906
907 #[test]
908 fn a_bare_address_gains_a_query() {
909 assert_eq!(
910 carrying("http://iz.sh/", "cycle", "link_tasks").as_deref(),
911 Some("/?refusal=cycle&on=link_tasks")
912 );
913 }
914
915 #[test]
916 fn an_open_modal_stays_open() {
917 assert_eq!(
918 carrying("http://iz.sh/?task=DZ-01", "cycle", "link_tasks").as_deref(),
919 Some("/?task=DZ-01&refusal=cycle&on=link_tasks")
920 );
921 }
922
923 #[test]
924 fn a_second_refusal_replaces_the_first() {
925 assert_eq!(
926 carrying(
927 "http://iz.sh/?task=DZ-01&refusal=cycle&on=link_tasks",
928 "not-found",
929 "link_tasks"
930 )
931 .as_deref(),
932 Some("/?task=DZ-01&refusal=not-found&on=link_tasks")
933 );
934 }
935
936 // The Referer of a cross-origin post is the other site's address, and it
937 // reaches this function as the Location. iz answers on its own ground or
938 // not at all.
939 #[test]
940 fn another_site_cannot_be_redirected_to() {
941 for elsewhere in [
942 "https://elsewhere.example",
943 "//elsewhere.example/steal",
944 "/\\elsewhere.example/steal",
945 "javascript:alert(1)",
946 "",
947 ] {
948 assert_eq!(
949 carrying(elsewhere, "cycle", "link_tasks").as_deref(),
950 Some("/?refusal=cycle&on=link_tasks"),
951 "{elsewhere} was not brought home"
952 );
953 }
954 // An address with a path keeps the path — it is read as a path on this
955 // site, which is the point: whatever the Referer claimed, the browser
956 // is sent somewhere on iz.
957 let carried = carrying(
958 "http://elsewhere.example/steal?task=DZ-01",
959 "cycle",
960 "link_tasks",
961 );
962 assert_eq!(
963 carried.as_deref(),
964 Some("/steal?task=DZ-01&refusal=cycle&on=link_tasks")
965 );
966 }
967
968 #[test]
969 fn a_path_on_this_site_is_kept() {
970 assert_eq!(
971 carrying("/board?task=DZ-01", "cycle", "link_tasks").as_deref(),
972 Some("/board?task=DZ-01&refusal=cycle&on=link_tasks")
973 );
974 }
975
976 #[test]
977 fn a_call_with_no_name_carries_nothing() {
978 assert_eq!(carrying("http://iz.sh/", "cycle", ""), None);
979 }
980}
981
982#[cfg(test)]
983mod refusal_message_tests {
984 use super::Refusal;
985
986 #[test]
987 fn every_refusal_survives_the_address_bar() {
988 let all = [
989 Refusal::Forbidden,
990 Refusal::SignInFirst,
991 Refusal::EmptyTitle,
992 Refusal::EmptyComment,
993 Refusal::NoFile,
994 Refusal::FileTooBig,
995 Refusal::FileTypeNotAllowed,
996 Refusal::BadDeadline,
997 Refusal::BadClock,
998 Refusal::BadTheme,
999 Refusal::BadLanguage,
1000 Refusal::BadEmail,
1001 Refusal::Cycle,
1002 Refusal::MovedAlready,
1003 Refusal::SubtasksOpen,
1004 Refusal::NotNestable,
1005 Refusal::NotFound,
1006 Refusal::NoSuchMember,
1007 Refusal::AlreadyMember,
1008 Refusal::TagInUse,
1009 Refusal::BadLimit,
1010 Refusal::BadPolicy,
1011 Refusal::Unavailable,
1012 ];
1013 for refusal in all {
1014 assert_eq!(
1015 Refusal::from_code(refusal.code()).as_ref(),
1016 Some(&refusal),
1017 "{} did not come back as itself",
1018 refusal.code()
1019 );
1020 }
1021 }
1022
1023 #[test]
1024 fn an_unknown_code_says_nothing() {
1025 assert_eq!(Refusal::from_code("not-a-refusal"), None);
1026 assert_eq!(Refusal::from_code(""), None);
1027 }
1028}
1029
1030#[cfg(test)]
1031mod refusal_of_tests {
1032 use super::{Cx, Refusal, refusal_of};
1033 use topcoat::context::CxTestBuilder;
1034
1035 fn cx_at(uri: &str) -> Cx {
1036 let (parts, ()) = http::Request::builder()
1037 .uri(uri)
1038 .body(())
1039 .unwrap()
1040 .into_parts();
1041 CxTestBuilder::new().request_context(parts).build()
1042 }
1043
1044 #[test]
1045 fn reads_a_matching_refusal_off_the_query() {
1046 let cx = cx_at("/?refusal=cycle&on=sign_in");
1047 assert_eq!(refusal_of(&cx, "sign_in"), Some(Refusal::Cycle));
1048 }
1049
1050 #[test]
1051 fn a_refusal_for_another_call_is_not_this_one() {
1052 let cx = cx_at("/?refusal=cycle&on=link_tasks");
1053 assert_eq!(refusal_of(&cx, "sign_in"), None);
1054 }
1055
1056 #[test]
1057 fn no_query_carries_nothing() {
1058 let cx = cx_at("/");
1059 assert_eq!(refusal_of(&cx, "sign_in"), None);
1060 }
1061}
1062
1063#[cfg(test)]
1064mod call_id_tests {
1065 use super::call_id;
1066
1067 #[test]
1068 fn a_call_is_named_by_its_last_path_piece() {
1069 assert_eq!(call_id("/api/link_tasks"), "link_tasks");
1070 assert_eq!(call_id("/api/link_tasks?x=1"), "link_tasksx1");
1071 }
1072}
1073
1074#[cfg(test)]
1075mod client_label_tests {
1076 use std::net::SocketAddr;
1077
1078 use topcoat::router::response::IntoResponse;
1079 use topcoat::router::{
1080 Body, Method, RemoteAddr, RouteFn, RouteFuture, Router, request::Request, to_bytes,
1081 };
1082
1083 use super::{client_label, trusted_proxies};
1084
1085 fn echo(cx: &topcoat::context::Cx, _body: Body) -> RouteFuture<'_> {
1086 Box::pin(async move { client_label(cx).into_response(cx) })
1087 }
1088
1089 fn router(trust_one_hop: bool) -> Router {
1090 let builder = Router::builder().route(RouteFn::new(Method::GET, "/label", echo));
1091 if trust_one_hop {
1092 builder.trusted_proxies(trusted_proxies()).build()
1093 } else {
1094 builder.build()
1095 }
1096 }
1097
1098 async fn label(trust_one_hop: bool, peer: &str, forwarded: Option<&str>) -> String {
1099 let mut builder = Request::builder()
1100 .method(Method::GET)
1101 .uri("/label")
1102 .extension(RemoteAddr(peer.parse::<SocketAddr>().unwrap()));
1103 if let Some(value) = forwarded {
1104 builder = builder.header("x-forwarded-for", value);
1105 }
1106 let response = router(trust_one_hop)
1107 .handle(builder.body(Body::empty()).unwrap())
1108 .await;
1109 String::from_utf8(to_bytes(response.into_body(), 64).await.unwrap().to_vec()).unwrap()
1110 }
1111
1112 #[tokio::test]
1113 async fn one_trusted_hop_reports_the_client_not_the_proxy() {
1114 let got = label(true, "10.0.0.1:4242", Some("198.51.100.1")).await;
1115 assert_eq!(got, "198.51.100.1");
1116 }
1117
1118 #[tokio::test]
1119 async fn a_missing_header_falls_back_to_the_peer() {
1120 let got = label(true, "203.0.113.9:4242", None).await;
1121 assert_eq!(got, "203.0.113.9");
1122 }
1123
1124 #[tokio::test]
1125 async fn an_untrusted_peer_cannot_spoof_the_forwarded_header() {
1126 let got = label(false, "203.0.113.9:4242", Some("198.51.100.1")).await;
1127 assert_eq!(got, "203.0.113.9");
1128 }
1129}