Skip to main content

gitpoulpi_core/domain/rewrite/
script.rs

1//! Scripts: the header both the editor and the engine read, the failure
2//! text and the result types of `rewrite_script_check` / `rewrite_script_test`
3//! (the history-rewrite design, "Scripts").
4//!
5//! The header is a block of `--!` comment lines at the top of a Lua script:
6//!
7//! ```lua
8//! --! name: Replace an email
9//! --! kinds: commit
10//! --! window: 0
11//! --! needs: []
12//! --! param old_email: text "Email to replace"
13//! --! param keep: bool "Keep the committer" = false
14//! ```
15//!
16//! Pure: no interpreter here, so the TUI builds its parameter form from the
17//! same parser the engine validates with.
18
19use std::collections::BTreeMap;
20
21use serde::{Deserialize, Serialize};
22
23use super::plan::FieldChange;
24use super::recipe::ScriptLanguage;
25use crate::domain::Oid;
26
27/// Per-request timeout of an external script when the settings say nothing.
28pub const DEFAULT_SCRIPT_TIMEOUT_MS: u64 = 5_000;
29/// Whole-pass timeout of an external script when the settings say nothing.
30pub const DEFAULT_SCRIPT_TOTAL_TIMEOUT_S: u64 = 3_600;
31
32/// What external scripts may do on one request. The daemon builds it from the
33/// settings (`rewrite.external_scripts`, the timeouts) and the repository's
34/// trust store, and replaces whatever a client sent: a frontend cannot grant
35/// itself anything. The default is the safe one a bare backend (a test)
36/// sees: shell scripts allowed, Python and external Lua off, nothing trusted.
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(default)]
39pub struct ScriptPolicy {
40    pub shell: bool,
41    pub python: bool,
42    pub lua: bool,
43    /// Per-request timeout in milliseconds.
44    pub timeout_ms: u64,
45    /// Whole-pass timeout in seconds.
46    pub total_timeout_s: u64,
47    /// Content hashes ([`script_hash`]) the user trusted, plus the ones the
48    /// caller vouched for on this request (a script the user typed).
49    pub trusted: Vec<String>,
50}
51
52impl Default for ScriptPolicy {
53    fn default() -> Self {
54        Self {
55            shell: true,
56            python: false,
57            lua: false,
58            timeout_ms: DEFAULT_SCRIPT_TIMEOUT_MS,
59            total_timeout_s: DEFAULT_SCRIPT_TOTAL_TIMEOUT_S,
60            trusted: Vec::new(),
61        }
62    }
63}
64
65impl ScriptPolicy {
66    pub fn is_default(&self) -> bool {
67        *self == Self::default()
68    }
69
70    /// Whether the settings allow `language` (the embedded Lua always).
71    pub fn allows(&self, language: ScriptLanguage) -> bool {
72        match language {
73            ScriptLanguage::Lua => true,
74            ScriptLanguage::Shell => self.shell,
75            ScriptLanguage::Python => self.python,
76            ScriptLanguage::LuaExternal => self.lua,
77        }
78    }
79
80    pub fn trusts(&self, hash: &str) -> bool {
81        self.trusted.iter().any(|t| t == hash)
82    }
83
84    /// The policy for a `rewrite.external_scripts` list (`shell`, `python`,
85    /// `lua`) and the two timeouts (`0` reads as the default).
86    pub fn from_settings(enabled: &[String], timeout_ms: u64, total_timeout_s: u64) -> Self {
87        let on = |name: &str| enabled.iter().any(|e| e.trim().eq_ignore_ascii_case(name));
88        Self {
89            shell: on("shell"),
90            python: on("python"),
91            lua: on("lua"),
92            timeout_ms: if timeout_ms == 0 {
93                DEFAULT_SCRIPT_TIMEOUT_MS
94            } else {
95                timeout_ms
96            },
97            total_timeout_s: if total_timeout_s == 0 {
98                DEFAULT_SCRIPT_TOTAL_TIMEOUT_S
99            } else {
100                total_timeout_s
101            },
102            trusted: Vec::new(),
103        }
104    }
105}
106
107/// The SHA-256 of a script's text as lowercase hex: what trust is keyed by,
108/// so a changed script asks again.
109pub fn script_hash(text: &str) -> String {
110    use sha2::{Digest, Sha256};
111    use std::fmt::Write;
112    let digest = Sha256::digest(text.as_bytes());
113    let mut out = String::with_capacity(64);
114    for byte in digest {
115        let _ = write!(out, "{byte:02x}");
116    }
117    out
118}
119
120/// Whether a script may run, as far as the user's trust goes.
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
122#[serde(rename_all = "snake_case")]
123pub enum ScriptTrust {
124    /// The embedded Lua is sandboxed: nothing to trust.
125    #[default]
126    NotNeeded,
127    Trusted,
128    /// Nobody trusted this exact text yet.
129    Untrusted,
130}
131
132/// The largest window a script may ask for.
133pub const MAX_WINDOW: u8 = 50;
134
135/// What a script is called on.
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(rename_all = "snake_case")]
138pub enum ScriptKind {
139    Commit,
140    Blob,
141    Tag,
142}
143
144/// The type of a parameter row in the rule form.
145#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
146#[serde(rename_all = "snake_case")]
147pub enum ParamKind {
148    Text,
149    Number,
150    Bool,
151}
152
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
154pub struct ScriptParam {
155    pub name: String,
156    pub kind: ParamKind,
157    pub label: String,
158    /// Used when the rule gives no value.
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub default: Option<String>,
161}
162
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
164pub struct ScriptHeader {
165    pub name: String,
166    pub kinds: Vec<ScriptKind>,
167    /// Commits before / after the current one given to the script (0..=50).
168    pub window: u8,
169    /// Extra data the script asks for: `changes`, `path`, `binary`.
170    pub needs: Vec<String>,
171    pub params: Vec<ScriptParam>,
172}
173
174impl Default for ScriptHeader {
175    fn default() -> Self {
176        Self {
177            name: String::new(),
178            kinds: vec![ScriptKind::Commit],
179            window: 0,
180            needs: Vec::new(),
181            params: Vec::new(),
182        }
183    }
184}
185
186impl ScriptHeader {
187    /// The value of every declared parameter: the rule's, else the default,
188    /// else empty (a bool defaults to `false`, a number to `0`).
189    pub fn resolve_params(
190        &self,
191        given: &BTreeMap<String, String>,
192    ) -> Result<BTreeMap<String, String>, String> {
193        for name in given.keys() {
194            if !self.params.iter().any(|p| &p.name == name) {
195                return Err(format!("the script declares no parameter `{name}`"));
196            }
197        }
198        let mut out = BTreeMap::new();
199        for p in &self.params {
200            let value = given
201                .get(&p.name)
202                .cloned()
203                .or_else(|| p.default.clone())
204                .unwrap_or_else(|| match p.kind {
205                    ParamKind::Text => String::new(),
206                    ParamKind::Number => "0".into(),
207                    ParamKind::Bool => "false".into(),
208                });
209            match p.kind {
210                ParamKind::Number if value.trim().parse::<f64>().is_err() => {
211                    return Err(format!("parameter `{}` is not a number", p.name))
212                }
213                ParamKind::Bool if value != "true" && value != "false" => {
214                    return Err(format!("parameter `{}` is not true or false", p.name))
215                }
216                _ => {}
217            }
218            out.insert(p.name.clone(), value);
219        }
220        Ok(out)
221    }
222
223    /// The text parameters that have neither a value nor a default.
224    pub fn missing_params(&self, given: &BTreeMap<String, String>) -> Vec<String> {
225        self.params
226            .iter()
227            .filter(|p| p.kind == ParamKind::Text && p.default.is_none())
228            .filter(|p| given.get(&p.name).is_none_or(|v| v.is_empty()))
229            .map(|p| p.name.clone())
230            .collect()
231    }
232}
233
234const PREFIX: &str = "--!";
235const HASH_PREFIX: &str = "#!";
236
237/// Reads the header of a Lua script: the `--!` lines at the top (blank lines
238/// and plain comments before them are skipped). A problem names the line.
239pub fn parse_header(script: &str) -> Result<ScriptHeader, String> {
240    parse_header_for(ScriptLanguage::Lua, script)
241}
242
243/// Reads the header of a script in `language`. Lua (embedded or external)
244/// uses `--!` lines; shell and Python use `#!` lines (`#! name: ...`), and a
245/// shebang (`#!/bin/sh`, `#!/usr/bin/env python3`) or any other `#` comment is
246/// skipped like a plain comment.
247pub fn parse_header_for(language: ScriptLanguage, script: &str) -> Result<ScriptHeader, String> {
248    let hash = matches!(language, ScriptLanguage::Shell | ScriptLanguage::Python);
249    let (prefix, plain) = if hash {
250        (HASH_PREFIX, "#")
251    } else {
252        (PREFIX, "--")
253    };
254    let mut header = ScriptHeader::default();
255    for (n, raw) in script.lines().enumerate() {
256        let line = raw.trim();
257        let is_shebang = hash && line.starts_with("#!") && line[2..].trim_start().starts_with('/');
258        let Some(body) = line.strip_prefix(prefix).filter(|_| !is_shebang) else {
259            if line.is_empty() || line.starts_with(plain) {
260                continue;
261            }
262            break;
263        };
264        let at = |msg: String| format!("header line {}: {msg}", n + 1);
265        let body = body.trim();
266        if let Some(param) = body.strip_prefix("param ") {
267            let p = parse_param(param).map_err(at)?;
268            if header.params.iter().any(|q| q.name == p.name) {
269                return Err(at(format!("parameter `{}` is declared twice", p.name)));
270            }
271            header.params.push(p);
272            continue;
273        }
274        let Some((key, value)) = body.split_once(':') else {
275            return Err(at(format!("expected `key: value`, got `{body}`")));
276        };
277        let value = value.trim();
278        match key.trim() {
279            "name" => header.name = value.to_string(),
280            "kinds" => {
281                header.kinds = list(value)
282                    .into_iter()
283                    .map(|k| match k.as_str() {
284                        "commit" => Ok(ScriptKind::Commit),
285                        "blob" => Ok(ScriptKind::Blob),
286                        "tag" => Ok(ScriptKind::Tag),
287                        other => Err(at(format!("unknown kind `{other}`"))),
288                    })
289                    .collect::<Result<_, _>>()?;
290                if header.kinds.is_empty() {
291                    return Err(at("`kinds` is empty".into()));
292                }
293            }
294            "window" => {
295                let w: u8 = value
296                    .parse()
297                    .map_err(|_| at(format!("`window` is not a number: `{value}`")))?;
298                if w > MAX_WINDOW {
299                    return Err(at(format!("`window` is at most {MAX_WINDOW}")));
300                }
301                header.window = w;
302            }
303            "needs" => {
304                header.needs = list(value);
305                if let Some(bad) = header
306                    .needs
307                    .iter()
308                    .find(|n| !matches!(n.as_str(), "changes" | "path" | "binary" | "blobs"))
309                {
310                    return Err(at(format!("unknown need `{bad}`")));
311                }
312            }
313            other => return Err(at(format!("unknown header key `{other}`"))),
314        }
315    }
316    Ok(header)
317}
318
319/// `a, b` or `[a, b]` or `["a", "b"]`.
320fn list(value: &str) -> Vec<String> {
321    value
322        .trim()
323        .trim_start_matches('[')
324        .trim_end_matches(']')
325        .split(',')
326        .map(|s| s.trim().trim_matches('"').trim().to_string())
327        .filter(|s| !s.is_empty())
328        .collect()
329}
330
331/// `name: kind "label" = default`.
332fn parse_param(text: &str) -> Result<ScriptParam, String> {
333    let (name, rest) = text
334        .split_once(':')
335        .ok_or_else(|| format!("expected `param name: kind \"label\"`, got `{text}`"))?;
336    let name = name.trim();
337    if name.is_empty()
338        || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
339        || name.starts_with(|c: char| c.is_ascii_digit())
340    {
341        return Err(format!("`{name}` is not a valid parameter name"));
342    }
343    let rest = rest.trim();
344    let (kind_word, rest) = rest.split_once(char::is_whitespace).unwrap_or((rest, ""));
345    let kind = match kind_word {
346        "text" => ParamKind::Text,
347        "number" => ParamKind::Number,
348        "bool" => ParamKind::Bool,
349        other => return Err(format!("unknown parameter kind `{other}`")),
350    };
351    let rest = rest.trim();
352    let (label, rest) = match rest.strip_prefix('"') {
353        Some(after) => {
354            let end = after
355                .find('"')
356                .ok_or_else(|| "the label has no closing quote".to_string())?;
357            (after[..end].to_string(), after[end + 1..].trim())
358        }
359        None => (name.to_string(), rest),
360    };
361    let default = match rest {
362        "" => None,
363        r => Some(
364            r.strip_prefix('=')
365                .ok_or_else(|| format!("unexpected `{r}` after the label"))?
366                .trim()
367                .trim_matches('"')
368                .to_string(),
369        ),
370    };
371    Ok(ScriptParam {
372        name: name.to_string(),
373        kind,
374        label,
375        default,
376    })
377}
378
379/// What `rewrite_script_check` found: the header, the functions the script
380/// defines and everything wrong with it (an empty `problems` is a script the
381/// engine accepts). A syntax error is a problem, not an error, so an editor
382/// can show it live.
383#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
384pub struct ScriptCheck {
385    pub header: ScriptHeader,
386    /// `rewrite_commit`, ... as defined by the script.
387    pub functions: Vec<String>,
388    pub problems: Vec<String>,
389    /// External scripts: the content hash trust is keyed by.
390    #[serde(default, skip_serializing_if = "Option::is_none")]
391    pub hash: Option<String>,
392    #[serde(default)]
393    pub trust: ScriptTrust,
394    /// External scripts: the program that will run it (when one was found).
395    #[serde(default, skip_serializing_if = "Option::is_none")]
396    pub interpreter: Option<String>,
397}
398
399impl ScriptCheck {
400    pub fn ok(&self) -> bool {
401        self.problems.is_empty()
402    }
403}
404
405/// One tested commit: what the script would change. Nothing is written.
406#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
407pub struct ScriptTestRow {
408    pub commit: Oid,
409    pub fields: Vec<FieldChange>,
410    /// The script's `log(text)` lines for this commit.
411    pub log: Vec<String>,
412}
413
414/// The detail of `RewriteRefusal::ScriptFailed`: `<commit hex>: <reason>`,
415/// or only the reason when no commit was running (compile errors).
416pub fn script_failure(commit: Option<Oid>, reason: &str) -> String {
417    match commit {
418        Some(c) => format!("{}: {reason}", c.to_hex()),
419        None => reason.to_string(),
420    }
421}
422
423/// Splits [`script_failure`] again.
424pub fn parse_script_failure(detail: &str) -> (Option<Oid>, String) {
425    if let Some((head, rest)) = detail.split_once(": ") {
426        if head.len() == 40 {
427            if let Some(oid) = Oid::from_hex(head) {
428                return (Some(oid), rest.to_string());
429            }
430        }
431    }
432    (None, detail.to_string())
433}
434
435#[cfg(test)]
436mod tests {
437    use super::*;
438
439    const SAMPLE: &str = "\
440--! name: Replace an email
441--! kinds: commit
442--! window: 3
443--! needs: [changes]
444--! param old_email: text \"Email to replace\"
445--! param count: number \"How many\" = 5
446--! param dry: bool
447-- ordinary comment
448function rewrite_commit(c, ctx) end
449--! name: ignored after code
450";
451
452    #[test]
453    fn parses_every_header_line() {
454        let h = parse_header(SAMPLE).unwrap();
455        assert_eq!(h.name, "Replace an email");
456        assert_eq!(h.kinds, vec![ScriptKind::Commit]);
457        assert_eq!(h.window, 3);
458        assert_eq!(h.needs, vec!["changes"]);
459        assert_eq!(h.params.len(), 3);
460        assert_eq!(h.params[0].label, "Email to replace");
461        assert_eq!(h.params[1].default.as_deref(), Some("5"));
462        assert_eq!(h.params[2].label, "dry");
463    }
464
465    #[test]
466    fn a_script_without_header_gets_defaults() {
467        let h = parse_header("function rewrite_commit() end").unwrap();
468        assert_eq!(h, ScriptHeader::default());
469    }
470
471    #[test]
472    fn rejects_bad_headers_with_the_line() {
473        for (text, needle) in [
474            ("--! window: 99", "header line 1"),
475            ("--! window: x", "not a number"),
476            ("--! kinds: movie", "unknown kind"),
477            ("--! bogus: 1", "unknown header key"),
478            ("--! param 1x: text", "valid parameter name"),
479            ("--! param a: blob", "unknown parameter kind"),
480            ("--! param a: text\n--! param a: text", "declared twice"),
481            ("--! needs: [sudo]", "unknown need"),
482        ] {
483            let e = parse_header(text).unwrap_err();
484            assert!(e.contains(needle), "{text}: {e}");
485        }
486    }
487
488    #[test]
489    fn resolves_params_with_defaults_and_types() {
490        let h = parse_header(SAMPLE).unwrap();
491        let mut given = BTreeMap::new();
492        given.insert("old_email".to_string(), "a@b".to_string());
493        let got = h.resolve_params(&given).unwrap();
494        assert_eq!(got["count"], "5");
495        assert_eq!(got["dry"], "false");
496        given.insert("count".into(), "many".into());
497        assert!(h.resolve_params(&given).unwrap_err().contains("number"));
498        given.insert("count".into(), "1".into());
499        given.insert("nope".into(), "1".into());
500        assert!(h.resolve_params(&given).unwrap_err().contains("nope"));
501        assert_eq!(h.missing_params(&BTreeMap::new()), vec!["old_email"]);
502    }
503
504    #[test]
505    fn failure_text_round_trips() {
506        let oid = Oid([7; 20]);
507        let text = script_failure(Some(oid), "too long");
508        assert_eq!(parse_script_failure(&text), (Some(oid), "too long".into()));
509        assert_eq!(
510            parse_script_failure("syntax error: x"),
511            (None, "syntax error: x".into())
512        );
513    }
514}
515
516#[cfg(test)]
517mod external_tests {
518    use super::*;
519
520    #[test]
521    fn hash_headers_skip_the_shebang_and_read_hash_bang_lines() {
522        let text = "#!/bin/sh\n#! name: Rename\n# a plain comment\n#! window: 2\n#! param who: text \"Who\"\necho hi\n#! name: ignored after code\n";
523        for language in [ScriptLanguage::Shell, ScriptLanguage::Python] {
524            let h = parse_header_for(language, text).unwrap();
525            assert_eq!(h.name, "Rename", "{language:?}");
526            assert_eq!(h.window, 2);
527            assert_eq!(h.params.len(), 1);
528        }
529        // `--!` is the Lua prefix, and a `#!` line is not a header there.
530        assert!(parse_header_for(ScriptLanguage::Lua, text)
531            .unwrap()
532            .name
533            .is_empty());
534        let lua = "--! name: Lua one\nreturn\n";
535        assert_eq!(
536            parse_header_for(ScriptLanguage::LuaExternal, lua)
537                .unwrap()
538                .name,
539            "Lua one"
540        );
541        // A shebang with a space before the path is still a shebang.
542        let spaced = "#! /usr/bin/env python3\n#! name: X\n";
543        assert_eq!(
544            parse_header_for(ScriptLanguage::Python, spaced)
545                .unwrap()
546                .name,
547            "X"
548        );
549        // A bad header line in a hash script names the line.
550        let err = parse_header_for(ScriptLanguage::Shell, "#!/bin/sh\n#! nonsense\n").unwrap_err();
551        assert!(err.contains("header line 2"), "{err}");
552    }
553
554    #[test]
555    fn the_hash_is_of_the_exact_text() {
556        assert_eq!(
557            script_hash(""),
558            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
559        );
560        assert_ne!(script_hash("a\n"), script_hash("a"));
561        assert_eq!(script_hash("x"), script_hash("x"));
562    }
563
564    #[test]
565    fn the_policy_follows_the_settings_and_trusts_by_hash() {
566        let p = ScriptPolicy::from_settings(&["shell".into(), "Python".into()], 0, 0);
567        assert!(p.shell && p.python && !p.lua);
568        assert_eq!(p.timeout_ms, DEFAULT_SCRIPT_TIMEOUT_MS);
569        assert_eq!(p.total_timeout_s, DEFAULT_SCRIPT_TOTAL_TIMEOUT_S);
570        assert!(
571            p.allows(ScriptLanguage::Lua),
572            "the embedded Lua is always on"
573        );
574        assert!(p.allows(ScriptLanguage::Python) && !p.allows(ScriptLanguage::LuaExternal));
575        let off = ScriptPolicy::from_settings(&[], 10, 20);
576        assert!(!off.shell && off.timeout_ms == 10 && off.total_timeout_s == 20);
577        let mut p = ScriptPolicy::default();
578        assert!(p.shell && !p.python && !p.lua && p.is_default());
579        p.trusted.push(script_hash("a"));
580        assert!(p.trusts(&script_hash("a")) && !p.trusts(&script_hash("b")));
581        assert!(!p.is_default());
582    }
583
584    #[test]
585    fn languages_have_names_settings_and_extensions() {
586        for language in ScriptLanguage::ALL {
587            assert_eq!(ScriptLanguage::from_name(language.name()), Some(language));
588        }
589        assert!(!ScriptLanguage::Lua.is_external());
590        assert!(ScriptLanguage::Shell.is_external());
591        assert_eq!(ScriptLanguage::Lua.setting_name(), None);
592        assert_eq!(ScriptLanguage::LuaExternal.setting_name(), Some("lua"));
593        assert_eq!(
594            ScriptLanguage::from_extension("a/b.PS1"),
595            Some(ScriptLanguage::Shell)
596        );
597        assert_eq!(
598            ScriptLanguage::from_extension("x.py"),
599            Some(ScriptLanguage::Python)
600        );
601        assert_eq!(ScriptLanguage::from_extension("x"), None);
602        // The wire names.
603        assert_eq!(
604            serde_json::to_string(&ScriptLanguage::LuaExternal).unwrap(),
605            "\"lua_external\""
606        );
607    }
608
609    #[test]
610    fn a_recipe_saved_forgets_its_policy() {
611        use super::super::{Recipe, Scope};
612        let mut r = Recipe::new("x", Scope::default(), Vec::new());
613        r.script_policy.python = true;
614        r.script_policy.trusted.push("aa".into());
615        assert!(r.saved().script_policy.is_default());
616        let json = serde_json::to_string(&r.saved()).unwrap();
617        assert!(!json.contains("script_policy"), "{json}");
618    }
619}