Skip to main content

agentmux_srv_core/backend/job_templates/
package.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A template package, in a folder or compiled in: its files, its content
5//! hash and its signature (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md
6//! §5.4).
7//!
8//! A template is data, so a package holds only its known files, at its top
9//! level. The content hash is the widgets' (`widget::packages::package_hash`)
10//! over every file except `template.sig`, which signs it.
11
12use std::collections::BTreeMap;
13use std::path::Path;
14
15use sha2::{Digest, Sha256};
16
17use super::graph;
18use super::manifest::{self, JobTemplateKind, JobTemplateManifest};
19use crate::backend::widget::packages as wp;
20use crate::backend::storage::drone_types::DroneGraph;
21use crate::backend::widget::signature as sig;
22
23pub const TEMPLATE_FILE: &str = "template.json";
24pub const BRIEF_FILE: &str = "brief.md";
25const GRAPH_FILE: &str = "graph.json";
26const README_FILE: &str = "README.md";
27const FILES: &[&str] = &[TEMPLATE_FILE, BRIEF_FILE, GRAPH_FILE, README_FILE];
28pub const MAX_BYTES: u64 = 256 * 1024;
29
30/// A template, read and checked.
31#[derive(Debug, Clone)]
32pub struct Package {
33    pub manifest: JobTemplateManifest,
34    pub brief: Option<String>,
35    /// A Drone template's graph (graph.json), checked.
36    pub graph: Option<DroneGraph>,
37    pub hash: String,
38    /// The key (base64) whose `template.sig` verifies, if it is signed.
39    pub signer: Option<String>,
40}
41
42/// Parse and check a template from its files (path → bytes), its signature
43/// left out; `folder` is the name of the folder it is in.
44pub fn parse(folder: &str, files: &BTreeMap<String, Vec<u8>>) -> Result<Package, String> {
45    if let Some(other) = files.keys().find(|p| !FILES.contains(&p.as_str())) {
46        return Err(format!(
47            "a template holds only {}, and {}; {other:?} isn't one of them",
48            FILES.join(", "),
49            sig::JOB_TEMPLATE.sig_file
50        ));
51    }
52    if files.values().map(|b| b.len() as u64).sum::<u64>() > MAX_BYTES {
53        return Err(format!("a template is at most {} KB", MAX_BYTES / 1024));
54    }
55    let raw = files.get(TEMPLATE_FILE).ok_or("no template.json")?;
56    let m: JobTemplateManifest = serde_json::from_slice(raw).map_err(|e| format!("template.json: {e}"))?;
57    let brief = files
58        .get(BRIEF_FILE)
59        .map(|b| String::from_utf8(b.clone()).map_err(|_| "brief.md isn't UTF-8 text".to_string()))
60        .transpose()?;
61    manifest::validate(&m, folder, brief.as_deref())?;
62    let graph = graph_of(&m, files)?;
63    let hashes = files.iter().map(|(p, b)| (p.clone(), hex::encode(Sha256::digest(b)))).collect();
64    Ok(Package { manifest: m, brief, graph, hash: wp::package_hash(&hashes), signer: None })
65}
66
67/// A Drone template's graph, checked; a job or cloud template has none.
68fn graph_of(m: &JobTemplateManifest, files: &BTreeMap<String, Vec<u8>>) -> Result<Option<DroneGraph>, String> {
69    match (m.kind == JobTemplateKind::Drone, files.get(GRAPH_FILE)) {
70        (true, Some(raw)) => {
71            if let Some(trigger) = &m.trigger {
72                if let Some(name) = graph::param_names_in(trigger)?.into_iter().find(|n| !m.params.properties.contains_key(n)) {
73                    return Err(format!("the trigger uses {{{{param.{name}}}}}, which isn't one of its parameters"));
74                }
75            }
76            let g = graph::parse(raw)?;
77            if let Some(name) = graph::param_names(&g)?.into_iter().find(|n| !m.params.properties.contains_key(n)) {
78                return Err(format!("graph.json uses {{{{param.{name}}}}}, which isn't one of its parameters"));
79            }
80            // The credentials the graph and trigger use count for the Rule of Two, whatever `secrets` declares.
81            manifest::rule_of_two_with(m, !graph::credentials(&g, m.trigger.as_ref()).is_empty(), graph::approval_guards_every_write(&g))?;
82            Ok(Some(g))
83        }
84        (true, None) => Err("a Drone template needs its graph in graph.json".to_string()),
85        (false, Some(_)) => Err("only a Drone template (kind \"drone\") carries graph.json".to_string()),
86        (false, None) => Ok(None),
87    }
88}
89
90/// The files of the template folder `dir`, without its signature: no links,
91/// no folders, within the size limit.
92pub fn read_files(dir: &Path) -> Result<BTreeMap<String, Vec<u8>>, String> {
93    let mut out = BTreeMap::new();
94    let mut total = 0u64;
95    let entries = std::fs::read_dir(dir).map_err(|e| format!("can't read {}: {e}", dir.display()))?;
96    for entry in entries {
97        let entry = entry.map_err(|e| e.to_string())?;
98        let name = entry.file_name().to_string_lossy().into_owned();
99        let ft = entry.file_type().map_err(|e| e.to_string())?;
100        if ft.is_symlink() {
101            return Err(format!("{name} is a link; a template can't contain links"));
102        }
103        if ft.is_dir() {
104            return Err(format!("{name}/ is a folder; a template holds only files"));
105        }
106        if name == sig::JOB_TEMPLATE.sig_file {
107            continue;
108        }
109        total += entry.metadata().map_err(|e| e.to_string())?.len();
110        if total > MAX_BYTES {
111            return Err(format!("a template is at most {} KB", MAX_BYTES / 1024));
112        }
113        out.insert(name.clone(), std::fs::read(entry.path()).map_err(|e| format!("can't read {name}: {e}"))?);
114    }
115    Ok(out)
116}
117
118/// The template in `dir`, checked as if its folder were named `folder`,
119/// with its signature verified.
120pub fn load_dir(dir: &Path, folder: &str) -> Result<Package, String> {
121    let mut pkg = parse(folder, &read_files(dir)?)?;
122    pkg.signer = match sig::check(&sig::JOB_TEMPLATE, dir, &pkg.manifest.id, &pkg.manifest.version, &pkg.hash) {
123        None => None,
124        Some(Ok(key)) => Some(key),
125        Some(Err(e)) => return Err(e),
126    };
127    Ok(pkg)
128}
129
130/// A compiled-in template: never signed, it is part of the app.
131pub fn load_embedded(id: &str, files: &[(&str, &[u8])]) -> Result<Package, String> {
132    parse(id, &files.iter().map(|(p, b)| (p.to_string(), b.to_vec())).collect())
133}