From 2416257cba7fea5afd60f2c96d4129a471d1e3bd Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Wed, 11 Nov 2026 13:16:54 +0100 Subject: [PATCH] lib.pf.PkgSecrets: Add The on-host store scopes its address space to the config paths backed by installed packages, but the scope lives inside KvFile: it derives the set from the distro itself and consults it in the individual operations. A context that carries a filter must behave as the filter mandates, so the wanted set belongs in a filter of its own. Add the pkg-secrets path filter, a Pkg whose space is the config paths of the matching packages' template files - the path with the .jw-tmpl suffix stripped - plus the directories leading to them. A compound or blob address maps to its config path, a key address to the config path of the compound it lives under; any other address is judged on its own. The spec form follows pkg: a bare spec matches every installed package, and pkg-secrets:url=~REGEX narrows the backing set to packages whose url matches. Pkg parses its criterion through an overridable _parse_spec(), and its _match_pkg() matches every package on a None criterion, so both filters share the parsing and matching code. Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.2 Signed-off-by: Jan Lindemann --- src/python/jw/pkg/lib/pf/Pkg.py | 15 +- src/python/jw/pkg/lib/pf/PkgSecrets.py | 91 ++++++++++++ .../python/jw/pkg/lib/pf/PkgSecrets/Makefile | 7 + .../python/jw/pkg/lib/pf/PkgSecrets/test.py | 138 ++++++++++++++++++ 4 files changed, 247 insertions(+), 4 deletions(-) create mode 100644 src/python/jw/pkg/lib/pf/PkgSecrets.py create mode 100644 test/unit/python/jw/pkg/lib/pf/PkgSecrets/Makefile create mode 100644 test/unit/python/jw/pkg/lib/pf/PkgSecrets/test.py diff --git a/src/python/jw/pkg/lib/pf/Pkg.py b/src/python/jw/pkg/lib/pf/Pkg.py index 9eddecdb..a11e9a0c 100644 --- a/src/python/jw/pkg/lib/pf/Pkg.py +++ b/src/python/jw/pkg/lib/pf/Pkg.py @@ -74,17 +74,24 @@ class Pkg(PackageFilter): # export def __init__(self, *, spec: str, file_context: FileContext, **kwargs: Any) -> None: super().__init__(spec = spec, file_context = file_context, **kwargs) - # -- Poor man's parsing for now + self.__criterion, self.__rx = self._parse_spec(spec) + + def _parse_spec(self, spec: str) -> tuple[str | None, re.Pattern[str] | None]: + # -- Poor man's parsing for now: "pkg:criterion=~regex", + # where the criterion picks the package attribute to + # match m = re.match(r'^\s*pkg\s*:\s*(\S+?)\s*=~\s*(.+?)\s*$', spec) if m is None: raise Exception(f'Unsupported filter string "{spec}"') - self.__criterion = m.group(1) - self.__rx = re.compile(m.group(2)) + return m.group(1), re.compile(m.group(2)) @override def _match_pkg(self, package: Package) -> bool: - if self.__criterion != 'url': + # -- A None criterion or regex matches every package + if self.__criterion not in (None, 'url'): return False + if self.__rx is None: + return True url = package.url if url is None: return False diff --git a/src/python/jw/pkg/lib/pf/PkgSecrets.py b/src/python/jw/pkg/lib/pf/PkgSecrets.py new file mode 100644 index 00000000..15703dc3 --- /dev/null +++ b/src/python/jw/pkg/lib/pf/PkgSecrets.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +import os +import re + +from pathlib import Path +from typing import TYPE_CHECKING, Any, override + +from ..ec.secret_store.layout import TMPL_SUFFIX, target_name +from .Pkg import Pkg + +if TYPE_CHECKING: + from ..Distro import Distro + from ..FileContext import FileContext + from ..PathFilter import PathFilter + +class PkgSecrets(Pkg): # export + + def __init__(self, *, spec: str, file_context: FileContext, **kwargs: Any) -> None: + super().__init__(spec = spec, file_context = file_context, **kwargs) + self.___targets: list[str] | None = None + self.___targets_set: set[str] | None = None + self.___targets_and_parents: set[str] | None = None + + @override + def _parse_spec(self, spec: str) -> tuple[str | None, re.Pattern[str] | None]: + # -- "pkg-secrets:criterion=~regex", following Pkg; a bare + # spec (no criterion) matches every installed package + m = re.match(r'^\s*pkg-secrets\s*:\s*(?:(\S+?)\s*=~\s*(.+?))?\s*$', spec) + if m is None: + raise Exception(f'Unsupported filter string "{spec}"') + criterion = m.group(1) + if criterion is not None and criterion != 'url': + raise Exception(f'Unsupported criterion "{criterion}" in "{spec}"') + rx = re.compile(m.group(2)) if m.group(2) is not None else None + return criterion, rx + + async def __targets(self) -> list[str]: + if self.___targets is None: + self.___targets = await self.distro_target_paths( + await self.distro(), filter = self + ) + return self.___targets + + async def __targets_set(self) -> set[str]: + if self.___targets_set is None: + self.___targets_set = set(await self.__targets()) + return self.___targets_set + + async def __targets_and_parents(self) -> set[str]: + if self.___targets_and_parents is None: + ret: set[str] = set() + cfgs = await self.__targets() + for p in cfgs: + item = Path(p) + for i in (item, *item.parents): + ret.add(str(i)) + self.___targets_and_parents = ret + return self.___targets_and_parents + + @override + async def _access(self, path: str, mode: int = os.F_OK) -> bool: + p = path.lstrip('/') + targets = target_name(p) + if targets is not None: + return targets in await self.__targets_and_parents() + if '/' in p: + parent = p.rpartition('/')[0] + ptargets = target_name(parent) + if ptargets is not None and ptargets in \ + await self.__targets_and_parents(): + return True + if parent in await self.__targets_set(): + return True + # -- A directory, a plain file, the root + return (p or '.') in await self.__targets_and_parents() + + @classmethod + async def distro_target_paths( + cls, + distro: Distro, + filter: PathFilter | None, + ) -> list[str]: + return sorted( + path.lstrip('/')[:-len(TMPL_SUFFIX)] + for path in await distro.paths(filter = filter) + if path.endswith(TMPL_SUFFIX) + ) + + async def target_paths(self) -> list[str]: + return await self.__targets() diff --git a/test/unit/python/jw/pkg/lib/pf/PkgSecrets/Makefile b/test/unit/python/jw/pkg/lib/pf/PkgSecrets/Makefile new file mode 100644 index 00000000..49c7c21f --- /dev/null +++ b/test/unit/python/jw/pkg/lib/pf/PkgSecrets/Makefile @@ -0,0 +1,7 @@ +TOPDIR = ../../../../../../../../ + +include $(TOPDIR)/make/proj.mk +include $(JWBDIR)/make/py-run.mk + +all: +test: run diff --git a/test/unit/python/jw/pkg/lib/pf/PkgSecrets/test.py b/test/unit/python/jw/pkg/lib/pf/PkgSecrets/test.py new file mode 100644 index 00000000..35d706f7 --- /dev/null +++ b/test/unit/python/jw/pkg/lib/pf/PkgSecrets/test.py @@ -0,0 +1,138 @@ +from __future__ import annotations + +import asyncio + +from typing import TYPE_CHECKING, Any, override + +from jw.pkg.lib.FileContext import FileContext +from jw.pkg.lib.Package import Package +from jw.pkg.lib.PathFilter import PathFilter, Verdict +from jw.pkg.lib.pf.PkgSecrets import PkgSecrets + +if TYPE_CHECKING: + from jw.pkg.lib.Result import Result + +class _StubFC(FileContext): + + def __init__(self) -> None: + super().__init__(uri = 'file:///') + + @override + async def _get( + self, path: str, wd: str | None, throw: bool, verbose: bool | None, title: str + ) -> Result: + raise NotImplementedError() + +# -- Unsupported specs raise at construction -- + +for bad in ['pkg-secrets', 'pkg-secrets:uri', 'pkg-secrets:name=~x']: + try: + PkgSecrets(spec = bad, file_context = _StubFC()) + assert False, f'Should have raised for "{bad}"' + except Exception: + pass + +class _FakeDistro: + + def __init__(self, pkgs: list[tuple[str, str | None, list[str]]]) -> None: + self.__pkgs = [ + (Package(name = name, url = url), files) for name, url, files in pkgs + ] + + async def select(self, + names: list[str] | None = None, + filter: Any = None) -> list[Package]: + return [p for p, _ in self.__pkgs if filter is None or filter.match_pkg(p)] + + async def pkg_paths(self, names: list[str] | None = None) -> list[str]: + ret: list[str] = [] + for p, files in self.__pkgs: + if names is None or p.name in names: + ret.extend(files) + return ret + + async def paths(self, filter: Any = None, pkg_names: Any = []) -> list[str]: + ret: list[str] = [] + for p, files in self.__pkgs: + if filter is not None and not filter.match_pkg(p): + continue + if pkg_names and p.name not in pkg_names: + continue + ret.extend(files) + return ret + +fake = _FakeDistro( + [ + ( + 'fixture', + 'https://example.com/fixture.rpm', + ['/etc/foo.conf.jw-tmpl', '/etc/fixture.conf', '/opt/jw-x/app.ini.jw-tmpl'], + ), + ('other', 'https://elsewhere.org/other.rpm', ['/etc/bar.conf.jw-tmpl']), + ] +) + +async def __run_tests() -> None: + from unittest import mock + + from jw.pkg.lib.Distro import Distro + from jw.pkg.lib.ec.Local import Local + + async def __instantiate(*args: Any, **kwargs: Any) -> _FakeDistro: + return fake + + with mock.patch.object(Distro, 'instantiate', new = classmethod(__instantiate)): + # -- Unscoped: every installed package backs + f = PkgSecrets(spec = 'pkg-secrets:', file_context = Local('local')) + # A compound, a key below it, and a blob are all addressable + assert await f.run('etc/foo.conf.jw-secret') == Verdict.ALLOW + assert await f.run('etc/foo.conf.jw-secret/key') == Verdict.ALLOW + # -- A key below the compound, its name unsuffixed + assert await f.run('etc/foo.conf/key') == Verdict.ALLOW + assert await f.run('opt/jw-x/app.ini/key') == Verdict.ALLOW + assert await f.run('etc/plain/key') == Verdict.IGNORE + assert await f.run('etc/foo.conf.jw-secret-file') == Verdict.ALLOW + # A deep target path + assert await f.run('opt/jw-x/app.ini.jw-secret') == Verdict.ALLOW + # The other package backs too, unscoped + assert await f.run('etc/bar.conf.jw-secret-file') == Verdict.ALLOW + # A plain file is not a target path + assert await f.run('etc/fixture.conf') == Verdict.IGNORE + # No template for this target path: the orphan case + assert await f.run('etc/fixture.conf.jw-secret') == Verdict.IGNORE + assert await f.run('nope.jw-secret') == Verdict.IGNORE + # Directories leading to target paths, and the root + assert await f.run('etc') == Verdict.ALLOW + assert await f.run('opt/jw-x') == Verdict.ALLOW + assert await f.run('') == Verdict.ALLOW + + # -- The backing set, as the filter computes it + assert await f.target_paths() == [ + 'etc/bar.conf', 'etc/foo.conf', 'opt/jw-x/app.ini' + ] + + # -- Scoped: only the matching packages back + f2 = PkgSecrets( + spec = 'pkg-secrets:url=~example\\.com', file_context = Local('local') + ) + assert await f2.run('etc/foo.conf.jw-secret') == Verdict.ALLOW + assert await f2.run('etc/bar.conf.jw-secret') == Verdict.IGNORE + assert await f2.target_paths() == ['etc/foo.conf', 'opt/jw-x/app.ini'] + + # -- PathFilter.create() resolves the kebab name + f3 = PathFilter.create( + spec = 'pkg-secrets:url=~example\\.com', file_context = Local('local') + ) + assert isinstance(f3, PkgSecrets) + + # -- A context that cannot be probed rejects + f4 = PkgSecrets(spec = 'pkg-secrets:', file_context = _StubFC()) + try: + await f4.run('etc/foo.conf.jw-secret') + assert False, 'An unbacked context should reject path queries' + except Exception as e: + assert 'backed by distributions' in str(e) + +asyncio.run(__run_tests()) + +print('All lib.pf.PkgSecrets tests passed')