use std::collections::BTreeMap;
use std::ffi::OsString;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use serde::Deserialize;
use crate::state::{Instance, State};
pub const OPEN_TTL: Duration = Duration::from_secs(30);
pub const OPEN_RATE_BURST: u32 = 5;
pub const OPEN_RATE_REFILL: Duration = Duration::from_secs(10);
pub const OPEN_ATTACH_WINDOW: Duration = Duration::from_secs(10 * 60);
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verdict {
Open,
BadChars,
BadScheme(String),
Expired { age: u64 },
Limited,
}
impl Verdict {
pub fn refusal(&self) -> Option<String> {
Some(match self {
Verdict::Open => return None,
Verdict::BadChars => "control characters or whitespace in the URL".to_string(),
Verdict::BadScheme(s) if s.is_empty() => "not a URL with a scheme".to_string(),
Verdict::BadScheme(s) => format!("scheme `{s}` (http and https only)"),
Verdict::Expired { age } => format!("queued {age}s ago (over {}s)", OPEN_TTL.as_secs()),
Verdict::Limited => format!("rate limit ({OPEN_RATE_BURST} per {}s)", OPEN_RATE_REFILL.as_secs()),
})
}
pub fn log_line(&self, instance: &str, url: &str) -> Option<String> {
let why = self.refusal()?;
let verb = if matches!(self, Verdict::Expired { .. }) { "dropped" } else { "refused" };
Some(format!("{}: open {verb}, {why}: {}", printable(instance), printable(url)))
}
}
fn bad_char(c: char) -> bool {
c.is_control() || c.is_whitespace()
}
pub fn has_bad_chars(url: &str) -> bool {
url.chars().any(bad_char)
}
pub fn printable(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if bad_char(c) && c != ' ' {
out.extend(c.escape_debug());
} else {
out.push(c);
}
}
out
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
Opened { unforwarded: Vec<Loopback> },
Refused(String),
Failed(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpenDone {
pub instance: String,
pub url: String,
pub profile: Option<String>,
pub outcome: Outcome,
}
const LINE_URL: usize = 120;
const LINE_WHY: usize = 160;
fn shorten(s: &str, max: usize) -> String {
match s.char_indices().nth(max.saturating_sub(1)) {
Some((at, _)) if s.chars().count() > max => format!("{}…", &s[..at]),
_ => s.to_string(),
}
}
impl OpenDone {
pub fn kind(&self) -> &'static str {
match self.outcome {
Outcome::Opened { .. } => "opened",
Outcome::Refused(_) => "refused",
Outcome::Failed(_) => "failed",
}
}
pub fn why(&self) -> Option<String> {
match &self.outcome {
Outcome::Opened { unforwarded } if unforwarded.is_empty() => None,
Outcome::Opened { unforwarded } => {
let ports: Vec<String> = unforwarded
.iter()
.map(|l| format!("{}port {}", if l.callback { "callback " } else { "" }, l.port))
.collect();
Some(format!("cannot forward {}", ports.join(", ")))
}
Outcome::Refused(why) | Outcome::Failed(why) => Some(why.clone()),
}
}
pub fn line(&self) -> String {
let why = self.why().map(|w| printable(&shorten(&w, LINE_WHY)));
let instance = printable(&self.instance);
match (&self.outcome, why) {
(Outcome::Opened { .. }, why) => {
let profile = self.profile.as_ref().map_or(String::new(), |p| format!(" ({})", printable(p)));
let note = why.map_or(String::new(), |w| format!("; {w}"));
format!("{instance}: opened {}{profile}{note}", printable(&shorten(&self.url, LINE_URL)))
}
(Outcome::Refused(_), why) => format!("{instance}: open refused: {}", why.unwrap_or_default()),
(Outcome::Failed(_), why) => format!("{instance}: open failed: {}", why.unwrap_or_default()),
}
}
}
pub type OnDone = Arc<dyn Fn(OpenDone) + Send + Sync>;
pub fn decide(url: &str, at: u64, now: u64, limit: impl FnOnce() -> bool) -> Verdict {
if has_bad_chars(url) {
return Verdict::BadChars;
}
let scheme = match url.split_once(':') {
Some((s, _)) if !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c)) => s,
_ => "",
};
let web = scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https");
if !web || !url[scheme.len()..].starts_with("://") {
return Verdict::BadScheme(scheme.to_string());
}
let age = now.saturating_sub(at);
if age > OPEN_TTL.as_secs() {
return Verdict::Expired { age };
}
if !limit() {
return Verdict::Limited;
}
Verdict::Open
}
pub fn opener_argv(os: &str, url: &str) -> Option<Vec<String>> {
match os {
"linux" => Some(vec!["xdg-open".into(), url.into()]),
"macos" => Some(vec!["open".into(), url.into()]),
_ => None,
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HostProfile {
pub open: Vec<String>,
}
pub type HostProfiles = BTreeMap<String, HostProfile>;
pub fn profiles_path() -> Result<PathBuf> {
Ok(State::path()?.with_file_name("profiles.toml"))
}
pub fn parse_profiles(contents: &str) -> Result<HostProfiles> {
let profiles: HostProfiles = toml::from_str(contents)?;
if let Some(name) = profiles.iter().find(|(_, p)| p.open.is_empty()).map(|(n, _)| n) {
bail!("[{name}]: `open` is empty (a command and its arguments)");
}
Ok(profiles)
}
pub fn load_profiles(path: &Path) -> Result<HostProfiles> {
match std::fs::read_to_string(path) {
Ok(contents) => parse_profiles(&contents).with_context(|| format!("invalid {}", path.display())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(HostProfiles::new()),
Err(e) => Err(e).with_context(|| format!("cannot read {}", path.display())),
}
}
pub fn open_argv(os: &str, profile: Option<&str>, profiles: &HostProfiles, url: &str) -> Option<Vec<String>> {
match profile.and_then(|p| profiles.get(p)) {
Some(p) => Some(p.open.iter().cloned().chain([url.to_string()]).collect()),
None => opener_argv(os, url),
}
}
pub fn profile_to_send(
instance: &str,
url: &str,
inst: Option<&Instance>,
allowed: impl FnOnce(&Instance) -> Option<Vec<String>>,
) -> (Option<String>, Option<String>) {
let Some((inst, profile)) = inst.and_then(|i| Some((i, i.profile.as_deref()?))) else {
return (None, None);
};
if crate::snapshot::profile_disallowed(Some(profile), allowed(inst).as_deref()) {
let warning =
format!("{instance}: profile `{profile}` no longer allowed by the config; opening {url} with the default opener");
return (None, Some(warning));
}
(Some(profile.to_string()), None)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ForwardTarget {
pub machine: Option<String>,
pub dir: PathBuf,
pub instance: String,
}
impl ForwardTarget {
pub fn local(inst: Option<(&str, &Instance)>) -> Result<ForwardTarget, String> {
let (key, i) = inst.ok_or_else(|| "not in state.toml".to_string())?;
let dir = i.config_dir.clone().ok_or_else(|| "no config root in state.toml".to_string())?;
Ok(ForwardTarget { machine: None, dir, instance: key.to_string() })
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpenJob {
pub instance: String,
pub url: String,
pub profile: Option<String>,
pub target: Result<ForwardTarget, String>,
}
pub fn local_job(
instance: &str,
url: &str,
found: Option<(&str, &Instance)>,
allowed: impl FnOnce(&Instance) -> Option<Vec<String>>,
) -> (OpenJob, Option<String>) {
let (profile, warning) = profile_to_send(instance, url, found.map(|(_, i)| i), allowed);
let job = OpenJob { instance: instance.to_string(), url: url.to_string(), profile, target: ForwardTarget::local(found) };
(job, warning)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Loopback {
pub port: u16,
pub callback: bool,
}
const CALLBACK_KEYS: [&str; 3] = ["redirect_uri", "redirect_url", "callback"];
struct Parts<'a> {
scheme: &'a str,
host_at: usize,
host: &'a str,
port: Option<&'a str>,
rest_at: usize,
}
fn parts(url: &str) -> Option<Parts<'_>> {
let (scheme, after) = url.split_once("://")?;
let start = scheme.len() + 3;
let authority = &after[..after.find(['/', '\\', '?', '#']).unwrap_or(after.len())];
let host_at = start + authority.rfind('@').map_or(0, |i| i + 1);
let host_port = &url[host_at..start + authority.len()];
let (host, port) = match host_port.strip_prefix('[') {
Some(v6) => {
let end = v6.find(']')? + 2;
let port = &host_port[end..];
let port = if port.is_empty() { None } else { Some(port.strip_prefix(':')?) };
(&host_port[..end], port)
}
None => match host_port.split_once(':') {
Some((h, p)) => (h, Some(p)),
None => (host_port, None),
},
};
Some(Parts { scheme, host_at, host, port, rest_at: start + authority.len() })
}
fn ipv4(host: &str) -> Option<Ipv4Addr> {
host.strip_suffix('.').unwrap_or(host).parse().ok()
}
fn is_loopback(host: &str) -> bool {
if host.strip_suffix('.').unwrap_or(host).eq_ignore_ascii_case("localhost") {
return true;
}
if let Some(ip) = ipv4(host) {
return ip.is_loopback() || ip.is_unspecified();
}
let v6 = host.strip_prefix('[').and_then(|h| h.strip_suffix(']'));
v6.and_then(|h| h.parse::<Ipv6Addr>().ok()).is_some_and(|ip| ip.is_loopback())
}
fn host_here(host: &str) -> Option<&'static str> {
let v6 = host.strip_prefix('[').and_then(|h| h.strip_suffix(']'));
if v6.and_then(|h| h.parse::<Ipv6Addr>().ok()).is_some_and(|ip| ip.is_loopback()) {
return Some("127.0.0.1");
}
let ip = ipv4(host)?;
if ip.is_unspecified() {
Some("localhost")
} else if ip.is_loopback() && ip != Ipv4Addr::LOCALHOST {
Some("127.0.0.1")
} else {
None
}
}
fn loopback_port(url: &str) -> Option<u16> {
let p = parts(url)?;
if !is_loopback(p.host) {
return None;
}
let default = match p.scheme.to_ascii_lowercase().as_str() {
"http" => 80,
"https" => 443,
_ => return None,
};
match p.port {
None | Some("") => Some(default),
Some(port) if port.bytes().all(|b| b.is_ascii_digit()) => port.parse().ok().filter(|&p| p != 0),
Some(_) => None,
}
}
fn percent_decode(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
let hex = || std::str::from_utf8(b.get(i + 1..i + 3)?).ok().and_then(|h| u8::from_str_radix(h, 16).ok());
match (b[i], hex()) {
(b'%', Some(byte)) => {
out.push(byte);
i += 3;
}
(c, _) => {
out.push(c);
i += 1;
}
}
}
String::from_utf8_lossy(&out).into_owned()
}
pub fn loopback_ports(url: &str) -> Vec<Loopback> {
let mut out: Vec<Loopback> = loopback_port(url).map(|port| Loopback { port, callback: false }).into_iter().collect();
let query = parts(url).map_or("", |p| {
let rest = &url[p.rest_at..];
let rest = &rest[..rest.find('#').unwrap_or(rest.len())];
rest.split_once('?').map_or("", |(_, q)| q)
});
let mut seen = Vec::new();
for (key, value) in query.split('&').filter_map(|kv| kv.split_once('=')) {
let key = percent_decode(key);
if !CALLBACK_KEYS.contains(&key.as_str()) || seen.contains(&key) {
continue;
}
seen.push(key);
let Some(port) = loopback_port(&percent_decode(value)) else { continue };
match out.iter_mut().find(|l| l.port == port) {
Some(l) => l.callback = true,
None => out.push(Loopback { port, callback: true }),
}
}
out
}
pub fn rewrite_direct(url: &str, port: Option<u16>) -> String {
let Some(p) = parts(url) else { return url.to_string() };
let host = host_here(p.host).unwrap_or(p.host);
let port = match (port, p.port) {
(Some(n), _) => format!(":{n}"),
(None, Some(text)) => format!(":{text}"),
(None, None) => String::new(),
};
format!("{}{host}{port}{}", &url[..p.host_at], &url[p.rest_at..])
}
pub type Forwarder = Arc<dyn Fn(&ForwardTarget, Loopback) -> Result<u16, Option<String>> + Send + Sync>;
pub fn forward_loopbacks(
instance: &str,
url: &str,
target: Result<&ForwardTarget, &str>,
forward: impl Fn(&ForwardTarget, Loopback) -> Result<u16, Option<String>>,
) -> (Result<String, String>, Vec<String>, Vec<Loopback>) {
let wanted = loopback_ports(url);
let direct = loopback_port(url);
let mut lines = Vec::new();
let mut unforwarded = Vec::new();
let mut bound = None;
if !wanted.is_empty() {
match target {
Err(why) => {
if let Some(port) = direct {
return (Err(format!("cannot forward port {port}: {why}")), lines, unforwarded);
}
let ports: Vec<String> = wanted.iter().map(|l| l.port.to_string()).collect();
let s = if ports.len() > 1 { "s" } else { "" };
lines.push(format!("{instance}: cannot forward callback port{s} {} for {url} ({why}); opening it as is", ports.join(", ")));
unforwarded = wanted;
}
Ok(target) => {
for lb in wanted {
let own = Some(lb.port) == direct;
match forward(target, lb) {
Ok(host_port) if own => bound = Some(host_port),
Ok(_) => {}
Err(why) if own => {
let why = why.unwrap_or_else(|| "it is also the callback port, which couldn't be bound".into());
return (Err(format!("cannot forward port {}: {why}", lb.port)), lines, unforwarded);
}
Err(None) => unforwarded.push(lb),
Err(Some(why)) => {
lines.push(format!("{instance}: cannot forward callback port {} for {url}: {why}", lb.port));
unforwarded.push(lb);
}
}
}
}
}
}
let rewrite = bound.filter(|&b| Some(b) != direct);
let opened = if rewrite.is_some() || parts(url).is_some_and(|p| host_here(p.host).is_some()) && direct.is_some() {
rewrite_direct(url, rewrite)
} else {
url.to_string()
};
(Ok(opened), lines, unforwarded)
}
const DISPLAY_ENV: [&str; 3] = ["DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY"];
pub fn has_display(os: &str, env: impl Fn(&str) -> Option<OsString>) -> bool {
os != "linux" || DISPLAY_ENV[..2].iter().any(|k| env(k).is_some_and(|v| !v.is_empty()))
}
pub fn session_display_env(show_environment: &str) -> Vec<(String, String)> {
show_environment
.lines()
.filter_map(|l| l.split_once('='))
.filter(|(k, v)| DISPLAY_ENV.contains(k) && !v.is_empty() && !v.starts_with("$'"))
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect()
}
fn display_env(os: &str) -> Option<Vec<(String, String)>> {
if has_display(os, |k| std::env::var_os(k)) {
return Some(Vec::new());
}
if os != "linux" {
return None;
}
let out = Command::new("systemctl")
.args(["--user", "show-environment"])
.stdin(Stdio::null())
.stderr(Stdio::null())
.output()
.ok()
.filter(|o| o.status.success())?;
let env = session_display_env(&String::from_utf8_lossy(&out.stdout));
let lookup = |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| OsString::from(v));
has_display(os, lookup).then_some(env)
}
pub fn prepare(instance: &str, instance_id: &str, url: &str, log: fn(&str)) -> OpenJob {
let state = State::load().unwrap_or_else(|e| {
log(&format!("{instance}: {e:#}; opening {url} with the default opener"));
State::default()
});
let found = state.instances.iter().find(|(_, i)| i.instance_id == instance_id).map(|(k, i)| (k.as_str(), i));
let allowed = |i: &Instance| crate::snapshot::allowed_now(&mut BTreeMap::new(), i);
let (job, warning) = local_job(instance, url, found, allowed);
if let Some(warning) = &warning {
log(warning);
}
job
}
pub fn open_here(job: OpenJob, forward: &Forwarder, log: fn(&str), done: &OnDone) {
let OpenJob { instance, url, profile, target } = job;
let who = match &target {
Ok(ForwardTarget { machine: Some(m), .. }) => format!("{m}/{instance}"),
_ => instance.clone(),
};
let finish = |url: &str, outcome: Outcome| done(OpenDone { instance: who.clone(), url: url.to_string(), profile: profile.clone(), outcome });
let os = std::env::consts::OS;
let Some(env) = display_env(os) else {
log(&format!("{instance}: no display to open {url} on"));
return finish(&url, Outcome::Failed("no display on this host".into()));
};
let profiles = profiles_path().and_then(|p| load_profiles(&p)).unwrap_or_else(|e| {
log(&format!("{instance}: {e:#}; opening {url} with the default opener"));
HostProfiles::new()
});
let (opened, lines, unforwarded) = forward_loopbacks(&instance, &url, target.as_ref().map_err(String::as_str), &**forward);
for line in &lines {
log(line);
}
let url = match opened {
Ok(url) => url,
Err(why) => {
log(&format!("{instance}: not opening {url}: {why}"));
return finish(&url, Outcome::Failed(why));
}
};
let Some(argv) = open_argv(os, profile.as_deref(), &profiles, &url) else {
log(&format!("{instance}: no opener on {os} for {url}"));
return finish(&url, Outcome::Failed(format!("no opener on {os}")));
};
let spawned = Command::new(&argv[0])
.args(&argv[1..])
.envs(env)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn();
match spawned {
Ok(mut child) => {
finish(&url, Outcome::Opened { unforwarded });
let _ = child.wait();
}
Err(e) => {
log(&format!("{instance}: cannot run `{}` to open {url}: {e}", argv[0]));
finish(&url, Outcome::Failed(format!("cannot run `{}`: {e}", argv[0])));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::devsbd::desktop::RateLimit;
use std::time::Instant;
const AT: u64 = 1_790_000_000;
fn open_now(url: &str) -> Verdict {
decide(url, AT, AT, || true)
}
#[test]
fn decide_allows_http_and_https_only() {
for url in ["https://example.com/a?b=c", "http://localhost:8080/", "HTTPS://EXAMPLE.COM"] {
assert_eq!(open_now(url), Verdict::Open, "{url}");
}
let bad = |url: &str, scheme: &str| assert_eq!(open_now(url), Verdict::BadScheme(scheme.into()), "{url}");
bad("ssh://host", "ssh");
bad("file:///etc/passwd", "file");
bad("javascript:alert(1)", "javascript");
bad("mailto:a@b.c", "mailto");
bad("vscode://file/x", "vscode");
bad("https:example.com", "https");
bad("/etc/passwd", "");
bad("report.pdf", "");
bad("", "");
bad("-https://x", "-https");
}
#[test]
fn decide_refuses_control_characters_and_whitespace_first() {
for url in [
"https://x/a b",
"https://x/\n",
"https://x/\r\nweb: opened https://evil",
"https://x/\u{1b}[2J",
"https://x/\t",
"https://x/\u{7f}",
"https://x/\u{2028}",
"https://x/\u{a0}",
"ssh://x y",
] {
assert_eq!(open_now(url), Verdict::BadChars, "{url:?}");
}
assert_eq!(decide("https://x/\n", AT, AT, || panic!("not asked")), Verdict::BadChars);
assert_eq!(open_now("https://x/a%20b%0A"), Verdict::Open, "percent-encoded is fine");
assert_eq!(open_now("https://x/é"), Verdict::Open);
}
#[test]
fn printable_escapes_controls_and_keeps_the_rest() {
assert_eq!(printable("web: a b é `x` hasn't"), "web: a b é `x` hasn't");
assert_eq!(printable("a\nb\r\t\u{1b}[2J\u{2028}"), "a\\nb\\r\\t\\u{1b}[2J\\u{2028}");
}
#[test]
fn decide_drops_records_past_the_ttl() {
let ttl = OPEN_TTL.as_secs();
assert_eq!(decide("https://x", AT, AT + ttl, || true), Verdict::Open, "exactly the TTL still opens");
assert_eq!(decide("https://x", AT, AT + ttl + 1, || true), Verdict::Expired { age: ttl + 1 });
assert_eq!(decide("https://x", AT + 5, AT, || true), Verdict::Open, "skewed into the future");
}
#[test]
fn decide_spends_the_limit_only_on_otherwise_good_opens() {
let mut rl = RateLimit::new(OPEN_RATE_BURST, OPEN_RATE_REFILL);
let t0 = Instant::now();
let mut try_open = |url: &str, at: u64, t: Instant| decide(url, at, AT, || rl.allow("web-1", None, t));
for _ in 0..10 {
assert_eq!(try_open("ssh://x", AT, t0), Verdict::BadScheme("ssh".into()));
assert!(matches!(try_open("https://x", AT - 60, t0), Verdict::Expired { .. }));
}
for _ in 0..OPEN_RATE_BURST {
assert_eq!(try_open("https://x", AT, t0), Verdict::Open);
}
assert_eq!(try_open("https://x", AT, t0), Verdict::Limited);
assert_eq!(try_open("https://x", AT, t0 + OPEN_RATE_REFILL), Verdict::Open, "one refilled");
assert!(rl.allow("web-2", None, t0));
}
#[test]
fn refusals_log_the_instance_and_url() {
assert_eq!(Verdict::Open.log_line("web-1", "https://x"), None);
let line = |v: Verdict| v.log_line("web-1", "ssh://x").unwrap();
assert_eq!(line(Verdict::BadScheme("ssh".into())), "web-1: open refused, scheme `ssh` (http and https only): ssh://x");
assert_eq!(line(Verdict::BadScheme(String::new())), "web-1: open refused, not a URL with a scheme: ssh://x");
assert_eq!(line(Verdict::Expired { age: 45 }), "web-1: open dropped, queued 45s ago (over 30s): ssh://x");
assert_eq!(line(Verdict::Limited), "web-1: open refused, rate limit (5 per 10s): ssh://x");
assert_eq!(
Verdict::BadChars.log_line("web\n-1", "https://x/\nweb: opened").unwrap(),
"web\\n-1: open refused, control characters or whitespace in the URL: https://x/\\nweb: opened",
"one line, whatever the URL holds"
);
}
#[test]
fn opener_argv_per_os() {
assert_eq!(opener_argv("linux", "https://x/?a=b c"), Some(vec!["xdg-open".into(), "https://x/?a=b c".into()]));
assert_eq!(opener_argv("macos", "https://x"), Some(vec!["open".into(), "https://x".into()]));
assert_eq!(opener_argv("windows", "https://x"), None);
}
#[test]
fn profiles_toml_parses_open_commands() {
let profiles = parse_profiles(
"[work]\nopen = [\"google-chrome\", \"--profile-directory=Profile 2\"]\n\n[personal]\nopen = [\"firefox\"]\n",
)
.unwrap();
assert_eq!(profiles.len(), 2);
assert_eq!(profiles["work"].open, vec!["google-chrome", "--profile-directory=Profile 2"]);
assert_eq!(profiles["personal"].open, vec!["firefox"]);
assert!(parse_profiles("").unwrap().is_empty(), "an empty file is no profiles");
assert!(parse_profiles("# nothing yet\n").unwrap().is_empty());
}
#[test]
fn profiles_toml_refuses_bad_entries() {
let err = |s: &str| format!("{:#}", parse_profiles(s).unwrap_err());
assert!(err("[work]\nopen = []\n").contains("[work]: `open` is empty"));
err("[work]\nopen = [\"chrome\", 2]\n");
err("[work]\nopen = \"chrome\"\n");
err("[work]\n");
assert!(err("[work]\nopen = [\"chrome\"]\nicon = \"x\"\n").contains("icon"), "unknown keys refused");
err("open = [\"chrome\"]\n");
}
#[test]
fn a_missing_profiles_toml_is_none() {
let dir = std::env::temp_dir().join(format!("devsandbox-open-test-{}", std::process::id()));
assert!(load_profiles(&dir.join("profiles.toml")).unwrap().is_empty());
}
fn profiles() -> HostProfiles {
parse_profiles("[work]\nopen = [\"chrome\", \"--profile-directory=Work\"]\n").unwrap()
}
#[test]
fn open_argv_uses_a_mapped_profile_else_the_system_opener() {
let url = "https://x/?a=b";
let argv = |v: &[&str]| Some(v.iter().map(|s| s.to_string()).collect::<Vec<_>>());
assert_eq!(open_argv("linux", Some("work"), &profiles(), url), argv(&["chrome", "--profile-directory=Work", url]));
assert_eq!(open_argv("macos", Some("work"), &profiles(), url), argv(&["chrome", "--profile-directory=Work", url]));
assert_eq!(open_argv("linux", Some("personal"), &profiles(), url), argv(&["xdg-open", url]), "unmapped");
assert_eq!(open_argv("macos", None, &profiles(), url), argv(&["open", url]), "no profile");
assert_eq!(open_argv("linux", None, &HostProfiles::new(), url), argv(&["xdg-open", url]));
}
fn instance(profile: Option<&str>) -> Instance {
let profile = profile.map_or(String::new(), |p| format!("profile = \"{p}\"\n"));
let state: State = toml::from_str(&format!(
"[instance.web-1]\nsandbox = \"web\"\ninstance_id = \"web-1\"\ncontainer = \"devsandbox-web-1\"\n\
folder = \"/src/web\"\nworkspace = \"/workspaces/web\"\ncreated_unix = 1\n{profile}"
))
.unwrap();
state.instances.into_values().next().unwrap()
}
#[test]
fn the_instances_profile_is_sent_unless_the_config_dropped_it() {
let url = "https://x";
let allowed = |set: &'static [&'static str]| {
move |_: &Instance| Some(set.iter().map(|s| s.to_string()).collect::<Vec<_>>())
};
let send = |inst: Option<&Instance>, set: &'static [&'static str]| profile_to_send("web-1", url, inst, allowed(set));
let named = |p: &str| (Some(p.to_string()), None);
let work = instance(Some("work"));
assert_eq!(send(Some(&work), &["work", "personal"]), named("work"));
assert_eq!(send(Some(&instance(Some("personal"))), &["work", "personal"]), named("personal"), "mapped or not: the opener's call");
assert_eq!(send(Some(&instance(None)), &["work"]), (None, None), "no profile");
assert_eq!(send(None, &["work"]), (None, None), "no instance");
assert_eq!(profile_to_send("web-1", url, Some(&work), |_| None), named("work"), "an allowed set that can't be told doesn't flag");
assert_eq!(
send(Some(&work), &["personal"]),
(
None,
Some("web-1: profile `work` no longer allowed by the config; opening https://x with the default opener".into())
),
"disallowed"
);
let unasked = |_: &Instance| -> Option<Vec<String>> { panic!("no profile: the config isn't loaded") };
profile_to_send("web-1", url, Some(&instance(None)), unasked);
}
#[test]
fn a_local_job_carries_the_profile_and_the_instances_target() {
let inst = Instance { config_dir: Some("/cfg".into()), ..instance(Some("work")) };
let (job, warning) = local_job("web", "https://x", Some(("web-1", &inst)), |_| None);
assert_eq!(warning, None);
assert_eq!(
job,
OpenJob {
instance: "web".into(),
url: "https://x".into(),
profile: Some("work".into()),
target: Ok(ForwardTarget { machine: None, dir: "/cfg".into(), instance: "web-1".into() }),
}
);
let bare = instance(None);
assert_eq!(local_job("web", "https://x", Some(("web-1", &bare)), |_| None).0.target, Err("no config root in state.toml".into()));
assert_eq!(local_job("web", "https://x", None, |_| None).0.target, Err("not in state.toml".into()));
}
fn direct(port: u16) -> Loopback {
Loopback { port, callback: false }
}
fn callback(port: u16) -> Loopback {
Loopback { port, callback: true }
}
#[test]
fn loopback_ports_of_direct_urls() {
let cases: &[(&str, &[Loopback])] = &[
("http://localhost:3000/app?x=1#top", &[direct(3000)]),
("http://127.0.0.1:8080", &[direct(8080)]),
("http://[::1]:5173/", &[direct(5173)]),
("http://[0:0:0:0:0:0:0:1]:5173/", &[direct(5173)]),
("http://0.0.0.0:8000/", &[direct(8000)]),
("HTTP://LOCALHOST:3000/", &[direct(3000)]),
("http://[::1]/", &[direct(80)]),
("http://localhost/", &[direct(80)]),
("https://localhost", &[direct(443)]),
("http://localhost:/", &[direct(80)]),
("http://user:pw@localhost:9000/", &[direct(9000)]),
("http://localhost.:3000/", &[direct(3000)]),
("http://127.0.0.1.:3000/", &[direct(3000)]),
("http://0.0.0.0.:3000/", &[direct(3000)]),
("http://127.0.0.2:3000/", &[direct(3000)]),
("http://127.255.1.9/", &[direct(80)]),
("http://evil.com\\@localhost:3000/", &[]),
("http://localhost\\@evil.com:3000/", &[direct(80)]),
("http://localhost@example.com:3000/", &[]),
("https://example.com/", &[]),
("http://localhost.evil.com:3000/", &[]),
("http://localhost..:3000/", &[]),
("http://128.0.0.1:3000/", &[]),
("http://[::2]:3000/", &[]),
("http://localhost:0/", &[]),
("http://localhost:65536/", &[]),
("http://localhost:3x/", &[]),
("http://localhost:+80/", &[]),
("http://localhost:-1/", &[]),
("http://localhost: 80/", &[]),
("http://[::1]x/", &[]),
("http://127.1:3000/", &[]),
("http://0x7f.0.0.1:3000/", &[]),
("http://2130706433:3000/", &[]),
("http://[fe80::1%25lo]:3000/", &[]),
("http://%6cocalhost:3000/", &[]),
("not a url", &[]),
];
for (url, want) in cases {
assert_eq!(loopback_ports(url), *want, "{url}");
}
}
#[test]
fn loopback_ports_of_callbacks() {
let cases: &[(&str, &[Loopback])] = &[
(
"https://github.com/login/oauth/authorize?client_id=x&redirect_uri=http%3A%2F%2Flocalhost%3A8085%2Fcb&state=y",
&[callback(8085)],
),
("https://idp.example/auth?redirect_uri=http://127.0.0.1:9004/cb", &[callback(9004)]),
("https://idp.example/auth?redirect_url=http%3a%2f%2f%5b%3a%3a1%5d%3a7000", &[callback(7000)]),
("https://idp.example/auth?callback=http://localhost/cb", &[callback(80)]),
(
"https://idp.example/auth?redirect_uri=http://localhost:1&redirect_url=http://localhost:2&callback=http://localhost:3",
&[callback(1), callback(2), callback(3)],
),
("https://idp.example/a?redirect_uri=http://localhost:1&redirect_uri=http://localhost:2", &[callback(1)]),
("https://idp.example/a?redirect_uri=https://example.com&redirect_uri=http://localhost:2", &[]),
("https://idp.example/a?callback=ssh://localhost:22", &[]),
("https://idp.example/a?callback=localhost:22", &[]),
("https://idp.example/a?redirect_uri=http://localhost.evil.com:1", &[]),
("https://idp.example/a?return_to=http://localhost:1", &[]),
("https://idp.example/a#redirect_uri=http://localhost:1", &[]),
("https://idp.example/a?x=1#redirect_uri=http://localhost:1", &[]),
("https://idp.example/a?next=https%3A%2F%2Fb%2F%3Fredirect_uri%3Dhttp%3A%2F%2Flocalhost%3A1", &[]),
("http://localhost:3000/login?redirect_uri=http://localhost:4000/cb", &[direct(3000), callback(4000)]),
("http://localhost:3000/login?redirect_uri=http://localhost:3000/cb", &[callback(3000)]),
];
for (url, want) in cases {
assert_eq!(loopback_ports(url), *want, "{url}");
}
}
#[test]
fn rewrite_direct_sets_the_port_and_leaves_the_rest() {
let cases: &[(&str, Option<u16>, &str)] = &[
("http://localhost:3000/a?b=c#d", Some(3001), "http://localhost:3001/a?b=c#d"),
("http://localhost/a", Some(3001), "http://localhost:3001/a"),
("https://localhost", Some(8443), "https://localhost:8443"),
("http://localhost?q=http://x:1", Some(5), "http://localhost:5?q=http://x:1"),
("http://[::1]:3000/", Some(3001), "http://127.0.0.1:3001/"),
("http://[::1]/", Some(3001), "http://127.0.0.1:3001/"),
("http://[::1]:3000/", None, "http://127.0.0.1:3000/"),
("http://u:p@127.0.0.1:3000/", Some(3001), "http://u:p@127.0.0.1:3001/"),
("http://0.0.0.0:8000/x", None, "http://localhost:8000/x"),
("http://0.0.0.0/x", None, "http://localhost/x"),
("http://0.0.0.0.:8000/x", None, "http://localhost:8000/x"),
("http://0.0.0.0:8000/x", Some(8001), "http://localhost:8001/x"),
("http://127.0.0.2:8000/x", None, "http://127.0.0.1:8000/x"),
("http://127.9.9.9:8000/x", Some(8001), "http://127.0.0.1:8001/x"),
("http://127.0.0.1.:8000/x", None, "http://127.0.0.1.:8000/x"),
("http://localhost.:3000/", Some(3001), "http://localhost.:3001/"),
("http://localhost:3000/", None, "http://localhost:3000/"),
("http://evil.com\\@localhost:3000/", None, "http://evil.com\\@localhost:3000/"),
("not a url", Some(1), "not a url"),
];
for (url, port, want) in cases {
assert_eq!(rewrite_direct(url, *port), *want, "{url} {port:?}");
}
}
fn local() -> ForwardTarget {
ForwardTarget::local(Some(("web-1", &Instance { config_dir: Some("/cfg".into()), ..instance(None) }))).unwrap()
}
type Call = (ForwardTarget, Loopback);
fn forwarding(
calls: &std::cell::RefCell<Vec<Call>>,
bound: impl Fn(Loopback) -> Result<u16, Option<String>>,
) -> impl Fn(&ForwardTarget, Loopback) -> Result<u16, Option<String>> {
move |t, lb| {
calls.borrow_mut().push((t.clone(), lb));
bound(lb)
}
}
fn opens(url: &str) -> Result<String, String> {
Ok(url.to_string())
}
#[test]
fn forward_loopbacks_rewrites_a_moved_direct_port() {
let calls = Default::default();
let t = local();
let got = forward_loopbacks("web", "http://localhost:3000/x", Ok(&t), forwarding(&calls, |_| Ok(3001)));
assert_eq!(got, (opens("http://localhost:3001/x"), vec![], vec![]));
assert_eq!(calls.into_inner(), vec![(t.clone(), direct(3000))]);
let got = forward_loopbacks("web", "http://localhost:3000/x", Ok(&t), |_: &ForwardTarget, lb: Loopback| Ok(lb.port));
assert_eq!(got, (opens("http://localhost:3000/x"), vec![], vec![]), "bound on the same port");
let got = forward_loopbacks("web", "http://0.0.0.0:8000/", Ok(&t), |_: &ForwardTarget, lb: Loopback| Ok(lb.port));
assert_eq!(got.0, opens("http://localhost:8000/"), "0.0.0.0 made localhost");
let got = forward_loopbacks("web", "http://0.0.0.0:8000/", Ok(&t), |_: &ForwardTarget, _| Ok(8001));
assert_eq!(got.0, opens("http://localhost:8001/"));
let got = forward_loopbacks("web", "http://127.0.0.5:8000/", Ok(&t), |_: &ForwardTarget, lb: Loopback| Ok(lb.port));
assert_eq!(got.0, opens("http://127.0.0.1:8000/"), "onto the forward's 127.0.0.1");
}
#[test]
fn forward_loopbacks_hands_a_machines_target_through() {
let calls = Default::default();
let t = ForwardTarget { machine: Some("box".into()), dir: "/home/u/cfg".into(), instance: "web-1".into() };
let url = "https://idp.example/a?redirect_uri=http://localhost:3000/";
let got = forward_loopbacks("web-1", url, Ok(&t), forwarding(&calls, |_| Err(Some("no machine named `box`".into()))));
assert_eq!(got.1, vec![format!("web-1: cannot forward callback port 3000 for {url}: no machine named `box`")]);
assert_eq!(got.2, vec![callback(3000)]);
assert_eq!(calls.into_inner(), vec![(t, callback(3000))]);
}
#[test]
fn forward_loopbacks_leaves_a_callback_url_as_is() {
let calls = Default::default();
let t = local();
let url = "https://github.com/login?redirect_uri=http%3A%2F%2Flocalhost%3A8085%2Fcb";
let got = forward_loopbacks("web", url, Ok(&t), forwarding(&calls, |lb| Ok(lb.port)));
assert_eq!(got, (opens(url), vec![], vec![]));
assert_eq!(calls.into_inner(), vec![(t.clone(), callback(8085))]);
let got = forward_loopbacks("web", url, Ok(&t), |_: &ForwardTarget, _| Err(None));
assert_eq!(got, (opens(url), vec![], vec![callback(8085)]));
let got = forward_loopbacks("web", url, Ok(&t), |_: &ForwardTarget, _| Err(Some("registry stopped".into())));
assert_eq!(got.1, vec![format!("web: cannot forward callback port 8085 for {url}: registry stopped")]);
assert_eq!((got.0, got.2), (opens(url), vec![callback(8085)]));
let never = |_: &ForwardTarget, _| -> Result<u16, Option<String>> { panic!("nothing to forward to") };
let url = "https://idp.example/a?redirect_uri=http://localhost:1&callback=http://localhost:2";
let got = forward_loopbacks("web", url, Err("not in state.toml"), never);
assert_eq!(
got,
(
opens(url),
vec![format!("web: cannot forward callback ports 1, 2 for {url} (not in state.toml); opening it as is")],
vec![callback(1), callback(2)]
)
);
}
#[test]
fn forward_loopbacks_never_opens_an_unforwarded_direct_port() {
let calls = Default::default();
let t = local();
let url = "http://localhost:3000/?redirect_uri=http://localhost:4000/cb";
let got = forward_loopbacks("web", url, Ok(&t), forwarding(&calls, |_| Err(Some("port 3000: nope".into()))));
assert_eq!(got, (Err("cannot forward port 3000: port 3000: nope".into()), vec![], vec![]));
assert_eq!(calls.into_inner(), vec![(t.clone(), direct(3000))], "the callback isn't bound");
let url = "http://localhost:3000/login?redirect_uri=http://localhost:3000/cb";
let got = forward_loopbacks("web", url, Ok(&t), |_: &ForwardTarget, _| Err(None));
assert_eq!(got.0, Err("cannot forward port 3000: it is also the callback port, which couldn't be bound".into()));
let url = "http://localhost:3000/?redirect_uri=http://localhost:4000/cb";
let got = forward_loopbacks("web", url, Ok(&t), |_: &ForwardTarget, lb: Loopback| if lb.callback { Err(None) } else { Ok(3001) });
assert_eq!(got, (opens("http://localhost:3001/?redirect_uri=http://localhost:4000/cb"), vec![], vec![callback(4000)]));
let never = |_: &ForwardTarget, _| -> Result<u16, Option<String>> { panic!("nothing to forward to") };
let got = forward_loopbacks("web", "http://0.0.0.0:3000/?callback=http://localhost:9", Err("not in state.toml"), never);
assert_eq!(got, (Err("cannot forward port 3000: not in state.toml".into()), vec![], vec![]));
assert_eq!(forward_loopbacks("web", "https://example.com/", Err("x"), never), (opens("https://example.com/"), vec![], vec![]));
let url = "http://evil.com\\@localhost:3000/";
assert_eq!(forward_loopbacks("web", url, Err("x"), never), (opens(url), vec![], vec![]), "not loopback, untouched");
}
fn done(profile: Option<&str>, outcome: Outcome) -> OpenDone {
OpenDone { instance: "web".into(), url: "https://x.example/a".into(), profile: profile.map(Into::into), outcome }
}
#[test]
fn each_outcome_is_one_status_line() {
let opened = Outcome::Opened { unforwarded: vec![] };
assert_eq!(done(Some("work"), opened.clone()).line(), "web: opened https://x.example/a (work)");
assert_eq!(done(None, opened.clone()).line(), "web: opened https://x.example/a");
assert_eq!((done(None, opened).kind(), done(None, Outcome::Opened { unforwarded: vec![] }).why()), ("opened", None));
let blocked = done(Some("work"), Outcome::Opened { unforwarded: vec![callback(8085), direct(3000)] });
assert_eq!(blocked.line(), "web: opened https://x.example/a (work); cannot forward callback port 8085, port 3000");
assert_eq!(blocked.why().as_deref(), Some("cannot forward callback port 8085, port 3000"));
let why = Verdict::BadScheme("ssh".into()).refusal().unwrap();
let refused = done(None, Outcome::Refused(why));
assert_eq!((refused.kind(), refused.line().as_str()), ("refused", "web: open refused: scheme `ssh` (http and https only)"));
let failed = done(Some("work"), Outcome::Failed("no display on this host".into()));
assert_eq!((failed.kind(), failed.line().as_str()), ("failed", "web: open failed: no display on this host"));
assert_eq!(failed.why().as_deref(), Some("no display on this host"));
let d = OpenDone { url: "https://x/\u{1b}[2J".into(), ..done(None, Outcome::Failed("nope\nweb: opened".into())) };
assert_eq!(d.line(), "web: open failed: nope\\nweb: opened");
let d = OpenDone { url: "https://x/\r\n".into(), ..done(None, Outcome::Opened { unforwarded: vec![] }) };
assert_eq!(d.line(), "web: opened https://x/\\r\\n");
}
#[test]
fn long_urls_and_reasons_are_shortened_in_the_line_only() {
let url = format!("https://idp.example/auth?{}", "q".repeat(500));
let d = OpenDone { url: url.clone(), ..done(Some("work"), Outcome::Opened { unforwarded: vec![] }) };
let line = d.line();
let shown = line.strip_prefix("web: opened ").unwrap().strip_suffix(" (work)").unwrap();
assert_eq!(shown.chars().count(), LINE_URL);
assert!(shown.ends_with('…') && url.starts_with(shown.trim_end_matches('…')));
assert_eq!(d.url, url, "the wire keeps it whole");
let d = done(None, Outcome::Failed("é".repeat(400)));
assert_eq!(d.line().strip_prefix("web: open failed: ").unwrap().chars().count(), LINE_WHY);
assert_eq!(shorten("abc", 3), "abc");
assert_eq!(shorten("abcd", 3), "ab…");
}
#[test]
fn display_comes_from_the_env_on_linux() {
let env = |set: &'static [(&'static str, &'static str)]| {
move |k: &str| set.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v))
};
assert!(!has_display("linux", env(&[])));
assert!(!has_display("linux", env(&[("DISPLAY", "")])));
assert!(has_display("linux", env(&[("DISPLAY", ":0")])));
assert!(has_display("linux", env(&[("WAYLAND_DISPLAY", "wayland-0")])));
assert!(!has_display("linux", env(&[("XAUTHORITY", "/run/user/1000/a")])), "auth alone isn't a display");
assert!(has_display("macos", env(&[])));
}
#[test]
fn session_display_env_picks_the_display_vars() {
let out = "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus\n\
DISPLAY=:0\n\
HOME=/home/u\n\
WAYLAND_DISPLAY=wayland-0\n\
XAUTHORITY=/run/user/1000/.mutter-Xwaylandauth.AB12\n\
XDG_CURRENT_DESKTOP=GNOME\n";
let pair = |k: &str, v: &str| (k.to_string(), v.to_string());
assert_eq!(
session_display_env(out),
vec![
pair("DISPLAY", ":0"),
pair("WAYLAND_DISPLAY", "wayland-0"),
pair("XAUTHORITY", "/run/user/1000/.mutter-Xwaylandauth.AB12"),
]
);
assert!(session_display_env("HOME=/home/u\nPATH=/usr/bin\n").is_empty());
assert!(session_display_env("DISPLAY=\nXAUTHORITY=$'/tmp/a b'\n").is_empty());
}
}