noctis 0.5.0

Open-source black-box vulnerability scanner: readable YAML checks that prove each bug on the live service, QoD-graded findings, REST API.
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
use std::collections::HashSet;
use std::path::{Path, PathBuf};

use indexmap::IndexMap;

use crate::error::{NoctisError, Result};
use crate::model::step::Step;
use crate::model::test_def::TestDef;

/// Load a test definition from `path`, recursively resolving `includes:`.
///
/// Include semantics:
///   - Included vars are merged first; the base test's vars override on conflict.
///   - Included steps are prepended before the base test's steps.
///   - Cycles are detected and rejected.
pub fn load(path: &Path) -> Result<TestDef> {
    let mut visited = HashSet::new();
    load_inner(path, &mut visited)
}

/// Parse one feed document.
///
/// serde-saphyr defaults to YAML 1.1-style inference for untyped values
/// (`vars:`, `var_value:`, `over:`, `set_vars:`): `yes`/`on` would become
/// booleans and `010` a number. These options pin YAML 1.2 Core semantics —
/// the behaviour feeds were written against with serde_yaml — so a var like
/// `answer: yes` or `pin: 0123` stays the string the author wrote.
/// Anti-alias-bomb budgets stay at their (enabled) defaults.
fn parse_feed(raw: &str) -> std::result::Result<TestDef, serde_saphyr::Error> {
    let options = serde_saphyr::options! {
        strict_booleans: true,
        leading_zero_numbers_as_strings: true,
        underscored_numbers_as_strings: true,
    };
    serde_saphyr::from_str_with_options(raw, options)
}

fn load_inner(path: &Path, visited: &mut HashSet<PathBuf>) -> Result<TestDef> {
    let canonical = path
        .canonicalize()
        .map_err(|_| NoctisError::IncludeNotFound(path.display().to_string()))?;

    if visited.contains(&canonical) {
        return Err(NoctisError::IncludeCycle(canonical.display().to_string()));
    }
    visited.insert(canonical.clone());

    let raw = std::fs::read_to_string(&canonical).map_err(NoctisError::Io)?;
    let mut def: TestDef = parse_feed(&raw).map_err(|e| NoctisError::Yaml {
        file: canonical.display().to_string(),
        source: Box::new(e),
    })?;

    if def.includes.is_empty() {
        visited.remove(&canonical);
        return Ok(def);
    }

    let base_dir = canonical.parent().unwrap_or(Path::new("."));

    let mut merged_vars: IndexMap<String, serde_json::Value> = IndexMap::new();
    let mut prepended_steps: Vec<Step> = Vec::new();

    for include_path in &def.includes {
        let inc_path = base_dir.join(include_path);
        let included = load_inner(&inc_path, visited)?;

        // Merge vars: included vars come first, base wins on key conflict
        for (k, v) in included.vars {
            merged_vars.entry(k).or_insert(v);
        }

        // Prepend steps from include (avoid id collisions by prefixing)
        for mut step in included.steps {
            step.id = format!("{}:{}", include_path, step.id);
            prepended_steps.push(step);
        }
    }

    // Base vars override included vars
    for (k, v) in def.vars {
        merged_vars.insert(k, v);
    }

    def.vars = merged_vars;
    prepended_steps.extend(def.steps);
    def.steps = prepended_steps;

    visited.remove(&canonical);
    Ok(def)
}

/// Glob-expand a list of patterns (file paths, directories or glob patterns)
/// into resolved PathBufs. A relative pattern that matches nothing from the
/// working directory is retried under `feeds_dir` (the directory
/// `noctis feeds update` installs into), so `"tests": ["vulnerabilities/"]`
/// works from anywhere.
pub fn resolve_test_paths(patterns: &[String], feeds_dir: Option<&Path>) -> Result<Vec<PathBuf>> {
    let mut paths = Vec::new();
    for pattern in patterns {
        let found = match (resolve_one(pattern)?, feeds_dir) {
            (None, Some(base)) if Path::new(pattern).is_relative() => {
                resolve_one(&base.join(pattern).to_string_lossy())?
            }
            (found, _) => found,
        };
        paths.extend(found.ok_or_else(|| NoctisError::IncludeNotFound(pattern.clone()))?);
    }
    Ok(paths)
}

