Skip to main content

geg_gastro_sim/
lib.rs

1//! Fake GEG Gastro ordering portal on loopback, for tests of clients of the
2//! portal. It serves synthetic data only.
3//!
4//! [`Sim::start`] serves an account of two children, "Muster, Max" (11111)
5//! and "Muster, Mia" (22222), with menus for the weeks 2026-W49 to
6//! 2026-W52, orders, 45 bookings and three invoices. Meals can be ordered and
7//! cancelled, which changes the balance, with the rules of the portal: one
8//! meal a day, before the deadlines, while the balance lasts. The login works like
9//! that of the portal: a CSRF token from the login page and its cookie, a
10//! `Referer`, then a session cookie. [`Sim::inject`] makes it fail in the
11//! ways the portal can, and [`Sim::requests`] tells what a client sent.
12//!
13//! ```
14//! # #[tokio::main(flavor = "current_thread")]
15//! # async fn main() -> std::io::Result<()> {
16//! let sim = geg_gastro_sim::Sim::start().await?;
17//! assert!(sim.url().starts_with("http://127.0.0.1:"));
18//! # Ok(())
19//! # }
20//! ```
21
22mod data;
23mod order;
24mod pages;
25
26use std::collections::BTreeMap;
27use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
28use std::time::Duration;
29
30use axum::Router;
31use axum::body::Body;
32use axum::extract::State;
33use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header};
34use axum::response::Response;
35use jiff::ToSpan;
36use jiff::civil::{Date, DateTime};
37
38use data::Booking;
39use pages::Orders;
40
41/// The user name of the account.
42pub const USERNAME: &str = "muster@example.org";
43/// The password of the account.
44pub const PASSWORD: &str = "geheim-123";
45/// The time of the portal unless [`Sim::set_now`] changes it: Monday of
46/// 2026-W49, 7 o'clock.
47pub const NOW: DateTime = DateTime::constant(2026, 11, 30, 7, 0, 0, 0);
48
49/// A way to make the portal fail. Each applies once, to the first request
50/// it fits.
51#[derive(Debug, Clone, PartialEq, Eq)]
52#[non_exhaustive]
53pub enum Injection {
54    /// The session ends before the next request of `path`, as if it had
55    /// timed out.
56    ExpireSession { path: String },
57    /// The next request of `path` gets the page with a new session cookie,
58    /// and the old one ends, as when the portal renews the session.
59    RenewSession { path: String },
60    /// The next login fails, as if the password were wrong.
61    RejectLogin,
62    /// The next request of `path` gets `status` and an empty page.
63    Respond { path: String, status: u16 },
64    /// The next request of `path` gets a page without its content.
65    Malformed { path: String },
66    /// The next request of `path` waits `delay` before it gets an answer.
67    Slow { path: String, delay: Duration },
68    /// The next order or cancellation is refused with `message`.
69    Refuse { message: String },
70}
71
72/// A request the portal got.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct Request {
75    pub method: String,
76    pub path: String,
77    pub query: Option<String>,
78    /// The fields of a form sent with POST.
79    pub form: Vec<(String, String)>,
80    pub user_agent: Option<String>,
81    pub referer: Option<String>,
82    /// Whether a script of a page sent it, with `X-Requested-With:
83    /// XMLHttpRequest`. Only such requests can order; others get the page.
84    pub script: bool,
85}
86
87/// A running fake portal. It stops when dropped.
88#[derive(Debug)]
89pub struct Sim {
90    url: String,
91    shared: Arc<Shared>,
92    task: tokio::task::JoinHandle<std::io::Result<()>>,
93}
94
95impl Sim {
96    /// Starts the portal on a free port of loopback.
97    pub async fn start() -> std::io::Result<Self> {
98        let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await?;
99        let url = format!("http://{}", listener.local_addr()?);
100        let shared = Arc::new(Shared::default());
101        let router = Router::new()
102            .fallback(handle)
103            .with_state(Arc::clone(&shared));
104        let task = tokio::spawn(async move { axum::serve(listener, router).await });
105        Ok(Self { url, shared, task })
106    }
107
108    /// The base URL, like `http://127.0.0.1:1234`, without a slash at the end.
109    pub fn url(&self) -> &str {
110        &self.url
111    }
112
113    /// Makes the portal fail once.
114    pub fn inject(&self, injection: Injection) {
115        self.shared.lock().injections.push(injection);
116    }
117
118    /// The requests so far, oldest first.
119    pub fn requests(&self) -> Vec<Request> {
120        self.shared.lock().requests.clone()
121    }
122
123    /// The time of the portal, which decides the deadlines.
124    pub fn set_now(&self, now: DateTime) {
125        self.shared.lock().now = now;
126    }
127
128    /// The balance of the account, in cents.
129    pub fn balance_cents(&self) -> i64 {
130        self.shared.lock().balance
131    }
132}
133
134impl Drop for Sim {
135    fn drop(&mut self) {
136        self.task.abort();
137    }
138}
139
140#[derive(Debug, Default)]
141struct Shared(Mutex<Portal>);
142
143impl Shared {
144    fn lock(&self) -> MutexGuard<'_, Portal> {
145        self.0.lock().unwrap_or_else(PoisonError::into_inner)
146    }
147}
148
149#[derive(Debug)]
150struct Portal {
151    now: DateTime,
152    balance: i64,
153    orders: Orders,
154    bookings: Vec<Booking>,
155    sessions: Vec<String>,
156    /// Numbers the tokens and sessions.
157    counter: u64,
158    injections: Vec<Injection>,
159    requests: Vec<Request>,
160}
161
162impl Default for Portal {
163    fn default() -> Self {
164        Self {
165            now: NOW,
166            balance: data::BALANCE_CENTS,
167            orders: data::ORDERS
168                .iter()
169                .map(|&(child, day, line)| ((child, day), line))
170                .collect::<BTreeMap<_, _>>(),
171            bookings: data::bookings(),
172            sessions: Vec::new(),
173            counter: 0,
174            injections: Vec::new(),
175            requests: Vec::new(),
176        }
177    }
178}
179
180const LOGIN: &str = "/login/";
181const START: &str = "/kunden/essen/";
182
183async fn handle(State(shared): State<Arc<Shared>>, request: axum::extract::Request) -> Response {
184    let (parts, body) = request.into_parts();
185    let body = axum::body::to_bytes(body, 1 << 20)
186        .await
187        .unwrap_or_default();
188    let path = parts.uri.path().to_owned();
189    let query = parts.uri.query().map(str::to_owned);
190    let form: Vec<(String, String)> = if parts.method == Method::POST {
191        form_urlencoded::parse(&body).into_owned().collect()
192    } else {
193        Vec::new()
194    };
195    let delay = {
196        let mut portal = shared.lock();
197        portal.requests.push(Request {
198            method: parts.method.to_string(),
199            path: path.clone(),
200            query: query.clone(),
201            form: form.clone(),
202            user_agent: header_value(&parts.headers, &header::USER_AGENT),
203            referer: header_value(&parts.headers, &header::REFERER),
204            script: script(&parts.headers),
205        });
206        portal.take(|injection| match injection {
207            Injection::Slow { path: slow, delay } if *slow == path => Some(*delay),
208            _ => None,
209        })
210    };
211    if let Some(delay) = delay {
212        tokio::time::sleep(delay).await;
213    }
214    let mut portal = shared.lock();
215    portal.respond(
216        &parts.method,
217        &path,
218        query.as_deref(),
219        &form,
220        &parts.headers,
221    )
222}
223
224/// Whether a script sent the request, as jQuery marks it.
225fn script(headers: &HeaderMap) -> bool {
226    headers
227        .get("x-requested-with")
228        .is_some_and(|value| value == "XMLHttpRequest")
229}
230
231fn header_value(headers: &HeaderMap, name: &header::HeaderName) -> Option<String> {
232    headers
233        .get(name)
234        .and_then(|value| value.to_str().ok())
235        .map(str::to_owned)
236}
237
238/// The value of a cookie of a request.
239fn cookie(headers: &HeaderMap, name: &str) -> Option<String> {
240    headers
241        .get_all(header::COOKIE)
242        .iter()
243        .filter_map(|value| value.to_str().ok())
244        .flat_map(|value| value.split(';'))
245        .find_map(|pair| {
246            let (key, value) = pair.trim().split_once('=')?;
247            (key == name).then(|| value.to_owned())
248        })
249}
250
251/// A field of a form or a query.
252fn field<'a>(fields: &'a [(String, String)], name: &str) -> Option<&'a str> {
253    fields
254        .iter()
255        .find(|(key, _)| key == name)
256        .map(|(_, value)| value.as_str())
257}
258
259fn html(status: StatusCode, body: String) -> Response {
260    response(status, "text/html; charset=utf-8", body.into_bytes())
261}
262
263fn response(status: StatusCode, content_type: &'static str, body: Vec<u8>) -> Response {
264    let mut response = Response::new(Body::from(body));
265    *response.status_mut() = status;
266    response
267        .headers_mut()
268        .insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
269    response
270}
271
272fn redirect(location: &str, cookie: Option<String>) -> Response {
273    let mut response = html(StatusCode::FOUND, String::new());
274    let headers = response.headers_mut();
275    // A `next` of a form that is no header value leads to the start page.
276    let location = HeaderValue::from_str(location).unwrap_or(HeaderValue::from_static(START));
277    headers.insert(header::LOCATION, location);
278    headers.extend(
279        cookie
280            .and_then(|cookie| HeaderValue::from_str(&cookie).ok())
281            .map(|cookie| (header::SET_COOKIE, cookie)),
282    );
283    response
284}
285
286/// A date like `30.11.2026`.
287fn date(text: &str) -> Option<Date> {
288    jiff::civil::Date::strptime("%d.%m.%Y", text).ok()
289}
290
291impl Portal {
292    /// Removes the first injection `pick` takes and returns what it gives.
293    fn take<T>(&mut self, pick: impl Fn(&Injection) -> Option<T>) -> Option<T> {
294        let (index, value) = self
295            .injections
296            .iter()
297            .enumerate()
298            .find_map(|(index, injection)| Some((index, pick(injection)?)))?;
299        self.injections.remove(index);
300        Some(value)
301    }
302
303    fn respond(
304        &mut self,
305        method: &Method,
306        path: &str,
307        query: Option<&str>,
308        form: &[(String, String)],
309        headers: &HeaderMap,
310    ) -> Response {
311        let respond = self.take(|injection| match injection {
312            Injection::Respond { path: at, status } if at == path => Some(*status),
313            _ => None,
314        });
315        if let Some(status) = respond {
316            let status = StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
317            return html(status, String::new());
318        }
319        let query: Vec<(String, String)> = query
320            .map(|query| {
321                form_urlencoded::parse(query.as_bytes())
322                    .into_owned()
323                    .collect()
324            })
325            .unwrap_or_default();
326        if path == LOGIN {
327            return if *method == Method::POST {
328                self.log_in(form, headers)
329            } else {
330                self.login_page(headers, field(&query, "next").unwrap_or(START), false)
331            };
332        }
333        let session = cookie(headers, "sessionid");
334        let mut valid = session
335            .as_ref()
336            .is_some_and(|session| self.sessions.contains(session));
337        let expire = self.take(|injection| match injection {
338            Injection::ExpireSession { path: at } if valid && at == path => Some(()),
339            _ => None,
340        });
341        if expire.is_some() {
342            self.sessions.clear();
343            valid = false;
344        }
345        if path == "/logout/" {
346            self.sessions.retain(|s| Some(s) != session.as_ref());
347            return redirect(LOGIN, None);
348        }
349        if !valid {
350            return redirect(&format!("{LOGIN}?next={path}"), None);
351        }
352        let malformed = self.take(|injection| match injection {
353            Injection::Malformed { path: at } if at == path => Some(()),
354            _ => None,
355        });
356        if malformed.is_some() {
357            return self.page("Wartung", "<p>Wartungsarbeiten</p>");
358        }
359        let response = self.route(path, &query, script(headers));
360        self.renew(path, session.as_deref(), response)
361    }
362
363    /// With [`Injection::RenewSession`] for `path`, ends `old` and sends the
364    /// cookie of a new session with `response`.
365    fn renew(&mut self, path: &str, old: Option<&str>, mut response: Response) -> Response {
366        let renew = self.take(|injection| match injection {
367            Injection::RenewSession { path: at } if at == path => Some(()),
368            _ => None,
369        });
370        if renew.is_some() {
371            self.sessions.retain(|s| Some(s.as_str()) != old);
372            let cookie = HeaderValue::from_str(&self.new_session()).ok();
373            response
374                .headers_mut()
375                .extend(cookie.map(|cookie| (header::SET_COOKIE, cookie)));
376        }
377        response
378    }
379
380    /// Starts a session and returns its cookie.
381    fn new_session(&mut self) -> String {
382        self.counter += 1;
383        let session = format!("session{:032}", self.counter);
384        self.sessions.push(session.clone());
385        format!("sessionid={session}; Path=/; HttpOnly; SameSite=Lax")
386    }
387
388    fn route(&mut self, path: &str, query: &[(String, String)], script: bool) -> Response {
389        match path {
390            START => self.week(None),
391            "/kunden/bestelluebersicht/" => {
392                let today = self.now.date();
393                let from = field(query, "date_from").and_then(date).unwrap_or(today);
394                let to = field(query, "date_to")
395                    .and_then(date)
396                    .unwrap_or_else(|| from.saturating_add(30.days()));
397                self.page("Bestellübersicht", &pages::overview(from, to, &self.orders))
398            }
399            "/kunden/guthaben/" => {
400                let number = field(query, "page").map_or(Some(1), |page| page.parse().ok());
401                match number.and_then(|number| pages::ledger(&self.bookings, number)) {
402                    Some(content) => self.page("Guthaben", &content),
403                    None => not_found(),
404                }
405            }
406            "/kunden/rechnungen/" => self.page("Rechnungen", &pages::invoices()),
407            "/kunden/kinder/" => self.page("Teilnehmer", &pages::children()),
408            "/kunden/abo/" => self.page("Dauerbestellung", &pages::subscription()),
409            _ => {
410                if let Some(name) = path.strip_prefix("/kunden/rechnungen/")
411                    && data::INVOICES.iter().any(|(invoice, ..)| *invoice == name)
412                {
413                    return response(StatusCode::OK, "application/pdf", data::invoice_pdf(name));
414                }
415                match week_of(path) {
416                    // Like the portal: an order only from the script of
417                    // the page, else the page and no order.
418                    Some(week) if script && field(query, "order").is_some() => {
419                        self.order(week, query)
420                    }
421                    Some(week) => self.week(Some(week)),
422                    None => not_found(),
423                }
424            }
425        }
426    }
427
428    /// An order or a cancellation, which the buttons of a week send.
429    fn order(&mut self, week: (i16, i8), query: &[(String, String)]) -> Response {
430        let refused = self.take(|injection| match injection {
431            Injection::Refuse { message } => Some(message.clone()),
432            _ => None,
433        });
434        let body = match refused {
435            Some(message) => order::refusal(&message, self.balance),
436            None => order::order(
437                week,
438                query,
439                &mut order::Account {
440                    now: self.now,
441                    balance: &mut self.balance,
442                    orders: &mut self.orders,
443                },
444            ),
445        };
446        response(StatusCode::OK, "application/json", body.into_bytes())
447    }
448
449    fn week(&self, week: Option<(i16, i8)>) -> Response {
450        match pages::week(week, self.now, &self.orders) {
451            Some(content) => self.page("Speiseplan", &content),
452            None => not_found(),
453        }
454    }
455
456    fn page(&self, title: &str, content: &str) -> Response {
457        html(StatusCode::OK, pages::layout(self.balance, title, content))
458    }
459
460    fn login_page(&mut self, headers: &HeaderMap, next: &str, failed: bool) -> Response {
461        let (token, new) = if let Some(token) = cookie(headers, "csrftoken") {
462            (token, false)
463        } else {
464            self.counter += 1;
465            (format!("csrf{:032}", self.counter), true)
466        };
467        let mut response = html(StatusCode::OK, pages::login(&token, next, failed));
468        if new && let Ok(value) = format!("csrftoken={token}; Path=/; SameSite=Lax").parse() {
469            response.headers_mut().insert(header::SET_COOKIE, value);
470        }
471        response
472    }
473
474    fn log_in(&mut self, form: &[(String, String)], headers: &HeaderMap) -> Response {
475        let token = field(form, "csrfmiddlewaretoken");
476        let referer = header_value(headers, &header::REFERER);
477        if token.is_none()
478            || token.map(str::to_owned) != cookie(headers, "csrftoken")
479            || !referer.is_some_and(|referer| referer.ends_with(LOGIN))
480        {
481            return html(
482                StatusCode::FORBIDDEN,
483                "<h1>Forbidden (403)</h1><p>CSRF verification failed.</p>".to_owned(),
484            );
485        }
486        let rejected = self
487            .take(|i| (*i == Injection::RejectLogin).then_some(()))
488            .is_some();
489        if rejected
490            || field(form, "username") != Some(USERNAME)
491            || field(form, "password") != Some(PASSWORD)
492        {
493            return self.login_page(headers, field(form, "next").unwrap_or(START), true);
494        }
495        let cookie = self.new_session();
496        let next = field(form, "next")
497            .filter(|next| next.starts_with('/'))
498            .unwrap_or(START);
499        redirect(next, Some(cookie))
500    }
501}
502
503fn not_found() -> Response {
504    html(StatusCode::NOT_FOUND, "<h1>Not Found</h1>".to_owned())
505}
506
507/// The week of a path like `/kunden/essen/2026/50/`.
508fn week_of(path: &str) -> Option<(i16, i8)> {
509    let rest = path.strip_prefix(START)?.strip_suffix('/')?;
510    let (year, week) = rest.split_once('/')?;
511    Some((year.parse().ok()?, week.parse().ok()?))
512}