1use 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#[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#[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 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
67#[serde(rename_all = "kebab-case")]
68pub enum TrustVia {
69 #[default]
71 App,
72 CliPrompt,
74 CliFlag,
76 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
93#[serde(rename_all = "snake_case")]
94pub enum LapseReason {
95 HistoryRewritten,
98 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#[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 #[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
127pub struct SourceRecord {
128 pub decision: SourceDecision,
129 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 #[serde(default, skip_serializing_if = "Option::is_none")]
138 pub machine: Option<String>,
139 #[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 #[schemars(extend("const" = 1))]
154 pub schema: i64,
155 #[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 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
220pub const INSECURE_KEY_PREFIXES: [&str; 2] = ["http://", "git://"];
223
224pub 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
232pub 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}