Skip to main content

surjection_core/model/
sources.rs

1//! `store/sources.toml`: trust decisions about install sources (SPEC 17,
2//! #24). One table per source key (`github.com/acme/skills` for one
3//! repository, `github.com/acme/*` for an owner, `git.acme.corp/*` for a
4//! host, `file:///C:/repos/x` for a local repository; `http://` or `git://`
5//! before the host for a source fetched without encryption), so a pull
6//! merges decisions about different sources field by field.
7
8use std::collections::BTreeMap;
9
10use schemars::JsonSchema;
11use serde::{Deserialize, Serialize};
12
13use crate::error::ErrorCode;
14use crate::model::validate::{Diagnostics, join};
15use crate::model::{SCHEMA_VERSION, StoreModel};
16use crate::sources::SourceRef;
17
18/// Trust a source, or never trust it (a block wins over any trust).
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
20#[serde(rename_all = "lowercase")]
21pub enum SourceDecision {
22    Trust,
23    Block,
24}
25
26impl SourceDecision {
27    pub const fn as_str(self) -> &'static str {
28        match self {
29            SourceDecision::Trust => "trust",
30            SourceDecision::Block => "block",
31        }
32    }
33}
34
35/// How much a record covers: one repository, every repository of one owner
36/// (user or organization), or every repository on one host.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
38#[serde(rename_all = "lowercase")]
39pub enum SourceScope {
40    Repo,
41    Owner,
42    Host,
43}
44
45impl SourceScope {
46    pub const fn as_str(self) -> &'static str {
47        match self {
48            SourceScope::Repo => "repo",
49            SourceScope::Owner => "owner",
50            SourceScope::Host => "host",
51        }
52    }
53
54    /// Reads `repo`, `owner` or `host`.
55    pub fn parse(text: &str) -> Option<Self> {
56        match text.trim().to_ascii_lowercase().as_str() {
57            "repo" => Some(SourceScope::Repo),
58            "owner" => Some(SourceScope::Owner),
59            "host" => Some(SourceScope::Host),
60            _ => None,
61        }
62    }
63}
64
65/// Where a decision was made: never by an agent on its own (#24).
66#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
67#[serde(rename_all = "kebab-case")]
68pub enum TrustVia {
69    /// The app's trust dialog or Settings > Sources.
70    #[default]
71    App,
72    /// An interactive `surject` prompt.
73    CliPrompt,
74    /// `--trust-source` on a non-interactive command.
75    CliFlag,
76    /// `surject source trust|block`.
77    CliCommand,
78}
79
80impl TrustVia {
81    pub const fn as_str(self) -> &'static str {
82        match self {
83            TrustVia::App => "app",
84            TrustVia::CliPrompt => "cli-prompt",
85            TrustVia::CliFlag => "cli-flag",
86            TrustVia::CliCommand => "cli-command",
87        }
88    }
89}
90
91/// Why trust lapsed.
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
93#[serde(rename_all = "snake_case")]
94pub enum LapseReason {
95    /// The followed branch no longer contains the commit installed last
96    /// (force-push).
97    HistoryRewritten,
98    /// The repository was renamed or transferred (the host redirects).
99    Moved,
100}
101
102impl LapseReason {
103    pub const fn as_str(self) -> &'static str {
104        match self {
105            LapseReason::HistoryRewritten => "history_rewritten",
106            LapseReason::Moved => "moved",
107        }
108    }
109}
110
111/// A trust that no longer admits the source until the user decides again.
112#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
113pub struct Lapse {
114    pub reason: LapseReason,
115    #[schemars(with = "String", extend("format" = "date-time"))]
116    pub at: toml::value::Datetime,
117    /// `moved`: the source key the repository moved to.
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub detail: Option<String>,
120    #[serde(flatten)]
121    #[schemars(skip)]
122    pub extra: toml::Table,
123}
124
125/// One decision about one source key.
126#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
127pub struct SourceRecord {
128    pub decision: SourceDecision,
129    /// Must fit the key: `repo` (`host/owner/repo`, `file:///...`),
130    /// `owner` (`host/owner`), `host` (`host`).
131    pub scope: SourceScope,
132    #[schemars(with = "String", extend("format" = "date-time"))]
133    pub decided_at: toml::value::Datetime,
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub via: Option<TrustVia>,
136    /// Label of the machine that decided.
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub machine: Option<String>,
139    /// The URL the decision was made for, without userinfo.
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub url: Option<String>,
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub lapsed: Option<Lapse>,
144    #[serde(flatten)]
145    #[schemars(skip)]
146    pub extra: toml::Table,
147}
148
149#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
150#[schemars(title = "Surjection source trust (store/sources.toml)")]
151pub struct SourcesFile {
152    /// Schema version; always 1.
153    #[schemars(extend("const" = 1))]
154    pub schema: i64,
155    /// Decisions by source key.
156    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
157    pub sources: BTreeMap<String, SourceRecord>,
158    #[serde(flatten)]
159    #[schemars(skip)]
160    pub extra: toml::Table,
161}
162
163impl StoreModel for SourcesFile {
164    const SCHEMA_NAME: &'static str = "sources";
165}
166
167impl Default for SourcesFile {
168    fn default() -> Self {
169        Self::new()
170    }
171}
172
173impl SourcesFile {
174    pub fn new() -> Self {
175        Self {
176            schema: SCHEMA_VERSION,
177            sources: BTreeMap::new(),
178            extra: toml::Table::new(),
179        }
180    }
181
182    /// Every key is a canonical source key (the key its own URL gets)
183    /// whose shape fits its record's scope.
184    pub fn validate(&self) -> Diagnostics {
185        let mut diagnostics = Diagnostics::new();
186        for (key, record) in &self.sources {
187            let path = join("sources", key);
188            match SourceRef::canonical_key(key) {
189                Err(_) => diagnostics.error(
190                    ErrorCode::InvalidValue,
191                    &path,
192                    format!(
193                        "{key:?} is not a source key (host/path for a repository, host/owner/* \
194                         for an owner, host/* for a host, file:///path for a local repository)"
195                    ),
196                ),
197                Ok((canonical, _)) if canonical != *key => diagnostics.error(
198                    ErrorCode::InvalidValue,
199                    &path,
200                    format!(
201                        "{key:?} is not written the way it is matched; write it as {canonical:?}"
202                    ),
203                ),
204                Ok((_, shape)) if shape != record.scope => diagnostics.error(
205                    ErrorCode::InvalidValue,
206                    join(&path, "scope"),
207                    format!(
208                        "scope {:?} does not fit the key {key:?} (a {} key)",
209                        record.scope.as_str(),
210                        shape.as_str()
211                    ),
212                ),
213                Ok(_) => {}
214            }
215        }
216        diagnostics
217    }
218}
219
220/// Key prefixes of sources fetched without encryption: their keys are not
221/// the keys of the same repository over HTTPS or SSH.
222pub const INSECURE_KEY_PREFIXES: [&str; 2] = ["http://", "git://"];
223
224/// `key` without an [`INSECURE_KEY_PREFIXES`] prefix.
225pub fn without_insecure_prefix(key: &str) -> &str {
226    INSECURE_KEY_PREFIXES
227        .iter()
228        .find_map(|prefix| key.strip_prefix(prefix))
229        .unwrap_or(key)
230}
231
232/// The scope a source key's shape stands for: `file:///<path>` and
233/// `<host>/<path>` are repositories, `<host>/<owner>/*` an owner,
234/// `<host>/*` a host (each may start with `http://` or `git://`). `None`
235/// for text that is not a key. Shape only: [`SourcesFile::validate`] also
236/// requires the canonical spelling.
237pub fn key_shape(key: &str) -> Option<SourceScope> {
238    if let Some(path) = key.strip_prefix("file:///") {
239        let ok = !path.is_empty()
240            && !path.ends_with('/')
241            && !path.contains(['*', '\\'])
242            && !path.chars().any(char::is_control);
243        return ok.then_some(SourceScope::Repo);
244    }
245    let bad_char = |c: char| c.is_whitespace() || c.is_control() || matches!(c, '\\' | '"' | '@');
246    if key.is_empty() || key.chars().any(bad_char) {
247        return None;
248    }
249    let key = without_insecure_prefix(key);
250    if key.contains("://") {
251        return None;
252    }
253    let parts: Vec<&str> = key.split('/').collect();
254    let host = parts[0];
255    let host_ok = !host.is_empty()
256        && host
257            .bytes()
258            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b".-:[]_".contains(&b));
259    let (path, wildcard) = match parts[1..].split_last() {
260        Some((&"*", rest)) => (rest, true),
261        _ => (&parts[1..], false),
262    };
263    let path_ok = path
264        .iter()
265        .all(|part| !part.is_empty() && *part != "." && *part != ".." && !part.contains('*'));
266    if !host_ok || !path_ok {
267        return None;
268    }
269    match (path.len(), wildcard) {
270        (0, true) => Some(SourceScope::Host),
271        (1, true) => Some(SourceScope::Owner),
272        (n, false) if n >= 1 => Some(SourceScope::Repo),
273        _ => None,
274    }
275}