Skip to main content

vault_core/
sites.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Sites: the places a credential is used (roadmap R40).
4//!
5//! A password manager keys a login to one URL. This vault keys it to an entry (a stable id and a
6//! name) and lets the entry list several places: a login page, an API address, a service on the
7//! LAN with its own port. A [`Site`] is only a normalised address. Nothing here reads a secret.
8//!
9//! Three rules decide whether a page may be offered a credential, and each is here because a wrong
10//! answer fills a password into the wrong place:
11//!
12//! * The host is compared after normalisation (lower case, no trailing dot, punycode), so
13//!   `Example.COM.` and `example.com` are one site and `paypa1.com` is not `paypal.com`.
14//! * Every loopback spelling is one host (`localhost`, `*.localhost`, `127.0.0.0/8`, `::1`), so a
15//!   password saved for `localhost:8989` also answers at `127.0.0.1:8989`. The port stays
16//!   significant: Sonarr and Radarr share a host and are different services.
17//! * A site stored without a scheme matches `https`, and matches `http` only on a private or
18//!   loopback host, so a public site is never downgraded to plain text by a missing scheme.
19//!
20//! The Rust side is the only implementation (invariant 10): the desktop reaches it over IPC and the
21//! extension host calls it directly.
22
23use serde::{Deserialize, Serialize};
24use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
25use url::{Host, Url};
26
27/// The longest address accepted. A URL in a vault is a hint, not a document.
28const MAX_LEN: usize = 2048;
29
30/// A normalised address: scheme if one was given, host, port if one was given. The path, query and
31/// fragment are dropped, because a credential belongs to a service and not to a page of it.
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub struct Site {
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub scheme: Option<String>,
36    pub host: String,
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub port: Option<u16>,
39}
40
41/// How strictly an origin must equal a stored site.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
43#[serde(rename_all = "snake_case")]
44pub enum Mode {
45    /// Same host, same scheme and same port (the default).
46    Exact,
47    /// Same host and scheme, any port: a service that moves between ports.
48    AnyPort,
49    /// Same host, any scheme and any port. The downgrade rule still applies.
50    Host,
51    /// Never offered here, whatever else matches.
52    Never,
53}
54
55impl Mode {
56    pub fn parse(s: &str) -> Option<Self> {
57        match s {
58            "exact" => Some(Self::Exact),
59            "any_port" => Some(Self::AnyPort),
60            "host" => Some(Self::Host),
61            "never" => Some(Self::Never),
62            _ => None,
63        }
64    }
65}
66
67impl Site {
68    /// `scheme://host:port` as far as each part is known; an IPv6 host is bracketed.
69    pub fn display(&self) -> String {
70        let host = if self.host.contains(':') {
71            format!("[{}]", self.host)
72        } else {
73            self.host.clone()
74        };
75        let mut out = match &self.scheme {
76            Some(s) => format!("{s}://{host}"),
77            None => host,
78        };
79        if let Some(p) = self.port {
80            out.push_str(&format!(":{p}"));
81        }
82        out
83    }
84}
85
86fn default_port(scheme: &str) -> Option<u16> {
87    match scheme {
88        "http" => Some(80),
89        "https" => Some(443),
90        "ssh" | "sftp" => Some(22),
91        "ftp" => Some(21),
92        "postgres" | "postgresql" => Some(5432),
93        "mysql" | "mariadb" => Some(3306),
94        "redis" | "rediss" => Some(6379),
95        "mongodb" => Some(27017),
96        _ => None,
97    }
98}
99
100fn valid_scheme(s: &str) -> bool {
101    let mut chars = s.chars();
102    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
103        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
104}
105
106/// Normalises `input`: a full URL (`https://sonarr.home:8989/app`), an address and port
107/// (`192.168.1.20:8989`), or a bare host (`localhost`).
108///
109/// A user name or password inside the address is refused: a credential in a URL is what this
110/// vault exists to keep out of URLs.
111pub fn parse_site(input: &str) -> Result<Site, String> {
112    let s = input.trim();
113    if s.is_empty() {
114        return Err("the address is empty".into());
115    }
116    if s.len() > MAX_LEN {
117        return Err(format!("the address is over {MAX_LEN} characters"));
118    }
119    if s.chars().any(|c| c.is_whitespace() || c.is_control()) {
120        return Err("an address holds no spaces or control characters".into());
121    }
122    let (scheme, rest) = match s.split_once("://") {
123        Some((scheme, rest)) => {
124            if !valid_scheme(scheme) {
125                return Err(format!("`{scheme}` is not a scheme"));
126            }
127            (Some(scheme.to_ascii_lowercase()), rest)
128        }
129        None => (None, s),
130    };
131    let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
132    let authority = &rest[..end];
133    if authority.is_empty() {
134        return Err("the address has no host".into());
135    }
136    if authority.contains('@') {
137        return Err("an address with a user name or password is not stored".into());
138    }
139    // The port is read from the text: the URL parser drops a port that is the default of http.
140    let (host_part, port) = match authority.rsplit_once(':') {
141        Some((h, p)) if !authority.ends_with(']') && !h.is_empty() && !h.ends_with(':') => {
142            if p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()) {
143                return Err("the port is not a number".into());
144            }
145            let port: u16 = p
146                .parse()
147                .map_err(|_| "the port is over 65535".to_string())?;
148            if port == 0 {
149                return Err("port 0 is not an address".into());
150            }
151            (h, Some(port))
152        }
153        _ => (authority, None),
154    };
155    let parsed =
156        Url::parse(&format!("http://{host_part}")).map_err(|e| format!("not an address: {e}"))?;
157    let host = match parsed.host() {
158        Some(Host::Domain(d)) => d.trim_end_matches('.').to_string(),
159        Some(Host::Ipv4(a)) => a.to_string(),
160        Some(Host::Ipv6(a)) => a.to_string(),
161        None => return Err("the address has no host".into()),
162    };
163    if host.is_empty() {
164        return Err("the address has no host".into());
165    }
166    Ok(Site { scheme, host, port })
167}
168
169/// True for every spelling of this machine: `localhost`, `*.localhost` (RFC 6761), `127.0.0.0/8`,
170/// `::1` and its IPv4-mapped form.
171pub fn is_loopback(host: &str) -> bool {
172    if host == "localhost" || host.ends_with(".localhost") {
173        return true;
174    }
175    match host.parse::<IpAddr>() {
176        Ok(IpAddr::V4(a)) => a.is_loopback(),
177        Ok(IpAddr::V6(a)) => a.is_loopback() || a.to_ipv4_mapped().is_some_and(|v| v.is_loopback()),
178        Err(_) => false,
179    }
180}
181
182fn private_v4(a: Ipv4Addr) -> bool {
183    a.is_private() || a.is_link_local() || a.is_loopback()
184}
185
186fn private_v6(a: Ipv6Addr) -> bool {
187    let s = a.segments();
188    a.is_loopback() || (s[0] & 0xfe00) == 0xfc00 || (s[0] & 0xffc0) == 0xfe80
189}
190
191/// A host that is not on the public internet: loopback, RFC 1918 and link-local addresses, a
192/// single-label name, and the names a home network uses (`.local`, `.lan`, `.home`, `.internal`).
193pub fn is_private_host(host: &str) -> bool {
194    if is_loopback(host) {
195        return true;
196    }
197    match host.parse::<IpAddr>() {
198        Ok(IpAddr::V4(a)) => private_v4(a),
199        Ok(IpAddr::V6(a)) => private_v6(a),
200        Err(_) => {
201            !host.contains('.')
202                || [
203                    ".local",
204                    ".lan",
205                    ".home",
206                    ".internal",
207                    ".home.arpa",
208                    ".localdomain",
209                ]
210                .iter()
211                .any(|suffix| host.ends_with(suffix))
212        }
213    }
214}
215
216/// The host as it is compared: every loopback spelling becomes one marker that no real host can
217/// equal.
218fn canonical_host(host: &str) -> &str {
219    if is_loopback(host) {
220        "@loopback"
221    } else {
222        host
223    }
224}
225
226/// Pairs of addresses that name the same place in a different spelling: `localhost:8989` and
227/// `127.0.0.1:8989`, or `tv.example.org` and `https://tv.example.org`. Both are kept (a stored
228/// address is never rewritten), but a person adding the second usually did not mean to. The same
229/// text twice is not a pair, and addresses that do not parse are skipped.
230pub fn alternate_spellings(urls: &[String]) -> Vec<(String, String)> {
231    let parsed: Vec<(&String, Site)> = urls
232        .iter()
233        .filter_map(|u| parse_site(u).ok().map(|s| (u, s)))
234        .collect();
235    let mut pairs = Vec::new();
236    for (i, (a, x)) in parsed.iter().enumerate() {
237        for (b, y) in &parsed[i + 1..] {
238            let schemes_agree = x.scheme.is_none() || y.scheme.is_none() || x.scheme == y.scheme;
239            if x.display() != y.display()
240                && schemes_agree
241                && x.port == y.port
242                && canonical_host(&x.host) == canonical_host(&y.host)
243            {
244                pairs.push(((*a).clone(), (*b).clone()));
245            }
246        }
247    }
248    pairs
249}
250
251/// Whether a page at `origin` may be offered a credential stored for `stored`.
252///
253/// `origin` is what a browser reports: it always has a scheme. A result of `false` is final; a
254/// result of `true` still only means "offer it", and the caller decides about filling.
255pub fn site_matches(stored: &Site, mode: Mode, origin: &Site) -> bool {
256    if mode == Mode::Never {
257        return false;
258    }
259    let Some(origin_scheme) = origin.scheme.as_deref() else {
260        return false;
261    };
262    if canonical_host(&stored.host) != canonical_host(&origin.host) {
263        return false;
264    }
265    // A missing scheme never downgrades a public site to plain text.
266    let plain_text = origin_scheme == "http";
267    if plain_text && stored.scheme.as_deref() != Some("http") && !is_private_host(&origin.host) {
268        return false;
269    }
270    if mode == Mode::Host {
271        return true;
272    }
273    if let Some(stored_scheme) = stored.scheme.as_deref() {
274        if stored_scheme != origin_scheme {
275            return false;
276        }
277    }
278    if mode == Mode::AnyPort {
279        return true;
280    }
281    let scheme_for_port = stored.scheme.as_deref().unwrap_or(origin_scheme);
282    let stored_port = stored.port.or_else(|| default_port(scheme_for_port));
283    let origin_port = origin.port.or_else(|| default_port(origin_scheme));
284    stored_port == origin_port
285}
286
287// ── Entry level: the `sites` list, families, and "is this entry offered here" ─────────────────────
288
289/// What a site is for. Free text is refused so the list stays something a UI can offer.
290pub const KINDS: [&str; 5] = ["web", "api", "local", "other", "android_app"];
291
292/// One address on an entry, as stored in the entry's `sites` array.
293#[derive(Debug, Clone, PartialEq, Eq)]
294pub struct EntrySite {
295    pub site: Site,
296    pub mode: Mode,
297    pub kind: String,
298    pub label: String,
299    pub source: String,
300}
301
302/// A named set of hosts that share a credential (for example MetaBrainz and its sister sites).
303#[derive(Debug, Clone, PartialEq, Eq)]
304pub struct Family {
305    pub name: String,
306    pub hosts: Vec<String>,
307}
308
309fn mode_name(m: Mode) -> &'static str {
310    match m {
311        Mode::Exact => "exact",
312        Mode::AnyPort => "any_port",
313        Mode::Host => "host",
314        Mode::Never => "never",
315    }
316}
317
318/// The kind a bare address most likely has: a private host is `local`, an `api.` host is `api`,
319/// anything else is `web`.
320pub fn guess_kind(site: &Site) -> &'static str {
321    if is_private_host(&site.host) {
322        "local"
323    } else if site.host.starts_with("api.") || site.host.contains(".api.") {
324        "api"
325    } else {
326        "web"
327    }
328}
329
330/// Builds the stored form of one site. The address is normalised, so what is stored is what is
331/// matched; the path of a URL is dropped (a credential belongs to a service, not a page).
332pub fn site_value(
333    input: &str,
334    kind: Option<&str>,
335    mode: Option<&str>,
336    label: &str,
337    source: &str,
338) -> Result<serde_json::Value, String> {
339    let site = parse_site(input)?;
340    let kind = match kind {
341        Some(k) if KINDS.contains(&k) => k,
342        Some(k) => return Err(format!("`{k}` is not a site kind ({})", KINDS.join(", "))),
343        None => guess_kind(&site),
344    };
345    let mode = match mode {
346        Some(m) => Mode::parse(m)
347            .ok_or_else(|| format!("`{m}` is not a mode (exact, any_port, host, never)"))?,
348        None => Mode::Exact,
349    };
350    Ok(serde_json::json!({
351        "url": site.display(),
352        "kind": kind,
353        "mode": mode_name(mode),
354        "label": label.trim(),
355        "source": source,
356        "added_at": crate::iso_now(),
357    }))
358}
359
360/// Every address an entry answers to: its `sites`, plus the older `api_url` read as one more site
361/// (a `web` site for a password, `api` for anything else), so nothing needs a migration.
362pub fn entry_sites(entry: &serde_json::Value) -> Vec<EntrySite> {
363    let mut out = Vec::new();
364    if let Some(list) = entry.get("sites").and_then(|v| v.as_array()) {
365        for s in list {
366            let Some(url) = s.get("url").and_then(|v| v.as_str()) else {
367                continue;
368            };
369            let Ok(site) = parse_site(url) else { continue };
370            let text = |k: &str| s.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string();
371            out.push(EntrySite {
372                mode: Mode::parse(&text("mode")).unwrap_or(Mode::Exact),
373                kind: if text("kind").is_empty() {
374                    guess_kind(&site).into()
375                } else {
376                    text("kind")
377                },
378                label: text("label"),
379                source: text("source"),
380                site,
381            });
382        }
383    }
384    if let Some(url) = entry.get("api_url").and_then(|v| v.as_str()) {
385        if let Ok(site) = parse_site(url) {
386            if !out.iter().any(|e| e.site == site) {
387                let password = entry.get("secretType").and_then(|v| v.as_str()) == Some("password");
388                out.push(EntrySite {
389                    site,
390                    mode: Mode::Exact,
391                    kind: if password { "web" } else { "api" }.into(),
392                    label: String::new(),
393                    source: "api_url".into(),
394                });
395            }
396        }
397    }
398    out
399}
400
401/// Adds `value` (from [`site_value`]) to the entry unless the same address is already there.
402/// Returns whether it was added.
403pub fn add_site(entry: &mut serde_json::Value, value: serde_json::Value) -> bool {
404    let url = value.get("url").and_then(|v| v.as_str()).unwrap_or("");
405    let have = entry
406        .get("sites")
407        .and_then(|v| v.as_array())
408        .is_some_and(|l| {
409            l.iter()
410                .any(|s| s.get("url").and_then(|v| v.as_str()) == Some(url))
411        });
412    if have {
413        return false;
414    }
415    match entry.get_mut("sites").and_then(|v| v.as_array_mut()) {
416        Some(list) => list.push(value),
417        None => entry["sites"] = serde_json::json!([value]),
418    }
419    true
420}
421
422/// Removes the site that normalises to `input`. Returns whether one was removed.
423pub fn remove_site(entry: &mut serde_json::Value, input: &str) -> Result<bool, String> {
424    let want = parse_site(input)?.display();
425    let Some(list) = entry.get_mut("sites").and_then(|v| v.as_array_mut()) else {
426        return Ok(false);
427    };
428    let before = list.len();
429    list.retain(|s| s.get("url").and_then(|v| v.as_str()) != Some(want.as_str()));
430    let removed = list.len() != before;
431    if list.is_empty() {
432        if let Some(o) = entry.as_object_mut() {
433            o.remove("sites");
434        }
435    }
436    Ok(removed)
437}
438
439/// The families kept in the vault: `site_families: [{name, hosts}]`.
440pub fn families(vault: &serde_json::Value) -> Vec<Family> {
441    vault
442        .get("site_families")
443        .and_then(|v| v.as_array())
444        .map(|list| {
445            list.iter()
446                .filter_map(|f| {
447                    let name = f.get("name")?.as_str()?.to_string();
448                    let hosts = f
449                        .get("hosts")?
450                        .as_array()?
451                        .iter()
452                        .filter_map(|h| h.as_str().map(String::from))
453                        .collect();
454                    Some(Family { name, hosts })
455                })
456                .collect()
457        })
458        .unwrap_or_default()
459}
460
461/// The families that ship with the program (`data/site-families.json`).
462pub fn builtin_families() -> Vec<Family> {
463    let doc: serde_json::Value = serde_json::from_str(include_str!("../data/site-families.json"))
464        .expect("site-families.json is valid JSON");
465    families(&serde_json::json!({ "site_families": doc["families"] }))
466}
467
468/// Every family an entry may name: the ones in the vault, then the shipped ones whose name the
469/// vault does not use (a family of yours with the same name replaces the shipped one).
470pub fn known_families(vault: &serde_json::Value) -> Vec<Family> {
471    let mut all = families(vault);
472    for f in builtin_families() {
473        if !all.iter().any(|mine| mine.name == f.name) {
474            all.push(f);
475        }
476    }
477    all
478}
479
480/// Adds hosts to the named family (creating it). Hosts are normalised to a bare host; a scheme,
481/// port or path in the input is dropped, because a family is a set of hosts.
482pub fn family_add(
483    vault: &mut serde_json::Value,
484    name: &str,
485    hosts: &[String],
486) -> Result<(), String> {
487    let name = name.trim();
488    if name.is_empty() || name.len() > 64 || name.chars().any(|c| c.is_control()) {
489        return Err("a family name is 1 to 64 characters".into());
490    }
491    let mut clean = Vec::new();
492    for h in hosts {
493        let host = parse_site(h)?.host;
494        if !clean.contains(&host) {
495            clean.push(host);
496        }
497    }
498    if vault
499        .get("site_families")
500        .and_then(|v| v.as_array())
501        .is_none()
502    {
503        vault["site_families"] = serde_json::json!([]);
504    }
505    let list = vault["site_families"].as_array_mut().expect("just made");
506    match list
507        .iter_mut()
508        .find(|f| f.get("name").and_then(|v| v.as_str()) == Some(name))
509    {
510        Some(f) => {
511            let mut have: Vec<String> = f["hosts"]
512                .as_array()
513                .map(|a| {
514                    a.iter()
515                        .filter_map(|h| h.as_str().map(String::from))
516                        .collect()
517                })
518                .unwrap_or_default();
519            for h in clean {
520                if !have.contains(&h) {
521                    have.push(h);
522                }
523            }
524            f["hosts"] = serde_json::json!(have);
525        }
526        None => list.push(serde_json::json!({ "name": name, "hosts": clean })),
527    }
528    Ok(())
529}
530
531/// Removes a host from a family, or the whole family when `host` is `None`. Returns whether
532/// anything was removed.
533pub fn family_remove(
534    vault: &mut serde_json::Value,
535    name: &str,
536    host: Option<&str>,
537) -> Result<bool, String> {
538    let host = match host {
539        Some(h) => Some(parse_site(h)?.host),
540        None => None,
541    };
542    let Some(list) = vault
543        .get_mut("site_families")
544        .and_then(|v| v.as_array_mut())
545    else {
546        return Ok(false);
547    };
548    let mut changed = false;
549    match host {
550        None => {
551            let before = list.len();
552            list.retain(|f| f.get("name").and_then(|v| v.as_str()) != Some(name));
553            changed = list.len() != before;
554        }
555        Some(h) => {
556            for f in list.iter_mut() {
557                if f.get("name").and_then(|v| v.as_str()) != Some(name) {
558                    continue;
559                }
560                if let Some(hosts) = f.get_mut("hosts").and_then(|v| v.as_array_mut()) {
561                    let before = hosts.len();
562                    hosts.retain(|x| x.as_str() != Some(h.as_str()));
563                    changed |= hosts.len() != before;
564                }
565            }
566        }
567    }
568    Ok(changed)
569}
570
571/// Whether `origin` is a host of the family. The family host itself and its subdomains match; a
572/// look-alike (`evilmusicbrainz.org`) does not. A public host is matched over `https` only.
573pub fn family_has(family: &Family, origin: &Site) -> bool {
574    if origin.scheme.as_deref() == Some("http") && !is_private_host(&origin.host) {
575        return false;
576    }
577    family.hosts.iter().any(|h| {
578        canonical_host(h) == canonical_host(&origin.host)
579            || origin
580                .host
581                .strip_suffix(h.as_str())
582                .is_some_and(|p| p.ends_with('.'))
583    })
584}
585
586/// Whether the entry may be offered at `origin`: one of its sites matches, or the family it names
587/// has the origin's host. A result of `true` still only means "offer it".
588pub fn entry_offered(entry: &serde_json::Value, families: &[Family], origin: &Site) -> bool {
589    if entry_sites(entry)
590        .iter()
591        .any(|e| site_matches(&e.site, e.mode, origin))
592    {
593        return true;
594    }
595    let Some(name) = entry.get("site_family").and_then(|v| v.as_str()) else {
596        return false;
597    };
598    families
599        .iter()
600        .any(|f| f.name == name && family_has(f, origin))
601}
602
603#[cfg(test)]
604mod tests {
605    use super::*;
606
607    fn site(s: &str) -> Site {
608        parse_site(s).unwrap()
609    }
610
611    fn matches(stored: &str, mode: Mode, origin: &str) -> bool {
612        site_matches(&site(stored), mode, &site(origin))
613    }
614
615    #[test]
616    fn an_address_is_reduced_to_scheme_host_and_port() {
617        let s = site("HTTPS://Sonarr.Home:8989/app/login?x=1#top");
618        assert_eq!(s.scheme.as_deref(), Some("https"));
619        assert_eq!(s.host, "sonarr.home");
620        assert_eq!(s.port, Some(8989));
621        assert_eq!(s.display(), "https://sonarr.home:8989");
622    }
623
624    #[test]
625    fn an_address_and_a_port_without_a_scheme_is_accepted() {
626        let s = site("192.168.1.20:8989");
627        assert_eq!(s.scheme, None);
628        assert_eq!(s.host, "192.168.1.20");
629        assert_eq!(s.port, Some(8989));
630        assert_eq!(site("localhost").port, None);
631    }
632
633    #[test]
634    fn a_trailing_dot_and_capitals_do_not_make_a_second_site() {
635        assert_eq!(site("Example.COM.").host, "example.com");
636        assert_eq!(site("https://example.com:443/").port, Some(443));
637    }
638
639    #[test]
640    fn an_international_name_is_stored_as_punycode() {
641        assert_eq!(site("https://b\u{fc}cher.de").host, "xn--bcher-kva.de");
642    }
643
644    #[test]
645    fn ipv6_hosts_keep_their_brackets_only_for_display() {
646        let s = site("[::1]:8080");
647        assert_eq!(s.host, "::1");
648        assert_eq!(s.port, Some(8080));
649        assert_eq!(s.display(), "[::1]:8080");
650    }
651
652    #[test]
653    fn what_is_not_an_address_is_refused_with_a_reason() {
654        for bad in [
655            "",
656            "   ",
657            "https://",
658            "javascript:alert(1)",
659            "https://user:secret@example.com",
660            "https://exam ple.com",
661            "example.com:notaport",
662            "example.com:99999",
663            "example.com:0",
664            "1http://example.com",
665        ] {
666            assert!(parse_site(bad).is_err(), "{bad:?} should be refused");
667        }
668        let long = format!("https://{}.com", "a".repeat(MAX_LEN));
669        assert!(parse_site(&long).is_err());
670    }
671
672    /// The disparity the maintainer named: a password saved for one spelling of this machine did
673    /// not appear at another.
674    #[test]
675    fn every_loopback_spelling_is_one_host() {
676        let stored = "http://localhost:8989";
677        for origin in [
678            "http://localhost:8989",
679            "http://127.0.0.1:8989",
680            "http://127.1.2.3:8989",
681            "http://[::1]:8989",
682            "http://sonarr.localhost:8989",
683        ] {
684            assert!(matches(stored, Mode::Exact, origin), "{origin}");
685        }
686        assert!(matches(
687            "http://127.0.0.1:8989",
688            Mode::Exact,
689            "http://localhost:8989"
690        ));
691    }
692
693    /// Sonarr and Radarr share a host and are different services: the port stays significant.
694    #[test]
695    fn a_different_port_is_a_different_service() {
696        assert!(!matches(
697            "http://localhost:8989",
698            Mode::Exact,
699            "http://localhost:7878"
700        ));
701        assert!(matches(
702            "http://localhost:8989",
703            Mode::AnyPort,
704            "http://localhost:7878"
705        ));
706        assert!(!matches(
707            "http://localhost:8989",
708            Mode::AnyPort,
709            "https://localhost:8989"
710        ));
711        assert!(matches(
712            "http://localhost:8989",
713            Mode::Host,
714            "https://localhost:7878"
715        ));
716    }
717
718    #[test]
719    fn a_lookalike_or_a_neighbour_host_does_not_match() {
720        assert!(!matches(
721            "https://paypal.com",
722            Mode::Exact,
723            "https://paypa1.com"
724        ));
725        assert!(!matches(
726            "https://example.com",
727            Mode::Exact,
728            "https://evil.example.com"
729        ));
730        assert!(!matches(
731            "https://example.com",
732            Mode::Exact,
733            "https://example.com.evil.net"
734        ));
735        assert!(!matches(
736            "https://localhost",
737            Mode::Exact,
738            "https://localhost.evil.net"
739        ));
740        assert!(matches(
741            "https://example.com",
742            Mode::Exact,
743            "https://EXAMPLE.com."
744        ));
745    }
746
747    #[test]
748    fn default_ports_are_equal_to_no_port() {
749        assert!(matches(
750            "https://example.com",
751            Mode::Exact,
752            "https://example.com:443"
753        ));
754        assert!(matches(
755            "https://example.com:443",
756            Mode::Exact,
757            "https://example.com"
758        ));
759        assert!(!matches(
760            "https://example.com",
761            Mode::Exact,
762            "https://example.com:8443"
763        ));
764        assert!(matches("ssh://box:22", Mode::Exact, "ssh://box"));
765    }
766
767    /// A site saved without a scheme must not downgrade a public site to plain text.
768    #[test]
769    fn a_missing_scheme_matches_https_everywhere_and_http_only_on_a_private_host() {
770        assert!(matches("example.com", Mode::Exact, "https://example.com"));
771        assert!(!matches("example.com", Mode::Exact, "http://example.com"));
772        assert!(!matches("example.com", Mode::Host, "http://example.com"));
773        assert!(matches(
774            "sonarr.home:8989",
775            Mode::Exact,
776            "http://sonarr.home:8989"
777        ));
778        assert!(matches(
779            "192.168.1.20:8989",
780            Mode::Exact,
781            "http://192.168.1.20:8989"
782        ));
783        assert!(matches("nas", Mode::Exact, "http://nas"));
784        // Written out, it is the maintainer's choice.
785        assert!(matches(
786            "http://example.com",
787            Mode::Exact,
788            "http://example.com"
789        ));
790        // Never a downgrade from a stored https.
791        assert!(!matches(
792            "https://example.com",
793            Mode::Host,
794            "http://example.com"
795        ));
796    }
797
798    #[test]
799    fn never_overrides_everything_and_an_origin_needs_a_scheme() {
800        assert!(!matches(
801            "https://example.com",
802            Mode::Never,
803            "https://example.com"
804        ));
805        let bare = site("example.com");
806        assert!(!site_matches(&site("example.com"), Mode::Exact, &bare));
807    }
808
809    #[test]
810    fn private_hosts_are_recognised() {
811        for h in [
812            "localhost",
813            "10.0.0.5",
814            "172.16.3.4",
815            "192.168.0.1",
816            "169.254.1.1",
817            "::1",
818            "fd00::1",
819            "nas",
820            "printer.local",
821            "media.home.arpa",
822        ] {
823            assert!(is_private_host(h), "{h}");
824        }
825        for h in [
826            "example.com",
827            "8.8.8.8",
828            "2001:4860:4860::8888",
829            "evil.localhost.com",
830        ] {
831            assert!(!is_private_host(h), "{h}");
832        }
833    }
834
835    #[test]
836    fn modes_parse_by_name() {
837        assert_eq!(Mode::parse("exact"), Some(Mode::Exact));
838        assert_eq!(Mode::parse("any_port"), Some(Mode::AnyPort));
839        assert_eq!(Mode::parse("host"), Some(Mode::Host));
840        assert_eq!(Mode::parse("never"), Some(Mode::Never));
841        assert_eq!(Mode::parse("base_domain"), None);
842    }
843    #[test]
844    fn an_entry_lists_several_sites_and_reads_api_url_as_one_more() {
845        let mut e =
846            serde_json::json!({ "secretType": "password", "api_url": "https://login.example.org" });
847        assert!(add_site(
848            &mut e,
849            site_value("localhost:8989", None, None, "tv", "manual").unwrap()
850        ));
851        let sites = entry_sites(&e);
852        assert!(sites
853            .iter()
854            .any(|s| s.source == "api_url" && s.kind == "web"));
855        assert!(sites.iter().any(|s| s.kind == "local" && s.label == "tv"));
856    }
857
858    #[test]
859    fn a_loopback_spelling_is_offered_the_entry_but_another_port_is_not() {
860        let mut e = serde_json::json!({});
861        add_site(
862            &mut e,
863            site_value("localhost:8989", None, None, "", "manual").unwrap(),
864        );
865        assert!(entry_offered(&e, &[], &site("http://127.0.0.1:8989")));
866        assert!(!entry_offered(&e, &[], &site("http://127.0.0.1:7878")));
867    }
868
869    #[test]
870    fn a_family_offers_the_entry_on_every_host_and_not_on_a_lookalike() {
871        let mut v = serde_json::json!({});
872        family_add(
873            &mut v,
874            "metabrainz",
875            &[
876                "musicbrainz.org".into(),
877                "https://listenbrainz.org/x".into(),
878            ],
879        )
880        .unwrap();
881        let fams = families(&v);
882        assert_eq!(fams[0].hosts, ["musicbrainz.org", "listenbrainz.org"]);
883        let e = serde_json::json!({ "site_family": "metabrainz" });
884        assert!(entry_offered(&e, &fams, &site("https://listenbrainz.org")));
885        assert!(entry_offered(
886            &e,
887            &fams,
888            &site("https://beta.musicbrainz.org")
889        ));
890        assert!(!entry_offered(
891            &e,
892            &fams,
893            &site("https://evilmusicbrainz.org")
894        ));
895        assert!(!entry_offered(&e, &fams, &site("http://listenbrainz.org")));
896        assert!(family_remove(&mut v, "metabrainz", Some("listenbrainz.org")).unwrap());
897        assert!(!entry_offered(
898            &e,
899            &families(&v),
900            &site("https://listenbrainz.org")
901        ));
902        assert!(family_remove(&mut v, "metabrainz", None).unwrap());
903    }
904
905    #[test]
906    fn a_site_with_a_credential_or_a_bad_kind_is_refused_and_remove_clears_the_field() {
907        assert!(site_value("https://u:p@x.test", None, None, "", "manual").is_err());
908        assert!(site_value("x.test", Some("blog"), None, "", "manual").is_err());
909        let mut e = serde_json::json!({});
910        add_site(
911            &mut e,
912            site_value("x.test", None, None, "", "manual").unwrap(),
913        );
914        assert!(remove_site(&mut e, "x.test").unwrap());
915        assert!(e.get("sites").is_none());
916    }
917
918    #[test]
919    fn shipped_families_are_well_formed_and_yield_to_the_vaults_own() {
920        let shipped = builtin_families();
921        assert!(shipped.len() >= 5);
922        let mut names = std::collections::BTreeSet::new();
923        for f in &shipped {
924            assert!(names.insert(f.name.clone()), "{} twice", f.name);
925            assert!(f.hosts.len() >= 2, "{} is one host, not a family", f.name);
926            for h in &f.hosts {
927                assert_eq!(&parse_site(h).unwrap().host, h, "{h} is not a bare host");
928            }
929        }
930        let mut vault = serde_json::json!({});
931        let all = known_families(&vault);
932        assert_eq!(all.len(), shipped.len());
933        family_add(&mut vault, "google", &["only.example".to_string()]).unwrap();
934        let all = known_families(&vault);
935        assert_eq!(all.len(), shipped.len());
936        let google = all.iter().find(|f| f.name == "google").unwrap();
937        assert_eq!(google.hosts, ["only.example"]);
938    }
939
940    #[test]
941    fn another_spelling_of_an_address_is_reported_once_and_a_different_one_is_not() {
942        let l = |a: &[&str]| -> Vec<String> { a.iter().map(|s| s.to_string()).collect() };
943        // Loopback spellings, and a bare host against the same host with a scheme.
944        assert_eq!(
945            alternate_spellings(&l(&[
946                "localhost:8989",
947                "http://127.0.0.1:8989",
948                "other.test"
949            ])),
950            [(
951                "localhost:8989".to_string(),
952                "http://127.0.0.1:8989".to_string()
953            )]
954        );
955        assert_eq!(
956            alternate_spellings(&l(&["tv.example.org", "https://tv.example.org"])).len(),
957            1
958        );
959        // A different port, a different scheme on both, a different host, the same text twice, and
960        // text that is not an address are all not pairs.
961        for none in [
962            l(&["localhost:8989", "127.0.0.1:9999"]),
963            l(&["http://a.test", "https://a.test"]),
964            l(&["a.test", "b.test"]),
965            l(&["a.test", "a.test"]),
966            l(&["a.test", "not an address"]),
967            l(&["only.test"]),
968            l(&[]),
969        ] {
970            assert!(alternate_spellings(&none).is_empty(), "{none:?}");
971        }
972    }
973
974    /// Loopback spellings answer each other in both directions on the same port, and no pair of
975    /// different canonical hosts ever matches, in any mode.
976    #[test]
977    fn matching_is_symmetric_across_loopback_spellings_and_never_crosses_hosts() {
978        let loop_hosts = [
979            "localhost",
980            "LOCALHOST",
981            "foo.localhost",
982            "127.0.0.1",
983            "127.9.9.9",
984            "[::1]",
985        ];
986        let other_hosts = ["example.test", "192.0.2.7", "sonarr.home"];
987        let modes = [Mode::Exact, Mode::AnyPort, Mode::Host];
988        for scheme in ["http", "https"] {
989            for a in loop_hosts {
990                for b in loop_hosts {
991                    let sa = parse_site(&format!("{scheme}://{a}:8989")).unwrap();
992                    let sb = parse_site(&format!("{scheme}://{b}:8989")).unwrap();
993                    for m in modes {
994                        assert!(site_matches(&sa, m, &sb), "{a} vs {b} {m:?}");
995                        assert_eq!(site_matches(&sa, m, &sb), site_matches(&sb, m, &sa));
996                    }
997                    // The port stays significant unless the mode says otherwise.
998                    let moved = parse_site(&format!("{scheme}://{b}:7878")).unwrap();
999                    assert!(!site_matches(&sa, Mode::Exact, &moved), "{a} vs {b}:7878");
1000                    assert!(site_matches(&sa, Mode::AnyPort, &moved));
1001                }
1002                for o in other_hosts {
1003                    let sa = parse_site(&format!("{scheme}://{a}:8989")).unwrap();
1004                    let so = parse_site(&format!("{scheme}://{o}:8989")).unwrap();
1005                    for m in modes {
1006                        assert!(!site_matches(&sa, m, &so), "{a} vs {o} {m:?}");
1007                        assert!(!site_matches(&so, m, &sa), "{o} vs {a} {m:?}");
1008                    }
1009                }
1010            }
1011        }
1012    }
1013
1014    /// The entry a 0.81 desktop saved, shared with the TypeScript form test
1015    /// (`tests/sites-roundtrip.test.ts`): what a stored address means must not change when the
1016    /// entry is read, re-normalised on save, or carried through a desktop that has no field for it.
1017    const STORED: &str = include_str!("../../tests/fixtures/parity/entry-sites.json");
1018
1019    #[test]
1020    fn a_stored_entry_reads_back_with_every_kind_mode_label_and_source() {
1021        let e: serde_json::Value = serde_json::from_str(STORED).unwrap();
1022        let got: Vec<(String, String, Mode, String, String)> = entry_sites(&e)
1023            .into_iter()
1024            .map(|s| (s.site.display(), s.kind, s.mode, s.label, s.source))
1025            .collect();
1026        assert_eq!(
1027            got,
1028            vec![
1029                (
1030                    "http://localhost:8989".into(),
1031                    "local".into(),
1032                    Mode::AnyPort,
1033                    "on this PC".into(),
1034                    "manual".into()
1035                ),
1036                (
1037                    "https://sonarr.home.lan".into(),
1038                    "web".into(),
1039                    Mode::Exact,
1040                    "".into(),
1041                    "learned".into()
1042                ),
1043                (
1044                    "https://api.sonarr.example".into(),
1045                    "api".into(),
1046                    Mode::Host,
1047                    "hosted".into(),
1048                    "catalogue".into()
1049                ),
1050            ]
1051        );
1052        // `api_url` is the same address as the second site (a path is dropped), so it adds none.
1053        assert_eq!(got.len(), 3);
1054    }
1055
1056    #[test]
1057    fn saving_a_stored_site_again_changes_nothing_but_the_date() {
1058        let e: serde_json::Value = serde_json::from_str(STORED).unwrap();
1059        for s in e["sites"].as_array().unwrap() {
1060            let text = |k: &str| s[k].as_str().unwrap();
1061            let again = site_value(
1062                text("url"),
1063                Some(text("kind")),
1064                Some(text("mode")),
1065                text("label"),
1066                text("source"),
1067            )
1068            .unwrap();
1069            for k in ["url", "kind", "mode", "label", "source"] {
1070                assert_eq!(again[k], s[k], "{k} of {}", text("url"));
1071            }
1072        }
1073    }
1074}