From c321eeeef12269903b06a660cc80b872b070ff60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 27 Aug 2026 01:22:11 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(topcoat):=20the=20server=20plu?= =?UTF-8?q?mbing=20crosses=20over?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ports izlek-web/src/server.rs's session cookie, Mail wrapper, and role guards, plus the Refusal enum/call_id and the carry_refusal_on_redirect layer from auth.rs, onto topcoat's cookie jar, app_context, memoize and #[layer] primitives. The cookie name and its attributes stay byte-identical. --- Cargo.lock | 2 + crates/izlek-topcoat/Cargo.toml | 4 + crates/izlek-topcoat/src/lib.rs | 1 + crates/izlek-topcoat/src/main.rs | 2 +- crates/izlek-topcoat/src/server.rs | 669 +++++++++++++++++++++++++++++ 5 files changed, 677 insertions(+), 1 deletion(-) create mode 100644 crates/izlek-topcoat/src/server.rs diff --git a/Cargo.lock b/Cargo.lock index 64c289a..7938f74 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2136,9 +2136,11 @@ version = "0.1.0" dependencies = [ "async-trait", "grass", + "http", "izlek-core", "lettre", "serde", + "serde_json", "thiserror", "time", "tokio", diff --git a/crates/izlek-topcoat/Cargo.toml b/crates/izlek-topcoat/Cargo.toml index fa06dc4..91edd49 100644 --- a/crates/izlek-topcoat/Cargo.toml +++ b/crates/izlek-topcoat/Cargo.toml @@ -20,6 +20,7 @@ topcoat = { version = "0.6.2", default-features = false, features = [ ] } izlek-core = { workspace = true, features = ["server"] } serde.workspace = true +serde_json.workspace = true time.workspace = true thiserror.workspace = true tokio = { workspace = true } @@ -37,3 +38,6 @@ lettre = { version = "0.11.23", default-features = false, features = [ [build-dependencies] grass = "0.13" + +[dev-dependencies] +http = "1.5" diff --git a/crates/izlek-topcoat/src/lib.rs b/crates/izlek-topcoat/src/lib.rs index 2ef9765..2c87b41 100644 --- a/crates/izlek-topcoat/src/lib.rs +++ b/crates/izlek-topcoat/src/lib.rs @@ -4,4 +4,5 @@ #![recursion_limit = "256"] pub mod layout; +pub mod server; pub mod smtp; diff --git a/crates/izlek-topcoat/src/main.rs b/crates/izlek-topcoat/src/main.rs index 03d931c..d2ce7ce 100644 --- a/crates/izlek-topcoat/src/main.rs +++ b/crates/izlek-topcoat/src/main.rs @@ -56,7 +56,7 @@ async fn main() { .cookies() .assets(AssetBundle::load().expect("failed to load the asset bundle")) .app_context(accounts) - .app_context(engine) + .app_context(izlek_topcoat::server::Mail::sending(engine.clone())) .build(); topcoat::start(router).await.expect("server error"); diff --git a/crates/izlek-topcoat/src/server.rs b/crates/izlek-topcoat/src/server.rs new file mode 100644 index 0000000..dbd9cfa --- /dev/null +++ b/crates/izlek-topcoat/src/server.rs @@ -0,0 +1,669 @@ +//! Server-side plumbing for the auth surface: the session cookie, the person +//! behind the current request, and the role guards. +//! +//! Every guard here is the real one. The UI hides what a role may not do, but +//! the answer that matters is the one given in this module, on the server. +//! +//! Ported from `izlek-web/src/server.rs` and the `Refusal`/`call_id` pieces of +//! `izlek-web/src/auth.rs`, onto topcoat's context/cookie/layer primitives. + +use izlek_core::accounts::{AccountError, Accounts}; +use izlek_core::board::Transition; +use izlek_core::mail::Engine; +use izlek_core::store::{Freeing, User}; +use serde::{Deserialize, Serialize}; +use topcoat::context::{Cx, app_context, memoize, try_app_context}; +use topcoat::cookie::{Cookie, Cookies, SameSite, cookie, cookies}; +use topcoat::router::request::headers; +use topcoat::router::{Body, HeaderValue, Next, StatusCode, header, response::Response, to_bytes}; + +/// The session cookie's name. One cookie, one browser, one session row. +pub const SESSION_COOKIE: &str = "izlek_session"; + +/// The workspace's account service, put into context by the router. +pub fn accounts(cx: &Cx) -> Accounts { + app_context::(cx).clone() +} + +/// The mail engine, or the fact that there is nobody to hand a crossing to. +/// +/// The running server always has an engine: the sender is workspace settings +/// now, so it can appear at any moment and the engine reads it per send. The +/// `None` is for tests, which drive the router without one and assert on the +/// ledger rather than on a mail server. +#[derive(Clone)] +pub struct Mail(Option>); + +impl Mail { + /// No engine at all. Crossings are recorded and nothing is handed on. + pub fn silent() -> Self { + Self(None) + } + + pub fn sending(engine: std::sync::Arc) -> Self { + Self(Some(engine)) + } + + /// Hands a committed crossing to the engine, off the request. + /// + /// The move is already written by the time this is called and the response + /// does not wait for it: a card that took thirty seconds to drop because + /// somebody's SMTP host was slow would be a board broken by its own mail + /// feature. What the send is owed is in the ledger, so a process that dies + /// mid-send loses nothing — the sweep picks it up. + pub fn after(&self, transition: Transition) { + let Some(engine) = self.0.clone() else { + return; + }; + tokio::spawn(async move { + let report = engine.on_transition(&transition).await; + Self::log(report); + }); + } + + /// Kicks the engine to send an invite mail now rather than on the next + /// sweep, off the request the same way `after` is. + /// + /// The invite is already on the ledger by the time this is called — this + /// only makes the wait before it leaves as short as the request itself, + /// so the admin does not sit wondering whether the mail is coming. + pub fn after_invite(&self) { + let Some(engine) = self.0.clone() else { + return; + }; + tokio::spawn(async move { + let report = engine + .deliver_owed(time::OffsetDateTime::now_utc(), 8) + .await; + Self::log(report); + }); + } + + /// Hands a recorded activity to the engine, off the request, the same way + /// `after` hands a transition. + /// + /// The activity row is already written by the time this is called; this + /// rehydrates it and lets the engine decide whether any rule owes a mail. + /// `store` is the same store the request already wrote through — the + /// engine has no public handle back to it, so the caller carries it. + pub fn after_activity(&self, store: std::sync::Arc, activity_id: String) { + let Some(engine) = self.0.clone() else { + return; + }; + tokio::spawn(async move { + let report = match store.event(&activity_id).await { + Ok(Some(izlek_core::store::Event::Happened(ev))) => { + match engine.on_activity(&ev).await { + Ok(_) => { + engine + .deliver_owed(time::OffsetDateTime::now_utc(), 8) + .await + } + Err(problem) => Err(problem), + } + } + Ok(_) => return, + Err(problem) => Err(problem), + }; + Self::log(report); + }); + } + + /// Hands a committed delete to the engine, off the request, the same way. + /// + /// A blocker being deleted frees the tasks that were waiting on it just as + /// finishing it would, so the unblocked rule fires on both. The freeing is + /// already written; this only reads it. + pub fn after_freeing(&self, freeing: Freeing, freed: Vec) { + let Some(engine) = self.0.clone() else { + return; + }; + tokio::spawn(async move { + let report = engine.on_freeing(&freeing, &freed).await; + Self::log(report); + }); + } + + /// Sends one test mail and waits for the answer, because the answer is the + /// whole point of pressing the button. `None` means this process has no + /// engine at all, which happens only in tests. + pub async fn test(&self, to: &str) -> Option> { + let engine = self.0.clone()?; + Some(engine.send_test(to).await) + } + + fn log(report: izlek_core::store::Result) { + match report { + Ok(report) if report.sent + report.failed + report.abandoned > 0 => { + println!( + "izlek mail {} sent, {} to retry, {} given up on", + report.sent, report.failed, report.abandoned + ); + } + Ok(_) => {} + Err(problem) => eprintln!("izlek mail the ledger could not be read: {problem}"), + } + } +} + +/// The engine for this request, or a silent one when the router was built +/// without an engine at all. +pub fn mail(cx: &Cx) -> Mail { + try_app_context::(cx).cloned().unwrap_or_else(Mail::silent) +} + +/// The application cookie jar, with the attributes every Izlek cookie wants. +fn app_cookies(cx: &Cx) -> impl Cookies { + cookies(cx) + .default_secure(true) + .default_http_only(true) + .default_same_site(SameSite::Lax) + .default_path("/") +} + +/// The cookie value this request presented, if it presented one. +pub fn presented_session(cx: &Cx) -> Option { + cookies(cx).get(SESSION_COOKIE).map(|c| c.value().to_string()) +} + +/// A stable-enough label for the client, for rate limiting. A proxy header is +/// only trusted because Izlek is meant to sit behind one; the address bucket is +/// the limit that actually protects the Argon2 work either way. +/// +/// topcoat 0.6.2 exposes no peer address; x-forwarded-for or nothing. +pub fn client_label(cx: &Cx) -> String { + let Some(forwarded) = headers(cx).get("x-forwarded-for") else { + return "unknown".to_string(); + }; + let Ok(raw) = forwarded.to_str() else { + return "unknown".to_string(); + }; + match raw.split(',').next() { + Some(first) if !first.trim().is_empty() => first.trim().to_string(), + _ => "unknown".to_string(), + } +} + +/// Writes the session cookie. `HttpOnly` so script cannot read it, `Secure` so +/// it never crosses plain HTTP, `SameSite=Lax` so another site's form cannot +/// post with it. +pub fn set_session_cookie(cx: &Cx, token: &str, lifetime: time::Duration) { + app_cookies(cx).add(cookie! { + SESSION_COOKIE = token.to_owned(); + Path = "/"; + Secure; + HttpOnly; + SameSite = Lax; + MaxAge = lifetime + }); +} + +/// Removes the session cookie from this browser. The server-side revocation is +/// what actually ends the session; this only tidies the client. +pub fn clear_session_cookie(cx: &Cx) { + app_cookies(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/").build()); +} + +/// The person behind this request, or nobody, or the store failing to say. +/// +/// A store error is not "nobody" — a busy database mid-drag is a fact about +/// the database, not about whether this browser is signed in, and a caller +/// that folded the two together would send a signed-in person to a sign-in +/// screen because a write elsewhere held a lock for a moment. +#[memoize(as_ref)] +pub async fn current_user(cx: &Cx) -> Result, AccountError> { + let Some(presented) = presented_session(cx) else { + return Ok(None); + }; + accounts(cx).authenticate(&presented).await +} + +/// The person behind this request, or a refusal the caller can return as-is. +/// +/// A store error becomes `Refusal::Unavailable` — the same place every other +/// account error already lands, via `refusal_for` below — rather than +/// `SignInFirst`, which would tell a signed-in person to sign in again over +/// what was only a database hiccup. +pub async fn require_user(cx: &Cx) -> Result { + match current_user(cx).await { + Ok(Some(user)) => Ok(user.clone()), + Ok(None) => Err(Refusal::SignInFirst), + Err(error) => Err(refusal_for(error)), + } +} + +/// The admin behind this request. A member or a viewer is refused *here*, not +/// merely hidden from in the UI. +pub async fn require_admin(cx: &Cx) -> Result { + let user = require_user(cx).await?; + if user.role.can_administer() { + Ok(user) + } else { + Err(Refusal::Forbidden) + } +} + +/// The person behind this request if they may change the board. +pub async fn require_writer(cx: &Cx) -> Result { + let user = require_user(cx).await?; + if user.role.can_write_tasks() { + Ok(user) + } else { + Err(Refusal::Forbidden) + } +} + +/// Shared by `From` and the `&AccountError` `current_user` +/// hands back once memoized, so both paths land on the exact same wording. +fn refusal_for(error: &AccountError) -> Refusal { + match error { + AccountError::Rejected => Refusal::Rejected, + AccountError::RateLimited => Refusal::RateLimited, + AccountError::Password(problem) => Refusal::Password(problem.to_string()), + AccountError::Forbidden => Refusal::Forbidden, + AccountError::AlreadyClaimed => Refusal::AlreadyClaimed, + AccountError::AddressTaken => Refusal::AddressTaken, + AccountError::Store(error) => { + eprintln!("store error: {error}"); + Refusal::Unavailable + } + AccountError::Auth(error) => { + eprintln!("auth error: {error}"); + Refusal::Unavailable + } + } +} + +impl From for Refusal { + fn from(error: AccountError) -> Self { + refusal_for(&error) + } +} + +/// Everything a refused call is allowed to say. +/// +/// Ported from `izlek-web/src/auth.rs`; the auth pages that construct most of +/// these variants land in a later slice, but the server plumbing above needs +/// the type now. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum Refusal { + /// Wrong address, wrong password, or no account at all — deliberately one + /// answer for all three. + Rejected, + RateLimited, + /// A password broke a stated rule. Only reachable once we know who the + /// person is, so it gives nothing away. + Password(String), + Forbidden, + SignInFirst, + AlreadyClaimed, + /// Admin-side wording, shown on the member list and nowhere public. + AddressTaken, + /// The link is spent, expired, or was never real. + LinkNotUsable, + /// A card with no title is not a card. + EmptyTitle, + /// A person with no name is not a person the board can show. + EmptyName, + /// A limit of nothing, or a limit wider than the disk should promise. + BadLimit, + /// Something in the allowed-types list is not a file extension. + BadFileType, + /// The sender panel was saved with a field it cannot work without, or with + /// one that is not what it claims to be. The message names the field: this + /// is a form somebody is filling in, not an attacker probing, and "that did + /// not work" would send them round the panel guessing. + BadSender(String), + /// A comment with nothing in it. + EmptyComment, + /// The upload arrived without a file in it. + NoFile, + /// The bytes kept coming past what this workspace allows per file. + FileTooBig, + /// The name does not end in one of the extensions the admin allows. + FileTypeNotAllowed, + /// A rule with no subject line: the mail it sends would arrive blank. + EmptySubject, + /// The date field did not hold a date. + BadDeadline, + /// The link asked for would put a task behind itself. + Cycle, + /// The card was already moved out of the column this request thought it + /// was in, by somebody else, while this person was deciding. + MovedAlready, + /// No such task — or none this account may see. Deliberately one answer for + /// both. + NotFound, + Unavailable, +} + +impl Refusal { + /// The refusal as a short word, for the address bar. + /// + /// A browser without script never sees a call's return value: it posts the + /// form, follows the redirect, and the page it lands on has to be told what + /// happened. That telling goes through the query, so every refusal needs a + /// name that survives a round trip through a URL. + pub fn code(&self) -> &'static str { + match self { + Refusal::Rejected => "rejected", + Refusal::RateLimited => "rate-limited", + // The problem itself, not the wording, so the sentence is built + // here on the way back rather than reflected out of the address. + Refusal::Password(problem) => { + if problem == "at least 10 characters" { + "password-short" + } else if problem == "not your address or your name" { + "password-you" + } else { + "rejected" + } + } + Refusal::Forbidden => "forbidden", + Refusal::SignInFirst => "sign-in-first", + Refusal::AlreadyClaimed => "already-claimed", + Refusal::AddressTaken => "address-taken", + Refusal::LinkNotUsable => "link-not-usable", + Refusal::EmptyTitle => "empty-title", + Refusal::EmptyName => "empty-name", + Refusal::BadLimit => "bad-limit", + Refusal::BadFileType => "bad-file-type", + Refusal::BadSender(_) => "bad-sender", + Refusal::EmptyComment => "empty-comment", + Refusal::NoFile => "no-file", + Refusal::FileTooBig => "file-too-big", + Refusal::FileTypeNotAllowed => "file-type", + Refusal::EmptySubject => "empty-subject", + Refusal::BadDeadline => "bad-deadline", + Refusal::Cycle => "cycle", + Refusal::MovedAlready => "moved-already", + Refusal::NotFound => "not-found", + Refusal::Unavailable => "unavailable", + } + } +} + +/// Which call a carried refusal belongs to. Two forms on one page must not both +/// claim the same sentence, so the redirect names the call and this is the name: +/// the last piece of the server function's path, with anything that is not a +/// plain word dropped so it can only ever be compared, never rendered. +pub fn call_id(path: &str) -> String { + path.rsplit('/') + .next() + .unwrap_or(path) + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-') + .collect() +} + +/// Puts a refusal on the redirect a browser without script follows. +/// +/// A hydrated page reads the call's return value straight off the action. A +/// browser without script has no such thing: it posts the form, the server +/// function handler answers with a redirect back to the page it came from, and +/// the value — the whole refusal — sits in a body nobody will ever look at. +/// The click then looks like nothing happening, which is the worst answer +/// Izlek can give. +/// +/// So the refusal is copied onto the `Location`, as `?refusal=&on=`, +/// and the page renders it from the query. This is one place rather than +/// thirty-eight because the shape is the same for every refusing call, present +/// and future: nothing here knows what any of them do. +/// +/// Requests carrying script are untouched — they are answered with the value +/// itself and never see a redirect. +/// +/// Ported from axum's `middleware::from_fn` onto a topcoat `#[layer]`. topcoat's +/// Post/Redirect/Get helper (`error::see_other`) answers with `303 See Other`, +/// not the `302 Found` axum's server-function redirect used, so the status this +/// checks for is `SEE_OTHER` — the guard's three conditions are otherwise +/// unchanged. +#[topcoat::router::layer("/api")] +async fn carry_refusal_on_redirect(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result { + // A form post from a browser asks for a page back. A server-function call + // from the hydrated bundle does not. + let wants_page = headers(cx) + .get(header::ACCEPT) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| value.contains("text/html")); + let called = call_id(topcoat::router::request::uri(cx).path()); + let has_referer = headers(cx).contains_key(header::REFERER); + let response = next.run(cx, body).await?; + if !wants_page || !has_referer || response.status() != StatusCode::SEE_OTHER { + return Ok(response); + } + + let (mut parts, body) = response.into_parts(); + // The body of one of these redirects is a serialised `Option` and + // nothing else; the cap is there so a response that is something else + // entirely cannot be read into memory whole. + let Ok(bytes) = to_bytes(body, 64 * 1024).await else { + return Ok(Response::from_parts(parts, Body::empty())); + }; + if let Ok(Some(refusal)) = serde_json::from_slice::>(&bytes) + && let Some(location) = parts.headers.get(header::LOCATION).and_then(|v| v.to_str().ok()) + && let Some(carried) = carrying(location, refusal.code(), &called) + && let Ok(value) = HeaderValue::from_str(&carried) + { + parts.headers.insert(header::LOCATION, value); + } + Ok(Response::from_parts(parts, Body::from(bytes))) +} + +/// `location` with the refusal in its query. +/// +/// The redirect goes back to the page the form was posted from, and that page +/// may already carry a query — `?task=DZ-01` is how a browser without script +/// opens the modal at all — so the two pairs are merged in, and the pair from +/// any earlier refusal is dropped rather than stacked on top of. +fn carrying(location: &str, code: &str, called: &str) -> Option { + if called.is_empty() { + return None; + } + // The Location we are rewriting came from the form post's Referer, and on a + // cross-origin post the Referer is whatever the other site is. Sending the + // browser back there would make Izlek an open redirect, so the address is + // rebuilt from its path and query alone and anything that is not a plain + // absolute path is answered with the board. + let here = same_origin(location); + let (path, query) = match here.split_once('?') { + Some((path, query)) => (path, query), + None => (here, ""), + }; + let mut pairs: Vec = query + .split('&') + .filter(|pair| { + !pair.is_empty() && !pair.starts_with("refusal=") && !pair.starts_with("on=") + }) + .map(str::to_string) + .collect(); + pairs.push(format!("refusal={code}&on={called}")); + Some(format!("{path}?{}", pairs.join("&"))) +} + +/// The path and query of `location`, with scheme and authority dropped. A +/// protocol-relative address (`//elsewhere.example/`) is another host wearing a +/// path's clothes, and a browser reads a backslash there as a slash, so both +/// are answered with the board rather than trusted. +fn same_origin(location: &str) -> &str { + let rest = match location.split_once("://") { + Some((_scheme, rest)) => match rest.find(['/', '?']) { + Some(at) => &rest[at..], + None => "/", + }, + None => location, + }; + let mut characters = rest.chars(); + match (characters.next(), characters.next()) { + (Some('/'), Some('/' | '\\')) => "/", + (Some('/'), _) => rest, + _ => "/", + } +} + +#[cfg(test)] +mod refusal_redirect_tests { + use super::carrying; + + #[test] + fn a_bare_address_gains_a_query() { + assert_eq!( + carrying("http://izlek.sh/", "cycle", "link_tasks").as_deref(), + Some("/?refusal=cycle&on=link_tasks") + ); + } + + #[test] + fn an_open_modal_stays_open() { + assert_eq!( + carrying("http://izlek.sh/?task=DZ-01", "cycle", "link_tasks").as_deref(), + Some("/?task=DZ-01&refusal=cycle&on=link_tasks") + ); + } + + #[test] + fn a_second_refusal_replaces_the_first() { + assert_eq!( + carrying( + "http://izlek.sh/?task=DZ-01&refusal=cycle&on=link_tasks", + "not-found", + "link_tasks" + ) + .as_deref(), + Some("/?task=DZ-01&refusal=not-found&on=link_tasks") + ); + } + + // The Referer of a cross-origin post is the other site's address, and it + // reaches this function as the Location. Izlek answers on its own ground or + // not at all. + #[test] + fn another_site_cannot_be_redirected_to() { + for elsewhere in [ + "https://elsewhere.example", + "//elsewhere.example/steal", + "/\\elsewhere.example/steal", + "javascript:alert(1)", + "", + ] { + assert_eq!( + carrying(elsewhere, "cycle", "link_tasks").as_deref(), + Some("/?refusal=cycle&on=link_tasks"), + "{elsewhere} was not brought home" + ); + } + // An address with a path keeps the path — it is read as a path on this + // site, which is the point: whatever the Referer claimed, the browser + // is sent somewhere on Izlek. + let carried = carrying( + "http://elsewhere.example/steal?task=DZ-01", + "cycle", + "link_tasks", + ); + assert_eq!( + carried.as_deref(), + Some("/steal?task=DZ-01&refusal=cycle&on=link_tasks") + ); + } + + #[test] + fn a_path_on_this_site_is_kept() { + assert_eq!( + carrying("/board?task=DZ-01", "cycle", "link_tasks").as_deref(), + Some("/board?task=DZ-01&refusal=cycle&on=link_tasks") + ); + } + + #[test] + fn a_call_with_no_name_carries_nothing() { + assert_eq!(carrying("http://izlek.sh/", "cycle", ""), None); + } +} + +#[cfg(test)] +mod call_id_tests { + use super::call_id; + + #[test] + fn a_call_is_named_by_its_last_path_piece() { + assert_eq!(call_id("/api/link_tasks"), "link_tasks"); + assert_eq!(call_id("/api/link_tasks?x=1"), "link_tasksx1"); + } +} + +#[cfg(test)] +mod session_cookie_tests { + use super::{SESSION_COOKIE, clear_session_cookie, presented_session, set_session_cookie}; + use topcoat::context::{Cx, CxTestBuilder}; + use topcoat::cookie::{CookieJarCell, write_cookies}; + + /// A `Cx` whose request carried the given `Cookie` header, ready for + /// `set_session_cookie`/`presented_session`/`clear_session_cookie` to read + /// and write through. + fn cx_with(cookie_header: Option<&str>) -> Cx { + let mut builder = http::Request::builder(); + if let Some(value) = cookie_header { + builder = builder.header(http::header::COOKIE, value); + } + let (parts, ()) = builder.body(()).unwrap().into_parts(); + CxTestBuilder::new() + .request_context(parts) + .request_context(CookieJarCell::new()) + .build() + } + + fn set_cookie_headers(cx: &Cx) -> Vec { + let mut headers = http::HeaderMap::new(); + write_cookies(cx, &mut headers); + headers + .get_all(http::header::SET_COOKIE) + .iter() + .map(|v| v.to_str().unwrap().to_owned()) + .collect() + } + + /// The cookie name is a wire contract: every existing browser's `Cookie` + /// header still says "izlek_session", and it must stay byte-identical or + /// every one of them is signed out at once. + #[test] + fn the_cookie_name_stayed_byte_identical() { + assert_eq!(SESSION_COOKIE, "izlek_session"); + } + + #[test] + fn setting_writes_the_session_cookie_with_the_right_attributes() { + let cx = cx_with(None); + set_session_cookie(&cx, "tok123", time::Duration::days(14)); + + let set = set_cookie_headers(&cx); + assert_eq!(set.len(), 1); + assert!(set[0].starts_with("izlek_session=tok123;"), "{}", set[0]); + for attr in ["Path=/", "Secure", "HttpOnly", "SameSite=Lax", "Max-Age=1209600"] { + assert!(set[0].contains(attr), "{} missing {attr}", set[0]); + } + } + + #[test] + fn presented_session_reads_the_cookie_the_browser_sent() { + let cx = cx_with(Some("izlek_session=tok123")); + assert_eq!(presented_session(&cx).as_deref(), Some("tok123")); + } + + #[test] + fn absent_cookie_presents_nothing() { + let cx = cx_with(None); + assert_eq!(presented_session(&cx), None); + } + + #[test] + fn clearing_expires_the_cookie_at_the_same_path() { + let cx = cx_with(Some("izlek_session=tok123")); + clear_session_cookie(&cx); + + let set = set_cookie_headers(&cx); + assert_eq!(set.len(), 1); + assert!(set[0].starts_with("izlek_session="), "{}", set[0]); + assert!(set[0].contains("Max-Age=0"), "{}", set[0]); + assert!(set[0].contains("Path=/"), "{}", set[0]); + } +}