Skip to main content

surjection_core/sources/
mod.rs

1//! Source trust (#24, SPEC 17): installing or updating from a source the
2//! user has not trusted asks first, a block wins over any trust, and a
3//! repository that was force-pushed, renamed or transferred makes its trust
4//! lapse so the user is asked again.
5//!
6//! Decisions live in `store/sources.toml` ([`SourcesFile`]), keyed by
7//! source key ([`SourceRef`]): one repository (`github.com/acme/skills`),
8//! one owner (`github.com/acme/*`) or one host (`git.acme.corp/*`). They
9//! sync with remotes like other store files.
10//!
11//! Only a person decides: the app's dialog, an interactive CLI prompt, or
12//! the explicit `--trust-source` flag ([`TrustVia`]). [`admit`] is the gate
13//! every install path calls before anything from a source is saved.
14
15pub mod detect;
16mod key;
17
18use std::path::Path;
19
20use crate::error::{CoreError, ErrorCode};
21use crate::model::TomlDocument;
22use crate::model::skill_meta::{SkillMeta, SkillSourceKind};
23pub use crate::model::sources::{
24    Lapse, LapseReason, SourceDecision, SourceRecord, SourceScope, SourcesFile, TrustVia,
25    key_shape, without_insecure_prefix,
26};
27use crate::skills::store::META_DIR;
28use crate::store::{CommitId, Operation, Store, StoreRead, Transaction, utc_datetime};
29pub use detect::{SourceChange, SourceChangeKind};
30pub use key::{AGGREGATOR_HOSTS, OFFICIAL_OWNERS, SourceRef};
31
32/// `store/sources.toml`.
33pub const SOURCES_FILE: &str = "sources.toml";
34/// The `Surjection-Entity` of source trust commits.
35pub const ENTITY: &str = "sources";
36
37/// The user's answer to the trust prompt.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
39pub enum TrustGrant {
40    /// Install or update this once; the next time asks again.
41    Once,
42    /// Record trust at this scope, then go ahead.
43    Always(SourceScope),
44}
45
46/// Why the prompt is shown.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48pub enum AskReason {
49    /// No decision about the source, and nothing installed from it.
50    FirstTime,
51    /// No decision, but skills from it are installed (trusted once before,
52    /// trust revoked, or installed before 0.5.0).
53    NotTrusted,
54    /// Trusted, but the repository changed under that trust.
55    Lapsed,
56}
57
58impl AskReason {
59    pub const fn as_str(self) -> &'static str {
60        match self {
61            AskReason::FirstTime => "first_time",
62            AskReason::NotTrusted => "not_trusted",
63            AskReason::Lapsed => "lapsed",
64        }
65    }
66}
67
68/// Where the store's decisions leave a source.
69#[derive(Debug, Clone, PartialEq)]
70pub enum TrustState {
71    /// The record at `key` trusts it.
72    Trusted { key: String, record: SourceRecord },
73    /// The record at `key` blocks it.
74    Blocked { key: String, record: SourceRecord },
75    /// The user must decide.
76    Ask {
77        reason: AskReason,
78        lapse: Option<Lapse>,
79    },
80}
81
82/// What the trust prompt shows about a source.
83#[derive(Debug, Clone, PartialEq)]
84pub struct TrustCheck {
85    pub source: SourceRef,
86    pub state: TrustState,
87    /// The scopes "always trust" offers, narrowest first.
88    pub scopes: Vec<SourceScope>,
89    pub official: bool,
90    /// Store skills whose git source has this repository key.
91    pub installed_skills: Vec<String>,
92}
93
94/// What [`admit`] did.
95#[derive(Debug, Clone)]
96pub struct Admission {
97    pub check: TrustCheck,
98    /// The commit recording "always trust", if one was made.
99    pub recorded: Option<CommitId>,
100}
101
102/// The decisions in the store; empty when there is no `sources.toml`.
103pub fn load(read: &dyn StoreRead) -> Result<SourcesFile, CoreError> {
104    Ok(load_doc(read)?.into_value())
105}
106
107fn load_doc(read: &dyn StoreRead) -> Result<TomlDocument<SourcesFile>, CoreError> {
108    let Some(text) = read.read_file(SOURCES_FILE)? else {
109        return Ok(TomlDocument::new(SourcesFile::new()));
110    };
111    let path = Path::new(SOURCES_FILE);
112    let doc = TomlDocument::<SourcesFile>::parse(&text)
113        .map_err(|diagnostic| diagnostic.to_core_error(Some(path)))?;
114    if let Some(err) = doc.value().validate().first_error(Some(path)) {
115        return Err(err);
116    }
117    Ok(doc)
118}
119
120/// Every decision, sorted by key.
121pub fn list(read: &dyn StoreRead) -> Result<Vec<(String, SourceRecord)>, CoreError> {
122    Ok(load(read)?.sources.into_iter().collect())
123}
124
125/// An opaque handle of the record at `key` (16 hex digits of its SHA-256),
126/// for frontends that must not carry a local path.
127pub fn record_id(key: &str) -> String {
128    use sha2::{Digest, Sha256};
129    let digest = Sha256::digest(key.as_bytes());
130    digest[..8]
131        .iter()
132        .map(|byte| format!("{byte:02x}"))
133        .collect()
134}
135
136/// The key of the record whose [`record_id`] is `id`.
137pub fn key_of_id(read: &dyn StoreRead, id: &str) -> Result<String, CoreError> {
138    load(read)?
139        .sources
140        .into_keys()
141        .find(|key| record_id(key) == id)
142        .ok_or_else(|| {
143            CoreError::new(
144                ErrorCode::NotFound,
145                "there is no such source decision any more; reload the list",
146            )
147        })
148}
149
150/// Where the store's decisions leave `source`. Read-only; never contacts
151/// the source.
152pub fn check(read: &dyn StoreRead, source: &SourceRef) -> Result<TrustCheck, CoreError> {
153    let file = load(read)?;
154    let state = state_of(&file, source);
155    let installed_skills = installed_skills(read, source)?;
156    let state = match state {
157        TrustState::Ask { lapse: None, .. } if !installed_skills.is_empty() => TrustState::Ask {
158            reason: AskReason::NotTrusted,
159            lapse: None,
160        },
161        state => state,
162    };
163    Ok(TrustCheck {
164        source: source.clone(),
165        state,
166        scopes: source.scopes(),
167        official: source.is_official(),
168        installed_skills,
169    })
170}
171
172/// Precedence: any matching block wins (a block of `host/...` also covers
173/// `http://host/...`); otherwise the most specific matching record decides
174/// (a lapsed trust asks); no record asks.
175fn state_of(file: &SourcesFile, source: &SourceRef) -> TrustState {
176    let decided = |keys: Vec<String>| -> Vec<(String, &SourceRecord)> {
177        keys.into_iter()
178            .filter_map(|key| file.sources.get(&key).map(|record| (key, record)))
179            .collect()
180    };
181    if let Some((key, record)) = decided(source.block_keys())
182        .into_iter()
183        .find(|(_, record)| record.decision == SourceDecision::Block)
184    {
185        return TrustState::Blocked {
186            key,
187            record: record.clone(),
188        };
189    }
190    let matching = decided(source.matching_keys());
191    match matching.first() {
192        Some((_, record)) if record.lapsed.is_some() => TrustState::Ask {
193            reason: AskReason::Lapsed,
194            lapse: record.lapsed.clone(),
195        },
196        Some((key, record)) => TrustState::Trusted {
197            key: key.clone(),
198            record: (*record).clone(),
199        },
200        None => TrustState::Ask {
201            reason: AskReason::FirstTime,
202            lapse: None,
203        },
204    }
205}
206
207/// Store skills installed from the repository `source` names.
208fn installed_skills(read: &dyn StoreRead, source: &SourceRef) -> Result<Vec<String>, CoreError> {
209    let mut ids = Vec::new();
210    for name in read.list_files(META_DIR)? {
211        let Some(id) = name.strip_suffix(".toml") else {
212            continue;
213        };
214        let Some(text) = read.read_file(&format!("{META_DIR}/{name}"))? else {
215            continue;
216        };
217        // A broken metadata file is reported where skills are listed; here
218        // it just does not count.
219        let Ok(doc) = TomlDocument::<SkillMeta>::parse(&text) else {
220            continue;
221        };
222        let from_source = doc
223            .value()
224            .source
225            .as_ref()
226            .filter(|skill_source| skill_source.kind == SkillSourceKind::Git)
227            .and_then(|skill_source| skill_source.url.as_deref())
228            .and_then(|url| SourceRef::from_git_url(url).ok())
229            .is_some_and(|other| other.key() == source.key());
230        if from_source {
231            ids.push(id.to_owned());
232        }
233    }
234    Ok(ids)
235}
236
237fn blocked_error(source: &SourceRef, key: &str) -> CoreError {
238    CoreError::new(
239        ErrorCode::SourceBlocked,
240        format!(
241            "the source {} is blocked ({key}); remove the block with `surject source untrust {key}` \
242             or in Settings > Sources",
243            source.key()
244        ),
245    )
246}
247
248fn trust_required(source: &SourceRef, reason: AskReason, lapse: Option<&Lapse>) -> CoreError {
249    let why = match (reason, lapse) {
250        (AskReason::Lapsed, Some(lapse)) => match lapse.reason {
251            LapseReason::HistoryRewritten => {
252                "its history was rewritten (force-push) since you trusted it".to_owned()
253            }
254            LapseReason::Moved => format!(
255                "it moved to {} since you trusted it",
256                lapse.detail.as_deref().unwrap_or("another location")
257            ),
258        },
259        (AskReason::Lapsed, None) => "it changed since you trusted it".to_owned(),
260        (AskReason::FirstTime, _) => "it is the first time you install from it".to_owned(),
261        (AskReason::NotTrusted, _) => "you have not trusted it".to_owned(),
262    };
263    CoreError::new(
264        ErrorCode::SourceTrustRequired,
265        format!(
266            "the source {} needs your decision: {why}. Skills and MCP servers can run commands and \
267             read your files; only install from sources you trust",
268            source.key()
269        ),
270    )
271}
272
273/// The trust gate. Trusted: Ok. Blocked: `source_blocked`. Undecided and
274/// no `grant`: `source_trust_required`. [`TrustGrant::Once`] goes ahead
275/// without recording anything; [`TrustGrant::Always`] records trust at
276/// that scope (one commit) first. A grant never overrides a block.
277pub fn admit(
278    store: &Store<'_>,
279    source: &SourceRef,
280    grant: Option<TrustGrant>,
281    via: TrustVia,
282) -> Result<Admission, CoreError> {
283    let check = would_admit(store, source, grant)?;
284    let recorded = match (&check.state, grant) {
285        (TrustState::Ask { .. }, Some(TrustGrant::Always(scope))) => {
286            trust(store, source, scope, via)?
287        }
288        _ => None,
289    };
290    Ok(Admission { check, recorded })
291}
292
293/// [`admit`] without recording anything: the same errors, so a caller can
294/// refuse before fetching a source it would refuse after.
295pub fn would_admit(
296    read: &dyn StoreRead,
297    source: &SourceRef,
298    grant: Option<TrustGrant>,
299) -> Result<TrustCheck, CoreError> {
300    let check = check(read, source)?;
301    match (&check.state, grant) {
302        (TrustState::Blocked { key, .. }, _) => Err(blocked_error(source, key)),
303        (TrustState::Ask { reason, lapse }, None) => {
304            Err(trust_required(source, *reason, lapse.as_ref()))
305        }
306        (TrustState::Ask { .. } | TrustState::Trusted { .. }, _) => Ok(check),
307    }
308}
309
310/// Refuses a blocked `source` (`source_blocked`) before anything contacts
311/// it: an install review fetches only what no block covers. An undecided
312/// source goes through (the review asks).
313pub fn refuse_blocked(read: &dyn StoreRead, source: &SourceRef) -> Result<TrustCheck, CoreError> {
314    let check = check(read, source)?;
315    match &check.state {
316        TrustState::Blocked { key, .. } => Err(blocked_error(source, key)),
317        _ => Ok(check),
318    }
319}
320
321fn scope_key(source: &SourceRef, scope: SourceScope) -> Result<String, CoreError> {
322    source.scope_key(scope).ok_or_else(|| {
323        CoreError::new(
324            ErrorCode::InvalidValue,
325            format!(
326                "the source {} has no {} scope",
327                source.key(),
328                scope.as_str()
329            ),
330        )
331    })
332}
333
334/// Runs one change of `sources.toml`; `None` when nothing changed.
335fn change(
336    store: &Store<'_>,
337    op: &str,
338    summary: String,
339    edit: impl FnOnce(&mut Transaction<'_>, &mut SourcesFile) -> Result<bool, CoreError>,
340) -> Result<Option<CommitId>, CoreError> {
341    let operation = Operation::new(op, summary).entity(ENTITY);
342    let committed = store.transaction(operation, |tx| {
343        let mut doc = load_doc(tx)?;
344        if !edit(tx, doc.value_mut())? {
345            return Ok(());
346        }
347        let text = doc.to_text()?;
348        tx.write(SOURCES_FILE, text)
349    })?;
350    Ok(committed.commit)
351}
352
353fn new_record(
354    tx: &Transaction<'_>,
355    decision: SourceDecision,
356    scope: SourceScope,
357    via: TrustVia,
358    url: Option<String>,
359) -> SourceRecord {
360    SourceRecord {
361        decision,
362        scope,
363        decided_at: utc_datetime(tx.store().env().now()),
364        via: Some(via),
365        machine: Some(tx.machine().label.clone()),
366        url,
367        lapsed: None,
368        extra: toml::Table::new(),
369    }
370}
371
372/// Whether a record at `key` covers the repository or owner key `other`
373/// (itself, or a key below an owner or host wildcard).
374fn covers(key: &str, other: &str) -> bool {
375    match key.strip_suffix('*') {
376        Some(prefix) => other.starts_with(prefix),
377        None => key == other,
378    }
379}
380
381/// Records `decision` at the source key `key` (one commit): a repository
382/// (`host/path`, `file:///path`), an owner (`host/owner/*`) or a host
383/// (`host/*`). Trust is refused for an [`AGGREGATOR_HOSTS`] host, and
384/// clears every lapse the new trust covers: the user decided again.
385/// `url` is shown with the record (repositories).
386pub fn record_key(
387    store: &Store<'_>,
388    key: &str,
389    decision: SourceDecision,
390    via: TrustVia,
391    url: Option<&str>,
392) -> Result<Option<CommitId>, CoreError> {
393    let scope = match SourceRef::canonical_key(key) {
394        Ok((canonical, scope)) if canonical == key => scope,
395        Ok((canonical, _)) => {
396            return Err(CoreError::new(
397                ErrorCode::InvalidValue,
398                format!("{key:?} is not a canonical source key; it is written {canonical:?}"),
399            ));
400        }
401        Err(_) => {
402            return Err(CoreError::new(
403                ErrorCode::InvalidValue,
404                format!(
405                    "{key:?} is not a source key: host/path for a repository, host/owner/* for \
406                     an owner, host/* for a host"
407                ),
408            ));
409        }
410    };
411    if decision == SourceDecision::Trust
412        && scope == SourceScope::Host
413        && AGGREGATOR_HOSTS.contains(&without_insecure_prefix(key).trim_end_matches("/*"))
414    {
415        return Err(CoreError::new(
416            ErrorCode::InvalidValue,
417            format!(
418                "{key} cannot be trusted as a whole: that host serves anyone's repositories; \
419                 trust an owner or a repository"
420            ),
421        ));
422    }
423    let (op, summary) = match decision {
424        SourceDecision::Trust => (
425            "source.trust",
426            format!("source: trust {key} ({})", scope.as_str()),
427        ),
428        SourceDecision::Block => ("source.block", format!("source: block {key}")),
429    };
430    change(store, op, summary, |tx, file| {
431        if decision == SourceDecision::Trust {
432            for (other, record) in &mut file.sources {
433                if record.decision == SourceDecision::Trust && covers(key, other) {
434                    record.lapsed = None;
435                }
436            }
437        }
438        let record = new_record(tx, decision, scope, via, url.map(str::to_owned));
439        file.sources.insert(key.to_owned(), record);
440        Ok(true)
441    })
442}
443
444/// Records trust in `source` at `scope`, one of [`SourceRef::scopes`]
445/// (one commit; see [`record_key`]).
446pub fn trust(
447    store: &Store<'_>,
448    source: &SourceRef,
449    scope: SourceScope,
450    via: TrustVia,
451) -> Result<Option<CommitId>, CoreError> {
452    if !source.scopes().contains(&scope) {
453        return Err(CoreError::new(
454            ErrorCode::InvalidValue,
455            format!(
456                "{} cannot be trusted at the {} scope{}",
457                source.key(),
458                scope.as_str(),
459                if scope == SourceScope::Host {
460                    ": that host serves anyone's repositories; trust an owner or a repository"
461                } else {
462                    ""
463                }
464            ),
465        ));
466    }
467    let key = scope_key(source, scope)?;
468    let url = (scope == SourceScope::Repo).then(|| source.url());
469    record_key(store, &key, SourceDecision::Trust, via, url)
470}
471
472/// Records a block of `source` at `scope` (one commit).
473pub fn block(
474    store: &Store<'_>,
475    source: &SourceRef,
476    scope: SourceScope,
477    via: TrustVia,
478) -> Result<Option<CommitId>, CoreError> {
479    let key = scope_key(source, scope)?;
480    let url = (scope == SourceScope::Repo).then(|| source.url());
481    record_key(store, &key, SourceDecision::Block, via, url)
482}
483
484fn missing_key(key: &str) -> CoreError {
485    CoreError::new(
486        ErrorCode::NotFound,
487        format!("there is no decision about the source {key:?}"),
488    )
489}
490
491/// Turns the record at `key` into a block at the same scope.
492pub fn block_key(
493    store: &Store<'_>,
494    key: &str,
495    via: TrustVia,
496) -> Result<Option<CommitId>, CoreError> {
497    change(
498        store,
499        "source.block",
500        format!("source: block {key}"),
501        |tx, file| {
502            let Some(old) = file.sources.get(key) else {
503                return Err(missing_key(key));
504            };
505            if old.decision == SourceDecision::Block {
506                return Ok(false);
507            }
508            let mut record = new_record(tx, SourceDecision::Block, old.scope, via, old.url.clone());
509            record.extra = old.extra.clone();
510            file.sources.insert(key.to_owned(), record);
511            Ok(true)
512        },
513    )
514}
515
516/// Removes the trust or block at `key`. Nothing installed is touched; the
517/// next install or update from that source asks again.
518pub fn untrust(store: &Store<'_>, key: &str) -> Result<Option<CommitId>, CoreError> {
519    change(
520        store,
521        "source.untrust",
522        format!("source: untrust {key}"),
523        |_, file| match file.sources.remove(key) {
524            Some(_) => Ok(true),
525            None => Err(missing_key(key)),
526        },
527    )
528}
529
530/// Makes the trust that admits `source` lapse because of `change` (one
531/// commit): the repository's record gets a `lapsed` table (a repository
532/// trusted through its owner or host gets its own lapsed record). Nothing
533/// is written when no trust admits the source (it asks or is blocked
534/// anyway) or the trust already lapsed.
535pub fn lapse(
536    store: &Store<'_>,
537    source: &SourceRef,
538    found: &SourceChange,
539) -> Result<Option<CommitId>, CoreError> {
540    let current = load(store)?;
541    let TrustState::Trusted { record, .. } = state_of(&current, source) else {
542        return Ok(None);
543    };
544    let reason = found.kind.reason();
545    let key = source.key().to_owned();
546    change(
547        store,
548        "source.lapse",
549        format!("source: trust lapsed for {key} ({})", reason.as_str()),
550        |tx, file| {
551            let lapse = Lapse {
552                reason,
553                at: utc_datetime(tx.store().env().now()),
554                detail: found.detail.clone(),
555                extra: toml::Table::new(),
556            };
557            match file.sources.get_mut(&key) {
558                Some(own) => own.lapsed = Some(lapse),
559                None => {
560                    let mut own = record.clone();
561                    own.scope = SourceScope::Repo;
562                    own.url = Some(source.url().to_owned());
563                    own.lapsed = Some(lapse);
564                    own.extra = toml::Table::new();
565                    file.sources.insert(key.clone(), own);
566                }
567            }
568            Ok(true)
569        },
570    )
571}
572
573#[cfg(test)]
574mod tests;