Skip to main content

openmoat_core/policy/
schema.rs

1//! The policy schema version (`version:`, ADR-103): read before the rest of
2//! the document, so a file for another schema is reported as that, with what
3//! to do, instead of by the first key this build does not know.
4
5use serde::Deserialize;
6
7use super::{PolicyError, SUPPORTED_VERSION};
8
9/// The `version:` a document declares.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum Declared {
12    /// The document has no `version:` key.
13    Missing,
14    /// The document's schema version.
15    Version(u32),
16    /// The document does not parse far enough to tell, or `version:` is not a
17    /// number: the full parse reports why.
18    Unreadable,
19}
20
21/// Just `version:`; every other key is ignored, so this reads any document a
22/// policy, a repository policy or a pack may be.
23#[derive(Deserialize)]
24struct Probe {
25    #[serde(default)]
26    version: Option<u32>,
27}
28
29/// The schema version `yaml` declares.
30#[must_use]
31pub fn declared(yaml: &str) -> Declared {
32    match crate::yaml::from_str::<Probe>(yaml) {
33        Ok(Probe { version: Some(v) }) => Declared::Version(v),
34        Ok(Probe { version: None }) => Declared::Missing,
35        Err(_) => Declared::Unreadable,
36    }
37}
38
39/// Refuse a document for a schema other than [`SUPPORTED_VERSION`], or one
40/// without `version:`, naming the version and what to do.
41pub(crate) fn check(yaml: &str) -> Result<(), PolicyError> {
42    match declared(yaml) {
43        Declared::Missing => Err(PolicyError::MissingVersion {
44            supported: SUPPORTED_VERSION,
45        }),
46        Declared::Version(found) => check_parsed(found),
47        Declared::Unreadable => Ok(()),
48    }
49}
50
51/// [`check`] for a document that deserialized in full as a policy, whose
52/// `version:` is `found`: the policy's `version` is a required number, so the
53/// probe would have read the same `Declared::Version(found)` from it, and no
54/// second deserialize is needed to read it.
55pub(crate) fn check_parsed(found: u32) -> Result<(), PolicyError> {
56    if found == SUPPORTED_VERSION {
57        return Ok(());
58    }
59    Err(PolicyError::Version {
60        found,
61        supported: SUPPORTED_VERSION,
62    })
63}
64
65/// What [`PolicyError::Version`] says: a newer schema needs a newer OpenMoat;
66/// an older one, `openmoat policy migrate`.
67pub(super) fn unsupported(found: u32, supported: u32) -> String {
68    if found > supported {
69        format!(
70            "unsupported policy version {found}: the policy is written for policy schema version \
71             {found}, which a newer OpenMoat reads; this build reads schema version {supported}: \
72             upgrade OpenMoat"
73        )
74    } else {
75        format!(
76            "unsupported policy version {found}: this build reads policy schema version \
77             {supported}; `openmoat policy migrate` rewrites an older schema"
78        )
79    }
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    #[test]
87    fn the_version_is_read_before_any_other_key() {
88        assert_eq!(
89            declared("version: 1\ndefaults: deny\n"),
90            Declared::Version(1)
91        );
92        assert_eq!(declared("defaults: deny\n"), Declared::Missing);
93        assert_eq!(declared("version: one\n"), Declared::Unreadable);
94        assert_eq!(declared("- not a mapping\n"), Declared::Unreadable);
95        // A key of a later schema does not hide the version it was written for.
96        let later = "version: 2\nnew_key: true\n";
97        let message = crate::Policy::parse(later).unwrap_err().to_string();
98        assert!(message.contains("schema version 2"), "{message}");
99        assert!(message.contains("upgrade OpenMoat"), "{message}");
100    }
101
102    #[test]
103    fn a_missing_or_older_version_points_at_migrate() {
104        for (yaml, says) in [
105            ("defaults: deny\n", "has no `version:`"),
106            ("version: 0\n", "unsupported policy version 0"),
107        ] {
108            let message = crate::Policy::parse(yaml).unwrap_err().to_string();
109            assert!(message.contains(says), "{message}");
110            assert!(message.contains("openmoat policy migrate"), "{message}");
111        }
112        let repo = crate::RepoPolicy::parse("deny: []\n").unwrap_err();
113        assert!(
114            matches!(repo, PolicyError::MissingVersion { supported: 1 }),
115            "{repo}"
116        );
117    }
118
119    /// `Policy::parse` reads `version:` from its one deserialize when the
120    /// document parses, and probes for it only when it does not: either way a
121    /// wrong or missing version gives the error the probe alone gave.
122    #[test]
123    fn a_wrong_or_missing_version_gives_the_same_error_with_one_deserialize() {
124        for yaml in [
125            // Parses in full: the version comes from the parsed policy.
126            "version: 0\n",
127            "version: 2\n",
128            "version: 7\ndefaults: deny\n",
129            // Does not parse in full: the probe reads it.
130            "defaults: deny\n",
131            "version: 2\nnew_key: true\n",
132            "version: 0\ndenny: []\n",
133            "version: ~\n",
134        ] {
135            let probed = check(yaml).unwrap_err().to_string();
136            let parsed = crate::Policy::parse(yaml).unwrap_err().to_string();
137            assert_eq!(parsed, probed, "{yaml}");
138        }
139        assert!(matches!(
140            crate::Policy::parse("version: 3\n"),
141            Err(PolicyError::Version {
142                found: 3,
143                supported: SUPPORTED_VERSION
144            })
145        ));
146        assert!(matches!(
147            crate::Policy::parse("defaults: deny\n"),
148            Err(PolicyError::MissingVersion {
149                supported: SUPPORTED_VERSION
150            })
151        ));
152        // A readable version 1 with a bad key is the parse's own error.
153        assert!(matches!(
154            crate::Policy::parse("version: 1\ndenny: []\n"),
155            Err(PolicyError::Parse(_))
156        ));
157    }
158
159    #[test]
160    fn a_field_error_names_the_schema_version() {
161        let message = crate::Policy::parse("version: 1\ndenny: []\n")
162            .unwrap_err()
163            .to_string();
164        assert!(message.contains("policy schema version 1"), "{message}");
165        assert!(message.contains("unknown field `denny`"), "{message}");
166    }
167}