// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! Share links in edge (ROADMAP ยง6 phase 2, tests first): a valid link lets the visitor in on //! its host and prefix only, without forward-auth; the token travels in the URL once and is //! then a path-scoped cookie; it never reaches the upstream or a log; expired, altered, //! wrong-host, wrong-path, stopped and password-less tokens are refused; wrong passwords are //! throttled; no path trick escapes the prefix. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #[cfg(unix)] mod common; #[cfg(not(unix))] #[test] fn skipped_on_windows() { eprintln!( "SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md", file!() ); } #[cfg(unix)] mod unix { use std::time::{Duration, SystemTime, UNIX_EPOCH}; use crate::common::{Edge, EdgeSpec, SHARE_KEY, host_file, start}; use ianitor_core::share::{LinkSpec, ShareId, ShareKey, mint}; use ianitor_testkit::authelia::MockAuthelia; use ianitor_testkit::client::{self, Req, Resp}; use ianitor_testkit::more::https_raw; use ianitor_testkit::upstream::Echo; const HOST: &str = "share.test"; fn now() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_secs() } fn key() -> ShareKey { ShareKey::new(SHARE_KEY).unwrap() } fn link(host: &str, id: u8, prefix: &str, expires_at: u64, password: Option<&str>) -> String { mint( &key(), host, &LinkSpec { id: ShareId([id; 16]), epoch: 0, expires_at, prefix, password, }, ) .unwrap() } struct Env { edge: Edge, echo: Echo, auth: MockAuthelia, } async fn env() -> Env { let auth = MockAuthelia::start().await; let echo = Echo::start("app").await; let site = format!("[forward_auth]\nurl = \"{}\"\n", auth.url()); let edge = start(EdgeSpec { site: &site, hosts: vec![ host_file( HOST, &format!( "upstreams = [\"{}\"]\nauth = \"forward-auth\"\nshare_links = true\naccess_log = \"truncated\"\n", echo.url() ), ), host_file( "closed.test", &format!( "upstreams = [\"{}\"]\nauth = \"forward-auth\"\nshare_links = false\n", echo.url() ), ), ], log_level: "debug", ..Default::default() }); Env { edge, echo, auth } } impl Env { async fn get(&self, host: &str, path: &str, cookie: Option<&str>) -> Resp { let mut req = Req::get(host, path); if let Some(c) = cookie { req = req.header("cookie", c); } client::https(self.edge.https, host, self.edge.roots(), &req) .await .unwrap() } async fn post_password(&self, token: &str, password: &str) -> Resp { let body = format!("t={}&password={}", urlencode(token), urlencode(password)); let req = Req::new("POST", HOST, "/.well-known/ianitor/share") .header("content-type", "application/x-www-form-urlencoded") .body(body.as_bytes()); client::https(self.edge.https, HOST, self.edge.roots(), &req) .await .unwrap() } /// Requests the upstream saw (health checks excluded). fn upstream_paths(&self) -> Vec { self.echo.proxied().iter().map(|r| r.path.clone()).collect() } } fn urlencode(s: &str) -> String { s.bytes() .map(|b| { if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") } }) .collect() } /// The `name=value` part of the share cookie a response sets. fn share_cookie(r: &Resp) -> String { let sc = r .header_all("set-cookie") .into_iter() .find(|c| c.starts_with("__Secure-ianitor-share=")) .unwrap_or_else(|| panic!("no share cookie in {:?}", r.headers)); sc.split(';').next().unwrap().to_owned() } fn assert_visitor_page(r: &Resp, status: u16, heading: &str) { assert_eq!(r.status, status, "{}", r.text()); assert!(r.text().contains(heading), "{heading}: {}", r.text()); assert_eq!(r.header("cache-control"), Some("no-store")); assert_eq!(r.header("referrer-policy"), Some("no-referrer")); assert!( r.header("content-security-policy") .is_some_and(|c| c.contains("default-src 'none'")) ); assert!(r.header("content-type").unwrap().starts_with("text/html")); assert!(!r.text().contains("")); assert!(e.upstream_paths().is_empty()); // A `share` parameter that is not ours is left alone (goes to the normal sign-in). let r = e.get(HOST, "/?share=holiday", None).await; assert_eq!(r.status, 302, "forward-auth portal redirect"); } #[tokio::test(flavor = "multi_thread")] async fn a_link_outside_its_prefix_falls_back_to_sign_in_and_never_leaks() { let e = env().await; let t = link(HOST, 6, "/albums", now() + 3600, None); let r = e.get(HOST, &format!("/private?share={t}"), None).await; assert_eq!(r.status, 302, "normal sign-in: {}", r.text()); // Signed in, the request goes through, but the token is not passed on. let r = e .get( HOST, &format!("/private?a=1&share={t}"), Some("authelia_session=good"), ) .await; assert_eq!(r.status, 200); let body: serde_json::Value = serde_json::from_slice(&r.body).unwrap(); assert_eq!(body["query"], "a=1", "token stripped before the upstream"); // On a host without share links the token gives nothing. let t2 = link("closed.test", 7, "/", now() + 3600, None); let r = e.get("closed.test", &format!("/?share={t2}"), None).await; assert_eq!(r.status, 302); // ...and is not passed on to the auth server or the upstream either. let r = e .get( "closed.test", &format!("/x?b=2&share={t2}"), Some("authelia_session=good"), ) .await; assert_eq!(r.status, 200); let body: serde_json::Value = serde_json::from_slice(&r.body).unwrap(); assert_eq!(body["query"], "b=2"); for req in e.auth.requests() { for (_, v) in &req.headers { assert!( !String::from_utf8_lossy(v).contains("ish1."), "token sent to the auth server" ); } } } #[tokio::test(flavor = "multi_thread")] async fn a_password_link_asks_checks_and_throttles() { let e = env().await; let t = link(HOST, 8, "/docs", now() + 3600, Some("correct horse")); let r = e.get(HOST, &format!("/docs/a?share={t}"), None).await; assert_visitor_page(&r, 401, "This link is protected"); assert!(r.text().contains("share.test")); assert!(r.text().contains("action=\"/.well-known/ianitor/share\"")); assert!(r.text().contains("name=\"password\"")); assert!(r.text().contains("The link works until")); assert!(share_cookie_absent(&r)); let r = e.post_password(&t, "wrong password").await; assert_visitor_page(&r, 401, "That password is not right"); assert!(share_cookie_absent(&r)); let r = e.post_password(&t, "correct horse").await; assert_eq!(r.status, 303, "{}", r.text()); assert_eq!(r.header("location"), Some("/docs")); let cookie = share_cookie(&r); assert_eq!(e.get(HOST, "/docs/a", Some(&cookie)).await.status, 200); // The cookie of a password link cannot be turned into a link that skips the password. let v = cookie.split_once('=').unwrap().1.to_owned(); let r = e .get( HOST, &format!("/docs?share={}", v.replacen("iss1.", "ish1.", 1)), None, ) .await; assert_ne!(r.status, 303); // Five wrong tries a minute, then a pause (the right password too). let t2 = link(HOST, 9, "/docs", now() + 3600, Some("correct horse")); for _ in 0..5 { assert_eq!(e.post_password(&t2, "nope nope").await.status, 401); } let r = e.post_password(&t2, "nope nope").await; assert_visitor_page(&r, 429, "Too many tries"); let r = e.post_password(&t2, "correct horse").await; assert_eq!(r.status, 429); // Other links are not affected. let t3 = link(HOST, 10, "/docs", now() + 3600, Some("correct horse")); assert_eq!(e.post_password(&t3, "correct horse").await.status, 303); // The password never reaches a log. assert!(!e.edge.all_output().contains("correct horse")); } fn share_cookie_absent(r: &Resp) -> bool { !r.header_all("set-cookie") .iter() .any(|c| c.starts_with("__Secure-ianitor-share=")) } #[tokio::test(flavor = "multi_thread")] async fn no_path_trick_escapes_the_cookie_prefix() { let e = env().await; let t = link(HOST, 11, "/a", now() + 3600, None); let r = e.get(HOST, &format!("/a?share={t}"), None).await; let cookie = share_cookie(&r); let before = e.upstream_paths().len(); for path in [ "/ab", "/A", "/A/x", "/b", "/a/../b", "/a/%2e%2e/b", "/a/%2E%2E/b", "/a/%252e%252e/b", "/a%2f..%2fb", "/a//b", "//a/b", "/a/..;/b", "/a/\\..\\b", "/a\\..\\b", ] { let raw = format!( "GET {path} HTTP/1.1\r\nHost: {HOST}\r\nCookie: {cookie}\r\nConnection: close\r\n\r\n" ); let r = https_raw(e.edge.https, HOST, e.edge.roots(), raw.as_bytes()) .await .unwrap(); assert_ne!(r.status, 200, "{path} got through: {}", r.text()); } assert_eq!( e.upstream_paths().len(), before, "no escaped request reached the upstream: {:?}", e.upstream_paths() ); } #[tokio::test(flavor = "multi_thread")] async fn stopped_links_and_stop_all_take_effect_at_once() { let e = env().await; let t = link(HOST, 12, "/", now() + 3600, None); let keep = link(HOST, 13, "/", now() + 3600, None); let cookie = share_cookie(&e.get(HOST, &format!("/?share={t}"), None).await); let keep_cookie = share_cookie(&e.get(HOST, &format!("/?share={keep}"), None).await); assert_eq!(e.get(HOST, "/", Some(&cookie)).await.status, 200); e.edge.write_revocations(0, &[ShareId([12; 16]).to_hex()]); let r = e .edge .admin("POST", "/v1/share-revocations/reload", None) .await; assert_eq!(r.status, 200, "{}", r.text); assert_eq!( e.get(HOST, "/", Some(&cookie)).await.status, 302, "back to sign-in" ); let r = e.get(HOST, &format!("/?share={t}"), None).await; assert_visitor_page(&r, 403, "This link no longer works"); assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 200); // Stop all: a new epoch ends every older link. e.edge.write_revocations(1, &[]); e.edge .admin("POST", "/v1/share-revocations/reload", None) .await; assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 302); // The epoch never goes back: a lower one is refused and the old state kept, so a // control that lost its records cannot revive stopped links. let fresh = mint( &key(), HOST, &LinkSpec { id: ShareId([14; 16]), epoch: 1, expires_at: now() + 3600, prefix: "/", password: None, }, ) .unwrap(); let fresh_cookie = share_cookie(&e.get(HOST, &format!("/?share={fresh}"), None).await); assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 200); e.edge.write_revocations(0, &[]); let r = e .edge .admin("POST", "/v1/share-revocations/reload", None) .await; assert_eq!(r.status, 422, "{}", r.text); assert!(r.text.contains("epoch"), "{}", r.text); assert_eq!( e.get(HOST, "/", Some(&keep_cookie)).await.status, 302, "still stopped" ); assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 200); // Without the admin call, edge notices a changed file within 5 s. e.edge.write_revocations(1, &[ShareId([14; 16]).to_hex()]); tokio::time::sleep(Duration::from_secs(6)).await; assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 302); // ...and a lower epoch written behind its back is refused there too. e.edge.write_revocations(0, &[]); tokio::time::sleep(Duration::from_secs(6)).await; assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 302); assert!(e.edge.stderr().contains("epoch"), "the refusal is logged"); // A broken file keeps the last good state; a missing one stops all share access. e.edge.write_revocations(1, &[]); e.edge .admin("POST", "/v1/share-revocations/reload", None) .await; assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 200); std::fs::write(e.edge.revocations_path(), "{ broken").unwrap(); let r = e .edge .admin("POST", "/v1/share-revocations/reload", None) .await; assert_eq!(r.status, 422); assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 200); std::fs::remove_file(e.edge.revocations_path()).unwrap(); e.edge .admin("POST", "/v1/share-revocations/reload", None) .await; assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 302); } }