subc-config 0.1.14

Shared configuration policy, canonical digests and approval records for subc.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
use crate::schema::pointer;
use serde_json::Value;
use std::collections::BTreeSet;
use std::fmt;

/// How the Settings headings on a module page match the schema's setting keys.
/// All lists are sorted and contain each key at most once.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SettingsCoverage {
    /// Whether the page has a `## Settings` heading.
    pub section_found: bool,
    /// Required setting keys without a heading in that section.
    pub missing: Vec<String>,
    /// Headings that name neither a setting key nor a container.
    pub unknown: Vec<String>,
    /// Keys produced by multiple schema paths or named by multiple headings.
    pub duplicate: Vec<String>,
}

/// The schema root is not a JSON object.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SettingsCoverageError {
    NonObjectSchema,
}

impl fmt::Display for SettingsCoverageError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NonObjectSchema => f.write_str("settings schema root must be a JSON object"),
        }
    }
}

impl std::error::Error for SettingsCoverageError {}

/// Compare schema keys with `###` headings containing only a code span in the
/// page's Settings section.
/// Containers may have headings but don't require them. Array indices and map
/// keys do not appear in setting keys. This check does not validate the schema.
pub fn settings_coverage(
    schema: &Value,
    page: &str,
) -> Result<SettingsCoverage, SettingsCoverageError> {
    if !schema.is_object() {
        return Err(SettingsCoverageError::NonObjectSchema);
    }

    let mut keys = SchemaKeys::default();
    keys.walk(schema, "");
    let (section_found, headings) = scan_headings(page, &mut keys.duplicate);

    Ok(SettingsCoverage {
        section_found,
        missing: keys
            .required
            .into_iter()
            .filter(|key| !headings.contains(key.as_str()))
            .collect(),
        unknown: headings
            .into_iter()
            .filter(|key| !keys.known.contains(*key))
            .map(str::to_owned)
            .collect(),
        duplicate: keys.duplicate.into_iter().collect(),
    })
}

#[derive(Default)]
struct SchemaKeys {
    known: BTreeSet<String>,
    required: BTreeSet<String>,
    duplicate: BTreeSet<String>,
}

impl SchemaKeys {
    /// Returns whether this node describes a container at `path`.
    fn walk(&mut self, schema: &Value, path: &str) -> bool {
        if is_atomic(schema) {
            return false;
        }

        let mut container = false;
        if let Some(fields) = schema.get("properties").and_then(Value::as_object) {
            container = true;
            for (name, child) in fields {
                let key = pointer(path, name);
                if !self.known.insert(key.clone()) {
                    self.duplicate.insert(key.clone());
                }
                if !self.walk(child, &key) {
                    self.required.insert(key);
                }
            }
        }

        let patterns = schema
            .get("patternProperties")
            .and_then(Value::as_object)
            .into_iter()
            .flat_map(|patterns| patterns.values());
        for entry in schema
            .get("items")
            .into_iter()
            .chain(patterns)
            .chain(schema.get("additionalProperties"))
        {
            // Collection entries don't contribute a segment of their own.
            if entry.get("properties").is_some_and(Value::is_object) && !is_atomic(entry) {
                self.walk(entry, path);
                container = true;
            }
        }

        for keyword in ["oneOf", "anyOf", "allOf"] {
            if let Some(branches) = schema.get(keyword).and_then(Value::as_array) {
                for branch in branches {
                    container |= self.walk(branch, path);
                }
            }
        }
        container
    }
}

fn is_atomic(schema: &Value) -> bool {
    matches!(
        schema.get("x-ck-kind").and_then(Value::as_str),
        Some("json" | "credential_ref")
    )
}

fn scan_headings<'a>(page: &'a str, duplicate: &mut BTreeSet<String>) -> (bool, BTreeSet<&'a str>) {
    let mut section_found = false;
    let mut headings = BTreeSet::new();
    let mut fence: Option<Fence> = None;

    for raw in page.lines() {
        let line = raw.trim_start_matches(' ');
        if raw.len() - line.len() > 3 {
            continue;
        }

        let marker = fence_marker(line);
        if let Some(open) = &fence {
            if marker.is_some_and(|(close, rest)| {
                close.marker == open.marker
                    && close.width >= open.width
                    && rest.trim_end_matches([' ', '\t']).is_empty()
            }) {
                fence = None;
            }
            continue;
        }
        if let Some((open, rest)) = marker {
            // Text after an opening backtick fence cannot contain backticks.
            if open.marker != '`' || !rest.contains('`') {
                fence = Some(open);
                continue;
            }
        }

        match atx_heading(line) {
            Some((1 | 2, _)) if section_found => break,
            Some((2, "Settings")) => section_found = true,
            Some((3, text)) if section_found => {
                if let Some(key) = code_span_key(text) {
                    if !headings.insert(key) {
                        duplicate.insert(key.to_owned());
                    }
                }
            }
            _ => {}
        }
    }

    (section_found, headings)
}

