Skip to main content

kian_plugin/hooks/sidecar/
manifest.rs

1//! The sidecar manifest (PLUGIN-SPEC §6.1, closed TOML) and §6.2's
2//! fourteen per-instance validation rules.
3//!
4//! The manifest grammar is a **closed subset** of TOML: the four sections
5//! `[plugin]`, `[process]`, `[grants]`, `[limits]`, their fixed keys, and
6//! value forms basic-string / integer / boolean / array-of-basic-strings
7//! (plus comments). Anything else is `malformed_manifest` (rule 1,
8//! deny-unknown-fields). The parser is hand-rolled because the round's
9//! one allowed new dependency is `sha2` (K10) — no `toml` edge exists and
10//! none may be added; a closed grammar needs none of a general parser's
11//! power, and refusing the general grammar is the point of rule 1.
12//!
13//! Validation is **per instance, fail-closed, no repair** (§6.2): every
14//! refusal names the offender and the `plugin/refuse` code, and the
15//! `required` flag a parsed manifest did carry (or `unknown` when the
16//! file could not be parsed far enough to read one). One broken instance
17//! never unmounts the others; which instances exist at all is the
18//! config surface's question (P3b), not this module's.
19
20use std::path::{Path, PathBuf};
21
22use super::super::grants::{Grant, GrantSet};
23use super::super::ids::HookId;
24
25/// Context the caller (boot assembly, P3b) supplies for the rules this
26/// crate cannot decide alone: which names are already taken (rule 3 —
27/// `KNOWN_PLUGINS`, tier-0 plugin names, sibling instance keys) and
28/// which environment names are kian secrets (rule 7).
29#[derive(Debug, Clone, Default)]
30pub struct ValidationCtx<'a> {
31    /// The `sidecars.plugins` instance key this manifest is mounted as
32    /// (rule 2: `[plugin].name` must equal it).
33    pub instance_key: &'a str,
34    /// Names a new instance may not take (rule 3).
35    pub reserved_names: &'a [String],
36    /// Kian secret environment variable names `env_allow` may not carry
37    /// (rule 7, §10.4).
38    pub secret_env: &'a [String],
39}
40
41/// The `plugin/refuse` code set (§6.2's table).
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum RefusalCode {
44    MalformedManifest,
45    NameInvalid,
46    NameCollision,
47    MissingBinary,
48    DigestMismatch,
49    UnknownHook,
50    UnknownCapability,
51    GrantMismatch,
52    AbiMismatch,
53    ReadyMismatch,
54    SpawnFailed,
55}
56
57impl RefusalCode {
58    pub fn as_str(self) -> &'static str {
59        match self {
60            RefusalCode::MalformedManifest => "malformed_manifest",
61            RefusalCode::NameInvalid => "name_invalid",
62            RefusalCode::NameCollision => "name_collision",
63            RefusalCode::MissingBinary => "missing_binary",
64            RefusalCode::DigestMismatch => "digest_mismatch",
65            RefusalCode::UnknownHook => "unknown_hook",
66            RefusalCode::UnknownCapability => "unknown_capability",
67            RefusalCode::GrantMismatch => "grant_mismatch",
68            RefusalCode::AbiMismatch => "abi_mismatch",
69            RefusalCode::ReadyMismatch => "ready_mismatch",
70            RefusalCode::SpawnFailed => "spawn_failed",
71        }
72    }
73}
74
75/// Whether the refused instance declared itself `required` (§6.2): a
76/// manifest that cannot be parsed cannot declare anything, so the audit
77/// line says `required=unknown` rather than guessing.
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub enum Required {
80    True,
81    False,
82    Unknown,
83}
84
85/// One per-instance refusal: the code, a message naming the offender,
86/// and the `required` value the instance did (or could not) declare.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct Refusal {
89    pub code: RefusalCode,
90    pub message: String,
91    pub required: Required,
92}
93
94impl Refusal {
95    fn new(code: RefusalCode, message: String, required: Required) -> Self {
96        Self {
97            code,
98            message,
99            required,
100        }
101    }
102}
103
104/// The accepted `abi` set (§7.3: grows additively only; v1 = `{1}`).
105pub const ACCEPTED_ABI: &[u32] = &[1];
106
107// ---------------------------------------------------------------------
108// §6.1 sections
109// ---------------------------------------------------------------------
110
111/// `[plugin]` (§6.1).
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct PluginSection {
114    pub name: String,
115    pub version: String,
116    pub abi: u32,
117    pub order: i32,
118    pub required: bool,
119}
120
121/// `[process]` (§6.1).
122#[derive(Debug, Clone, PartialEq, Eq)]
123pub struct ProcessSection {
124    pub argv: Vec<String>,
125    pub sha256: String,
126    pub cwd: Option<PathBuf>,
127    pub env_allow: Vec<String>,
128    pub startup_timeout_ms: u64,
129}
130
131/// `[grants]` (§6.1).
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct GrantsSection {
134    pub hooks: Vec<HookId>,
135    pub grants: GrantSet,
136}
137
138/// `[limits]` (§6.1) — every value already inside its clamp.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub struct LimitsSection {
141    pub deadline_ms: u64,
142    pub max_payload_kib: u64,
143    pub restarts_per_window: u64,
144    pub restart_window_ms: u64,
145    pub max_settle_vetoes: u64,
146    pub max_stderr_line_kib: u64,
147    pub stderr_rate_kib_per_min: u64,
148}
149
150impl Default for LimitsSection {
151    fn default() -> Self {
152        Self {
153            deadline_ms: 500,
154            max_payload_kib: 256,
155            restarts_per_window: 3,
156            restart_window_ms: 60_000,
157            // §6.1: the settle budget's default is 3 (n2) — an
158            // explicit `0` in a manifest disables the gate, but the
159            // struct default must never carry 0 or any future
160            // `..LimitsSection::default()` silently re-creates the M1
161            // bug (a disabled gate where §6.1 mandates 3).
162            max_settle_vetoes: super::super::bus::DEFAULT_MAX_SETTLE_VETOS,
163            max_stderr_line_kib: 8,
164            stderr_rate_kib_per_min: 1024,
165        }
166    }
167}
168
169impl LimitsSection {
170    /// §7.6's wire bound in bytes (`max_payload_kib`).
171    pub fn max_frame_bytes(&self) -> usize {
172        (self.max_payload_kib as usize) * 1024
173    }
174}
175
176/// A parsed, validated manifest (§6.1).
177#[derive(Debug, Clone, PartialEq, Eq)]
178pub struct Manifest {
179    pub plugin: PluginSection,
180    pub process: ProcessSection,
181    pub grants: GrantsSection,
182    pub limits: LimitsSection,
183}
184
185impl Manifest {
186    /// The manifest's own declared `required` (§6.2).
187    pub fn required(&self) -> Required {
188        if self.plugin.required {
189            Required::True
190        } else {
191            Required::False
192        }
193    }
194}
195
196// ---------------------------------------------------------------------
197// Closed-TOML subset parser (rule 1's deny-unknown-fields substrate)
198// ---------------------------------------------------------------------
199
200#[derive(Debug, Clone, PartialEq)]
201enum RawValue {
202    Str(String),
203    Int(i64),
204    Bool(bool),
205    Arr(Vec<String>),
206}
207
208impl RawValue {
209    fn type_name(&self) -> &'static str {
210        match self {
211            RawValue::Str(_) => "string",
212            RawValue::Int(_) => "integer",
213            RawValue::Bool(_) => "boolean",
214            RawValue::Arr(_) => "array",
215        }
216    }
217}
218
219/// One raw `section.key = value` triple in file order.
220struct RawEntry {
221    section: String,
222    key: String,
223    value: RawValue,
224    line: usize,
225}
226
227fn parse_raw(text: &str) -> Result<Vec<RawEntry>, String> {
228    let mut entries = Vec::new();
229    let mut section = String::new();
230    for (index, raw_line) in text.lines().enumerate() {
231        let line = raw_line.trim();
232        if line.is_empty() || line.starts_with('#') {
233            continue;
234        }
235        if let Some(header) = line.strip_prefix('[') {
236            let name = header
237                .strip_suffix(']')
238                .ok_or_else(|| format!("line {}: unterminated section header", index + 1))?;
239            let name = name.trim();
240            if name.is_empty() || name.contains('[') || name.contains(']') {
241                return Err(format!("line {}: malformed section header", index + 1));
242            }
243            section = name.to_string();
244            continue;
245        }
246        let (key, value) = line
247            .split_once('=')
248            .ok_or_else(|| format!("line {}: expected `key = value` or `[section]`", index + 1))?;
249        let key = key.trim().to_string();
250        if key.is_empty() {
251            return Err(format!("line {}: empty key", index + 1));
252        }
253        let value = parse_value(value.trim()).map_err(|e| format!("line {}: {e}", index + 1))?;
254        if entries
255            .iter()
256            .any(|e: &RawEntry| e.section == section && e.key == key)
257        {
258            return Err(format!("line {}: duplicate key `{key}`", index + 1));
259        }
260        entries.push(RawEntry {
261            section: section.clone(),
262            key,
263            value,
264            line: index + 1,
265        });
266    }
267    Ok(entries)
268}
269
270/// Parses one closed-subset value: basic string, integer, boolean, or an
271/// array of basic strings. A trailing comment is allowed outside
272/// strings. Everything else — multiline strings, literal strings,
273/// dotted keys, floats, heterogeneous arrays — is out of the closed
274/// grammar and therefore `malformed_manifest`.
275fn parse_value(text: &str) -> Result<RawValue, String> {
276    let text = strip_trailing_comment(text)?;
277    match text.as_bytes().first() {
278        Some(b'"') => parse_basic_string(&text).map(RawValue::Str),
279        Some(b'[') => parse_string_array(&text).map(RawValue::Arr),
280        Some(b't' | b'f') if text == "true" || text == "false" => {
281            Ok(RawValue::Bool(text == "true"))
282        }
283        Some(c) if c.is_ascii_digit() || *c == b'-' => text
284            .parse::<i64>()
285            .map(RawValue::Int)
286            .map_err(|_| format!("`{text}` is not an integer")),
287        _ => Err(format!(
288            "`{text}` is not one of string / integer / boolean / array"
289        )),
290    }
291}
292
293fn strip_trailing_comment(text: &str) -> Result<String, String> {
294    let mut out = String::new();
295    let mut in_string = false;
296    let mut escaped = false;
297    for ch in text.chars() {
298        if in_string {
299            out.push(ch);
300            if escaped {
301                escaped = false;
302            } else if ch == '\\' {
303                escaped = true;
304            } else if ch == '"' {
305                in_string = false;
306            }
307            continue;
308        }
309        match ch {
310            '"' => {
311                in_string = true;
312                out.push(ch);
313            }
314            '#' => return Ok(out.trim_end().to_string()),
315            _ => out.push(ch),
316        }
317    }
318    if in_string {
319        return Err("unterminated string".to_string());
320    }
321    Ok(out.trim_end().to_string())
322}
323
324fn parse_basic_string(text: &str) -> Result<String, String> {
325    let inner = text
326        .strip_prefix('"')
327        .and_then(|t| t.strip_suffix('"'))
328        .ok_or_else(|| format!("`{text}` is not a basic string"))?;
329    // Unescape exactly \" and \\ — the closed grammar's two escapes.
330    let mut out = String::with_capacity(inner.len());
331    let mut chars = inner.chars();
332    while let Some(ch) = chars.next() {
333        match ch {
334            '\\' => match chars.next() {
335                Some('"') => out.push('"'),
336                Some('\\') => out.push('\\'),
337                other => {
338                    return Err(format!(
339                        "unsupported escape `\\{}` (only `\\\"` and `\\\\` exist)",
340                        other.unwrap_or(' ')
341                    ));
342                }
343            },
344            '"' => return Err("unescaped quote inside string".to_string()),
345            c if c.is_control() => return Err("control character in string".to_string()),
346            c => out.push(c),
347        }
348    }
349    Ok(out)
350}
351
352fn parse_string_array(text: &str) -> Result<Vec<String>, String> {
353    let inner = text
354        .strip_prefix('[')
355        .and_then(|t| t.strip_suffix(']'))
356        .ok_or_else(|| format!("`{text}` is not an array"))?;
357    let inner = inner.trim();
358    if inner.is_empty() {
359        return Ok(Vec::new());
360    }
361    let mut items = Vec::new();
362    for part in split_top_level(inner)? {
363        let part = part.trim();
364        if part.is_empty() {
365            return Err("empty array element".to_string());
366        }
367        items.push(parse_basic_string(part)?);
368    }
369    Ok(items)
370}
371
372fn split_top_level(text: &str) -> Result<Vec<String>, String> {
373    let mut parts = Vec::new();
374    let mut current = String::new();
375    let mut in_string = false;
376    let mut escaped = false;
377    for ch in text.chars() {
378        if in_string {
379            current.push(ch);
380            if escaped {
381                escaped = false;
382            } else if ch == '\\' {
383                escaped = true;
384            } else if ch == '"' {
385                in_string = false;
386            }
387            continue;
388        }
389        match ch {
390            '"' => {
391                in_string = true;
392                current.push(ch);
393            }
394            ',' => {
395                parts.push(current.clone());
396                current.clear();
397            }
398            _ => current.push(ch),
399        }
400    }
401    if in_string {
402        return Err("unterminated string in array".to_string());
403    }
404    parts.push(current);
405    Ok(parts)
406}
407
408// ---------------------------------------------------------------------
409// §6.2 validation — the fourteen rules, in table order
410// ---------------------------------------------------------------------
411
412/// Parses and validates one instance manifest (§6.2). Every failure is
413/// a typed [`Refusal`] naming the offender; there is no repair and no
414/// default that invents a missing field's intent (optional fields carry
415/// documented defaults; required fields do not).
416pub fn parse_manifest(text: &str, ctx: &ValidationCtx<'_>) -> Result<Manifest, Refusal> {
417    let malformed =
418        |message: String| Refusal::new(RefusalCode::MalformedManifest, message, Required::Unknown);
419    let entries = parse_raw(text).map_err(|e| malformed(format!("parse error: {e}")))?;
420
421    // ---- rule 1: deny-unknown-fields (unknown section or key) ----
422    let known = |section: &str, key: &str| -> bool {
423        match section {
424            "plugin" => matches!(key, "name" | "version" | "abi" | "order" | "required"),
425            "process" => matches!(
426                key,
427                "argv" | "sha256" | "cwd" | "env_allow" | "startup_timeout_ms"
428            ),
429            "grants" => matches!(key, "hooks" | "capabilities"),
430            "limits" => matches!(
431                key,
432                "deadline_ms"
433                    | "max_payload_kib"
434                    | "restarts_per_window"
435                    | "restart_window_ms"
436                    | "max_settle_vetoes"
437                    | "max_stderr_line_kib"
438                    | "stderr_rate_kib_per_min"
439            ),
440            _ => false,
441        }
442    };
443    for entry in &entries {
444        if !known(&entry.section, &entry.key) {
445            let where_ = if entry.section.is_empty() {
446                String::new()
447            } else {
448                format!("[{}].", entry.section)
449            };
450            return Err(malformed(format!(
451                "unknown key `{where_}{}` (line {}): the manifest grammar is closed",
452                entry.key, entry.line
453            )));
454        }
455    }
456    // Entries before any section header are not part of the grammar.
457    if entries.iter().any(|e| e.section.is_empty()) {
458        return Err(malformed(
459            "keys before the first `[section]` header".to_string(),
460        ));
461    }
462    for section in ["plugin", "process", "grants", "limits"] {
463        if !entries.iter().any(|e| e.section == section) {
464            return Err(malformed(format!("missing section `[{section}]`")));
465        }
466    }
467
468    // Typed extraction. Wrong types are malformed (rule 4 for
469    // `order`/`required`; rule 1's spirit for the rest — a closed
470    // schema has no coercion).
471    let find = |section: &str, key: &str| -> Option<&RawValue> {
472        entries
473            .iter()
474            .find(|e| e.section == section && e.key == key)
475            .map(|e| &e.value)
476    };
477    let typed_str = |section: &str, key: &str| -> Result<String, Refusal> {
478        match find(section, key) {
479            Some(RawValue::Str(s)) => Ok(s.clone()),
480            Some(other) => Err(malformed(format!(
481                "[{section}].{key} must be a string, got {}",
482                other.type_name()
483            ))),
484            None => Err(malformed(format!(
485                "missing required key `[{section}].{key}`"
486            ))),
487        }
488    };
489    let typed_int = |section: &str, key: &str| -> Result<Option<i64>, Refusal> {
490        match find(section, key) {
491            Some(RawValue::Int(v)) => Ok(Some(*v)),
492            Some(other) => Err(malformed(format!(
493                "[{section}].{key} must be an integer, got {}",
494                other.type_name()
495            ))),
496            None => Ok(None),
497        }
498    };
499    let typed_bool = |section: &str, key: &str| -> Result<Option<bool>, Refusal> {
500        match find(section, key) {
501            Some(RawValue::Bool(v)) => Ok(Some(*v)),
502            Some(other) => Err(malformed(format!(
503                "[{section}].{key} must be a boolean, got {}",
504                other.type_name()
505            ))),
506            None => Ok(None),
507        }
508    };
509    let typed_arr = |section: &str, key: &str| -> Result<Option<Vec<String>>, Refusal> {
510        match find(section, key) {
511            Some(RawValue::Arr(v)) => Ok(Some(v.clone())),
512            Some(other) => Err(malformed(format!(
513                "[{section}].{key} must be an array of strings, got {}",
514                other.type_name()
515            ))),
516            None => Ok(None),
517        }
518    };
519
520    let name = typed_str("plugin", "name")?;
521    let version = typed_str("plugin", "version")?;
522    let abi = typed_int("plugin", "abi")?
523        .ok_or_else(|| malformed("missing required key `[plugin].abi`".to_string()))?;
524    let order_int = typed_int("plugin", "order")?;
525    let required = typed_bool("plugin", "required")?;
526    // Fail-closed default: an instance that does not say is one whose
527    // refusal must be fatal (§6.2's posture).
528    let required = required.unwrap_or(true);
529    // Rules past 2 get the parsed `required` value; a manifest that
530    // could not be parsed far enough to read one reports `unknown`
531    // (§6.2's boundary case).
532    let refuse = |code: RefusalCode, message: String| {
533        let required = if matches!(
534            code,
535            RefusalCode::MalformedManifest | RefusalCode::NameInvalid
536        ) {
537            Required::Unknown
538        } else if required {
539            Required::True
540        } else {
541            Required::False
542        };
543        Refusal::new(code, message, required)
544    };
545
546    // ---- rule 2: name grammar + instance-key equality ----
547    let valid_name = {
548        let mut chars = name.chars();
549        match chars.next() {
550            Some(c) if c.is_ascii_lowercase() || c.is_ascii_digit() => {
551                chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
552            }
553            _ => false,
554        }
555    };
556    if !valid_name || name.len() > 64 {
557        return Err(refuse(
558            RefusalCode::NameInvalid,
559            format!("`[plugin].name = \"{name}\" is not ^[a-z0-9][a-z0-9-]{{0,63}}$"),
560        ));
561    }
562    if name != ctx.instance_key {
563        return Err(refuse(
564            RefusalCode::NameInvalid,
565            format!(
566                "`[plugin].name = \"{name}\" does not equal the instance key `{}`",
567                ctx.instance_key
568            ),
569        ));
570    }
571
572    // ---- rule 3: name collisions ----
573    if ctx
574        .reserved_names
575        .iter()
576        .any(|reserved| reserved.as_str() == name)
577    {
578        return Err(refuse(
579            RefusalCode::NameCollision,
580            format!("`[plugin].name = \"{name}\" collides with a reserved name"),
581        ));
582    }
583
584    // ---- rule 4: semver, order/required types, accepted abi set ----
585    if !is_semver(&version) {
586        return Err(refuse(
587            RefusalCode::MalformedManifest,
588            format!("`[plugin].version = \"{version}\" is not semver"),
589        ));
590    }
591    let abi = u32::try_from(abi).map_err(|_| {
592        refuse(
593            RefusalCode::MalformedManifest,
594            format!("`[plugin].abi = {abi}` is out of range"),
595        )
596    })?;
597    if !ACCEPTED_ABI.contains(&abi) {
598        return Err(refuse(
599            RefusalCode::AbiMismatch,
600            format!("`[plugin].abi = {abi}` is outside the accepted set {{1}} (§7.3)"),
601        ));
602    }
603    let order = i32::try_from(order_int.unwrap_or(0)).map_err(|_| {
604        refuse(
605            RefusalCode::MalformedManifest,
606            format!(
607                "`[plugin].order = {}` is out of range",
608                order_int.unwrap_or(0)
609            ),
610        )
611    })?;
612
613    // ---- rule 5: argv ----
614    let argv = typed_arr("process", "argv")?
615        .ok_or_else(|| malformed("missing required key `[process].argv`".to_string()))?;
616    if argv.is_empty() {
617        return Err(refuse(
618            RefusalCode::MissingBinary,
619            "`[process].argv` is empty".to_string(),
620        ));
621    }
622    let argv0 = Path::new(&argv[0]);
623    if !argv0.is_absolute() {
624        return Err(refuse(
625            RefusalCode::MissingBinary,
626            format!(
627                "`argv[0] = \"{}` is not absolute — no PATH lookup, no shell",
628                argv[0]
629            ),
630        ));
631    }
632    match std::fs::metadata(argv0) {
633        Ok(meta) if meta.is_file() => {}
634        Ok(_) => {
635            return Err(refuse(
636                RefusalCode::MissingBinary,
637                format!("`argv[0] = \"{}\" is not a regular file", argv[0]),
638            ));
639        }
640        Err(e) => {
641            return Err(refuse(
642                RefusalCode::MissingBinary,
643                format!("`argv[0] = \"{}\" does not exist: {e}", argv[0]),
644            ));
645        }
646    }
647
648    // ---- rule 6: sha256 shape (the file digest itself is verified at
649    // spawn and every respawn, §10.3 step 6) ----
650    let sha256 = typed_str("process", "sha256")?;
651    if sha256.len() != 64
652        || !sha256
653            .bytes()
654            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
655    {
656        return Err(refuse(
657            RefusalCode::DigestMismatch,
658            format!("`[process].sha256 = \"{sha256}\" is not 64 lowercase hex digits"),
659        ));
660    }
661
662    // ---- rule 7: env_allow grammar, duplicates, kian secrets ----
663    let env_allow = typed_arr("process", "env_allow")?.unwrap_or_default();
664    let valid_env = |s: &str| {
665        let mut chars = s.chars();
666        matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_')
667            && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
668    };
669    for entry in &env_allow {
670        if !valid_env(entry) {
671            return Err(refuse(
672                RefusalCode::MalformedManifest,
673                format!("`env_allow` entry `{entry}` is not ^[A-Za-z_][A-Za-z0-9_]*$"),
674            ));
675        }
676        if env_allow.iter().filter(|e| *e == entry).count() > 1 {
677            return Err(refuse(
678                RefusalCode::MalformedManifest,
679                format!("`env_allow` entry `{entry}` is duplicated"),
680            ));
681        }
682        if ctx.secret_env.iter().any(|s| s == entry) {
683            return Err(refuse(
684                RefusalCode::MalformedManifest,
685                format!("`env_allow` entry `{entry}` names a kian secret variable"),
686            ));
687        }
688    }
689    let startup_timeout_ms =
690        u64::try_from(typed_int("process", "startup_timeout_ms")?.unwrap_or(2000))
691            .map_err(|_| malformed("`[process].startup_timeout_ms` is out of range".to_string()))?;
692    if !(100..=30_000).contains(&startup_timeout_ms) {
693        return Err(malformed(format!(
694            "`[process].startup_timeout_ms = {startup_timeout_ms}` is outside 100..=30000"
695        )));
696    }
697
698    // ---- rule 8: hooks in the catalog (harness/* registry is empty;
699    // plugin/* is bus-owned, never sidecar-subscribable) ----
700    let hook_names = typed_arr("grants", "hooks")?
701        .ok_or_else(|| malformed("missing required key `[grants].hooks`".to_string()))?;
702    let mut hooks = Vec::new();
703    for entry in &hook_names {
704        match HookId::parse(entry) {
705            Some(id) if id.sidecar_subscribable() && !matches!(id, HookId::Harness(_)) => {
706                hooks.push(id)
707            }
708            _ => {
709                return Err(refuse(
710                    RefusalCode::UnknownHook,
711                    format!("`[grants].hooks` entry `{entry}` is not sidecar-subscribable in v1"),
712                ));
713            }
714        }
715    }
716
717    // ---- rules 9/10: capabilities closed set + grant consistency ----
718    let capability_names = typed_arr("grants", "capabilities")?
719        .ok_or_else(|| malformed("missing required key `[grants].capabilities`".to_string()))?;
720    let grants = GrantSet::from_names(
721        &capability_names
722            .iter()
723            .map(String::as_str)
724            .collect::<Vec<_>>(),
725    )
726    .map_err(|e| match e {
727        super::super::grants::GrantError::UnknownCapability { name } => refuse(
728            RefusalCode::UnknownCapability,
729            format!("`[grants].capabilities` entry `{name}` is outside the §5.1 closed set"),
730        ),
731        super::super::grants::GrantError::MissingObserve { veto, observe } => refuse(
732            RefusalCode::GrantMismatch,
733            format!("grant `{veto}` requires its matching `{observe}` (§5.1)"),
734        ),
735    })?;
736    for hook in &hooks {
737        if !grants.observes_class(hook.class()) {
738            return Err(refuse(
739                RefusalCode::GrantMismatch,
740                format!(
741                    "subscribed hook `{hook}` has no matching `observe:{}` grant (§6.2 rule 10)",
742                    hook.class().as_str()
743                ),
744            ));
745        }
746    }
747    let veto_needs_subscription = |grant: Grant, hook: &HookId| -> bool {
748        match grant {
749            Grant::VetoAdmit => matches!(hook, HookId::AdmitPre),
750            Grant::VetoTool => matches!(hook, HookId::ToolPre),
751            Grant::VetoSettle => matches!(hook, HookId::SettlePre),
752            _ => false,
753        }
754    };
755    for grant in grants.iter() {
756        let is_veto = matches!(
757            grant,
758            Grant::VetoAdmit | Grant::VetoTool | Grant::VetoSettle
759        );
760        if is_veto
761            && !hooks
762                .iter()
763                .any(|hook| veto_needs_subscription(grant, hook))
764        {
765            return Err(refuse(
766                RefusalCode::GrantMismatch,
767                format!("grant `{grant}` has no subscribing veto-capable hook (§6.2 rule 10)"),
768            ));
769        }
770    }
771
772    // ---- rules 11: limits clamps ----
773    // §6.1: `max_settle_vetoes` defaults to 3 — the struct `Default`
774    // carries it (n2), so an absent key parses to 3 here too while an
775    // explicit `0` still disables the settle gate; every other key's
776    // default is the struct's.
777    let mut limits = LimitsSection::default();
778    let clamped = |key: &str, value: i64, range: (u64, u64)| -> Result<u64, Refusal> {
779        let value =
780            u64::try_from(value).map_err(|_| malformed(format!("`[limits].{key}` is negative")))?;
781        if !(range.0..=range.1).contains(&value) {
782            return Err(malformed(format!(
783                "`[limits].{key} = {value}` is outside {}..={}",
784                range.0, range.1
785            )));
786        }
787        Ok(value)
788    };
789    if let Some(v) = typed_int("limits", "deadline_ms")? {
790        limits.deadline_ms = clamped("deadline_ms", v, (50, 5_000))?;
791    }
792    if let Some(v) = typed_int("limits", "max_payload_kib")? {
793        limits.max_payload_kib = clamped("max_payload_kib", v, (16, 1_024))?;
794    }
795    if let Some(v) = typed_int("limits", "restarts_per_window")? {
796        limits.restarts_per_window = clamped("restarts_per_window", v, (1, 10))?;
797    }
798    if let Some(v) = typed_int("limits", "restart_window_ms")? {
799        limits.restart_window_ms = clamped("restart_window_ms", v, (1_000, 3_600_000))?;
800    }
801    if let Some(v) = typed_int("limits", "max_settle_vetoes")? {
802        limits.max_settle_vetoes = clamped("max_settle_vetoes", v, (0, 10))?;
803    }
804    if let Some(v) = typed_int("limits", "max_stderr_line_kib")? {
805        limits.max_stderr_line_kib = clamped("max_stderr_line_kib", v, (1, 64))?;
806    }
807    if let Some(v) = typed_int("limits", "stderr_rate_kib_per_min")? {
808        limits.stderr_rate_kib_per_min = clamped("stderr_rate_kib_per_min", v, (64, 65_536))?;
809    }
810
811    // ---- rule 14: cwd (boot-time configuration check, not a spawn
812    // step — the server never creates an operator-supplied directory) --
813    let cwd = match find("process", "cwd") {
814        Some(RawValue::Str(p)) => {
815            let path = PathBuf::from(p);
816            if !path.is_absolute() {
817                return Err(malformed(format!(
818                    "`[process].cwd = \"{p}\"` is not absolute"
819                )));
820            }
821            match std::fs::metadata(&path) {
822                Ok(meta) if meta.is_dir() => {}
823                Ok(_) => {
824                    return Err(malformed(format!(
825                        "`[process].cwd = \"{p}\" is not a directory"
826                    )));
827                }
828                Err(e) => {
829                    return Err(malformed(format!(
830                        "`[process].cwd = \"{p}\" is not usable: {e}"
831                    )));
832                }
833            }
834            // Readable and writable by the server's user: probe with a
835            // file the server itself creates and removes.
836            let probe = path.join(format!(".kian-cwd-probe-{}", std::process::id()));
837            match std::fs::write(&probe, b"") {
838                Ok(()) => {
839                    let _ = std::fs::remove_file(&probe);
840                }
841                Err(e) => {
842                    return Err(malformed(format!(
843                        "`[process].cwd = \"{p}\" is not writable: {e}"
844                    )));
845                }
846            }
847            Some(path)
848        }
849        Some(other) => {
850            return Err(malformed(format!(
851                "[process].cwd must be a string, got {}",
852                other.type_name()
853            )));
854        }
855        None => None,
856    };
857
858    Ok(Manifest {
859        plugin: PluginSection {
860            name,
861            version,
862            abi,
863            order,
864            required,
865        },
866        process: ProcessSection {
867            argv,
868            sha256,
869            cwd,
870            env_allow,
871            startup_timeout_ms,
872        },
873        grants: GrantsSection { hooks, grants },
874        limits,
875    })
876}
877
878/// `MAJOR.MINOR.PATCH` with optional pre-release/build (rule 4).
879fn is_semver(s: &str) -> bool {
880    let (core, rest) = match s.split_once(['-', '+']) {
881        Some((core, rest)) => (core, Some(rest)),
882        None => (s, None),
883    };
884    let mut parts = core.split('.');
885    let numeric = |p: Option<&str>| match p {
886        Some(p) => !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()),
887        None => false,
888    };
889    if !(numeric(parts.next()) && numeric(parts.next()) && numeric(parts.next())) {
890        return false;
891    }
892    if parts.next().is_some() {
893        return false;
894    }
895    match rest {
896        Some(rest) => {
897            !rest.is_empty()
898                && rest
899                    .bytes()
900                    .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-' || b == b'+')
901        }
902        None => true,
903    }
904}
905
906// `HookClass::as_str` does not exist on the P1 surface; the grant-
907// mismatch message needs the class spelling, so derive it locally.
908trait ClassSpell {
909    fn as_str(&self) -> &'static str;
910}
911
912impl ClassSpell for super::super::ids::HookClass {
913    fn as_str(&self) -> &'static str {
914        match self {
915            super::super::ids::HookClass::Admit => "admit",
916            super::super::ids::HookClass::Turn => "turn",
917            super::super::ids::HookClass::Tool => "tool",
918            super::super::ids::HookClass::Recover => "recover",
919            super::super::ids::HookClass::Settle => "settle",
920            super::super::ids::HookClass::Harness => "harness",
921            super::super::ids::HookClass::Plugin => "plugin",
922        }
923    }
924}
925
926#[cfg(test)]
927mod tests {
928    use super::*;
929
930    fn ctx<'a>() -> ValidationCtx<'a> {
931        ValidationCtx {
932            instance_key: "approval-gate",
933            reserved_names: &[],
934            secret_env: &[],
935        }
936    }
937
938    use crate::hooks::bus::DEFAULT_MAX_SETTLE_VETOS;
939
940    fn valid_toml() -> String {
941        [
942            "[plugin]",
943            "name = \"approval-gate\"",
944            "version = \"0.1.0\"",
945            "abi = 1",
946            "",
947            "[process]",
948            "argv = [\"/bin/cat\"]",
949            "sha256 = \"a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2\"",
950            "",
951            "[grants]",
952            "hooks = [\"tool/pre\", \"tool/post\"]",
953            "capabilities = [\"observe:tool\", \"veto:tool\"]",
954            "",
955            "[limits]",
956            "deadline_ms = 500",
957        ]
958        .iter()
959        .map(|l| format!("{l}\n"))
960        .collect()
961    }
962
963    #[test]
964    fn parses_the_spec_example() {
965        let manifest = parse_manifest(&valid_toml(), &ctx()).expect("valid manifest");
966        assert_eq!(manifest.plugin.name, "approval-gate");
967        assert_eq!(manifest.plugin.version, "0.1.0");
968        assert_eq!(manifest.plugin.abi, 1);
969        assert_eq!(manifest.plugin.order, 0, "order defaults to 0");
970        assert!(manifest.plugin.required, "required defaults fail-closed");
971        assert_eq!(manifest.process.argv, vec!["/bin/cat".to_string()]);
972        assert_eq!(manifest.limits.deadline_ms, 500);
973        assert_eq!(manifest.limits.max_payload_kib, 256, "limits default");
974        assert_eq!(manifest.grants.hooks.len(), 2);
975        assert!(manifest.grants.grants.contains(Grant::VetoTool));
976    }
977
978    /// n2: the struct `Default` carries §6.1's settle default, so no
979    /// future `..LimitsSection::default()` can silently disable the
980    /// settle gate; an absent key parses to 3, an explicit `0` is the
981    /// only way to disable.
982    #[test]
983    fn limits_default_carries_the_settle_budget() {
984        assert_eq!(
985            LimitsSection::default().max_settle_vetoes,
986            DEFAULT_MAX_SETTLE_VETOS,
987            "§6.1: Default must carry 3, never 0 (the M1 trap)"
988        );
989        // The `valid_toml()` fixture omits `max_settle_vetoes` — the
990        // absent key parses to the same default.
991        let manifest = parse_manifest(&valid_toml(), &ctx()).expect("valid manifest");
992        assert_eq!(
993            manifest.limits.max_settle_vetoes, DEFAULT_MAX_SETTLE_VETOS,
994            "an absent key parses to §6.1's 3"
995        );
996        // An explicit 0 is honored as "disabled" (clamped range 0..=10).
997        let disabled = valid_toml().replace("[limits]\n", "[limits]\nmax_settle_vetoes = 0\n");
998        let manifest = parse_manifest(&disabled, &ctx()).expect("valid manifest");
999        assert_eq!(manifest.limits.max_settle_vetoes, 0, "explicit 0 disables");
1000    }
1001
1002    #[test]
1003    fn rule_1_unknown_key_is_malformed() {
1004        for text in [
1005            valid_toml().replace("[plugin]\n", "[plugin]\nbogus = 1\n"),
1006            valid_toml().replace("[limits]\n", "[limits]\nretries = 9\n"),
1007            valid_toml().replace("[plugin]", "[plumbing]"),
1008        ] {
1009            let refusal = parse_manifest(&text, &ctx()).expect_err("unknown key refuses");
1010            assert_eq!(refusal.code, RefusalCode::MalformedManifest);
1011            assert_eq!(refusal.required, Required::Unknown);
1012            assert!(
1013                refusal.message.contains("unknown") || refusal.message.contains("section"),
1014                "names the offender: {}",
1015                refusal.message
1016            );
1017        }
1018    }
1019
1020    #[test]
1021    fn rule_2_name_grammar_and_instance_key() {
1022        for name in ["Approval", "-x", "has space", &"a".repeat(65)] {
1023            let text = valid_toml().replace("\"approval-gate\"", &format!("\"{name}\""));
1024            let refusal = parse_manifest(&text, &ctx()).expect_err("bad name refuses");
1025            assert_eq!(refusal.code, RefusalCode::NameInvalid);
1026        }
1027        let text = valid_toml(); // name != instance key
1028        let other = ValidationCtx {
1029            instance_key: "other-key",
1030            ..ctx()
1031        };
1032        let refusal = parse_manifest(&text, &other).expect_err("key mismatch refuses");
1033        assert_eq!(refusal.code, RefusalCode::NameInvalid);
1034    }
1035
1036    #[test]
1037    fn rule_3_reserved_name_collides() {
1038        let reserved = ValidationCtx {
1039            instance_key: "approval-gate",
1040            reserved_names: &["approval-gate".to_string()],
1041            secret_env: &[],
1042        };
1043        let refusal = parse_manifest(&valid_toml(), &reserved).expect_err("collision refuses");
1044        assert_eq!(refusal.code, RefusalCode::NameCollision);
1045    }
1046
1047    #[test]
1048    fn rule_4_semver_and_abi() {
1049        let bad_version = valid_toml().replace("0.1.0", "0.1");
1050        assert_eq!(
1051            parse_manifest(&bad_version, &ctx()).unwrap_err().code,
1052            RefusalCode::MalformedManifest
1053        );
1054        let bad_abi = valid_toml().replace("abi = 1", "abi = 2");
1055        assert_eq!(
1056            parse_manifest(&bad_abi, &ctx()).unwrap_err().code,
1057            RefusalCode::AbiMismatch
1058        );
1059        // Valid pre-release semver is accepted.
1060        let ok = valid_toml().replace("0.1.0", "1.2.3-rc.1");
1061        assert!(parse_manifest(&ok, &ctx()).is_ok());
1062    }
1063
1064    #[test]
1065    fn rule_5_argv_must_exist_and_be_absolute() {
1066        let relative = valid_toml().replace("\"/bin/cat\"", "\"cat\"");
1067        assert_eq!(
1068            parse_manifest(&relative, &ctx()).unwrap_err().code,
1069            RefusalCode::MissingBinary
1070        );
1071        let missing = valid_toml().replace("/bin/cat", "/nonexistent/definitely-absent");
1072        let refusal = parse_manifest(&missing, &ctx()).unwrap_err();
1073        assert_eq!(refusal.code, RefusalCode::MissingBinary);
1074        assert!(refusal.message.contains("does not exist"));
1075    }
1076
1077    #[test]
1078    fn rule_6_sha256_shape() {
1079        let bad = valid_toml().replace(
1080            "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2",
1081            "A1B2C3D4E5F6A7B8C9D0E1F2A3B4C5D6E7F8A9B0C1D2E3F4A5B6C7D8E9F0A1B2",
1082        );
1083        assert_eq!(
1084            parse_manifest(&bad, &ctx()).unwrap_err().code,
1085            RefusalCode::DigestMismatch
1086        );
1087    }
1088
1089    #[test]
1090    fn rule_7_env_allow_grammar_duplicates_secrets() {
1091        let secret = ValidationCtx {
1092            instance_key: "approval-gate",
1093            reserved_names: &[],
1094            secret_env: &["KIAN_WORKER_TOKEN".to_string()],
1095        };
1096        let bad = valid_toml().replace(
1097            "[grants]",
1098            "env_allow = [\"KIAN_WORKER_TOKEN\"]\n\n[grants]",
1099        );
1100        assert_eq!(
1101            parse_manifest(&bad, &secret).unwrap_err().code,
1102            RefusalCode::MalformedManifest
1103        );
1104        let dup = valid_toml().replace("[grants]", "env_allow = [\"URL\", \"URL\"]\n\n[grants]");
1105        assert!(parse_manifest(&dup, &ctx()).is_err());
1106        let bad_name = valid_toml().replace("[grants]", "env_allow = [\"1BAD\"]\n\n[grants]");
1107        assert!(parse_manifest(&bad_name, &ctx()).is_err());
1108    }
1109
1110    #[test]
1111    fn rule_8_unknown_hook() {
1112        for hook in [
1113            "tool/preflight",
1114            "plugin/load",
1115            "harness/dsh/start",
1116            "nonsense",
1117        ] {
1118            let text = valid_toml().replace(
1119                "hooks = [\"tool/pre\", \"tool/post\"]",
1120                &format!("hooks = [\"{hook}\"]"),
1121            );
1122            let refusal = parse_manifest(&text, &ctx()).unwrap_err();
1123            assert_eq!(refusal.code, RefusalCode::UnknownHook, "{hook}");
1124        }
1125    }
1126
1127    #[test]
1128    fn rules_9_10_capabilities_and_grant_consistency() {
1129        let unknown = valid_toml().replace(
1130            "capabilities = [\"observe:tool\", \"veto:tool\"]",
1131            "capabilities = [\"mutate:context\"]",
1132        );
1133        assert_eq!(
1134            parse_manifest(&unknown, &ctx()).unwrap_err().code,
1135            RefusalCode::UnknownCapability
1136        );
1137        // Subscribed hook without the matching observe grant
1138        // (an unused observe grant alone is legal — rule 10 constrains
1139        // subscriptions and veto grants, not extra observes).
1140        let no_observe = valid_toml().replace(
1141            "hooks = [\"tool/pre\", \"tool/post\"]",
1142            "hooks = [\"admit/pre\"]",
1143        );
1144        let refusal = parse_manifest(&no_observe, &ctx()).unwrap_err();
1145        assert_eq!(refusal.code, RefusalCode::GrantMismatch);
1146        // A veto grant with no veto-capable subscribed hook.
1147        let orphan_veto = valid_toml().replace(
1148            "hooks = [\"tool/pre\", \"tool/post\"]",
1149            "hooks = [\"tool/post\"]",
1150        );
1151        assert_eq!(
1152            parse_manifest(&orphan_veto, &ctx()).unwrap_err().code,
1153            RefusalCode::GrantMismatch
1154        );
1155    }
1156
1157    #[test]
1158    fn rule_11_limit_clamps() {
1159        let over = valid_toml().replace("deadline_ms = 500", "deadline_ms = 9999");
1160        assert_eq!(
1161            parse_manifest(&over, &ctx()).unwrap_err().code,
1162            RefusalCode::MalformedManifest
1163        );
1164        let under = valid_toml().replace("deadline_ms = 500", "deadline_ms = 10");
1165        assert!(parse_manifest(&under, &ctx()).is_err());
1166        let restarts = valid_toml().replace("deadline_ms = 500", "restarts_per_window = 0");
1167        assert!(parse_manifest(&restarts, &ctx()).is_err());
1168    }
1169
1170    #[test]
1171    fn rule_14_cwd_checks() {
1172        let relative = valid_toml().replace("[grants]", "cwd = \"relative/dir\"\n\n[grants]");
1173        assert_eq!(
1174            parse_manifest(&relative, &ctx()).unwrap_err().code,
1175            RefusalCode::MalformedManifest
1176        );
1177        let missing = valid_toml().replace(
1178            "[grants]",
1179            "cwd = \"/nonexistent/definitely-absent-dir\"\n\n[grants]",
1180        );
1181        let refusal = parse_manifest(&missing, &ctx()).unwrap_err();
1182        assert_eq!(refusal.code, RefusalCode::MalformedManifest);
1183        assert!(refusal.message.contains("cwd"));
1184    }
1185
1186    #[test]
1187    fn wrong_types_are_malformed() {
1188        let bad_order = valid_toml().replace("abi = 1", "order = \"zero\"");
1189        assert_eq!(
1190            parse_manifest(&bad_order, &ctx()).unwrap_err().code,
1191            RefusalCode::MalformedManifest
1192        );
1193        let bad_required = valid_toml().replace("abi = 1", "required = 1");
1194        assert!(parse_manifest(&bad_required, &ctx()).is_err());
1195        let duplicate = valid_toml().replace("[process]", "[process]\nabi = 1\n");
1196        assert!(parse_manifest(&duplicate, &ctx()).is_err());
1197    }
1198}