/// One pattern: a file, a directory (recursive *.yaml / *.yml, possibly none)
/// or a glob. `None` when the path doesn't exist and the glob matches nothing.
fn resolve_one(pattern: &str) -> Result<Option<Vec<PathBuf>>> {
    let p = Path::new(pattern);
    let mut paths = Vec::new();
    if p.is_file() {
        paths.push(p.to_path_buf());
    } else if p.is_dir() {
        collect_yaml(p, &mut paths)?;
    } else {
        paths.extend(
            glob::glob(pattern)
                .map_err(|e| {
                    NoctisError::Io(std::io::Error::new(std::io::ErrorKind::InvalidInput, e))
                })?
                .filter_map(|r| r.ok()),
        );
        if paths.is_empty() {
            return Ok(None);
        }
    }
    Ok(Some(paths))
}

fn collect_yaml(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
    for entry in std::fs::read_dir(dir).map_err(NoctisError::Io)? {
        let entry = entry.map_err(NoctisError::Io)?;
        let p = entry.path();
        if p.is_dir() {
            // Staging / backup directories of `noctis feeds update`.
            if entry.file_name().to_string_lossy().starts_with(".noctis-") {
                continue;
            }
            collect_yaml(&p, out)?;
        } else if matches!(p.extension().and_then(|e| e.to_str()), Some("yaml" | "yml")) {
            out.push(p);
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use uuid::Uuid;

    /// Writes a minimal valid YAML file into a temporary directory.
    fn write_yaml(dir: &Path, filename: &str, content: &str) -> PathBuf {
        let path = dir.join(filename);
        std::fs::write(&path, content).unwrap();
        path
    }

    fn tmp_dir() -> PathBuf {
        let dir = std::env::temp_dir().join(format!("noctis-test-{}", Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn minimal_yaml(uid: &str) -> String {
        format!("uid: {uid}\nname: Test\ntype: misconfig\nseverity: info\nsteps: []\n")
    }

    // ── load ──────────────────────────────────────────────────────────────

    #[test]
    fn load_valid_file() {
        let dir = tmp_dir();
        let uid = Uuid::new_v4();
        let path = write_yaml(&dir, "test.yaml", &minimal_yaml(&uid.to_string()));
        let def = load(&path).unwrap();
        assert_eq!(def.uid, uid);
        assert_eq!(def.name, "Test");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn load_nonexistent_file() {
        let err = load(Path::new("/does/not/exist.yaml")).unwrap_err();
        assert!(matches!(err, crate::error::NoctisError::IncludeNotFound(_)));
    }

    #[test]
    fn load_invalid_yaml() {
        let dir = tmp_dir();
        let path = write_yaml(&dir, "bad.yaml", "uid: [\nbroken yaml: {{{{");
        assert!(load(&path).is_err());
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn load_missing_uid_field() {
        let dir = tmp_dir();
        let path = write_yaml(
            &dir,
            "no_uid.yaml",
            "name: Test\ntype: misconfig\nseverity: info\nsteps: []\n",
        );
        assert!(load(&path).is_err());
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn load_with_include_prepends_steps() {
        let dir = tmp_dir();

        // Included file with one step
        let inc_uid = Uuid::new_v4();
        write_yaml(&dir, "common.yaml", &format!(
            "uid: {inc_uid}\nname: Common\ntype: misconfig\nseverity: info\nsteps:\n  - id: common-step\n    action: set_var\n"
        ));

        // Main file that includes common and adds its own step
        let main_uid = Uuid::new_v4();
        write_yaml(&dir, "main.yaml", &format!(
            "uid: {main_uid}\nname: Main\ntype: misconfig\nseverity: info\nincludes:\n  - common.yaml\nsteps:\n  - id: main-step\n    action: set_var\n"
        ));

        let def = load(&dir.join("main.yaml")).unwrap();
        assert_eq!(def.steps.len(), 2);
        // Included step is prepended
        assert!(def.steps[0].id.contains("common-step"));
        assert_eq!(def.steps[1].id, "main-step");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn load_include_cycle_detected() {
        let dir = tmp_dir();
        let uid_a = Uuid::new_v4();
        let uid_b = Uuid::new_v4();
        write_yaml(&dir, "a.yaml", &format!(
            "uid: {uid_a}\nname: A\ntype: misconfig\nseverity: info\nincludes:\n  - b.yaml\nsteps: []\n"
        ));
        write_yaml(&dir, "b.yaml", &format!(
            "uid: {uid_b}\nname: B\ntype: misconfig\nseverity: info\nincludes:\n  - a.yaml\nsteps: []\n"
        ));
        let err = load(&dir.join("a.yaml")).unwrap_err();
        assert!(matches!(err, crate::error::NoctisError::IncludeCycle(_)));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn load_include_var_merge_base_wins() {
        let dir = tmp_dir();
        let inc_uid = Uuid::new_v4();
        write_yaml(&dir, "common.yaml", &format!(
            "uid: {inc_uid}\nname: Common\ntype: misconfig\nseverity: info\nvars:\n  shared: from_common\n  only_common: yes\nsteps: []\n"
        ));
        let main_uid = Uuid::new_v4();
        write_yaml(&dir, "main.yaml", &format!(
            "uid: {main_uid}\nname: Main\ntype: misconfig\nseverity: info\nincludes:\n  - common.yaml\nvars:\n  shared: from_main\nsteps: []\n"
        ));
        let def = load(&dir.join("main.yaml")).unwrap();
        assert_eq!(def.vars["shared"].as_str().unwrap(), "from_main");
        assert!(def.vars.contains_key("only_common"));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    // ── resolve_test_paths ────────────────────────────────────────────────

    #[test]
    fn resolve_single_file() {
        let dir = tmp_dir();
        let uid = Uuid::new_v4();
        let path = write_yaml(&dir, "test.yaml", &minimal_yaml(&uid.to_string()));
        let paths = resolve_test_paths(&[path.to_str().unwrap().to_string()], None).unwrap();
        assert_eq!(paths.len(), 1);
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn resolve_directory_finds_yamls() {
        let dir = tmp_dir();
        let uid1 = Uuid::new_v4();
        let uid2 = Uuid::new_v4();
        write_yaml(&dir, "a.yaml", &minimal_yaml(&uid1.to_string()));
        write_yaml(&dir, "b.yml", &minimal_yaml(&uid2.to_string()));
        std::fs::write(dir.join("ignore.txt"), "not yaml").unwrap();
        let paths = resolve_test_paths(&[dir.to_str().unwrap().to_string()], None).unwrap();
        assert_eq!(paths.len(), 2);
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn resolve_nonexistent_pattern_errors() {
        let result = resolve_test_paths(&["/nonexistent/path/*.yaml".to_string()], None);
        assert!(result.is_err());
    }

    #[test]
    fn relative_pattern_falls_back_to_feeds_dir() {
        let base = std::env::temp_dir().join(format!("noctis-fd-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(base.join("vulnerabilities/p")).unwrap();
        std::fs::write(base.join("vulnerabilities/p/a.yaml"), "x").unwrap();
        let unique = format!("noctis-only-in-base-{}/", uuid::Uuid::new_v4());
        std::fs::rename(base.join("vulnerabilities"), base.join(&unique)).unwrap();

        let got = resolve_test_paths(std::slice::from_ref(&unique), Some(&base)).unwrap();
        assert_eq!(got.len(), 1);
        assert!(got[0].starts_with(&base));
        // Globs fall back too.
        let glob = format!("{unique}*/*.yaml");
        assert_eq!(resolve_test_paths(&[glob], Some(&base)).unwrap().len(), 1);
        // Without a feeds dir, or for an absolute pattern, nothing is retried.
        assert!(resolve_test_paths(std::slice::from_ref(&unique), None).is_err());
        let abs = "/nonexistent-noctis/x.yaml".to_string();
        assert!(resolve_test_paths(&[abs], Some(&base)).is_err());
        std::fs::remove_dir_all(base).unwrap();
    }

    #[test]
    fn existing_empty_directory_resolves_to_nothing() {
        let base = std::env::temp_dir().join(format!("noctis-fd-{}", uuid::Uuid::new_v4()));
        let empty = base.join("empty");
        std::fs::create_dir_all(&empty).unwrap();
        std::fs::create_dir_all(base.join("feeds/empty")).unwrap();
        std::fs::write(base.join("feeds/empty/a.yaml"), "x").unwrap();
        let pat = empty.to_string_lossy().into_owned();
        assert!(resolve_test_paths(&[pat], Some(&base.join("feeds")))
            .unwrap()
            .is_empty());

        // Relative: an empty directory that exists from the working directory
        // (the crate root under `cargo test`) is not retried under the feeds dir.
        let rel = format!("target/noctis-empty-{}", uuid::Uuid::new_v4());
        std::fs::create_dir_all(&rel).unwrap();
        std::fs::create_dir_all(base.join("feeds").join(&rel)).unwrap();
        std::fs::write(base.join("feeds").join(&rel).join("a.yaml"), "x").unwrap();
        let got = resolve_test_paths(std::slice::from_ref(&rel), Some(&base.join("feeds")));
        std::fs::remove_dir_all(&rel).unwrap();
        assert!(got.unwrap().is_empty());
        std::fs::remove_dir_all(base).unwrap();
    }

    #[test]
    fn directory_walk_skips_feeds_update_staging() {
        let base = std::env::temp_dir().join(format!("noctis-fd-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(base.join("vulnerabilities")).unwrap();
        std::fs::create_dir_all(base.join(".noctis-old-x/vulnerabilities")).unwrap();
        std::fs::write(base.join("vulnerabilities/a.yaml"), "x").unwrap();
        std::fs::write(base.join(".noctis-old-x/vulnerabilities/a.yaml"), "x").unwrap();
        let pat = base.to_string_lossy().into_owned();
        assert_eq!(resolve_test_paths(&[pat], None).unwrap().len(), 1);
        std::fs::remove_dir_all(base).unwrap();
    }

    #[test]
    fn working_directory_wins_over_feeds_dir() {
        let base = std::env::temp_dir().join(format!("noctis-fd-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(base.join("tests/common")).unwrap();
        std::fs::write(base.join("tests/common/decoy.yaml"), "x").unwrap();
        // tests/common exists in the crate root: those files are used, not the decoy.
        let got = resolve_test_paths(&["tests/common/".to_string()], Some(&base)).unwrap();
        assert!(got.iter().all(|p| !p.starts_with(&base)));
        std::fs::remove_dir_all(base).unwrap();
    }

    // ── YAML parser contract (serde-saphyr, see parse_feed) ─────────────────

    /// Every feed and include shipped in the repo must load. Guards the parser
    /// swap and any future YAML-library change against silently dropping feeds.
    #[test]
    fn every_shipped_feed_loads() {
        let root = Path::new(env!("CARGO_MANIFEST_DIR"));
        let mut n = 0;
        for pat in ["tests/vulnerabilities/*/*.yaml", "tests/common/*.yaml"] {
            for p in glob::glob(root.join(pat).to_str().unwrap()).unwrap() {
                let p = p.unwrap();
                if let Err(e) = load(&p) {
                    panic!("{} failed to load: {e}", p.display());
                }
                n += 1;
            }
        }
        assert!(n > 100, "expected the shipped feeds, found only {n}");
    }

    const HEAD: &str =
        "uid: 00000000-0000-4000-8000-000000000000\nname: t\nseverity: info\nsteps: []\n";

    /// Untyped values keep YAML 1.2 Core semantics, as they did under serde_yaml.
    #[test]
    fn untyped_vars_use_yaml12_core_resolution() {
        let doc = format!(
            "{HEAD}vars:\n  y: yes\n  on_: on\n  no_: NO\n  oct: 010\n  pin: 0123\n  big: 1_000\n  \
             t: true\n  hex: 0x10\n  f: 1.5\n  n: ~\n  q: \"007\"\n  tpl: '{{{{port}}}}'\n"
        );
        let def = parse_feed(&doc).unwrap();
        let v = |k: &str| def.vars[k].clone();
        use serde_json::json;
        assert_eq!(v("y"), json!("yes"));
        assert_eq!(v("on_"), json!("on"));
        assert_eq!(v("no_"), json!("NO"));
        assert_eq!(v("oct"), json!("010"));
        assert_eq!(v("pin"), json!("0123"));
        assert_eq!(v("big"), json!("1_000"));
        assert_eq!(v("t"), json!(true));
        assert_eq!(v("hex"), json!(16));
        assert_eq!(v("f"), json!(1.5));
        assert_eq!(v("n"), json!(null));
        assert_eq!(v("q"), json!("007"));
        assert_eq!(v("tpl"), json!("{{port}}"));
    }

    #[test]
    fn duplicate_keys_are_rejected() {
        let doc = format!("{HEAD}name: again\n");
        let err = parse_feed(&doc).unwrap_err().to_string();
        assert!(err.contains("duplicate"), "{err}");
    }

    #[test]
    fn parse_error_reports_line() {
        let err = parse_feed(&format!("{HEAD}tags: [unclosed\n"))
            .unwrap_err()
            .to_string();
        assert!(err.contains("line"), "{err}");
    }
}