diff --git a/src/python/jw/util/load_yaml.py b/src/python/jw/util/load_yaml.py index 9870f4d..70c7938 100644 --- a/src/python/jw/util/load_yaml.py +++ b/src/python/jw/util/load_yaml.py @@ -31,6 +31,13 @@ supports three extensions: values may reference environment variables as ``$(VAR)`` or ``${VAR}``. Only the top-level document may declare ``jw.include-map``. +- ``jw.include-map-no-absolute`` — when true, an absolute include + spec that matched no map entry raises ValueError, naming the + spec and the file, guarding a test against silently reading a + real production path. An identity entry (LHS and RHS the + same) whitelists a path that may be read. The key defaults to + false and applies to the whole include tree; only the + top-level document may set it. - ``jw.link`` — replaces a node with the value found at a dot-separated target path. A prefix before the first ``|`` names the resulting key instead of replacing the node in place. @@ -323,6 +330,7 @@ def _parse_include_spec( path: Path, include_map: IncludeMap, expand_vars: bool, + no_absolute: bool, ) -> list[IncludeSpec]: """Parse a jw.include spec into one or more IncludeSpec entries. @@ -333,7 +341,9 @@ def _parse_include_spec( *include_map* before resolution; the rewritten specs are resolved and glob-expanded by the normal pipeline. When *expand_vars* is true (the top-level document only), $(VAR) and ${VAR} references - in the file part are expanded from the environment first. + in the file part are expanded from the environment first. When + *no_absolute* is true, an absolute spec that matched no entry + raises ValueError instead of being read from disk. """ if not spec: raise ValueError('Empty include spec') @@ -354,6 +364,11 @@ def _parse_include_spec( qualified = _canonicalize_path(spec, path.parent) rewrites = _apply_include_map(qualified, include_map) if rewrites is None: + if no_absolute and spec.startswith('/'): + raise ValueError( + f'jw.include-map-no-absolute: absolute include ' + f'{spec!r} in {path} is not covered by the include map' + ) rewrites = [qualified] paths: list[Path] = [] for rewrite in rewrites: @@ -367,6 +382,7 @@ def _normalize_include_specs( path: Path, include_map: IncludeMap, expand_vars: bool, + no_absolute: bool, ) -> Includes: if specs is None: return [] @@ -378,7 +394,9 @@ def _normalize_include_specs( for spec in specs: if not isinstance(spec, str): raise TypeError(f'Unsupported include entry: {spec!r}') - ret.extend(_parse_include_spec(spec, path, include_map, expand_vars)) + ret.extend( + _parse_include_spec(spec, path, include_map, expand_vars, no_absolute) + ) return ret # -- Include target-path merging ----------------------------------------------- @@ -594,6 +612,7 @@ def _load_yaml( seen: set[Path], depth: int, include_map: IncludeMap | None, + no_absolute: bool, ) -> dict[str, Any]: path = Path(path).resolve() if path in seen: @@ -618,19 +637,22 @@ def _load_yaml( return {} raise if include_map is None: + no_absolute = bool(ret.pop('jw.include-map-no-absolute', False)) include_map = _parse_include_map( ret.pop('jw.include-map', None), path.parent, str(path) ) - elif 'jw.include-map' in ret: + elif 'jw.include-map' in ret \ + or 'jw.include-map-no-absolute' in ret: raise ValueError( - f'jw.include-map is only allowed in the top-level ' - f'document: {path}' + f'jw.include-map and jw.include-map-no-absolute are ' + f'only allowed in the top-level document: {path}' ) includes = _normalize_include_specs( ret.get('jw.include', []), path, include_map = include_map, - expand_vars = depth == 0 + expand_vars = depth == 0, + no_absolute = no_absolute ) ret.pop('jw.include', None) included_all: dict[str, Any] = {} @@ -641,7 +663,8 @@ def _load_yaml( optional = opt, seen = seen, depth = depth + 1, - include_map = include_map + include_map = include_map, + no_absolute = no_absolute ) if not included_next: # An empty document contributes nothing; in particular @@ -660,7 +683,9 @@ def _load_yaml( def load_yaml(path: str | Path, optional: bool = False) -> dict[str, Any]: # export seen: set[Path] = set() return _expand_links( - _load_yaml(path, optional, seen, depth = 0, include_map = None) + _load_yaml( + path, optional, seen, depth = 0, include_map = None, no_absolute = False + ) ) if __name__ == '__main__': diff --git a/test/unit/python/jw/util/load_yaml/test.py b/test/unit/python/jw/util/load_yaml/test.py index 39e1ea5..49edb53 100644 --- a/test/unit/python/jw/util/load_yaml/test.py +++ b/test/unit/python/jw/util/load_yaml/test.py @@ -1487,6 +1487,106 @@ class TestIncludeMap: data = load_yaml(main) assert data['ok'] == 1 +class TestIncludeMapNoAbsolute: + """Tests for the jw.include-map-no-absolute guard.""" + + def test_absolute_uncovered_raises(self, temp_dir: _TempDir) -> None: + """An absolute spec with no matching entry raises.""" + base = temp_dir( + [ + ( + 'wrapper.yaml', + 'jw.include-map: []\n' + 'jw.include-map-no-absolute: true\n' + 'jw.include: /etc/app.yaml\n' + ), + ] + ) + with pytest.raises(ValueError, match = 'not covered by the include map'): + load_yaml(pathlib.Path(base) / 'wrapper.yaml') + + def test_absolute_covered_ok(self, temp_dir: _TempDir) -> None: + """An absolute spec covered by the map loads.""" + base = temp_dir( + [ + ('app.yaml', 'ok: 1\n'), + ( + 'wrapper.yaml', + 'jw.include-map:\n' + ' - /etc/app.yaml: app.yaml\n' + 'jw.include-map-no-absolute: true\n' + 'jw.include: /etc/app.yaml\n' + ), + ] + ) + data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') + assert data['ok'] == 1 + + def test_nested_absolute_uncovered_raises(self, temp_dir: _TempDir) -> None: + """The guard covers nested includes, not just the wrapper's own.""" + base = temp_dir( + [ + ('prod.yaml', 'jw.include: /etc/app.yaml\n'), + ( + 'wrapper.yaml', + 'jw.include-map: []\n' + 'jw.include-map-no-absolute: true\n' + 'jw.include: prod.yaml\n' + ), + ] + ) + with pytest.raises(ValueError, match = 'not covered by the include map'): + load_yaml(pathlib.Path(base) / 'wrapper.yaml') + + def test_relative_specs_pass(self, temp_dir: _TempDir) -> None: + """Relative specs are unaffected by the guard.""" + base = temp_dir( + [ + ('app.yaml', 'ok: 1\n'), + ( + 'wrapper.yaml', + 'jw.include-map: []\n' + 'jw.include-map-no-absolute: true\n' + 'jw.include: app.yaml\n' + ), + ] + ) + data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') + assert data['ok'] == 1 + + def test_identity_entry_whitelists(self, temp_dir: _TempDir) -> None: + """An identity entry whitelists an absolute path.""" + base = temp_dir([('real.yaml', 'ok: 1\n')]) + main = pathlib.Path(base) / 'wrapper.yaml' + main.write_text( + 'jw.include-map:\n' + f' - {base}/real.yaml: {base}/real.yaml\n' + 'jw.include-map-no-absolute: true\n' + f'jw.include: {base}/real.yaml\n' + ) + data = load_yaml(main) + assert data['ok'] == 1 + + def test_default_is_false(self, temp_dir: _TempDir) -> None: + """Without the flag, an uncovered absolute spec is read from disk.""" + base = temp_dir( + [('wrapper.yaml', 'jw.include-map: []\n' + 'jw.include: /etc/app.yaml\n')] + ) + with pytest.raises(FileNotFoundError): + load_yaml(pathlib.Path(base) / 'wrapper.yaml') + + def test_nested_flag_raises(self, temp_dir: _TempDir) -> None: + """The flag in a non-top-level document raises.""" + base = temp_dir( + [ + ('inner.yaml', 'jw.include-map-no-absolute: true\n'), + ('wrapper.yaml', 'jw.include: inner.yaml\n'), + ] + ) + with pytest.raises(ValueError, match = 'top-level'): + load_yaml(pathlib.Path(base) / 'wrapper.yaml') + # -- jw.include with target path ------------------------------------------------ class TestPathResolution: