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) if found != SUPPORTED_VERSION => Err(PolicyError::Version {
47            found,
48            supported: SUPPORTED_VERSION,
49        }),
50        Declared::Version(_) | Declared::Unreadable => Ok(()),
51    }
52}
53
54/// What [`PolicyError::Version`] says: a newer schema needs a newer OpenMoat;
55/// an older one, `openmoat policy migrate`.
56pub(super) fn unsupported(found: u32, supported: u32) -> String {
57    if found > supported {
58        format!(
59            "unsupported policy version {found}: the policy is written for policy schema version \
60             {found}, which a newer OpenMoat reads; this build reads schema version {supported}: \
61             upgrade OpenMoat"
62        )
63    } else {
64        format!(
65            "unsupported policy version {found}: this build reads policy schema version \
66             {supported}; `openmoat policy migrate` rewrites an older schema"
67        )
68    }
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    #[test]
76    fn the_version_is_read_before_any_other_key() {
77        assert_eq!(
78            declared("version: 1\ndefaults: deny\n"),
79            Declared::Version(1)
80        );
81        assert_eq!(declared("defaults: deny\n"), Declared::Missing);
82        assert_eq!(declared("version: one\n"), Declared::Unreadable);
83        assert_eq!(declared("- not a mapping\n"), Declared::Unreadable);
84        // A key of a later schema does not hide the version it was written for.
85        let later = "version: 2\nnew_key: true\n";
86        let message = crate::Policy::parse(later).unwrap_err().to_string();
87        assert!(message.contains("schema version 2"), "{message}");
88        assert!(message.contains("upgrade OpenMoat"), "{message}");
89    }
90
91    #[test]
92    fn a_missing_or_older_version_points_at_migrate() {
93        for (yaml, says) in [
94            ("defaults: deny\n", "has no `version:`"),
95            ("version: 0\n", "unsupported policy version 0"),
96        ] {
97            let message = crate::Policy::parse(yaml).unwrap_err().to_string();
98            assert!(message.contains(says), "{message}");
99            assert!(message.contains("openmoat policy migrate"), "{message}");
100        }
101        let repo = crate::RepoPolicy::parse("deny: []\n").unwrap_err();
102        assert!(
103            matches!(repo, PolicyError::MissingVersion { supported: 1 }),
104            "{repo}"
105        );
106    }
107
108    #[test]
109    fn a_field_error_names_the_schema_version() {
110        let message = crate::Policy::parse("version: 1\ndenny: []\n")
111            .unwrap_err()
112            .to_string();
113        assert!(message.contains("policy schema version 1"), "{message}");
114        assert!(message.contains("unknown field `denny`"), "{message}");
115    }
116}