struct Fence {
    marker: char,
    width: usize,
}

fn fence_marker(line: &str) -> Option<(Fence, &str)> {
    let marker = line.chars().next()?;
    if !matches!(marker, '`' | '~') {
        return None;
    }
    let (width, rest) = marker_run(line, marker);
    (width >= 3).then_some((Fence { marker, width }, rest))
}

fn atx_heading(line: &str) -> Option<(usize, &str)> {
    let (level, rest) = marker_run(line, '#');
    if !(1..=6).contains(&level) || (!rest.is_empty() && !rest.starts_with([' ', '\t'])) {
        return None;
    }
    let rest = rest.trim_end_matches([' ', '\t']);
    let text = rest.trim_end_matches('#');
    // Closing hashes are optional and only count if separated from the text.
    let text = if text.ends_with([' ', '\t']) {
        text
    } else {
        rest
    };
    Some((level, text.trim_matches([' ', '\t'])))
}

fn code_span_key(text: &str) -> Option<&str> {
    let (width, content) = marker_run(text, '`');
    if width == 0 {
        return None;
    }

    let mut rest = content;
    while let Some(index) = rest.find('`') {
        let (ticks, after) = marker_run(&rest[index..], '`');
        if ticks == width {
            // The first equal-width run closes the span; no other text may follow it.
            if !after.is_empty() {
                return None;
            }
            let code = &content[..content.len() - rest.len() + index];
            // Markdown removes one padding space at either end when both are present.
            let code = code
                .strip_prefix(' ')
                .and_then(|code| code.strip_suffix(' '))
                .unwrap_or(code);
            return code.starts_with('/').then_some(code);
        }
        rest = after;
    }
    None
}

