Skip to main content

mur_common/startup_override/
validate.rs

1//! The override file's schema and the boot-time check (boot step 4).
2//! Fail-closed: any failure rejects the whole file, never part of it.
3
4use chrono::{DateTime, Utc};
5use serde::{Deserialize, Serialize};
6
7use super::{ConfirmedBy, IssuedBy, OVERRIDE_AGE_MARGIN_SECS, is_valid_pair, override_max_age};
8use crate::agent::{OverrideFlags, OverrideRecord, OverrideRejection};
9
10/// The only `version` this build understands.
11pub const OVERRIDE_SCHEMA_VERSION: u32 = 1;
12/// Every nonce is `NONCE_PREFIX` + `NONCE_HEX_LEN` lowercase hex digits.
13pub const NONCE_PREFIX: &str = "ovr-";
14pub const NONCE_HEX_LEN: usize = 32;
15
16/// Flags this build can apply. A file asking for any other flag is rejected
17/// whole. `no_hitl` is applied as the runtime's `StartupWaiver`;
18/// `net_unrestricted` and `full_perms` by [`super::merge::apply`] at boot
19/// step 6. Every field is `true` today; the check stays so a flag added to
20/// the schema is refused until a build knows how to apply it.
21pub const SUPPORTED: OverrideFlags = OverrideFlags {
22    no_hitl: true,
23    net_unrestricted: true,
24    full_perms: true,
25};
26
27pub const REASON_UNPARSEABLE: &str = "override rejected: unparseable";
28pub const REASON_UNKNOWN_CONFIRMED_BY: &str = "override rejected: unknown confirmed_by";
29pub const REASON_UNKNOWN_ISSUED_BY: &str = "override rejected: unknown issued_by";
30pub const REASON_UNKNOWN_FIELD: &str = "override rejected: unknown field";
31pub const REASON_UNSUPPORTED_VERSION: &str = "override rejected: unsupported version";
32pub const REASON_MALFORMED_NONCE: &str = "override rejected: malformed nonce";
33pub const REASON_STALE: &str = "override rejected: stale";
34pub const REASON_FUTURE: &str = "override rejected: created in the future";
35pub const REASON_INVALID_PAIR: &str = "override rejected: invalid issued_by/confirmed_by pair";
36/// Followed by the field name, e.g. `override rejected: unsupported flag: no_hitl`.
37pub const REASON_UNSUPPORTED_FLAG_PREFIX: &str = "override rejected: unsupported flag: ";
38
39/// `<mur_home>/secrets/startup-overrides/<agent>.json`, as written by
40/// `mur agent start|restart` and the Hub.
41#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
42#[serde(deny_unknown_fields)]
43pub struct OverrideFile {
44    pub version: u32,
45    pub nonce: String,
46    pub created_at: DateTime<Utc>,
47    pub issued_by: IssuedBy,
48    pub confirmed_by: ConfirmedBy,
49    pub no_hitl: bool,
50    pub net_unrestricted: bool,
51    pub full_perms: bool,
52}
53
54impl OverrideFile {
55    pub fn flags(&self) -> OverrideFlags {
56        OverrideFlags {
57            no_hitl: self.no_hitl,
58            net_unrestricted: self.net_unrestricted,
59            full_perms: self.full_perms,
60        }
61    }
62}
63
64/// `ovr-` followed by exactly 32 lowercase hex digits.
65pub fn is_well_formed_nonce(nonce: &str) -> bool {
66    nonce.strip_prefix(NONCE_PREFIX).is_some_and(|hex| {
67        hex.len() == NONCE_HEX_LEN && hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
68    })
69}
70
71/// Parse and check an override file. `Ok` is the record to put on the lock.
72///
73/// Order, first failure wins: parse → version → nonce shape → pair → age →
74/// unsupported flags. `stop_timeout_secs` is the booting profile's own
75/// `lifecycle.stop_timeout_secs`.
76pub fn validate(
77    bytes: &[u8],
78    now: DateTime<Utc>,
79    stop_timeout_secs: u64,
80) -> Result<OverrideRecord, OverrideRejection> {
81    let file: OverrideFile = serde_json::from_slice(bytes).map_err(|e| OverrideRejection {
82        nonce: lenient_nonce(bytes),
83        reason: classify_parse_error(bytes, &e).to_string(),
84    })?;
85
86    let reject = |reason: String| {
87        let nonce = is_well_formed_nonce(&file.nonce).then(|| file.nonce.clone());
88        OverrideRejection { nonce, reason }
89    };
90
91    if file.version != OVERRIDE_SCHEMA_VERSION {
92        return Err(reject(REASON_UNSUPPORTED_VERSION.into()));
93    }
94    if !is_well_formed_nonce(&file.nonce) {
95        return Err(reject(REASON_MALFORMED_NONCE.into()));
96    }
97    if !is_valid_pair(file.issued_by, file.confirmed_by) {
98        return Err(reject(REASON_INVALID_PAIR.into()));
99    }
100
101    let max_age = chrono::Duration::from_std(override_max_age(stop_timeout_secs))
102        .unwrap_or(chrono::Duration::MAX);
103    if now - file.created_at > max_age {
104        return Err(reject(REASON_STALE.into()));
105    }
106    let margin = chrono::Duration::seconds(OVERRIDE_AGE_MARGIN_SECS as i64);
107    if file.created_at - now > margin {
108        return Err(reject(REASON_FUTURE.into()));
109    }
110
111    let flags = file.flags();
112    for (name, asked, supported) in [
113        ("no_hitl", flags.no_hitl, SUPPORTED.no_hitl),
114        (
115            "net_unrestricted",
116            flags.net_unrestricted,
117            SUPPORTED.net_unrestricted,
118        ),
119        ("full_perms", flags.full_perms, SUPPORTED.full_perms),
120    ] {
121        if asked && !supported {
122            return Err(reject(format!("{REASON_UNSUPPORTED_FLAG_PREFIX}{name}")));
123        }
124    }
125
126    Ok(OverrideRecord {
127        nonce: file.nonce,
128        flags,
129        confirmed_by: file.confirmed_by,
130    })
131}
132
133/// The `nonce` of a file that failed strict parsing, only if it is JSON and
134/// the nonce is well formed. Never trust anything else from such a file.
135fn lenient_nonce(bytes: &[u8]) -> Option<String> {
136    let value: serde_json::Value = serde_json::from_slice(bytes).ok()?;
137    let nonce = value.get("nonce")?.as_str()?;
138    is_well_formed_nonce(nonce).then(|| nonce.to_string())
139}
140
141/// Name the strict-parse failure. An unrecognised `confirmed_by` /
142/// `issued_by` string is checked on the raw value (serde's message does not
143/// name the field); an unknown key comes from `deny_unknown_fields`.
144fn classify_parse_error(bytes: &[u8], err: &serde_json::Error) -> &'static str {
145    if let Ok(value) = serde_json::from_slice::<serde_json::Value>(bytes) {
146        let unknown = |key: &str, ok: fn(serde_json::Value) -> bool| {
147            value
148                .get(key)
149                .is_some_and(|v| v.is_string() && !ok(v.clone()))
150        };
151        if unknown("confirmed_by", |v| {
152            serde_json::from_value::<ConfirmedBy>(v).is_ok()
153        }) {
154            return REASON_UNKNOWN_CONFIRMED_BY;
155        }
156        if unknown("issued_by", |v| {
157            serde_json::from_value::<IssuedBy>(v).is_ok()
158        }) {
159            return REASON_UNKNOWN_ISSUED_BY;
160        }
161    }
162    if err.to_string().starts_with("unknown field") {
163        return REASON_UNKNOWN_FIELD;
164    }
165    REASON_UNPARSEABLE
166}