use std::collections::BTreeMap;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::error::ErrorCode;
use crate::model::validate::{Diagnostics, join};
use crate::model::{SCHEMA_VERSION, StoreModel};
use crate::sources::SourceRef;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum SourceDecision {
Trust,
Block,
}
impl SourceDecision {
pub const fn as_str(self) -> &'static str {
match self {
SourceDecision::Trust => "trust",
SourceDecision::Block => "block",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum SourceScope {
Repo,
Owner,
Host,
}
impl SourceScope {
pub const fn as_str(self) -> &'static str {
match self {
SourceScope::Repo => "repo",
SourceScope::Owner => "owner",
SourceScope::Host => "host",
}
}
pub fn parse(text: &str) -> Option<Self> {
match text.trim().to_ascii_lowercase().as_str() {
"repo" => Some(SourceScope::Repo),
"owner" => Some(SourceScope::Owner),
"host" => Some(SourceScope::Host),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum TrustVia {
#[default]
App,
CliPrompt,
CliFlag,
CliCommand,
}
impl TrustVia {
pub const fn as_str(self) -> &'static str {
match self {
TrustVia::App => "app",
TrustVia::CliPrompt => "cli-prompt",
TrustVia::CliFlag => "cli-flag",
TrustVia::CliCommand => "cli-command",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum LapseReason {
HistoryRewritten,
Moved,
}
impl LapseReason {
pub const fn as_str(self) -> &'static str {
match self {
LapseReason::HistoryRewritten => "history_rewritten",
LapseReason::Moved => "moved",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Lapse {
pub reason: LapseReason,
#[schemars(with = "String", extend("format" = "date-time"))]
pub at: toml::value::Datetime,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub detail: Option<String>,
#[serde(flatten)]
#[schemars(skip)]
pub extra: toml::Table,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct SourceRecord {
pub decision: SourceDecision,
pub scope: SourceScope,
#[schemars(with = "String", extend("format" = "date-time"))]
pub decided_at: toml::value::Datetime,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub via: Option<TrustVia>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub machine: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub lapsed: Option<Lapse>,
#[serde(flatten)]
#[schemars(skip)]
pub extra: toml::Table,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[schemars(title = "Surjection source trust (store/sources.toml)")]
pub struct SourcesFile {
#[schemars(extend("const" = 1))]
pub schema: i64,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub sources: BTreeMap<String, SourceRecord>,
#[serde(flatten)]
#[schemars(skip)]
pub extra: toml::Table,
}
impl StoreModel for SourcesFile {
const SCHEMA_NAME: &'static str = "sources";
}
impl Default for SourcesFile {
fn default() -> Self {
Self::new()
}
}
impl SourcesFile {
pub fn new() -> Self {
Self {
schema: SCHEMA_VERSION,
sources: BTreeMap::new(),
extra: toml::Table::new(),
}
}
pub fn validate(&self) -> Diagnostics {
let mut diagnostics = Diagnostics::new();
for (key, record) in &self.sources {
let path = join("sources", key);
match SourceRef::canonical_key(key) {
Err(_) => diagnostics.error(
ErrorCode::InvalidValue,
&path,
format!(
"{key:?} is not a source key (host/path for a repository, host/owner/* \
for an owner, host/* for a host, file:///path for a local repository)"
),
),
Ok((canonical, _)) if canonical != *key => diagnostics.error(
ErrorCode::InvalidValue,
&path,
format!(
"{key:?} is not written the way it is matched; write it as {canonical:?}"
),
),
Ok((_, shape)) if shape != record.scope => diagnostics.error(
ErrorCode::InvalidValue,
join(&path, "scope"),
format!(
"scope {:?} does not fit the key {key:?} (a {} key)",
record.scope.as_str(),
shape.as_str()
),
),
Ok(_) => {}
}
}
diagnostics
}
}
pub const INSECURE_KEY_PREFIXES: [&str; 2] = ["http://", "git://"];
pub fn without_insecure_prefix(key: &str) -> &str {
INSECURE_KEY_PREFIXES
.iter()
.find_map(|prefix| key.strip_prefix(prefix))
.unwrap_or(key)
}
pub fn key_shape(key: &str) -> Option<SourceScope> {
if let Some(path) = key.strip_prefix("file:///") {
let ok = !path.is_empty()
&& !path.ends_with('/')
&& !path.contains(['*', '\\'])
&& !path.chars().any(char::is_control);
return ok.then_some(SourceScope::Repo);
}
let bad_char = |c: char| c.is_whitespace() || c.is_control() || matches!(c, '\\' | '"' | '@');
if key.is_empty() || key.chars().any(bad_char) {
return None;
}
let key = without_insecure_prefix(key);
if key.contains("://") {
return None;
}
let parts: Vec<&str> = key.split('/').collect();
let host = parts[0];
let host_ok = !host.is_empty()
&& host
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b".-:[]_".contains(&b));
let (path, wildcard) = match parts[1..].split_last() {
Some((&"*", rest)) => (rest, true),
_ => (&parts[1..], false),
};
let path_ok = path
.iter()
.all(|part| !part.is_empty() && *part != "." && *part != ".." && !part.contains('*'));
if !host_ok || !path_ok {
return None;
}
match (path.len(), wildcard) {
(0, true) => Some(SourceScope::Host),
(1, true) => Some(SourceScope::Owner),
(n, false) if n >= 1 => Some(SourceScope::Repo),
_ => None,
}
}