Skip to main content

surjection_core/sources/
key.rs

1//! Source keys: which repository a git URL or local path names, and the
2//! owner and host keys above it.
3//!
4//! A git URL is parsed the way git and curl parse it (WHATWG, the `url`
5//! crate), after refusing anything that could make them contact another
6//! host or path than the key names: `?`, `#`, `\`, `.`/`..` segments,
7//! percent-encoded `.`, `/` or `\`, empty segments, control characters, a
8//! second `@`. Git is handed the URL rebuilt from the parsed parts
9//! ([`SourceRef::fetch_url`]), so what is trusted is what git contacts.
10//! Sources reached over plain `http://` or `git://` have keys of their own
11//! (`http://host/path`): trust given over HTTPS or SSH does not admit them.
12
13use std::path::{Path, PathBuf};
14
15use url::Url;
16
17use crate::error::{CoreError, ErrorCode};
18use crate::model::sources::{SourceScope, key_shape};
19
20/// Hosts that serve anyone's repositories: trusting the whole host would
21/// trust every publisher on it, so only an owner or a repository can be
22/// trusted there.
23pub const AGGREGATOR_HOSTS: [&str; 7] = [
24    "github.com",
25    "gitlab.com",
26    "bitbucket.org",
27    "codeberg.org",
28    "gitee.com",
29    "git.sr.ht",
30    "huggingface.co",
31];
32
33/// Hosts whose owner and repository names are case-insensitive.
34const CASE_INSENSITIVE_HOSTS: [&str; 4] =
35    ["github.com", "gitlab.com", "bitbucket.org", "codeberg.org"];
36
37/// Owners shown with an "official" marker (`host/owner`). The marker never
38/// skips the prompt.
39pub const OFFICIAL_OWNERS: [&str; 2] = ["github.com/anthropics", "github.com/modelcontextprotocol"];
40
41/// How git reaches a source.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43enum Transport {
44    Https,
45    Http,
46    Ssh,
47    Git,
48    /// `user@host:path`.
49    Scp,
50    Local,
51}
52
53impl Transport {
54    fn of_scheme(scheme: &str) -> Option<Self> {
55        match scheme.to_ascii_lowercase().as_str() {
56            "https" => Some(Transport::Https),
57            "http" => Some(Transport::Http),
58            "ssh" => Some(Transport::Ssh),
59            "git" => Some(Transport::Git),
60            _ => None,
61        }
62    }
63
64    const fn scheme(self) -> &'static str {
65        match self {
66            Transport::Https => "https",
67            Transport::Http => "http",
68            Transport::Ssh | Transport::Scp => "ssh",
69            Transport::Git => "git",
70            Transport::Local => "file",
71        }
72    }
73
74    /// Left out of keys and URLs, so `https://` and `ssh://` URLs of one
75    /// repository give one key.
76    const fn default_port(self) -> Option<u16> {
77        match self {
78            Transport::Https => Some(443),
79            Transport::Http => Some(80),
80            Transport::Ssh => Some(22),
81            Transport::Git => Some(9418),
82            Transport::Scp | Transport::Local => None,
83        }
84    }
85
86    /// The key prefix of a transport without encryption.
87    const fn marker(self) -> &'static str {
88        match self {
89            Transport::Http => "http://",
90            Transport::Git => "git://",
91            _ => "",
92        }
93    }
94}
95
96/// A source: the repository a git URL or a local path names. Never holds
97/// credentials ([`SourceRef::fetch_url`] takes them from the URL given).
98#[derive(Debug, Clone, PartialEq, Eq, Hash)]
99pub struct SourceRef {
100    /// `github.com/acme/skills`, `http://git.acme.corp/tools` or
101    /// `file:///C:/repos/x`.
102    key: String,
103    /// The canonical URL without credentials (a local source: its
104    /// `file:///` key).
105    url: String,
106    /// Remote sources: what follows `scheme://[userinfo@]` in the URL
107    /// (`host[:port]/path`), or `host:path` for `user@host:path`.
108    address: String,
109    /// Remote sources: the host (with a non-default port).
110    host: Option<String>,
111    /// Remote sources whose path has two or more segments: the first.
112    owner: Option<String>,
113    transport: Transport,
114    /// A host as a whole ([`SourceRef::whole_host`]): the key is
115    /// `host/*`, the only scope the host.
116    whole_host: bool,
117}
118
119/// A remote URL in canonical parts. The userinfo is only carried to
120/// [`SourceRef::fetch_url`].
121struct Remote {
122    transport: Transport,
123    /// `user[:password]` as given (percent-encoded).
124    userinfo: Option<String>,
125    /// Lowercase, without a trailing dot, with a non-default `:port`.
126    host: String,
127    /// `user@host:/path` (rather than a path below the user's home).
128    absolute: bool,
129    /// Checked and percent-normalized, before any cut.
130    segments: Vec<String>,
131}
132
133enum Parsed {
134    Remote(Remote),
135    /// An absolute path (`/`-separated or not).
136    Local(String),
137}
138
139fn invalid(text: &str, why: &str) -> CoreError {
140    CoreError::new(
141        ErrorCode::InvalidValue,
142        format!(
143            "{:?} is not a source: {why}",
144            SourceRef::redact_userinfo(text)
145        ),
146    )
147}
148
149/// `user@host:path` (not a Windows drive path): `(user@host, path)`.
150fn scp_like(text: &str) -> Option<(&str, &str)> {
151    let (user_host, rest) = text.split_once(':')?;
152    if !user_host.contains('@') || user_host.contains(['/', '\\']) || rest.starts_with("//") {
153        return None;
154    }
155    Some((user_host, rest))
156}
157
158fn is_windows_drive(text: &str) -> bool {
159    let bytes = text.as_bytes();
160    bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':'
161}
162
163fn is_local_path(text: &str) -> bool {
164    Path::new(text).is_absolute() || is_windows_drive(text) || text.starts_with('/')
165}
166
167/// What could make git contact another host or path than the key names.
168fn check_text(text: &str) -> Result<(), &'static str> {
169    if text.chars().any(|c| c.is_control() || c.is_whitespace()) {
170        return Err("it contains spaces or control characters");
171    }
172    if text.contains('\\') {
173        return Err("it contains a backslash");
174    }
175    if text.contains(['?', '#']) {
176        return Err("a query or fragment (`?`, `#`) does not name a repository");
177    }
178    let lower = text.to_ascii_lowercase();
179    if ["%2e", "%2f", "%5c"]
180        .iter()
181        .any(|code| lower.contains(code))
182    {
183        return Err("it percent-encodes `.`, `/` or `\\`");
184    }
185    if text.matches('@').count() > 1 {
186        return Err("it has more than one `@`");
187    }
188    Ok(())
189}
190
191/// The segments of a path (without its leading `/`): no empty, `.` or `..`
192/// segment; one trailing `/` is fine.
193fn checked_segments(path: &str) -> Result<Vec<&str>, &'static str> {
194    let path = path.strip_suffix('/').unwrap_or(path);
195    if path.is_empty() {
196        return Ok(Vec::new());
197    }
198    path.split('/')
199        .map(|segment| match segment {
200            "" => Err("it has an empty path segment (`//`)"),
201            "." | ".." => Err("it has a `.` or `..` path segment"),
202            segment => Ok(segment),
203        })
204        .collect()
205}
206
207/// Percent escapes of unreserved characters decoded, the others in
208/// uppercase hex, so one name has one spelling.
209fn normalize_escapes(segment: &str) -> Result<String, &'static str> {
210    let mut out = String::with_capacity(segment.len());
211    let mut rest = segment;
212    while let Some(at) = rest.find('%') {
213        out.push_str(&rest[..at]);
214        let hex = rest
215            .get(at + 1..at + 3)
216            .filter(|hex| hex.bytes().all(|b| b.is_ascii_hexdigit()))
217            .ok_or("it has a `%` that is not a percent-encoded byte")?;
218        let byte = u8::from_str_radix(hex, 16).map_err(|_| "it has a bad percent escape")?;
219        if byte.is_ascii_alphanumeric() || b"-_~".contains(&byte) {
220            out.push(char::from(byte));
221        } else {
222            out.push('%');
223            out.push_str(&hex.to_ascii_uppercase());
224        }
225        rest = &rest[at + 3..];
226    }
227    out.push_str(rest);
228    Ok(out)
229}
230
231/// Lowercase, without a trailing dot (`github.com.` is `github.com`); a
232/// name of non-empty labels or a bracketed IPv6 address.
233fn canonical_host(host: &str) -> Result<String, &'static str> {
234    let lower = host.to_ascii_lowercase();
235    let host = lower.strip_suffix('.').unwrap_or(&lower);
236    let ok = match host.strip_prefix('[').and_then(|ip| ip.strip_suffix(']')) {
237        Some(ip) => {
238            !ip.is_empty()
239                && ip
240                    .bytes()
241                    .all(|b| b.is_ascii_hexdigit() || b == b':' || b == b'.')
242        }
243        None => {
244            !host.is_empty()
245                && host.split('.').all(|label| {
246                    !label.is_empty()
247                        && label.bytes().all(|b| {
248                            b.is_ascii_lowercase() || b.is_ascii_digit() || b"-_".contains(&b)
249                        })
250                })
251        }
252    };
253    if ok {
254        Ok(host.to_owned())
255    } else {
256        Err("its host is not a host name")
257    }
258}
259
260/// `scheme://[userinfo@]host[:port]/path`.
261fn url_remote(text: &str, transport: Transport) -> Result<Remote, &'static str> {
262    check_text(text)?;
263    let rest = text.split_once("://").map_or("", |(_, rest)| rest);
264    let (authority, raw_path) = rest.split_once('/').unwrap_or((rest, ""));
265    if authority
266        .rsplit_once('@')
267        .map_or(authority, |(_, host)| host)
268        .is_empty()
269    {
270        return Err("it has no host");
271    }
272    if raw_path.contains('@') {
273        return Err("it has an `@` in the path");
274    }
275    let raw = checked_segments(raw_path)?;
276    let parsed = Url::parse(text).map_err(|_| "it is not a valid URL")?;
277    let host = canonical_host(parsed.host_str().ok_or("it has no host")?)?;
278    let host = match parsed.port() {
279        Some(port) if Some(port) != transport.default_port() => format!("{host}:{port}"),
280        _ => host,
281    };
282    let userinfo = match (parsed.username(), parsed.password()) {
283        ("", None) => None,
284        (user, None) => Some(user.to_owned()),
285        (user, Some(password)) => Some(format!("{user}:{password}")),
286    };
287    let path = parsed.path();
288    let path = path.strip_prefix('/').unwrap_or(path);
289    let segments = checked_segments(path)?
290        .into_iter()
291        .map(normalize_escapes)
292        .collect::<Result<Vec<_>, _>>()?;
293    // Dot segments were refused above, so the parser cannot have dropped
294    // any; a difference means the text is not what it seems.
295    if segments.len() != raw.len() {
296        return Err("it is not a valid URL");
297    }
298    Ok(Remote {
299        transport,
300        userinfo,
301        host,
302        absolute: true,
303        segments,
304    })
305}
306
307/// `user@host:path`: git takes the path as written (no percent escapes).
308fn scp_remote(text: &str, user_host: &str, path: &str) -> Result<Remote, &'static str> {
309    check_text(text)?;
310    if path.contains(['%', '@']) {
311        return Err("an scp-style path cannot contain `%` or `@`");
312    }
313    let (user, host) = user_host.rsplit_once('@').unwrap_or(("", user_host));
314    let host = canonical_host(host)?;
315    let absolute = path.starts_with('/');
316    let segments = checked_segments(path.strip_prefix('/').unwrap_or(path))?
317        .into_iter()
318        .map(str::to_owned)
319        .collect();
320    Ok(Remote {
321        transport: Transport::Scp,
322        userinfo: (!user.is_empty()).then(|| user.to_owned()),
323        host,
324        absolute,
325        segments,
326    })
327}
328
329impl SourceRef {
330    /// The source a git URL names: `https://`, `http://`, `ssh://`,
331    /// `git://`, `user@host:path`, `file://` or an absolute local path (a
332    /// local repository). `invalid_value` for anything else, and for a URL
333    /// git could read as another host or path than its key names.
334    pub fn from_git_url(url: &str) -> Result<Self, CoreError> {
335        let text = url.trim();
336        Self::parse(text, text).map(|(source, _)| source)
337    }
338
339    /// The repository a source key (`host/path`, `http://host/path`,
340    /// `file:///path`) or a git URL names.
341    pub fn from_key_or_url(text: &str) -> Result<Self, CoreError> {
342        let text = text.trim();
343        Self::parse(&as_url(text), text).map(|(source, _)| source)
344    }
345
346    /// The canonical form of a source key or git URL, with the scope its
347    /// shape stands for: `host/path` (or a URL) a repository,
348    /// `host/owner/*` an owner, `host/*` a host; keys of plain `http://`
349    /// and `git://` sources keep that prefix. `sources.toml` keys and the
350    /// CLI's key arguments go through it (`github.com/Acme/*` is
351    /// `github.com/acme/*`, `github.com./x/y.git` is `github.com/x/y`).
352    pub fn canonical_key(text: &str) -> Result<(String, SourceScope), CoreError> {
353        let text = text.trim();
354        let Some(base) = text.strip_suffix("/*") else {
355            return Ok((Self::from_key_or_url(text)?.key, SourceScope::Repo));
356        };
357        // `base/x` names a repository below the owner or host.
358        let Parsed::Remote(remote) = Self::split(&as_url(&format!("{base}/x")), text)? else {
359            return Err(invalid(text, "a local source has no owner or host key"));
360        };
361        match remote.segments.as_slice() {
362            [_] => Ok((
363                format!("{}{}/*", remote.transport.marker(), remote.host),
364                SourceScope::Host,
365            )),
366            [_, _] => {
367                let (source, _) = Self::from_remote(remote).map_err(|why| invalid(text, why))?;
368                match source.scope_key(SourceScope::Owner) {
369                    Some(key) => Ok((key, SourceScope::Owner)),
370                    None => Err(invalid(text, "it has no owner")),
371                }
372            }
373            _ => Err(invalid(
374                text,
375                "a key ending in `/*` is host/* (a host) or host/owner/* (an owner)",
376            )),
377        }
378    }
379
380    /// `text` with the userinfo of every URL in it replaced by `***`, for
381    /// messages: a URL can carry a token (`https://user:token@host/...`).
382    pub fn redact_userinfo(text: &str) -> String {
383        let mut out = String::with_capacity(text.len());
384        let mut rest = text;
385        while let Some(at) = rest.find("://") {
386            let (head, tail) = rest.split_at(at + 3);
387            out.push_str(head);
388            let end = tail
389                .find(|c: char| c == '/' || c.is_whitespace() || matches!(c, '"' | '\'' | '`'))
390                .unwrap_or(tail.len());
391            match tail[..end].rfind('@') {
392                Some(at) => {
393                    out.push_str("***");
394                    out.push_str(&tail[at..end]);
395                }
396                None => out.push_str(&tail[..end]),
397            }
398            rest = &tail[end..];
399        }
400        out.push_str(rest);
401        out
402    }
403
404    /// `text` split into a remote URL's parts or a local path; `shown` in
405    /// errors.
406    fn split(text: &str, shown: &str) -> Result<Parsed, CoreError> {
407        if text.to_ascii_lowercase().starts_with("file://") {
408            let path = &text["file://".len()..];
409            // `file:///C:/x` and `file:///home/x`; a `file://host/...` share
410            // keeps its host as the first path part.
411            return Ok(Parsed::Local(match path.strip_prefix('/') {
412                Some(rest) if is_windows_drive(rest) => rest.to_owned(),
413                Some(_) => path.to_owned(),
414                None => format!("//{path}"),
415            }));
416        }
417        let remote = if let Some((scheme, _)) = text.split_once("://") {
418            let transport = Transport::of_scheme(scheme)
419                .ok_or_else(|| invalid(shown, "unsupported URL scheme"))?;
420            url_remote(text, transport)
421        } else if let Some((user_host, path)) = scp_like(text) {
422            scp_remote(text, user_host, path)
423        } else if is_local_path(text) {
424            return Ok(Parsed::Local(text.to_owned()));
425        } else {
426            return Err(invalid(shown, "not a git URL or an absolute path"));
427        };
428        remote
429            .map(Parsed::Remote)
430            .map_err(|why| invalid(shown, why))
431    }
432
433    /// The source and the userinfo given with it.
434    fn parse(text: &str, shown: &str) -> Result<(Self, Option<String>), CoreError> {
435        match Self::split(text, shown)? {
436            Parsed::Local(path) => Ok((Self::local(&path, shown)?, None)),
437            Parsed::Remote(remote) => Self::from_remote(remote).map_err(|why| invalid(shown, why)),
438        }
439    }
440
441    /// A local folder or repository (absolute path).
442    pub fn from_local_path(path: &Path) -> Result<Self, CoreError> {
443        let text = path.to_string_lossy();
444        if !is_local_path(&text) {
445            return Err(invalid(&text, "not an absolute path"));
446        }
447        Self::local(&text, &text)
448    }
449
450    /// The host of an `https://` (or `http://`) endpoint as a whole: the
451    /// key `host/*` (`http://host/*` without encryption), trusted or
452    /// blocked only at the host scope. A registry entry's remote server is
453    /// gated on it (#26): every path of that host is one operator's.
454    pub fn whole_host(url: &str) -> Result<Self, CoreError> {
455        let text = url.trim();
456        let parsed = Url::parse(text).map_err(|_| invalid(text, "it is not a valid URL"))?;
457        let transport = match parsed.scheme() {
458            "https" => Transport::Https,
459            "http" => Transport::Http,
460            _ => return Err(invalid(text, "unsupported URL scheme")),
461        };
462        if !parsed.username().is_empty() || parsed.password().is_some() {
463            return Err(invalid(text, "it carries a user name or password"));
464        }
465        let host = canonical_host(
466            parsed
467                .host_str()
468                .ok_or_else(|| invalid(text, "it has no host"))?,
469        )
470        .map_err(|why| invalid(text, why))?;
471        let host = match parsed.port() {
472            Some(port) if Some(port) != transport.default_port() => format!("{host}:{port}"),
473            _ => host,
474        };
475        let key = format!("{}{host}/*", transport.marker());
476        if key_shape(&key) != Some(SourceScope::Host) {
477            return Err(invalid(text, "its host cannot be a source key"));
478        }
479        Ok(Self {
480            url: format!("{}://{host}", transport.scheme()),
481            address: host.clone(),
482            key,
483            host: Some(host),
484            owner: None,
485            transport,
486            whole_host: true,
487        })
488    }
489
490    fn local(path: &str, original: &str) -> Result<Self, CoreError> {
491        let mut path = path.replace('\\', "/");
492        while path.len() > 1 && path.ends_with('/') {
493            path.pop();
494        }
495        if is_windows_drive(&path) {
496            path[..1].make_ascii_uppercase();
497        }
498        let rest = if path.starts_with("//") {
499            path.as_str()
500        } else {
501            path.trim_start_matches('/')
502        };
503        let key = format!("file:///{rest}");
504        if key_shape(&key) != Some(SourceScope::Repo) {
505            return Err(invalid(original, "not a usable local path"));
506        }
507        Ok(Self {
508            url: key.clone(),
509            key,
510            address: String::new(),
511            host: None,
512            owner: None,
513            transport: Transport::Local,
514            whole_host: false,
515        })
516    }
517
518    /// The repository of `remote`: the path up to GitLab's `/-/`, only
519    /// `owner/repo` on GitHub, without a trailing `.git`, lowercase on
520    /// case-insensitive hosts.
521    fn from_remote(remote: Remote) -> Result<(Self, Option<String>), &'static str> {
522        let Remote {
523            transport,
524            userinfo,
525            host,
526            absolute,
527            mut segments,
528        } = remote;
529        if let Some(cut) = segments.iter().position(|part| part == "-") {
530            segments.truncate(cut);
531        }
532        if host == "github.com" {
533            segments.truncate(2);
534        }
535        if CASE_INSENSITIVE_HOSTS.contains(&host.as_str()) {
536            segments
537                .iter_mut()
538                .for_each(|part| part.make_ascii_lowercase());
539        }
540        let dot_git = match segments.last_mut() {
541            Some(last) if last.ends_with(".git") => {
542                last.truncate(last.len() - ".git".len());
543                if last.is_empty() {
544                    return Err("it has no repository name");
545                }
546                true
547            }
548            _ => false,
549        };
550        if segments.is_empty() {
551            return Err("it has no repository path");
552        }
553        let path = segments.join("/");
554        let key = format!("{}{host}/{path}", transport.marker());
555        if key_shape(&key) != Some(SourceScope::Repo) {
556            return Err("it has characters a source key cannot hold");
557        }
558        let fetch_path = if dot_git { format!("{path}.git") } else { path };
559        let address = if transport == Transport::Scp {
560            format!("{host}:{}{fetch_path}", if absolute { "/" } else { "" })
561        } else {
562            format!("{host}/{fetch_path}")
563        };
564        // An SSH user is part of the address, not a secret: it is shown.
565        let user = match transport {
566            Transport::Ssh | Transport::Scp => userinfo
567                .as_deref()
568                .map(|info| info.split_once(':').map_or(info, |(user, _)| user)),
569            _ => None,
570        };
571        let url = with_userinfo(transport, user, &address);
572        let source = Self {
573            key,
574            url,
575            address,
576            owner: (segments.len() >= 2).then(|| segments[0].clone()),
577            host: Some(host),
578            transport,
579            whole_host: false,
580        };
581        Ok((source, userinfo))
582    }
583
584    /// The repository key.
585    pub fn key(&self) -> &str {
586        &self.key
587    }
588
589    /// The canonical URL without credentials (an SSH user stays); a local
590    /// source's `file:///` key.
591    pub fn url(&self) -> &str {
592        &self.url
593    }
594
595    /// The URL git must fetch the source from: the canonical URL rebuilt
596    /// from the parsed parts, with the userinfo of `given` (the URL as the
597    /// user gave it) when `given` names this same source. Never show it or
598    /// store it: it can carry a token. A local source: `given` when it
599    /// names this source, else its `file:///` URL.
600    pub fn fetch_url(&self, given: &str) -> String {
601        let given = given.trim();
602        let Ok((other, userinfo)) = Self::parse(given, "") else {
603            return self.url.clone();
604        };
605        let same = other.transport == self.transport
606            && other.key == self.key
607            && other.address == self.address;
608        match (same, self.transport, userinfo) {
609            (true, Transport::Local, _) => given.to_owned(),
610            (true, _, Some(userinfo)) => {
611                with_userinfo(self.transport, Some(&userinfo), &self.address)
612            }
613            _ => self.url.clone(),
614        }
615    }
616
617    /// Fetched over a connection without encryption (`http://`, `git://`):
618    /// anyone on the network path can change what arrives.
619    pub fn is_insecure(&self) -> bool {
620        !self.transport.marker().is_empty()
621    }
622
623    pub fn is_local(&self) -> bool {
624        self.host.is_none()
625    }
626
627    /// A local source's path, for showing it under its placeholder root.
628    pub fn local_path(&self) -> Option<PathBuf> {
629        if !self.is_local() {
630            return None;
631        }
632        let rest = self.key.strip_prefix("file:///")?;
633        Some(if is_windows_drive(rest) || rest.starts_with("//") {
634            PathBuf::from(rest)
635        } else {
636            PathBuf::from(format!("/{rest}"))
637        })
638    }
639
640    pub fn host(&self) -> Option<&str> {
641        self.host.as_deref()
642    }
643
644    pub fn owner(&self) -> Option<&str> {
645        self.owner.as_deref()
646    }
647
648    /// The key of `scope` (`host/owner/*`, `host/*`, with the `http://` or
649    /// `git://` prefix of an insecure source); `None` when the source has
650    /// no such scope (a local source, a repository without an owner
651    /// segment).
652    pub fn scope_key(&self, scope: SourceScope) -> Option<String> {
653        let marker = self.transport.marker();
654        match scope {
655            SourceScope::Repo => Some(self.key.clone()),
656            SourceScope::Owner => Some(format!(
657                "{marker}{}/{}/*",
658                self.host.as_ref()?,
659                self.owner.as_ref()?
660            )),
661            SourceScope::Host => Some(format!("{marker}{}/*", self.host.as_ref()?)),
662        }
663    }
664
665    /// Every key whose trust applies, most specific first.
666    pub fn matching_keys(&self) -> Vec<String> {
667        let mut keys: Vec<String> = [SourceScope::Repo, SourceScope::Owner, SourceScope::Host]
668            .into_iter()
669            .filter_map(|scope| self.scope_key(scope))
670            .collect();
671        keys.dedup();
672        keys
673    }
674
675    /// Every key whose block applies, most specific first: the
676    /// [`Self::matching_keys`], then for an insecure source the keys of the
677    /// same source over an encrypted transport (a block covers every
678    /// transport, a trust only its own).
679    pub fn block_keys(&self) -> Vec<String> {
680        let mut keys = self.matching_keys();
681        let marker = self.transport.marker();
682        if !marker.is_empty() {
683            let secure: Vec<String> = keys
684                .iter()
685                .filter_map(|key| key.strip_prefix(marker).map(str::to_owned))
686                .collect();
687            keys.extend(secure);
688        }
689        keys
690    }
691
692    /// The scopes "always trust" offers, narrowest first: a host only
693    /// when it is not an [`AGGREGATOR_HOSTS`] host.
694    pub fn scopes(&self) -> Vec<SourceScope> {
695        if self.whole_host {
696            return match &self.host {
697                Some(host) if !AGGREGATOR_HOSTS.contains(&host.as_str()) => {
698                    vec![SourceScope::Host]
699                }
700                _ => Vec::new(),
701            };
702        }
703        let mut scopes = vec![SourceScope::Repo];
704        if self.owner.is_some() {
705            scopes.push(SourceScope::Owner);
706        }
707        if let Some(host) = &self.host
708            && !AGGREGATOR_HOSTS.contains(&host.as_str())
709        {
710            scopes.push(SourceScope::Host);
711        }
712        scopes
713    }
714
715    /// An [`OFFICIAL_OWNERS`] repository, fetched over an encrypted
716    /// transport.
717    pub fn is_official(&self) -> bool {
718        match (&self.host, &self.owner) {
719            (Some(host), Some(owner)) if !self.is_insecure() => {
720                OFFICIAL_OWNERS.contains(&format!("{host}/{owner}").as_str())
721            }
722            _ => false,
723        }
724    }
725}
726
727/// `scheme://[userinfo@]address`, or `[userinfo@]address` for
728/// `user@host:path`.
729fn with_userinfo(transport: Transport, userinfo: Option<&str>, address: &str) -> String {
730    let at = userinfo.map(|info| format!("{info}@")).unwrap_or_default();
731    match transport {
732        Transport::Scp => format!("{at}{address}"),
733        _ => format!("{}://{at}{address}", transport.scheme()),
734    }
735}
736
737/// A source key without a scheme (`host/path`) as an `https://` URL; URLs,
738/// `user@host:path` and local paths as they are.
739fn as_url(text: &str) -> String {
740    if text.contains("://") || scp_like(text).is_some() || is_local_path(text) {
741        text.to_owned()
742    } else {
743        format!("https://{text}")
744    }
745}