Skip to main content

perishables_core/
bundle.rs

1//! Loading a bundle from disk into the concepts the checks read.
2//!
3//! Loading never writes. Files are read in sorted path order so a
4//! bundle always loads identically. Reserved files (`index.md` and
5//! `log.md`), symlinks, and hidden paths are not concepts. A Markdown
6//! file is a concept when its frontmatter parses and carries a `type`.
7//! A bundle root that cannot be read is an error, never an empty
8//! bundle, because an auditor that reports a clean pass over a bundle
9//! it could not read has failed at its only job.
10
11use std::fs;
12use std::path::{Path, PathBuf};
13
14use crate::frontmatter::{
15    Value, body_of, citation_labels, claimed_result, code_blocks, parse_frontmatter,
16};
17use crate::time::parse_timestamp;
18
19/// One entry of a concept `sources` list.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct SourceRef {
22    /// The source id, when the entry carries one.
23    pub id: Option<String>,
24    /// The resource the entry points at, when it carries one.
25    pub resource: Option<String>,
26    /// A recorded content hash for the resource, when the entry
27    /// carries one under the `sha256` key.
28    pub sha256: Option<String>,
29}
30
31/// One declared parameter of an Attested Computation.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct Parameter {
34    /// The parameter name.
35    pub name: String,
36    /// The declared parameter type, such as `string`, `integer`,
37    /// `number`, or `boolean`, when specified in frontmatter.
38    pub param_type: Option<String>,
39    /// The declared value, when the bundle binds one.
40    pub value: Option<String>,
41}
42
43/// One verification event as recorded in frontmatter, before any
44/// judgement about its currency or shape.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct VerifiedEvent {
47    /// The actor string, such as `human:ahormati`, when present.
48    pub by: Option<String>,
49    /// The raw timestamp text, when present.
50    pub at_text: Option<String>,
51    /// The parsed timestamp, when the text parses.
52    pub at: Option<i64>,
53}
54
55impl VerifiedEvent {
56    /// Whether this event has an actor and a parseable timestamp.
57    pub fn is_well_formed(&self) -> bool {
58        self.by.is_some() && self.at.is_some()
59    }
60
61    /// Why this event is malformed, in plain words.
62    pub fn malformed_reason(&self) -> Option<String> {
63        if self.by.is_none() {
64            return Some("verification event has no by actor".to_string());
65        }
66        match (&self.at_text, &self.at) {
67            (None, _) => Some("verification event has no at timestamp".to_string()),
68            (Some(text), None) => Some(format!("verification timestamp {text} does not parse")),
69            _ => None,
70        }
71    }
72
73    /// Whether this event uses the `human:` actor scheme, the only
74    /// scheme that qualifies for the `human-reviewed` tier.
75    pub fn is_human(&self) -> bool {
76        self.by
77            .as_deref()
78            .is_some_and(|by| by.starts_with("human:"))
79    }
80}
81
82/// One concept and the trust fields the checks read.
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct Concept {
85    /// Bundle-relative path without the `.md` suffix, POSIX style.
86    pub id: String,
87    /// The concept type, such as `Metric` or `Attested Computation`.
88    pub concept_type: String,
89    /// The lifecycle status. Absent status means `stable`.
90    pub status: String,
91    /// The raw `superseded_by` value, when present.
92    pub superseded_by: Option<String>,
93    /// The parsed `generated.at`, when present and parseable.
94    pub generated_at: Option<i64>,
95    /// The raw `generated.at` text, when present.
96    pub generated_text: Option<String>,
97    /// The raw `stale_after` text, when present.
98    pub stale_after_text: Option<String>,
99    /// The parsed `stale_after`, when present and parseable.
100    pub stale_after: Option<i64>,
101    /// Recorded verification events, in document order.
102    pub verified: Vec<VerifiedEvent>,
103    /// The concept's recorded sources.
104    pub sources: Vec<SourceRef>,
105    /// The footnote labels the concept body cites.
106    pub citations: Vec<String>,
107    /// The declared runtime, for `Attested Computation` concepts.
108    pub runtime: Option<String>,
109    /// The declared parameters, for `Attested Computation` concepts.
110    pub parameters: Vec<Parameter>,
111    /// The fenced code blocks of the body, `(language, code)`.
112    pub code_blocks: Vec<(String, String)>,
113    /// The text of a computation file the body links to, when the
114    /// computation lives in a file rather than inline.
115    pub file_code: Option<String>,
116    /// The attested result the body claims, when it states one.
117    pub claimed_result: Option<String>,
118}
119
120/// A loaded bundle.
121#[derive(Debug, Clone, Default, PartialEq, Eq)]
122pub struct Bundle {
123    /// Concepts in sorted id order.
124    pub concepts: Vec<Concept>,
125    /// The `okf_version` declared by the bundle index, when any.
126    pub okf_version: Option<String>,
127    /// Every file in the bundle as a POSIX-relative path, when the
128    /// bundle was loaded from disk. In-memory bundles carry `None`,
129    /// and checks that need the inventory skip file existence checks.
130    pub files: Option<std::collections::BTreeSet<String>>,
131    /// The bytes of in-bundle sources that record a content hash,
132    /// keyed by bundle-relative path.
133    pub source_bytes: std::collections::BTreeMap<String, Vec<u8>>,
134    /// Explicit source modification instants supplied by a caller
135    /// (for example from version-control commit timestamps), as epoch
136    /// seconds keyed by bundle-relative path. Disk loads leave this
137    /// map empty so host filesystem `mtime` never alters audit output.
138    pub source_modified: std::collections::BTreeMap<String, i64>,
139}
140
141/// Classification of a `sources.resource` or path field.
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub(crate) enum ResourceTarget {
144    /// External URI carrying an RFC 3986 scheme (such as `https://` or `s3://`).
145    ExternalUri,
146    /// Valid normalized POSIX path strictly within the bundle root.
147    InBundle(String),
148    /// Empty path, Windows drive path, or relative `..` path escaping the bundle root.
149    InvalidOrEscapes,
150}
151
152/// Whether a value carries an external URI scheme (`https:`, `s3:`,
153/// `mailto:`, `urn:`). Single-letter Windows drive prefixes (`C:\` or
154/// `C:/`) are local filesystem paths rather than URI schemes.
155pub(crate) fn has_uri_scheme(raw: &str) -> bool {
156    let Some(colon) = raw.find(':') else {
157        return false;
158    };
159    let scheme = &raw[..colon];
160    if scheme.len() < 2 || scheme.contains(['/', '\\']) {
161        return false;
162    }
163    let mut chars = scheme.chars();
164    chars.next().is_some_and(|c| c.is_ascii_alphabetic())
165        && chars.all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.')
166}
167
168/// Classify a path or resource string relative to `from_concept`.
169pub(crate) fn classify_resource_path(from_concept: &str, raw: &str) -> ResourceTarget {
170    let raw = raw.trim();
171    if raw.is_empty() {
172        return ResourceTarget::InvalidOrEscapes;
173    }
174    if has_uri_scheme(raw) {
175        return ResourceTarget::ExternalUri;
176    }
177    // Reject single-letter Windows drive paths such as `C:\secret.csv`.
178    if raw.len() >= 2 && raw.as_bytes()[0].is_ascii_alphabetic() && raw.as_bytes()[1] == b':' {
179        return ResourceTarget::InvalidOrEscapes;
180    }
181    let normalized = raw.replace('\\', "/");
182    let stripped = normalized.strip_prefix('/').unwrap_or(&normalized);
183    let combined = if normalized.starts_with('/') {
184        stripped.to_string()
185    } else {
186        let parent = from_concept.rsplit_once('/').map(|(p, _)| p).unwrap_or("");
187        if parent.is_empty() {
188            stripped.to_string()
189        } else {
190            format!("{parent}/{stripped}")
191        }
192    };
193    let mut parts: Vec<&str> = Vec::new();
194    for segment in combined.split('/') {
195        match segment {
196            "" | "." => {}
197            ".." => {
198                if parts.pop().is_none() {
199                    return ResourceTarget::InvalidOrEscapes;
200                }
201            }
202            other => parts.push(other),
203        }
204    }
205    if parts.is_empty() {
206        ResourceTarget::InvalidOrEscapes
207    } else {
208        ResourceTarget::InBundle(parts.join("/"))
209    }
210}
211
212/// Resolve a path field to a bundle-relative file path. External URIs
213/// and paths that escape the bundle return `None`.
214pub(crate) fn resolve_file_path(from_concept: &str, raw: &str) -> Option<String> {
215    match classify_resource_path(from_concept, raw) {
216        ResourceTarget::InBundle(path) => Some(path),
217        ResourceTarget::ExternalUri | ResourceTarget::InvalidOrEscapes => None,
218    }
219}
220
221impl Bundle {
222    /// Whether the SPEC 12.1 fallbacks apply to this bundle. They
223    /// apply when the bundle declares version `0.2` or earlier, or
224    /// declares no version at all. A declared version that does not
225    /// parse is treated as current, never as an old version.
226    pub fn uses_v02_fallback(&self) -> bool {
227        match &self.okf_version {
228            None => true,
229            Some(version) => {
230                let mut parts = version.split('.');
231                let (Some(Ok(major)), Some(Ok(minor))) = (
232                    parts.next().map(|p| p.parse::<u32>()),
233                    parts.next().map(|p| p.parse::<u32>()),
234                ) else {
235                    return false;
236                };
237                (major, minor) <= (0, 2)
238            }
239        }
240    }
241
242    /// Load every concept under a bundle root directory.
243    pub fn load(root: &Path) -> std::io::Result<Bundle> {
244        let okf_version = read_okf_version(root);
245        let mut inventory = Vec::new();
246        collect_files(root, &mut inventory)?;
247        inventory.sort();
248        let files: std::collections::BTreeSet<String> = inventory
249            .iter()
250            .map(|path| {
251                path.strip_prefix(root)
252                    .unwrap_or(path)
253                    .to_string_lossy()
254                    .replace('\\', "/")
255            })
256            .collect();
257        let mut markdown: Vec<&PathBuf> = inventory
258            .iter()
259            .filter(|path| {
260                let name = path
261                    .file_name()
262                    .map(|n| n.to_string_lossy().to_string())
263                    .unwrap_or_default();
264                name.ends_with(".md") && name != "index.md" && name != "log.md"
265            })
266            .collect();
267        markdown.sort();
268        let mut concepts = Vec::new();
269        for path in markdown {
270            let text = fs::read_to_string(path)?;
271            let Some(fm) = parse_frontmatter(&text) else {
272                continue;
273            };
274            if fm.get("type").and_then(Value::as_str).is_none() {
275                continue;
276            }
277            let rel = path.strip_prefix(root).unwrap_or(path);
278            let id = to_posix_id(rel);
279            concepts.push(concept_from_frontmatter(id, &fm, &text, root, &files));
280        }
281        concepts.sort_by(|a, b| a.id.cmp(&b.id));
282        let mut source_bytes = std::collections::BTreeMap::new();
283        for concept in &concepts {
284            for source in &concept.sources {
285                let Some(resource) = &source.resource else {
286                    continue;
287                };
288                let Some(path) = resolve_file_path(&concept.id, resource) else {
289                    continue;
290                };
291                if !files.contains(&path) {
292                    continue;
293                }
294                if source.sha256.is_some() && !source_bytes.contains_key(&path) {
295                    let disk_path = root.join(path_from_posix(&path));
296                    source_bytes.insert(path, fs::read(disk_path)?);
297                }
298            }
299        }
300        Ok(Bundle {
301            concepts,
302            okf_version,
303            files: Some(files),
304            source_bytes,
305            source_modified: std::collections::BTreeMap::new(),
306        })
307    }
308
309    /// Build a bundle from in-memory concepts.
310    pub fn from_concepts(mut concepts: Vec<Concept>) -> Bundle {
311        concepts.sort_by(|a, b| a.id.cmp(&b.id));
312        Bundle {
313            concepts,
314            okf_version: None,
315            files: None,
316            source_bytes: std::collections::BTreeMap::new(),
317            source_modified: std::collections::BTreeMap::new(),
318        }
319    }
320
321    /// Look up one concept by id.
322    pub fn concept(&self, id: &str) -> Option<&Concept> {
323        self.concepts.iter().find(|c| c.id == id)
324    }
325}
326
327fn path_from_posix(posix: &str) -> PathBuf {
328    let mut pb = PathBuf::new();
329    for seg in posix.split('/') {
330        if !seg.is_empty() {
331            pb.push(seg);
332        }
333    }
334    pb
335}
336
337fn collect_files(dir: &Path, out: &mut Vec<PathBuf>) -> std::io::Result<()> {
338    let entries = fs::read_dir(dir)?;
339    for entry in entries {
340        let entry = entry?;
341        let name = entry.file_name().to_string_lossy().to_string();
342        if name.starts_with('.') {
343            continue;
344        }
345        let ft = entry.file_type()?;
346        if ft.is_symlink() {
347            continue;
348        }
349        let path = entry.path();
350        if ft.is_dir() {
351            collect_files(&path, out)?;
352        } else if ft.is_file() {
353            out.push(path);
354        }
355    }
356    Ok(())
357}
358
359/// The bundle index is a reserved file, not a concept, and carries
360/// the declared `okf_version`.
361fn read_okf_version(root: &Path) -> Option<String> {
362    let index_path = root.join("index.md");
363    let meta = fs::symlink_metadata(&index_path).ok()?;
364    if meta.file_type().is_symlink() || !meta.is_file() {
365        return None;
366    }
367    let text = fs::read_to_string(index_path).ok()?;
368    let fm = parse_frontmatter(&text)?;
369    fm.get("okf_version")
370        .and_then(Value::as_str)
371        .map(str::to_string)
372}
373
374fn to_posix_id(rel: &Path) -> String {
375    let text = rel.to_string_lossy().replace('\\', "/");
376    text.strip_suffix(".md").unwrap_or(&text).to_string()
377}
378
379/// The first in-bundle Python file a body links to, read as text.
380fn linked_python_file(
381    id: &str,
382    body: &str,
383    root: &Path,
384    files: &std::collections::BTreeSet<String>,
385) -> Option<String> {
386    let mut rest = body;
387    while let Some(start) = rest.find("](") {
388        let after = &rest[start + 2..];
389        let Some(end) = after.find(')') else {
390            break;
391        };
392        let target = after[..end].trim();
393        if target.ends_with(".py")
394            && let Some(path) = resolve_file_path(id, target)
395            && files.contains(&path)
396        {
397            return fs::read_to_string(root.join(path_from_posix(&path))).ok();
398        }
399        rest = &after[end + 1..];
400    }
401    None
402}
403
404fn concept_from_frontmatter(
405    id: String,
406    fm: &Value,
407    text: &str,
408    root: &Path,
409    files: &std::collections::BTreeSet<String>,
410) -> Concept {
411    let status = fm
412        .get("status")
413        .and_then(Value::as_str)
414        .unwrap_or("stable")
415        .to_string();
416    let superseded_by = fm
417        .get("superseded_by")
418        .and_then(Value::as_str)
419        .map(str::to_string);
420    let generated_text = fm
421        .get("generated")
422        .and_then(|g| g.get("at"))
423        .and_then(Value::as_str)
424        .map(str::to_string);
425    let generated_at = generated_text.as_deref().and_then(parse_timestamp);
426    let stale_after_text = fm
427        .get("stale_after")
428        .and_then(Value::as_str)
429        .map(str::to_string);
430    let stale_after = stale_after_text.as_deref().and_then(parse_timestamp);
431    let mut verified = Vec::new();
432    if let Some(value) = fm.get("verified") {
433        for item in value.as_items() {
434            let by = item.get("by").and_then(Value::as_str).map(str::to_string);
435            let at_text = item.get("at").and_then(Value::as_str).map(str::to_string);
436            let at = at_text.as_deref().and_then(parse_timestamp);
437            verified.push(VerifiedEvent { by, at_text, at });
438        }
439    }
440    let mut sources = Vec::new();
441    if let Some(value) = fm.get("sources") {
442        for item in value.as_items() {
443            sources.push(SourceRef {
444                id: item.get("id").and_then(Value::as_str).map(str::to_string),
445                resource: item
446                    .get("resource")
447                    .and_then(Value::as_str)
448                    .map(str::to_string),
449                sha256: item
450                    .get("sha256")
451                    .and_then(Value::as_str)
452                    .map(str::to_string),
453            });
454        }
455    }
456    let mut parameters = Vec::new();
457    if let Some(value) = fm.get("parameters") {
458        for item in value.as_items() {
459            if let Some(name) = item.get("name").and_then(Value::as_str) {
460                parameters.push(Parameter {
461                    name: name.to_string(),
462                    param_type: item.get("type").and_then(Value::as_str).map(str::to_string),
463                    value: item
464                        .get("value")
465                        .and_then(Value::as_str)
466                        .map(str::to_string),
467                });
468            }
469        }
470    }
471    let body = body_of(text);
472    let citations = citation_labels(body);
473    let runtime = fm
474        .get("runtime")
475        .and_then(Value::as_str)
476        .map(str::to_string);
477    let blocks = code_blocks(body);
478    let file_code = linked_python_file(&id, body, root, files);
479    let claimed = claimed_result(body);
480    let concept_type = fm
481        .get("type")
482        .and_then(Value::as_str)
483        .unwrap_or("")
484        .to_string();
485    Concept {
486        id,
487        concept_type,
488        status,
489        superseded_by,
490        generated_at,
491        generated_text,
492        stale_after_text,
493        stale_after,
494        verified,
495        sources,
496        citations,
497        runtime,
498        parameters,
499        code_blocks: blocks,
500        file_code,
501        claimed_result: claimed,
502    }
503}