Files
ianitor/crates/edge/tests/share_links.rs
T

558 lines
21 KiB
Rust

// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Part of Ianitor, under the Common Public Attribution
// License 1.0: see LICENSE (its Exhibit A is this file's notice).
//! 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;
// On Windows this target has nothing to run: it shows as one *ignored* test, never as a
// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md).
#[cfg(not(unix))]
#[test]
#[ignore = "needs Linux (Pingora runner, Caddy, Pebble): run it in WSL2, see CLAUDE.md"]
fn needs_linux() {}
#[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<String> {
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("<script"), "no JavaScript");
assert!(
!r.text().contains("http://") && !r.text().contains("https://"),
"no external requests"
);
assert!(r.body.len() < 8 * 1024);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_valid_link_lets_the_visitor_in_without_forward_auth() {
let e = env().await;
let t = link(HOST, 1, "/albums", now() + 3600, None);
let r = e
.get(HOST, &format!("/albums/summer?x=1&share={t}&y=2"), None)
.await;
assert_eq!(r.status, 303, "{}", r.text());
assert_eq!(r.header("location"), Some("/albums/summer?x=1&y=2"));
assert_eq!(r.header("referrer-policy"), Some("no-referrer"));
let set = r
.header_all("set-cookie")
.into_iter()
.find(|c| c.starts_with("__Secure-ianitor-share="))
.unwrap()
.to_owned();
for attr in [
"Path=/albums",
"HttpOnly",
"Secure",
"SameSite=Lax",
"Max-Age=",
] {
assert!(set.contains(attr), "{attr} missing in {set}");
}
assert!(!set.contains(&t), "the cookie is not the link token");
assert!(
e.upstream_paths().is_empty(),
"the token request never reached the upstream"
);
let auth_calls = e.auth.requests().len();
let cookie = share_cookie(&r);
let r = e
.get(
HOST,
"/albums/summer?x=1&y=2",
Some(&format!("{cookie}; other=1")),
)
.await;
assert_eq!(r.status, 200, "{}", r.text());
assert_eq!(
e.auth.requests().len(),
auth_calls,
"no forward-auth for a share visitor"
);
let seen = e.echo.proxied();
let last = seen.last().unwrap();
assert_eq!(last.path, "/albums/summer");
let cookie_sent = last
.header("cookie")
.map(|c| String::from_utf8_lossy(c).into_owned())
.unwrap_or_default();
assert!(
!cookie_sent.contains("ianitor-share"),
"share cookie stripped: {cookie_sent}"
);
assert!(
cookie_sent.contains("other=1"),
"other cookies kept: {cookie_sent}"
);
assert!(last.header("referer").is_none());
// The prefix itself and deeper paths are covered.
assert_eq!(e.get(HOST, "/albums", Some(&cookie)).await.status, 200);
assert_eq!(
e.get(HOST, "/albums/a/b/c.jpg", Some(&cookie)).await.status,
200
);
// Neither the token nor the cookie appears in any log.
tokio::time::sleep(Duration::from_millis(200)).await;
let logs = e.edge.all_output();
assert!(!logs.contains(&t[5..40]), "token in logs");
assert!(!logs.contains(&cookie[30..60]), "cookie in logs");
assert!(
!e.edge.access_log().contains("share="),
"query in access log"
);
for r in e.echo.requests() {
for (_, v) in &r.headers {
assert!(!String::from_utf8_lossy(v).contains(&t[5..40]));
}
}
}
#[tokio::test(flavor = "multi_thread")]
async fn bad_tokens_get_plain_english_pages() {
let e = env().await;
// Expired: the signature proves the date.
let t = link(HOST, 2, "/", now() - 10, None);
let r = e.get(HOST, &format!("/?share={t}"), None).await;
assert_visitor_page(&r, 410, "This link has expired");
// Another host's token, an altered token, a token made with another key.
let other = link("closed.test", 3, "/", now() + 3600, None);
let mut altered = link(HOST, 4, "/", now() + 3600, None);
let last = altered.pop().unwrap();
altered.push(if last == 'A' { 'B' } else { 'A' });
let foreign = mint(
&ShareKey::new(b"another-key-another-key-another-key-0000").unwrap(),
HOST,
&LinkSpec {
id: ShareId([5; 16]),
epoch: 0,
expires_at: now() + 3600,
prefix: "/",
password: None,
},
)
.unwrap();
for bad in [other, altered, foreign, "ish1.garbage".to_owned()] {
let r = e.get(HOST, &format!("/?share={bad}"), None).await;
assert_visitor_page(&r, 403, "This link no longer works");
}
// Escaping: only the hostname and the date come from the request.
let r = e.get(HOST, "/?share=ish1.%3Cscript%3E", None).await;
assert!(!r.text().contains("<script>"));
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");
// Edge remembers the highest epoch in its own state: after a restart a lower one
// (control's files rolled back) is still refused.
e.edge.write_revocations(1, &[]);
e.edge
.admin("POST", "/v1/share-revocations/reload", None)
.await;
let mut e = e;
e.edge.restart();
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_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 302);
// 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);
}
#[tokio::test(flavor = "multi_thread")]
async fn an_unreadable_epoch_floor_refuses_share_links() {
let mut e = env().await;
let t = link(HOST, 15, "/", now() + 3600, None);
let cookie = share_cookie(&e.get(HOST, &format!("/?share={t}"), None).await);
assert_eq!(e.get(HOST, "/", Some(&cookie)).await.status, 200);
std::fs::write(e.edge.dir.join("state/share-epoch-floor"), "garbage").unwrap();
e.edge.restart();
assert_eq!(
e.get(HOST, "/", Some(&cookie)).await.status,
302,
"fails closed"
);
let r = e
.edge
.admin("POST", "/v1/share-revocations/reload", None)
.await;
assert_eq!(r.status, 422, "{}", r.text);
assert!(e.edge.stderr().contains("share-epoch-floor"));
// A missing floor is simply 0.
std::fs::remove_file(e.edge.dir.join("state/share-epoch-floor")).unwrap();
e.edge.restart();
assert_eq!(e.get(HOST, "/", Some(&cookie)).await.status, 200);
}
}