fn marker_run(text: &str, marker: char) -> (usize, &str) {
    let rest = text.trim_start_matches(marker);
    (text.len() - rest.len(), rest)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn assert_complete(schema: &Value, page: &str) {
        assert_eq!(
            settings_coverage(schema, page).unwrap(),
            SettingsCoverage {
                section_found: true,
                missing: vec![],
                unknown: vec![],
                duplicate: vec![],
            }
        );
    }

    #[test]
    fn reports_missing_and_unknown_keys_in_the_settings_section() {
        let schema = json!({"properties": {"a": {}, "b": {"properties": {"c": {}}}}});

        let coverage = settings_coverage(&schema, "## Settings\n### `/a`\n### `/x`").unwrap();
        assert!(coverage.section_found);
        assert_eq!(coverage.missing, ["/b/c"]);
        assert_eq!(coverage.unknown, ["/x"]);
        assert!(coverage.duplicate.is_empty());

        assert_complete(&schema, "## Settings\n### `/a`\n### `/b/c`");
        assert_complete(&schema, "## Settings\n### `/a`\n### `/b`\n### `/b/c`");

        let coverage = settings_coverage(&schema, "Settings\n--------\n### `/a`").unwrap();
        assert!(!coverage.section_found);
        assert_eq!(coverage.missing, ["/a", "/b/c"]);
        assert!(coverage.unknown.is_empty());
    }

    #[test]
    fn collection_objects_omit_indices_and_map_keys_recursively() {
        let schema = json!({"properties": {
            "preload": {"type": "array", "items": {"type": "object", "properties": {
                "engine": {"type": "string"},
                "options": {"type": "object", "additionalProperties": {"properties": {
                    "enabled": {"type": "boolean"}
                }}}
            }}},
            "providers": {"type": "object", "patternProperties": {"^.+$": {"type": "object", "properties": {
                "base_url": {"type": "string"}
            }}}}
        }});

        assert_complete(
            &schema,
            "## Settings\n### `/preload/engine`\n### `/preload/options/enabled`\n### `/providers/base_url`",
        );

        let coverage = settings_coverage(
            &schema,
            "## Settings\n### `/preload`\n### `/preload/options`\n### `/providers`\n### `/preload/1/engine`\n### `/providers/acme/base_url`",
        )
        .unwrap();
        assert_eq!(
            coverage.missing,
            [
                "/preload/engine",
                "/preload/options/enabled",
                "/providers/base_url"
            ]
        );
        assert_eq!(
            coverage.unknown,
            ["/preload/1/engine", "/providers/acme/base_url"]
        );
        assert!(coverage.duplicate.is_empty());
    }

    #[test]
    fn scalar_collections_and_annotated_values_stay_single_keys() {
        let schema = json!({"properties": {
            "list": {"type": "array", "items": {"type": "string"}},
            "map": {"type": "object", "patternProperties": {"^.+$": {"type": "string"}}},
            "open_map": {"type": "object", "additionalProperties": {"type": "string"}},
            "nested_list": {"items": {"items": {"properties": {"ignored": {}}}}},
            "opaque": {"x-ck-kind": "json", "properties": {"ignored": {}},
                "oneOf": [{"properties": {"also_ignored": {}}}]},
            "reference": {"x-ck-kind": "credential_ref", "properties": {"vault_ref": {}}},
            "opaque_items": {"items": {"x-ck-kind": "json", "properties": {"ignored": {}}}}
        }});

        let coverage = settings_coverage(&schema, "## Settings").unwrap();
        assert_eq!(
            coverage.missing,
            [
                "/list",
                "/map",
                "/nested_list",
                "/opaque",
                "/opaque_items",
                "/open_map",
                "/reference"
            ]
        );
    }

    #[test]
    fn combines_schema_collisions_and_repeated_headings_in_sorted_duplicate_list() {
        let schema = json!({"properties": {"settings": {
            "properties": {"port": {}},
            "patternProperties": {"^.+$": {"properties": {"port": {}}}},
            "additionalProperties": {"properties": {"port": {}}}
        }}});
        let page = "## Settings\n### `/z`\n### `/a`\n### `/z`\n### `/z`\n### `/a`";
        let coverage = settings_coverage(&schema, page).unwrap();
        assert_eq!(coverage.missing, ["/settings/port"]);
        assert_eq!(coverage.unknown, ["/a", "/z"]);
        assert_eq!(coverage.duplicate, ["/a", "/settings/port", "/z"]);
    }

    #[test]
    fn variants_union_branch_keys_at_the_same_pointer() {
        let schema = json!({"properties": {"mode": {
            "oneOf": [
                {"properties": {"alpha": {}}},
                {"anyOf": [{"properties": {"beta": {}}}, {"allOf": [{"properties": {"gamma": {}}}]}]}
            ]
        }}});
        assert_complete(
            &schema,
            "## Settings\n### `/mode/alpha`\n### `/mode/beta`\n### `/mode/gamma`",
        );
    }

    #[test]
    fn rejects_non_object_schema_roots() {
        for schema in [
            json!(null),
            json!(false),
            json!([]),
            json!("object"),
            json!(0),
        ] {
            assert_eq!(
                settings_coverage(&schema, "## Settings"),
                Err(SettingsCoverageError::NonObjectSchema)
            );
        }
        assert_complete(&json!({}), "## Settings");
    }

    #[test]
    fn scanner_requires_one_code_span_in_an_atx_h3() {
        let schema = json!({"properties": {"a~b/c": {}, "has`tick": {}, "last": {}}});
        let page = "\
## Settings (draft)
### `/before`
   ##\tSettings ###
  ### `/a~0b~1c` ###
### `` /has`tick ``
#### `/h4`
    ### `/indented`
###`/no-space`
### `/extra` text
### `/first` `/second`
### `/no-space-before-closer`###
### `not-a-key`
`/setext`
---------
### `/last`
## Commands
### `/after`";

        assert_complete(&schema, page);
    }

    #[test]
    fn fenced_headings_do_not_open_end_or_contribute_to_settings() {
        let schema = json!({"properties": {"first": {}, "last": {}}});
        let page = "\
  ~~~markdown
## Settings
### `/hidden-before`
  ~~~~
## Settings
### `/first`
````markdown
# Hidden H1
```
### `/after-short-fence`
~~~~~
### `/after-tilde-fence`
```` not a closing fence
### `/after-fence-with-info`
`````
### `/last`
# End of Settings
### `/after`";

        assert_complete(&schema, page);
    }
}