Medlar/crates/core/tests/auth.rs
2026-11-25 05:58:23 -06:00

758 lines
32 KiB
Rust

//! Logins, cookies, proxies and certificates, and that none of the secrets get anywhere else.
use medlar_core::auth::Login;
use medlar_core::host::{Caps, Hosts};
use medlar_core::http::{ClientOptions, Error, Monitor, Options, Shared, client, download};
use medlar_core::manager::{Command, Config, Manager};
use medlar_core::model::{ErrorKind, State, Task};
use medlar_core::net_state::Bus;
use medlar_core::secret::{Kept, Secret, Secrets};
use medlar_core::settings::{Limits, Settings};
use medlar_core::site::{Site, Sites};
use medlar_core::store::{self, Store};
use medlar_testserver::proxy::Proxy;
use medlar_testserver::{Faults, Request, TestServer, expected};
use std::collections::HashMap;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::process::{Child, Stdio};
use std::sync::{Arc, Mutex, Once};
use std::time::Duration;
use tokio::sync::watch;
use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value};
const PASSWORD: &str = "S3CRETpass";
/// All that anything logged, before redaction.
static LOGGED: Mutex<String> = Mutex::new(String::new());
struct Recorder;
impl log::Log for Recorder {
fn enabled(&self, _: &log::Metadata) -> bool {
true
}
fn log(&self, r: &log::Record) {
// zbus traces the keyring's own messages; the log file takes nothing but warnings from others.
if r.target().starts_with("medlar") || r.level() <= log::Level::Warn {
LOGGED.lock().unwrap().push_str(&format!("{} {}\n", r.target(), r.args()));
}
}
fn flush(&self) {}
}
fn record() {
static ONCE: Once = Once::new();
ONCE.call_once(|| {
log::set_logger(&Recorder).unwrap();
log::set_max_level(log::LevelFilter::Trace);
});
}
struct Bench {
server: TestServer,
dir: tempfile::TempDir,
store: Arc<Store>,
sites: Arc<Sites>,
}
/// Straight to every server, unless told otherwise.
fn settings() -> Settings {
Settings { proxy: "direct".into(), proxy_bypass: vec![], ..Settings::default() }
}
fn sites(server: &TestServer, settings: &Settings, bus: Bus) -> Arc<Sites> {
sites_with(server.cert_der().into_iter().collect(), settings, bus)
}
fn sites_with(only_certs: Vec<Vec<u8>>, settings: &Settings, bus: Bus) -> Arc<Sites> {
let options = ClientOptions { idle_timeout: Duration::from_millis(2000), only_certs, ..ClientOptions::default() };
Sites::new(options, settings, Arc::new(Secrets::new(bus.clone())), bus).unwrap()
}
fn login(password: &str) -> Login {
Login { user: "me".into(), password: password.into() }
}
fn site(pattern: &str) -> Site {
Site { pattern: pattern.into(), ..Site::default() }
}
impl Bench {
async fn new() -> Bench {
Bench::with(TestServer::start().await, Bus::Off)
}
fn with(server: TestServer, bus: Bus) -> Bench {
record();
let dir = tempfile::tempdir().unwrap();
let store = Arc::new(Store::open(&dir.path().join("medlar.db")).unwrap());
let sites = sites(&server, &settings(), bus);
Bench { server, dir, store, sites }
}
fn set(&self, change: impl FnOnce(&mut Settings)) {
let mut s = settings();
change(&mut s);
self.sites.set(&s);
}
fn task(&self, path: &str) -> Task {
Task { url: self.server.url(path), folder: self.dir.path().join("files"), ..Task::default() }
}
/// A secret for this task alone.
async fn own(&self, mut task: Task, secret: Secret) -> Task {
let secret = Secret { home: Some(task.url.clone()), ..secret };
self.sites.secrets.save("task", "127.0.0.1", &secret).await;
task.secret = Some("task".into());
task
}
async fn get(&self, task: Task) -> Result<Vec<u8>, Error> {
let hosts = Hosts::new(Caps { burst: 1000, per_second: 1000.0, ..Caps::default() });
let shared = Shared { client: client(&ClientOptions::default()).unwrap(), store: self.store.clone(), hosts };
let options = Options { tries: 2, tick: Duration::from_millis(20), backoff: Duration::from_millis(20), ..Options::default() };
let id = self.store.add_task(task.clone()).unwrap();
let source = self.sites.source(&task).await?;
let (_keep, stop) = watch::channel(false);
let path = download(&shared, id, source, &options, &Monitor::new(4), stop).await?;
Ok(std::fs::read(path).unwrap())
}
/// The whole file came.
async fn gets(&self, task: Task) {
let url = task.url.clone();
let data = self.get(task).await.unwrap_or_else(|e| panic!("{url}: {e:?}"));
assert!(data == expected(7, 0, 300_000), "{url}");
}
}
fn path(prefix: &str) -> String {
format!("{prefix}/data/7/300000/f.bin")
}
fn status(result: Result<Vec<u8>, Error>) -> u16 {
match result {
Err(Error::Status { code, .. }) => code,
other => panic!("{:?}", other.map(|d| d.len())),
}
}
fn with_login(password: &str) -> Secret {
Secret { login: Some(login(password)), ..Secret::default() }
}
#[tokio::test]
async fn basic_and_digest() {
let b = Bench::new().await;
for kind in ["basic", "digest"] {
let path = path(&format!("/{kind}/me/{PASSWORD}"));
b.gets(b.own(b.task(&path), with_login(PASSWORD)).await).await;
let first = &b.server.log()[0];
assert_eq!((first.header("authorization"), first.status), (None, 401), "nothing before it is asked for");
b.server.clear_log();
assert_eq!(status(b.get(b.own(b.task(&path), with_login("wrong")).await).await), 401);
assert!(b.server.log().len() <= 2, "a wrong password is tried once");
assert_eq!(status(b.get(b.task(&path)).await), 401);
b.server.clear_log();
}
}
#[tokio::test]
async fn logins_and_cookies_of_a_site() {
let b = Bench::new().await;
b.sites.secrets.save("home", "h", &Secret { cookies: Some("x=1; session=tok".into()), ..with_login(PASSWORD) }).await;
b.set(|s| s.sites = vec![Site { secret: Some("home".into()), ..site("127.0.0.1") }]);
for prefix in [format!("/digest/me/{PASSWORD}"), format!("/basic/me/{PASSWORD}"), "/cookie/tok".into()] {
b.gets(b.task(&path(&prefix))).await;
}
b.set(|s| s.sites = vec![Site { secret: Some("home".into()), ..site("*") }]);
assert_eq!(status(b.get(b.task(&path("/cookie/tok"))).await), 403, "not for everyone's pattern");
}
#[tokio::test]
async fn headers_cookies_referrer_and_agent_of_a_download() {
let b = Bench::new().await;
b.set(|s| s.sites = vec![Site { user_agent: Some("Site/1".into()), ..site("127.0.0.1") }]);
let mut task = b.task(&path("/referrer/page.example"));
task.headers = vec![("Referer".into(), "https://page.example/".into()), ("X-Own".into(), "1".into()), ("Range".into(), "bytes=5-6".into())];
b.gets(task.clone()).await;
assert!(b.server.log().iter().all(|r| r.header("user-agent") == Some("Site/1") && r.header("x-own") == Some("1")));
assert_eq!(b.server.log()[0].header("range"), Some("bytes=0-0"), "the engine's own");
b.server.clear_log();
task.headers.push(("User-Agent".into(), "Own/2".into()));
b.gets(task).await;
assert!(b.server.log().iter().all(|r| r.header("user-agent") == Some("Own/2")));
let cookies = Secret { cookies: Some("session=tok".into()), ..Secret::default() };
b.gets(b.own(b.task(&path("/cookie/tok")), cookies).await).await;
let token = Secret { headers: vec![("X-Api-Key".into(), "k".into())], ..Secret::default() };
b.server.clear_log();
b.gets(b.own(b.task(&path("")), token).await).await;
assert!(b.server.log().iter().all(|r| r.header("x-api-key") == Some("k")));
}
/// Everything secret a request could carry.
fn secret_parts(r: &Request) -> Vec<&str> {
let names = ["authorization", "proxy-authorization", "cookie", "x-api-key", "x-own"];
names.iter().filter_map(|n| r.header(n)).collect()
}
#[tokio::test]
async fn nothing_follows_a_redirect_to_another_host() {
let (b, other) = (Bench::new().await, TestServer::start().await);
let everything = || Secret {
cookies: Some("session=tok".into()),
headers: vec![("X-Api-Key".into(), "k".into()), ("Authorization".into(), "Bearer x".into())],
..with_login(PASSWORD)
};
b.sites.secrets.save("home", "h", &everything()).await;
// By port: both are on the same address.
b.set(|s| s.sites = vec![Site { secret: Some("home".into()), ..site(&format!("127.0.0.1:{}", b.server.port())) }]);
// To the file, on the way to it, and to one that asks for a login.
let far = other.url(&path(""));
let back = b.server.url(&path("/cookie/tok"));
for to in [far.clone(), other.url(&format!("/redirect/1?to={back}"))] {
let mut task = b.task(&format!("/redirect/2?to={to}"));
task.headers = vec![("X-Own".into(), "1".into())];
b.gets(b.own(task, everything()).await).await;
}
for kind in ["basic", "digest"] {
let to = other.url(&path(&format!("/{kind}/me/{PASSWORD}")));
assert_eq!(status(b.get(b.own(b.task(&format!("/redirect/1?to={to}")), with_login(PASSWORD)).await).await), 401);
assert_eq!(status(b.get(b.task(&format!("/redirect/1?to={to}"))).await), 401);
}
let seen = other.log();
assert!(seen.len() > 4);
for r in &seen {
assert!(secret_parts(r).is_empty(), "{r:?}");
}
assert!(b.server.log().iter().any(|r| r.header("cookie").is_some_and(|c| c.contains("session=tok"))));
// A login in the redirect itself is not the user's.
let to = far.replace("http://", "http://evil:x@");
b.gets(b.task(&format!("/redirect/1?to={to}"))).await;
assert!(other.log().iter().all(|r| secret_parts(r).is_empty()));
}
#[tokio::test]
async fn a_new_link_elsewhere_does_not_get_the_old_secrets() {
let (b, other) = (Bench::new().await, TestServer::start().await);
let mut task = b.own(b.task(&path("")), Secret { cookies: Some("session=tok".into()), ..with_login(PASSWORD) }).await;
task.url = other.url(&path(""));
b.gets(task.clone()).await;
assert!(other.log().iter().all(|r| secret_parts(r).is_empty()));
task.url = other.url(&path(&format!("/basic/me/{PASSWORD}")));
assert_eq!(status(b.get(task).await), 401);
}
#[tokio::test]
async fn a_login_is_not_taken_from_tls_to_plain_text() {
let (b, plain) = (Bench::with(TestServer::start_tls().await, Bus::Off), TestServer::start().await);
b.sites.secrets.save("home", "h", &Secret { cookies: Some("session=tok".into()), ..with_login(PASSWORD) }).await;
b.set(|s| s.sites = vec![Site { secret: Some("home".into()), ..site("127.0.0.1") }]);
b.gets(b.task(&path(&format!("/basic/me/{PASSWORD}")))).await;
let to = plain.url(&path(&format!("/basic/me/{PASSWORD}")));
assert_eq!(status(b.get(b.task(&format!("/redirect/1?to={to}"))).await), 401);
assert!(plain.log().iter().all(|r| secret_parts(r).is_empty()));
}
#[tokio::test]
async fn cookies_set_on_the_way_come_along() {
let b = Bench::new().await;
let task = b.task("/cookie/tok/login");
let source = b.sites.source(&task).await.unwrap();
let (_keep, mut stop) = watch::channel(false);
let client = client(&ClientOptions::default()).unwrap();
medlar_core::http::probe(&client, &source, &mut stop).await.unwrap();
let there = source.at(&b.server.url(&path("/cookie/tok")).parse().unwrap());
assert!(medlar_core::http::probe(&client, &there, &mut stop).await.unwrap().ranges);
}
fn holds(dir: &Path, what: &str) -> Vec<std::path::PathBuf> {
let mut found = vec![];
for entry in std::fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
found.extend(holds(&path, what));
} else if std::fs::read(&path).unwrap().windows(what.len()).any(|w| w == what.as_bytes()) {
found.push(path);
}
}
found
}
#[tokio::test]
async fn secrets_are_in_the_keyring_only() {
let ring = Ring::start(false).await;
let b = Bench::with(TestServer::start().await, ring.bus());
let marks = [PASSWORD, "S3CRETcookie", "S3CRETkey", "S3CRETproxy"];
let proxy = Proxy::start_http(Some(("me", marks[3]))).await;
let address = format!("http://{}", proxy.addr());
assert_eq!(b.sites.save_proxy_login(&address, login(marks[3])).await, Some(Kept::Keyring));
let secret = Secret {
cookies: Some(format!("session={}", marks[1])),
headers: vec![("X-Api-Key".into(), marks[2].into())],
..with_login(marks[0])
};
for path in [path(&format!("/digest/me/{PASSWORD}")), path("/basic/me/other"), "/status/500".into()] {
let mut task = b.own(b.task(&path), secret.clone()).await;
let shown = format!("{:?} {task:?} {:?}", b.sites.source(&task).await.unwrap(), b.sites);
assert!(marks[1..].iter().all(|m| !shown.contains(m)), "{shown}");
task.proxy = Some(address.clone());
// The test server has the password in its paths.
let _ = b.get(task).await;
}
assert!(proxy.seen().iter().any(|s| s.allowed && s.credentials.is_some()), "{:?}", proxy.seen());
for refused in [
Task { headers: vec![("Cookie".into(), marks[1].into())], ..b.task("/f") },
Task { proxy: Some("http://me:S3CRETproxy@p:1".into()), ..b.task("/f") },
Task { url: "http://me:S3CRETpass@h/f".into(), ..b.task("/f") },
] {
assert!(matches!(b.store.add_task(refused), Err(store::Error::Secret)));
}
let settings = Settings { sites: vec![Site { secret: Some("home".into()), ..site("h") }], ..settings() };
settings.save(&b.dir.path().join("settings.json")).unwrap();
for mark in &marks[1..] {
assert_eq!(holds(b.dir.path(), mark), Vec::<std::path::PathBuf>::new());
assert!(!LOGGED.lock().unwrap().contains(mark));
assert!(!std::fs::read("/proc/self/cmdline").unwrap().windows(mark.len()).any(|w| w == mark.as_bytes()));
}
assert!(ring.holds(marks[1]) && ring.holds(marks[3]));
assert!(!format!("{secret:?}{:?}", secret.login).contains("S3CRET"));
}
// The keyring: a Secret Service of our own on a private D-Bus.
/// Label, attributes, value.
type Item = (String, HashMap<String, String>, Vec<u8>);
#[derive(Default)]
struct Vault {
locked: bool,
/// The user says no.
refuse: bool,
asked: u32,
items: HashMap<String, Item>,
}
type Shelf = Arc<Mutex<Vault>>;
fn object(path: &str) -> OwnedObjectPath {
OwnedObjectPath::try_from(path).unwrap()
}
const COLLECTION: &str = "/org/freedesktop/secrets/collection/login";
const PROMPT: &str = "/org/freedesktop/secrets/prompt/p1";
struct FakeService(Shelf);
#[zbus::interface(name = "org.freedesktop.Secret.Service")]
impl FakeService {
fn open_session(&self, algorithm: &str, _input: OwnedValue) -> (OwnedValue, OwnedObjectPath) {
assert_eq!(algorithm, "plain");
(Value::from("").try_into().unwrap(), object("/org/freedesktop/secrets/session/s1"))
}
fn read_alias(&self, name: &str) -> OwnedObjectPath {
object(if name == "default" { COLLECTION } else { "/" })
}
fn search_items(&self, attributes: HashMap<String, String>) -> (Vec<OwnedObjectPath>, Vec<OwnedObjectPath>) {
let vault = self.0.lock().unwrap();
let found = vault.items.iter().filter(|(_, item)| attributes.iter().all(|(k, v)| item.1.get(k) == Some(v)));
let found = found.map(|(path, _)| object(path)).collect();
if vault.locked { (vec![], found) } else { (found, vec![]) }
}
fn unlock(&self, objects: Vec<OwnedObjectPath>) -> (Vec<OwnedObjectPath>, OwnedObjectPath) {
if self.0.lock().unwrap().locked { (vec![], object(PROMPT)) } else { (objects, object("/")) }
}
}
struct FakeCollection(Shelf);
#[zbus::interface(name = "org.freedesktop.Secret.Collection")]
impl FakeCollection {
async fn create_item(
&self,
#[zbus(object_server)] server: &zbus::ObjectServer,
properties: HashMap<String, OwnedValue>,
secret: (OwnedObjectPath, Vec<u8>, Vec<u8>, String),
replace: bool,
) -> (OwnedObjectPath, OwnedObjectPath) {
assert!(replace && !self.0.lock().unwrap().locked);
let get = |name: &str| properties[&format!("org.freedesktop.Secret.Item.{name}")].try_clone().unwrap();
let label = String::try_from(get("Label")).unwrap();
let attributes: HashMap<String, String> = get("Attributes").try_into().unwrap();
let known = self.0.lock().unwrap().items.iter().find(|(_, i)| i.1 == attributes).map(|(p, _)| p.clone());
let path = known.unwrap_or_else(|| format!("{COLLECTION}/{}", self.0.lock().unwrap().items.len()));
self.0.lock().unwrap().items.insert(path.clone(), (label, attributes, secret.2));
server.at(path.as_str(), FakeItem(self.0.clone(), path.clone())).await.unwrap();
(object(&path), object("/"))
}
}
struct FakeItem(Shelf, String);
#[zbus::interface(name = "org.freedesktop.Secret.Item")]
impl FakeItem {
fn get_secret(&self, session: OwnedObjectPath) -> ((OwnedObjectPath, Vec<u8>, Vec<u8>, String),) {
((session, vec![], self.0.lock().unwrap().items[&self.1].2.clone(), "application/json".into()),)
}
fn delete(&self) -> OwnedObjectPath {
self.0.lock().unwrap().items.remove(&self.1);
object("/")
}
}
struct FakePrompt(Shelf);
#[zbus::interface(name = "org.freedesktop.Secret.Prompt")]
impl FakePrompt {
async fn prompt(&self, #[zbus(signal_emitter)] emitter: zbus::object_server::SignalEmitter<'_>, _window: &str) {
let refused = {
let mut vault = self.0.lock().unwrap();
vault.asked += 1;
vault.locked = vault.refuse;
vault.refuse
};
FakePrompt::completed(&emitter, refused, Value::from("")).await.unwrap();
}
#[zbus(signal)]
async fn completed(emitter: &zbus::object_server::SignalEmitter<'_>, dismissed: bool, result: Value<'_>) -> zbus::Result<()>;
}
struct FakePortal(String);
#[zbus::interface(name = "org.freedesktop.portal.ProxyResolver")]
impl FakePortal {
fn lookup(&self, uri: &str) -> Vec<String> {
assert!(uri.ends_with('/') && uri.matches('/').count() == 3, "only the server's name: {uri}");
vec![self.0.clone()]
}
}
struct Ring {
child: Child,
address: String,
vault: Shelf,
_bus: Option<zbus::Connection>,
_dir: tempfile::TempDir,
}
impl Ring {
/// A bus without anything on it.
fn empty() -> Ring {
// Without the system's services: a name nobody has must start nothing real, such as the user's own keyring.
let dir = tempfile::tempdir().unwrap();
let config = dir.path().join("bus.conf");
let text = "<busconfig><type>custom</type><listen>unix:tmpdir=/tmp</listen><auth>EXTERNAL</auth><policy context=\"default\">\
<allow send_destination=\"*\" eavesdrop=\"true\"/><allow eavesdrop=\"true\"/><allow own=\"*\"/></policy></busconfig>";
std::fs::write(&config, text).unwrap();
let mut child = std::process::Command::new("dbus-daemon")
.arg(format!("--config-file={}", config.display()))
.args(["--nofork", "--print-address=1"])
.env("XDG_RUNTIME_DIR", dir.path())
.stdout(Stdio::piped())
.spawn()
.expect("dbus-daemon");
let mut address = String::new();
BufReader::new(child.stdout.take().unwrap()).read_line(&mut address).unwrap();
Ring { child, address: address.trim().into(), vault: Shelf::default(), _bus: None, _dir: dir }
}
async fn start(locked: bool) -> Ring {
let mut ring = Ring::empty();
ring.vault.lock().unwrap().locked = locked;
let shelf = || ring.vault.clone();
let builder = zbus::connection::Builder::address(ring.address.as_str()).unwrap();
let builder = builder.serve_at("/org/freedesktop/secrets", FakeService(shelf())).unwrap();
let builder = builder.serve_at(COLLECTION, FakeCollection(shelf())).unwrap();
let builder = builder.serve_at(PROMPT, FakePrompt(shelf())).unwrap();
ring._bus = Some(builder.name("org.freedesktop.secrets").unwrap().build().await.unwrap());
ring
}
fn bus(&self) -> Bus {
Bus::At(self.address.clone())
}
fn holds(&self, what: &str) -> bool {
self.vault.lock().unwrap().items.values().any(|i| i.2.windows(what.len()).any(|w| w == what.as_bytes()))
}
}
impl Drop for Ring {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
#[tokio::test]
async fn keyring_saves_replaces_and_removes() {
let ring = Ring::start(false).await;
let secrets = Secrets::new(ring.bus());
assert_eq!(secrets.load("a").await, None);
for secret in [with_login("one"), Secret { cookies: Some("c=1".into()), ..with_login("two") }] {
assert_eq!(secrets.save("a", "h.example", &secret).await, Kept::Keyring);
// Also after a restart.
assert_eq!(Secrets::new(ring.bus()).load("a").await, Some(secret));
}
assert_eq!(secrets.save("b", "other", &with_login("three")).await, Kept::Keyring);
assert_eq!(ring.vault.lock().unwrap().items.len(), 2);
assert!(ring.vault.lock().unwrap().items.values().any(|i| i.0 == "Medlar login for h.example"));
secrets.remove("a").await;
assert_eq!((secrets.load("a").await, secrets.load("b").await), (None, Some(with_login("three"))));
}
#[tokio::test]
async fn a_locked_keyring_is_asked_to_open() {
let ring = Ring::start(true).await;
let secrets = Secrets::new(ring.bus());
assert_eq!(secrets.save("a", "h", &with_login("one")).await, Kept::Keyring);
ring.vault.lock().unwrap().locked = true;
assert_eq!(secrets.load("a").await, Some(with_login("one")));
ring.vault.lock().unwrap().locked = true;
ring.vault.lock().unwrap().refuse = true;
assert_eq!(secrets.load("a").await, None);
let kept = secrets.save("a", "h", &with_login("two")).await;
assert_eq!((kept, ring.vault.lock().unwrap().asked), (Kept::Memory, 4));
assert!(!ring.holds("two"));
assert_eq!(secrets.load("a").await, Some(with_login("two")));
}
#[tokio::test]
async fn without_a_keyring_secrets_stay_in_memory_and_that_is_said() {
let empty = Ring::empty();
for bus in [Bus::Off, empty.bus(), Bus::At("unix:path=/nonexistent".into())] {
let secrets = Secrets::new(bus.clone());
let kept = secrets.save("a", "h", &with_login("one")).await;
assert!(kept == Kept::Memory && kept.words().unwrap().contains("until Medlar closes"));
assert_eq!(secrets.load("a").await, Some(with_login("one")));
assert_eq!(Secrets::new(bus).load("a").await, None);
secrets.remove("a").await;
assert_eq!(secrets.load("a").await, None);
}
assert_eq!(Kept::Keyring.words(), None);
}
// Proxies.
/// A name that only the proxy knows.
const FAR: &str = "files.invalid";
fn far(b: &Bench, proxies: &[&Proxy]) -> Task {
for p in proxies {
p.map_host(FAR, b.server.addr());
}
Task { url: format!("http://{FAR}:{}{}", b.server.port(), path("")), ..b.task("") }
}
#[tokio::test]
async fn http_and_socks_proxies_look_names_up() {
let b = Bench::new().await;
let proxies = [Proxy::start_http(None).await, Proxy::start_socks5(None).await];
let task = far(&b, &[&proxies[0], &proxies[1]]);
for (proxy, scheme) in proxies.iter().zip(["http", "socks5"]) {
b.set(|s| s.proxy = format!("{scheme}://{}", proxy.addr()));
b.gets(task.clone()).await;
assert!(!proxy.seen().is_empty() && proxy.seen().iter().all(|s| s.allowed && s.target.starts_with(FAR)), "{:?}", proxy.seen());
}
// Without them the name leads nowhere.
b.set(|_| ());
assert!(matches!(b.get(task).await, Err(Error::Net(_))));
}
#[tokio::test]
async fn tls_goes_through_proxies_too() {
let b = Bench::with(TestServer::start_tls().await, Bus::Off);
let proxies = [Proxy::start_http(None).await, Proxy::start_socks5(None).await];
for (proxy, scheme) in proxies.iter().zip(["http", "socks5"]) {
b.set(|s| s.proxy = format!("{scheme}://{}", proxy.addr()));
b.gets(b.task(&path(""))).await;
assert!(proxy.seen().iter().all(|s| s.kind == if scheme == "http" { "connect" } else { "socks5" }));
assert!(!proxy.seen().is_empty());
}
}
#[tokio::test]
async fn download_site_and_app_choose_a_proxy_in_this_order() {
let b = Bench::new().await;
let (app, host, own) = (Proxy::start_http(None).await, Proxy::start_http(None).await, Proxy::start_socks5(None).await);
let counts = || (app.seen().len(), host.seen().len(), own.seen().len());
let of = |p: &Proxy, scheme: &str| format!("{scheme}://{}", p.addr());
let address = of(&app, "http");
let at_site = |proxy: String| vec![Site { proxy: Some(proxy), ..site("127.0.0.1") }];
b.set(|s| s.proxy = address.clone());
b.gets(b.task(&path(""))).await;
let one = counts();
assert!(one.0 > 0 && one.1 == 0 && one.2 == 0);
b.set(|s| (s.proxy, s.sites) = (address.clone(), at_site(of(&host, "http"))));
b.gets(b.task(&path(""))).await;
let two = counts();
assert!(two.0 == one.0 && two.1 > 0 && two.2 == 0);
b.gets(Task { proxy: Some(of(&own, "socks5")), ..b.task(&path("")) }).await;
let three = counts();
assert!((three.0, three.1) == (two.0, two.1) && three.2 > 0);
// Straight: by choice, by the site's, and by the list.
b.gets(Task { proxy: Some("direct".into()), ..b.task(&path("")) }).await;
b.set(|s| (s.proxy, s.sites) = (address.clone(), at_site("direct".into())));
b.gets(b.task(&path(""))).await;
b.set(|s| (s.proxy, s.proxy_bypass) = (address.clone(), vec!["127.0.0.0/8".into()]));
b.gets(b.task(&path(""))).await;
assert_eq!(counts(), three);
}
#[tokio::test]
async fn a_redirect_goes_the_way_of_its_own_host() {
let b = Bench::new().await;
let proxy = Proxy::start_http(None).await;
let task = far(&b, &[&proxy]);
b.set(|s| s.sites = vec![Site { proxy: Some(format!("http://{}", proxy.addr())), ..site("*.invalid") }]);
b.gets(b.task(&format!("/redirect/1?to={}", task.url))).await;
assert!(proxy.seen().iter().all(|s| s.target.starts_with(FAR)) && !proxy.seen().is_empty());
}
fn failure(e: &Error) -> (ErrorKind, String) {
let place = medlar_core::error::Place { server: "files.example", folder: Path::new("/"), begun: false };
let f = medlar_core::error::Failure::of(e, place);
(f.kind, f.text)
}
#[tokio::test]
async fn proxy_logins() {
let b = Bench::with(TestServer::start_tls().await, Bus::Off);
let plain = Bench::new().await;
for (b, socks) in [(&b, false), (&b, true), (&plain, false), (&plain, true)] {
let auth = Some(("me", "p@ss:word"));
let proxy = if socks { Proxy::start_socks5(auth).await } else { Proxy::start_http(auth).await };
let address = format!("{}://{}", if socks { "socks5" } else { "http" }, proxy.addr());
b.set(|s| s.proxy = address.clone());
let (kind, text) = match b.get(b.task(&path(""))).await {
Err(e) => failure(&e),
Ok(_) => panic!("no login was needed"),
};
assert!(kind == ErrorKind::Login && text.contains("proxy"), "socks {socks}: {kind:?} {text}");
b.sites.save_proxy_login(&address, login("wrong")).await;
let wrong = failure(&b.get(b.task(&path(""))).await.unwrap_err());
assert_eq!(wrong.0, ErrorKind::Login, "socks {socks}: {}", wrong.1);
b.sites.save_proxy_login(&address, login("p@ss:word")).await;
b.gets(b.task(&path(""))).await;
assert!(b.server.log().iter().all(|r| r.header("proxy-authorization").is_none()));
}
}
#[tokio::test]
async fn a_proxy_that_fails_is_never_gone_around() {
let b = Bench::new().await;
let down = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap();
for setting in [format!("http://{down}"), format!("socks5://{down}"), "junk".into(), String::new(), "http://me:x@h:1".into()] {
b.set(|s| s.proxy = setting.clone());
let (kind, text) = failure(&b.get(b.task(&path(""))).await.unwrap_err());
assert_eq!(kind, ErrorKind::Proxy, "{setting}: {text}");
assert!(text.starts_with("No connection through the proxy") && !text.contains("os error"), "{text}");
}
assert!(b.server.log().is_empty());
}
#[tokio::test]
async fn the_desktop_names_a_proxy() {
let ring = Ring::empty();
let b = Bench::with(TestServer::start().await, ring.bus());
let proxy = Proxy::start_socks5(None).await;
let portal = zbus::connection::Builder::address(ring.address.as_str()).unwrap();
let portal = portal.serve_at("/org/freedesktop/portal/desktop", FakePortal(format!("socks5://{}", proxy.addr()))).unwrap();
let portal = portal.name("org.freedesktop.portal.Desktop").unwrap().build().await.unwrap();
b.set(|s| s.proxy = "system".into());
b.gets(far(&b, &[&proxy])).await;
assert!(!proxy.seen().is_empty());
// Without it: straight.
drop(portal);
b.set(|s| s.proxy = "system".into());
b.gets(b.task(&path(""))).await;
}
// TLS.
#[tokio::test]
async fn certificates_are_checked_and_exceptions_are_exact() {
let b = Bench::with(TestServer::start_tls().await, Bus::Off);
let other = TestServer::start_tls().await;
// Trusts the system's roots, which know nothing of the test server.
let strict = sites_with(vec![], &settings(), Bus::Off);
let b = Bench { sites: strict, ..b };
let (kind, text) = failure(&b.get(b.task(&path(""))).await.unwrap_err());
assert_eq!(kind, ErrorKind::Tls);
assert!(text.contains("Nobody this computer trusts vouches for files.example"), "{text}");
assert!(b.server.log().is_empty());
let print = b.sites.trust.refused("127.0.0.1").unwrap();
let except = |pattern: &str, certificate: &str| vec![Site { certificate: Some(certificate.into()), ..site(pattern) }];
for (pattern, certificate) in [("*", print.as_str()), ("localhost", &print), ("*.0.0.1", &print), ("127.0.0.1", "00"), ("127.0.0.1", "")] {
b.set(|s| s.sites = except(pattern, certificate));
assert!(b.get(b.task(&path(""))).await.is_err(), "{pattern} {certificate}");
}
b.set(|s| s.sites = except("127.0.0.1", &print.to_uppercase()));
b.gets(b.task(&path(""))).await;
// Another certificate on the same host is another question.
let task = Task { url: other.url(&path("")), ..b.task("") };
assert!(b.get(task).await.is_err());
assert_ne!(b.sites.trust.refused("127.0.0.1").unwrap(), print);
b.set(|_| ());
assert!(b.get(b.task(&path(""))).await.is_err(), "taken back");
}
#[tokio::test]
async fn a_certificate_for_another_name_says_so() {
let b = Bench::with(TestServer::start_tls().await, Bus::Off);
let proxy = Proxy::start_http(None).await;
proxy.map_host(FAR, b.server.addr());
b.set(|s| s.proxy = format!("http://{}", proxy.addr()));
let task = Task { url: format!("https://{FAR}:{}/f", b.server.port()), ..b.task("") };
let (kind, text) = failure(&b.get(task).await.unwrap_err());
assert!(kind == ErrorKind::Tls && text.contains("belongs to another server than files.example"), "{text}");
}
// All of it, from the manager.
#[tokio::test]
async fn the_manager_uses_the_sites() {
let b = Bench::new().await;
let hosts = Hosts::new(Caps { burst: 1000, per_second: 1000.0, ..Caps::default() });
let shared = Shared { client: client(&ClientOptions::default()).unwrap(), store: b.store.clone(), hosts };
let mut config = Config::new(shared, Limits::default());
config.sites = Some(b.sites.clone());
b.sites.secrets.save("home", "h", &with_login(PASSWORD)).await;
b.set(|s| s.sites = vec![Site { secret: Some("home".into()), max_connections: Some(1), ..site("127.0.0.1") }]);
let path = format!("/digest/me/{PASSWORD}/data/7/8m/f.bin");
b.server.set_faults(&path, Faults { throttle_conn: Some(6 << 20), ..Faults::default() });
let manager = Arc::new(Manager::open(config).unwrap());
let id = manager.send(Command::Add(Box::new(b.task(&path)))).await.unwrap();
let mut most = 0;
for _ in 0..500 {
let shot = manager.snapshot();
let view = shot.get(id).unwrap();
most = most.max(view.connections);
if view.task.state == State::Done {
break;
}
assert_ne!(view.task.state, State::Failed, "{:?}", view.task.error);
tokio::time::sleep(Duration::from_millis(20)).await;
}
let shot = manager.snapshot();
let task = &shot.get(id).unwrap().task;
assert_eq!((task.state, most.max(1)), (State::Done, 1));
assert!(std::fs::read(task.folder.join(&task.name)).unwrap() == expected(7, 0, 8 << 20));
}