From 5ac36ec2716002c667ae5a3d4f5b418d13fba579 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Thu, 12 Nov 2026 10:48:05 +0100 Subject: [PATCH 1/9] lib.Distro.pkg_files() -> .pkg_paths() "files" is a term that can be used for many aspects of a file, its path, its content, a handle, so better use "pkg_paths" instead of "pkg_files" for Distro's method to inform about which files a package holds. That also aligns better with the recent move from PackageFilter toward PathFilter. Signed-off-by: Jan Lindemann --- src/python/jw/pkg/cmds/pkg/CmdLs.py | 2 +- .../jw/pkg/cmds/secrets/lib/DistroContext.py | 2 +- src/python/jw/pkg/lib/Distro.py | 8 ++++---- src/python/jw/pkg/lib/distros/arch/Distro.py | 2 +- src/python/jw/pkg/lib/distros/debian/Distro.py | 2 +- src/python/jw/pkg/lib/distros/redhat/Distro.py | 2 +- src/python/jw/pkg/lib/distros/suse/Distro.py | 2 +- src/python/jw/pkg/lib/ec/secret_store/KvFile.py | 2 +- src/python/jw/pkg/lib/pf/Pkg.py | 2 +- test/integration/jw_pkg/secrets/test.py | 2 +- test/unit/python/jw/pkg/lib/Distro/test.py | 16 ++++++++-------- .../jw/pkg/lib/ec/secret_store/KvFile/test.py | 2 +- .../jw/pkg/lib/ec/secret_store/Sops/test.py | 2 +- .../jw/pkg/lib/ec/secret_store/TarGpg/test.py | 2 +- .../jw/pkg/lib/ec/secret_store/Vault/test.py | 2 +- test/unit/python/jw/pkg/lib/pf/Pkg/test.py | 2 +- 16 files changed, 26 insertions(+), 26 deletions(-) diff --git a/src/python/jw/pkg/cmds/pkg/CmdLs.py b/src/python/jw/pkg/cmds/pkg/CmdLs.py index b3a74d6f..c162eda8 100644 --- a/src/python/jw/pkg/cmds/pkg/CmdLs.py +++ b/src/python/jw/pkg/cmds/pkg/CmdLs.py @@ -21,4 +21,4 @@ class CmdLs(NamedPkgsCmd): # export @override async def _run(self, args: Namespace) -> None: for name in args.names: - print('\n'.join(await self.distro.pkg_files(name))) + print('\n'.join(await self.distro.pkg_paths(name))) diff --git a/src/python/jw/pkg/cmds/secrets/lib/DistroContext.py b/src/python/jw/pkg/cmds/secrets/lib/DistroContext.py index 8f5b8cf4..3006a1a2 100644 --- a/src/python/jw/pkg/cmds/secrets/lib/DistroContext.py +++ b/src/python/jw/pkg/cmds/secrets/lib/DistroContext.py @@ -35,7 +35,7 @@ class DistroContext(FilesContext): async def match_files(self, pkg_names: Collection[str], pattern: str) -> list[str]: ret: list[str] = [] for pkg_name in pkg_names: - for path in await self.__distro.pkg_files(pkg_name): + for path in await self.__distro.pkg_paths(pkg_name): if re.match(pattern, path): ret.append(path) return ret diff --git a/src/python/jw/pkg/lib/Distro.py b/src/python/jw/pkg/lib/Distro.py index b1f911c5..4e4a98f3 100644 --- a/src/python/jw/pkg/lib/Distro.py +++ b/src/python/jw/pkg/lib/Distro.py @@ -504,13 +504,13 @@ class Distro(abc.ABC): return return await self._delete(names) - # -- pkg_files + # -- pkg_paths @abc.abstractmethod - async def _pkg_files(self, names: list[str] | None) -> Iterable[str]: + async def _pkg_paths(self, names: list[str] | None) -> Iterable[str]: pass - async def pkg_files(self, names: str | list[str] | None = None) -> Iterable[str]: + async def pkg_paths(self, names: str | list[str] | None = None) -> Iterable[str]: # -- The file paths of the packages selected by the # argument: None, the default selection, filtered to the # app's packages when a filter is set, all installed @@ -521,7 +521,7 @@ class Distro(abc.ABC): names = [names] if names is None and self.default_path_filter is not None: names = [p.name for p in await self.select()] - return await self._pkg_files(names) + return await self._pkg_paths(names) # -- verify diff --git a/src/python/jw/pkg/lib/distros/arch/Distro.py b/src/python/jw/pkg/lib/distros/arch/Distro.py index cc31b9c4..362c5708 100644 --- a/src/python/jw/pkg/lib/distros/arch/Distro.py +++ b/src/python/jw/pkg/lib/distros/arch/Distro.py @@ -67,7 +67,7 @@ class Distro(Base): ) @override - async def _pkg_files(self, names: list[str] | None) -> Iterable[str]: + async def _pkg_paths(self, names: list[str] | None) -> Iterable[str]: raise NotImplementedError( 'distro pkg ls yet implemented for Arch-like distributions' ) diff --git a/src/python/jw/pkg/lib/distros/debian/Distro.py b/src/python/jw/pkg/lib/distros/debian/Distro.py index b6f472d0..a9d73fa9 100644 --- a/src/python/jw/pkg/lib/distros/debian/Distro.py +++ b/src/python/jw/pkg/lib/distros/debian/Distro.py @@ -156,7 +156,7 @@ class Distro(Base): await self.dpkg(['-P', *names], sudo = True) @override - async def _pkg_files(self, names: list[str] | None) -> Iterable[str]: + async def _pkg_paths(self, names: list[str] | None) -> Iterable[str]: return await list_files(names, ec = self.ctx) @override diff --git a/src/python/jw/pkg/lib/distros/redhat/Distro.py b/src/python/jw/pkg/lib/distros/redhat/Distro.py index b365c3ad..c8f6b77a 100644 --- a/src/python/jw/pkg/lib/distros/redhat/Distro.py +++ b/src/python/jw/pkg/lib/distros/redhat/Distro.py @@ -88,7 +88,7 @@ class Distro(Base): await self.rpm(['-e', *names], sudo = True) @override - async def _pkg_files(self, names: list[str] | None) -> Iterable[str]: + async def _pkg_paths(self, names: list[str] | None) -> Iterable[str]: return await list_files(names, ec = self.ctx) @override diff --git a/src/python/jw/pkg/lib/distros/suse/Distro.py b/src/python/jw/pkg/lib/distros/suse/Distro.py index b143d839..aae12133 100644 --- a/src/python/jw/pkg/lib/distros/suse/Distro.py +++ b/src/python/jw/pkg/lib/distros/suse/Distro.py @@ -107,7 +107,7 @@ class Distro(Base): await self.rpm(['-e', *names], sudo = True) @override - async def _pkg_files(self, names: list[str] | None) -> Iterable[str]: + async def _pkg_paths(self, names: list[str] | None) -> Iterable[str]: return await list_files(names, ec = self.ctx) @override diff --git a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py index afcca673..039d4342 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py +++ b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py @@ -102,7 +102,7 @@ class KvFile(Base): async def __config_paths(self) -> list[str]: if self.___config_paths is None: ret: set[str] = set() - for f in await (await self.__distro()).pkg_files(): + for f in await (await self.__distro()).pkg_paths(): if not f.endswith('.jw-tmpl'): continue ret.add(f.lstrip('/')[:-len('.jw-tmpl')]) diff --git a/src/python/jw/pkg/lib/pf/Pkg.py b/src/python/jw/pkg/lib/pf/Pkg.py index b45dff44..be26db2e 100644 --- a/src/python/jw/pkg/lib/pf/Pkg.py +++ b/src/python/jw/pkg/lib/pf/Pkg.py @@ -66,7 +66,7 @@ class PackageFilter(FileContextFilter): # export if self.__space is None: distro = await self.distro() names = [p.name for p in await distro.select([], filter = self)] - self.__space = set(self.__add_parent_paths(await distro.pkg_files(names))) + self.__space = set(self.__add_parent_paths(await distro.pkg_paths(names))) return path in self.__space class Pkg(PackageFilter): # export diff --git a/test/integration/jw_pkg/secrets/test.py b/test/integration/jw_pkg/secrets/test.py index 3daed322..b61ed17d 100644 --- a/test/integration/jw_pkg/secrets/test.py +++ b/test/integration/jw_pkg/secrets/test.py @@ -72,7 +72,7 @@ class FakeDistro(SuseDistro): return [Package(name) for name in names if name in self.__files] @override - async def _pkg_files(self, names: list[str] | None) -> list[str]: + async def _pkg_paths(self, names: list[str] | None) -> list[str]: if names is None: names = list(self.__files) ret: list[str] = [] diff --git a/test/unit/python/jw/pkg/lib/Distro/test.py b/test/unit/python/jw/pkg/lib/Distro/test.py index 6af6c125..620bde88 100644 --- a/test/unit/python/jw/pkg/lib/Distro/test.py +++ b/test/unit/python/jw/pkg/lib/Distro/test.py @@ -63,7 +63,7 @@ class DummyDistro(Distro): pass @override - async def _pkg_files(self, names: list[str] | None) -> Iterable[str]: + async def _pkg_paths(self, names: list[str] | None) -> Iterable[str]: return [] @override @@ -97,7 +97,7 @@ vd.verified = None assert asyncio.run(vd.verify()) == [] assert vd.verified is None -# -- pkg_files -- +# -- pkg_paths -- # -- Without a filter, the selection is passed through as the # whole system; the paths come back unfiltered @@ -113,7 +113,7 @@ class TmplDistro(DummyDistro): return [Package(n) for n in self.files] @override - async def _pkg_files(self, names: list[str] | None) -> list[str]: + async def _pkg_paths(self, names: list[str] | None) -> list[str]: if names is None: names = list(self.files) ret: list[str] = [] @@ -126,12 +126,12 @@ t.files = { 'a': ['/usr/share/a/a.conf.jw-tmpl', '/usr/bin/a'], 'b': ['/etc/b/b.conf.jw-tmpl'], } -assert sorted(asyncio.run(t.pkg_files())) == [ +assert sorted(asyncio.run(t.pkg_paths())) == [ '/etc/b/b.conf.jw-tmpl', '/usr/bin/a', '/usr/share/a/a.conf.jw-tmpl' ] # -- A single package name as a str is accepted for compatibility -assert sorted(asyncio.run(t.pkg_files('a'))) == [ +assert sorted(asyncio.run(t.pkg_paths('a'))) == [ '/usr/bin/a', '/usr/share/a/a.conf.jw-tmpl', ] @@ -261,7 +261,7 @@ class CannedRpmLocal(Local): cl = CannedRpmLocal() sd = SuseDistro(cl, id = 'suse', os_release_str = OS_RELEASE_SUSE) -assert asyncio.run(sd.pkg_files()) == [ +assert asyncio.run(sd.pkg_paths()) == [ '/usr/bin/x', '/etc/a/a.conf.jw-tmpl', ] @@ -273,7 +273,7 @@ sdf = SuseDistro( os_release_str = OS_RELEASE_SUSE, default_path_filter = Pkg(spec = 'pkg:url=~jw.dev', file_context = cl) ) -assert asyncio.run(sdf.pkg_files()) == \ +assert asyncio.run(sdf.pkg_paths()) == \ ['/etc/a/a.conf.jw-tmpl', '/etc/b/b.conf.jw-tmpl'] assert cl.cmds[-1] == ['/usr/bin/rpm', '-ql', 'a', 'b'] @@ -283,7 +283,7 @@ sde = SuseDistro( os_release_str = OS_RELEASE_SUSE, default_path_filter = Pkg(spec = 'pkg:url=~zzz-nomatch', file_context = cl) ) -assert asyncio.run(sde.pkg_files()) == [] +assert asyncio.run(sde.pkg_paths()) == [] assert '--queryformat' in cl.cmds[-1] # -- _install_local_files -- diff --git a/test/unit/python/jw/pkg/lib/ec/secret_store/KvFile/test.py b/test/unit/python/jw/pkg/lib/ec/secret_store/KvFile/test.py index 7cbaebbc..c511b641 100644 --- a/test/unit/python/jw/pkg/lib/ec/secret_store/KvFile/test.py +++ b/test/unit/python/jw/pkg/lib/ec/secret_store/KvFile/test.py @@ -212,7 +212,7 @@ async def run_tests() -> None: self.queries = 0 @override - async def _pkg_files(self, names: list[str] | None) -> list[str]: + async def _pkg_paths(self, names: list[str] | None) -> list[str]: self.queries += 1 return self.files diff --git a/test/unit/python/jw/pkg/lib/ec/secret_store/Sops/test.py b/test/unit/python/jw/pkg/lib/ec/secret_store/Sops/test.py index a6d163cd..a8f4c8fd 100644 --- a/test/unit/python/jw/pkg/lib/ec/secret_store/Sops/test.py +++ b/test/unit/python/jw/pkg/lib/ec/secret_store/Sops/test.py @@ -336,7 +336,7 @@ async def run_tests() -> None: self.files = files @override - async def _pkg_files(self, names: list[str] | None) -> list[str]: + async def _pkg_paths(self, names: list[str] | None) -> list[str]: return self.files fake = FakeDistro( diff --git a/test/unit/python/jw/pkg/lib/ec/secret_store/TarGpg/test.py b/test/unit/python/jw/pkg/lib/ec/secret_store/TarGpg/test.py index b202b15a..b89de064 100644 --- a/test/unit/python/jw/pkg/lib/ec/secret_store/TarGpg/test.py +++ b/test/unit/python/jw/pkg/lib/ec/secret_store/TarGpg/test.py @@ -321,7 +321,7 @@ async def run_tests() -> None: self.files = files @override - async def _pkg_files(self, names: list[str] | None) -> list[str]: + async def _pkg_paths(self, names: list[str] | None) -> list[str]: return self.files fake = FakeDistro( diff --git a/test/unit/python/jw/pkg/lib/ec/secret_store/Vault/test.py b/test/unit/python/jw/pkg/lib/ec/secret_store/Vault/test.py index ff3892b6..1ae661a6 100644 --- a/test/unit/python/jw/pkg/lib/ec/secret_store/Vault/test.py +++ b/test/unit/python/jw/pkg/lib/ec/secret_store/Vault/test.py @@ -351,7 +351,7 @@ async def run_tests() -> None: self.files = files @override - async def _pkg_files(self, names: list[str] | None) -> list[str]: + async def _pkg_paths(self, names: list[str] | None) -> list[str]: return self.files fake = FakeDistro( diff --git a/test/unit/python/jw/pkg/lib/pf/Pkg/test.py b/test/unit/python/jw/pkg/lib/pf/Pkg/test.py index ad10bde0..6444e260 100644 --- a/test/unit/python/jw/pkg/lib/pf/Pkg/test.py +++ b/test/unit/python/jw/pkg/lib/pf/Pkg/test.py @@ -77,7 +77,7 @@ class _FakeDistro: filter: Any = None) -> list[Package]: return [p for p, _ in self.__pkgs if filter is None or filter.match_pkg(p)] - async def pkg_files(self, names: list[str] | None = None) -> list[str]: + 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: -- 2.56.1 From 372356a8df47839e52464ff4a6fe9970704f1640 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Wed, 11 Nov 2026 09:09:02 +0100 Subject: [PATCH 2/9] lib.util: Add kebab_to_pascal() and pascal_to_kebab() PathFilter.create() currently instantiates individual filters in a match - case over the filter URI's protocol. The plan is to instantiate filters without match / case based on a protocol naming scheme only, so we better introduce one at this point. Adopt jw-python's kebab_to_pascal() and pascal_to_kebab() functions as a foundation for a future naming convention. Signed-off-by: Jan Lindemann --- src/python/jw/pkg/lib/PathFilter.py | 4 +++- src/python/jw/pkg/lib/util.py | 10 ++++++++++ test/unit/python/jw/pkg/lib/pf/Pkg/test.py | 8 ++++++++ test/unit/python/jw/pkg/lib/util/test.py | 9 ++++++++- 4 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/python/jw/pkg/lib/PathFilter.py b/src/python/jw/pkg/lib/PathFilter.py index dd1148aa..6f0b43c4 100644 --- a/src/python/jw/pkg/lib/PathFilter.py +++ b/src/python/jw/pkg/lib/PathFilter.py @@ -54,7 +54,9 @@ class PathFilter(abc.ABC): f'Unsupported filter spec "{spec}": expected a "name:spec" ' 'form, where the name picks the filter class' ) - class_name = name.capitalize() + from .util import kebab_to_pascal + + class_name = kebab_to_pascal(name) module_name = 'jw.pkg.lib.pf.' + class_name filter_classes: LoadTypes[PathFilter] = LoadTypes( [module_name], diff --git a/src/python/jw/pkg/lib/util.py b/src/python/jw/pkg/lib/util.py index ab06270c..f8eb78bd 100644 --- a/src/python/jw/pkg/lib/util.py +++ b/src/python/jw/pkg/lib/util.py @@ -2,6 +2,7 @@ from __future__ import annotations import json import os +import re import sys from enum import Enum, auto @@ -38,6 +39,15 @@ def pretty_cmd(cmd: list[str] | None = None, wd: str | None = None) -> str: ret += f' in {wd}' return ret +def kebab_to_pascal(value: str) -> str: + return ''.join(part.capitalize() for part in value.split('-')) + +def pascal_to_kebab(value: str) -> str: + # Handles normal CamelCase / PascalCase, including many acronym cases + s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1-\2', value) + s2 = re.sub(r'([a-z0-9])([A-Z])', r'\1-\2', s1) + return s2.lower() + # See ExecContext.run() for what this function does async def run_cmd( *args: Any, diff --git a/test/unit/python/jw/pkg/lib/pf/Pkg/test.py b/test/unit/python/jw/pkg/lib/pf/Pkg/test.py index 6444e260..9260a7a7 100644 --- a/test/unit/python/jw/pkg/lib/pf/Pkg/test.py +++ b/test/unit/python/jw/pkg/lib/pf/Pkg/test.py @@ -6,6 +6,7 @@ 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 from jw.pkg.lib.pf.Pkg import Pkg if TYPE_CHECKING: @@ -65,6 +66,13 @@ for definition in ('', f = Pkg(file_context = fc, spec = 'pkg:url=~example\\.com') assert repr(f) == 'filter:pkg:url=~example\\.com' +# -- PathFilter.create() resolves the name kebab-to-pascal -- + +f3 = PathFilter.create(spec = 'pkg:url=~example\\.com', file_context = fc) +assert isinstance(f3, Pkg) +assert f3.match_pkg(pkg) +assert not f3.match_pkg(pkg_other) + class _FakeDistro: def __init__(self, pkgs: list[tuple[str, str | None, list[str]]]) -> None: diff --git a/test/unit/python/jw/pkg/lib/util/test.py b/test/unit/python/jw/pkg/lib/util/test.py index 8771a905..aaf65cbc 100644 --- a/test/unit/python/jw/pkg/lib/util/test.py +++ b/test/unit/python/jw/pkg/lib/util/test.py @@ -4,12 +4,19 @@ import stat import tempfile from jw.pkg.lib.ec.Local import Local -from jw.pkg.lib.util import copy +from jw.pkg.lib.util import copy, kebab_to_pascal, pascal_to_kebab def uri(path: str) -> str: return 'local://localhost' + path async def run_tests() -> None: + # -- kebab <-> pascal: the name conversion behind the dynamic + # loading of filters and, later, file contexts + assert kebab_to_pascal('pkg') == 'Pkg' + assert kebab_to_pascal('pkg-secrets') == 'PkgSecrets' + assert pascal_to_kebab('Pkg') == 'pkg' + assert pascal_to_kebab('PkgSecrets') == 'pkg-secrets' + with tempfile.TemporaryDirectory() as tmp: # -- Source tree # -- 2.56.1 From 9bf5e07da02aee39b3fe52cd00981f698edf847a Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Thu, 12 Nov 2026 15:59:48 +0100 Subject: [PATCH 3/9] lib.FileContext: Add _set / _create_path_filter() Make the __create_path_filter() closure an overwritable, protected method _create_path_filter(), and add _set_path_filter() to allow subclasses to hook into external path filter manipulations, too. Signed-off-by: Jan Lindemann --- src/python/jw/pkg/lib/FileContext.py | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/python/jw/pkg/lib/FileContext.py b/src/python/jw/pkg/lib/FileContext.py index 2caa26f9..e5ced518 100644 --- a/src/python/jw/pkg/lib/FileContext.py +++ b/src/python/jw/pkg/lib/FileContext.py @@ -124,29 +124,31 @@ class FileContext(abc.ABC): def chroot(self) -> bool: return self.__chroot + def _create_path_filter( + self, candidate: str | PathFilter | Literal[False] | None + ) -> PathFilter | Literal[False]: + if candidate is None or candidate is False: + return False + if isinstance(candidate, PathFilter): + return candidate + return PathFilter.create(spec = candidate, file_context = self) + @property def path_filter(self) -> PathFilter | None: - - def __create_path_filter( - candidate: str | None | PathFilter | Literal[False] - ) -> PathFilter | Literal[False]: - if candidate is None or candidate is False: - return False - if isinstance(candidate, PathFilter): - return candidate - return PathFilter.create(spec = candidate, file_context = self) - if self.__path_filter is None: query = self.__uri.query_dict if self.__uri.query_dict else {} candidate: str | PathFilter | Literal[False] | None = \ query.get('path-filter') if candidate is None: candidate = self.__default_path_filter - self.__path_filter = __create_path_filter(candidate) + self.__path_filter = self._create_path_filter(candidate) return self.__path_filter or None @path_filter.setter def path_filter(self, value: str | PathFilter | None | Literal[False]) -> None: + self._set_path_filter(value) + + def _set_path_filter(self, value: str | PathFilter | None | Literal[False]) -> None: self.__path_filter = None self.__default_path_filter = value -- 2.56.1 From dc9ef58c8b7afbfddab43e5af8bc10365dba522b Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Thu, 12 Nov 2026 16:02:58 +0100 Subject: [PATCH 4/9] lib.Distro.paths(): Add method After the introduction of path-based filters, accompany the existing pkg_paths() method by a more fine-grained paths() method, taking a PathFilter instead of a PackageFilter. It additionally takes a "pkg_names" argument, which is then dispatched to the filter if it's a package filter. The API isn't glorious, but works for now and is easily changeable in the future: **kwargs comes to mind, or a PackageFilter which brings its own package names. Signed-off-by: Jan Lindemann --- src/python/jw/pkg/lib/Distro.py | 45 ++++++++++++++++++++- test/unit/python/jw/pkg/lib/Distro/test.py | 46 +++++++++++++++++++++- 2 files changed, 88 insertions(+), 3 deletions(-) diff --git a/src/python/jw/pkg/lib/Distro.py b/src/python/jw/pkg/lib/Distro.py index 4e4a98f3..2352be5a 100644 --- a/src/python/jw/pkg/lib/Distro.py +++ b/src/python/jw/pkg/lib/Distro.py @@ -10,6 +10,8 @@ from typing import TYPE_CHECKING, Any from .base import InputMode from .log import ERR, INFO, WARNING, log +from .PathFilter import Verdict +from .pf.Pkg import PackageFilter if TYPE_CHECKING: from collections.abc import Collection @@ -20,7 +22,6 @@ if TYPE_CHECKING: from .FlaggedFile import FlaggedFile from .Package import Package from .PathFilter import PathFilter - from .pf.Pkg import PackageFilter class Distro(abc.ABC): @@ -519,10 +520,50 @@ class Distro(abc.ABC): # compatibility with the single-package call if isinstance(names, str): names = [names] - if names is None and self.default_path_filter is not None: + elif names is None and self.default_path_filter is not None: names = [p.name for p in await self.select()] return await self._pkg_paths(names) + # -- paths + + async def _paths( + self, + filter: PathFilter | None = None, + pkg_names: Collection[str] = [], + ) -> Iterable[str]: + if filter and pkg_names and not isinstance(filter, PackageFilter): + raise Exception( + f'Tried to select files from {self} with non-package-filter {filter} ' + f'and package list {", ".join(pkg_names)}' + ) + if not filter: + filter = self.__default_path_filter + # -- pkg_names follows the select() convention: an empty + # list selects every package, which is listed in one + # whole-system query instead of by name + if isinstance(filter, PackageFilter): + pkg_names = [p.name for p in await self._select(pkg_names, filter)] + ret: list[str] = [ + path for path in await self.pkg_paths(names = list(pkg_names)) + ] + elif pkg_names: + pkg_names = [p.name for p in await self._select_by_name(pkg_names)] + ret = [path for path in await self.pkg_paths(names = list(pkg_names))] + else: + # -- _pkg_paths() directly: pkg_paths() would re-resolve + # the default filter, which _paths() already did + ret = [path for path in await self._pkg_paths(None)] + if filter and not isinstance(filter, PackageFilter): + ret = [path for path in ret if await filter.run(path) == Verdict.ALLOW] + return ret + + async def paths( + self, + filter: PathFilter | None = None, + pkg_names: Collection[str] = [], + ) -> Iterable[str]: + return await self._paths(filter, pkg_names) + # -- verify @abc.abstractmethod diff --git a/test/unit/python/jw/pkg/lib/Distro/test.py b/test/unit/python/jw/pkg/lib/Distro/test.py index 620bde88..0ec1ef89 100644 --- a/test/unit/python/jw/pkg/lib/Distro/test.py +++ b/test/unit/python/jw/pkg/lib/Distro/test.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +import os from typing import TYPE_CHECKING, Iterable, cast, override @@ -8,6 +9,7 @@ from jw.pkg.lib.Distro import Distro from jw.pkg.lib.distros.suse.Distro import Distro as SuseDistro from jw.pkg.lib.ec.Local import Local from jw.pkg.lib.Package import Package +from jw.pkg.lib.PathFilter import Handle, PathFilter from jw.pkg.lib.pf.Pkg import Pkg from jw.pkg.lib.Result import Result @@ -252,7 +254,9 @@ class CannedRpmLocal(Local): ) -> Result: self.cmds.append(cmd) if '-qal' in cmd: - out = '/usr/bin/x\n/etc/a/a.conf.jw-tmpl\n' + out = ('/usr/bin/x\n' + '/etc/a/a.conf.jw-tmpl\n' + '/etc/b/b.conf.jw-tmpl\n') elif '-ql' in cmd: out = '/etc/a/a.conf.jw-tmpl\n/etc/b/b.conf.jw-tmpl\n' else: @@ -264,6 +268,7 @@ sd = SuseDistro(cl, id = 'suse', os_release_str = OS_RELEASE_SUSE) assert asyncio.run(sd.pkg_paths()) == [ '/usr/bin/x', '/etc/a/a.conf.jw-tmpl', + '/etc/b/b.conf.jw-tmpl', ] assert cl.cmds[-1] == ['/usr/bin/rpm', '-qal'] @@ -286,6 +291,45 @@ sde = SuseDistro( assert asyncio.run(sde.pkg_paths()) == [] assert '--queryformat' in cl.cmds[-1] +# -- paths() -- + +# -- No filter and a bare path filter take the one-shot +# whole-system query, the second then checking the files one by +# one; a package filter selects the backing packages and lists +# their files by name; a path filter with package names is +# refused +class _AllowList(PathFilter): + + def __init__(self, allowed: set[str]) -> None: + super().__init__(spec = 'test:allow', handle = Handle(0)) + self.allowed = allowed + + @override + async def _access(self, path: str, mode: int = os.F_OK) -> bool: + return path in self.allowed + +allow = _AllowList({'/etc/b/b.conf.jw-tmpl'}) + +assert sorted(asyncio.run(sd.paths())) == \ + ['/etc/a/a.conf.jw-tmpl', '/etc/b/b.conf.jw-tmpl', '/usr/bin/x'] +assert cl.cmds[-1] == ['/usr/bin/rpm', '-qal'] + +assert sorted( + asyncio.run(sd.paths(filter = Pkg(spec = 'pkg:url=~jw.dev', file_context = cl))) +) == ['/etc/a/a.conf.jw-tmpl', '/etc/b/b.conf.jw-tmpl'] +assert cl.cmds[-1] == ['/usr/bin/rpm', '-ql', 'a', 'b'] + +assert asyncio.run(sd.paths(filter = allow)) == ['/etc/b/b.conf.jw-tmpl'] +assert cl.cmds[-1] == ['/usr/bin/rpm', '-qal'] + +try: + asyncio.run(sd.paths(filter = allow, pkg_names = ['a'])) + assert False, 'Should have raised' +except AssertionError: + raise +except Exception: + pass + # -- _install_local_files -- # -- With dependency resolution, the files go to the package manager; -- 2.56.1 From ea751d3949c84f893c1994df2beb84c0e919f22a Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Thu, 12 Nov 2026 16:03:58 +0100 Subject: [PATCH 5/9] pf.Pkg._access(): Use Distro.paths() Distro.paths() now allows to spare a detour in Pkg._access() - we can directly get to the list of paths instead of via Distro.select() -> pkg_paths(). Signed-off-by: Jan Lindemann --- src/python/jw/pkg/lib/pf/Pkg.py | 5 +++-- test/unit/python/jw/pkg/lib/pf/Pkg/test.py | 10 ++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/python/jw/pkg/lib/pf/Pkg.py b/src/python/jw/pkg/lib/pf/Pkg.py index be26db2e..9eddecdb 100644 --- a/src/python/jw/pkg/lib/pf/Pkg.py +++ b/src/python/jw/pkg/lib/pf/Pkg.py @@ -65,8 +65,9 @@ class PackageFilter(FileContextFilter): # export async def _access(self, path: str, mode: int = os.F_OK) -> bool: if self.__space is None: distro = await self.distro() - names = [p.name for p in await distro.select([], filter = self)] - self.__space = set(self.__add_parent_paths(await distro.pkg_paths(names))) + self.__space = set( + self.__add_parent_paths(await distro.paths(filter = self)) + ) return path in self.__space class Pkg(PackageFilter): # export diff --git a/test/unit/python/jw/pkg/lib/pf/Pkg/test.py b/test/unit/python/jw/pkg/lib/pf/Pkg/test.py index 9260a7a7..16656998 100644 --- a/test/unit/python/jw/pkg/lib/pf/Pkg/test.py +++ b/test/unit/python/jw/pkg/lib/pf/Pkg/test.py @@ -92,6 +92,16 @@ class _FakeDistro: 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( [ ( -- 2.56.1 From 48ec9fdb9584d1abf5b1379df244b2026b4b9d97 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Thu, 12 Nov 2026 17:05:42 +0100 Subject: [PATCH 6/9] lib.ec.secret_store: "content|config" -> "target" Rename lib.ec.secret_store.layout.content_name() to target_name() and KvFile's config_path to target_path(). "Target" is a better name to settle on instead of "config" or "content". It's used in other contexts, too, referring to secret compilation output. Signed-off-by: Jan Lindemann --- .../jw/pkg/lib/ec/secret_store/KvFile.py | 100 +++++++++--------- .../jw/pkg/lib/ec/secret_store/layout.py | 13 ++- .../jw/pkg/lib/ec/secret_store/layout/test.py | 10 +- 3 files changed, 63 insertions(+), 60 deletions(-) diff --git a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py index 039d4342..2154594e 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py +++ b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py @@ -63,7 +63,7 @@ class KvFile(Base): ) self.__backend_path_filter = __create_backend_path_filter() self.___distro: Distro | None = None - self.___config_paths: list[str] | None = None + self.___target_paths: list[str] | None = None self.__root = self.uri.path.lstrip('/') self.__ctx = FcCache(self.__inner) @@ -99,44 +99,44 @@ class KvFile(Base): ) return self.___distro - async def __config_paths(self) -> list[str]: - if self.___config_paths is None: + async def __target_paths(self) -> list[str]: + if self.___target_paths is None: ret: set[str] = set() for f in await (await self.__distro()).pkg_paths(): if not f.endswith('.jw-tmpl'): continue ret.add(f.lstrip('/')[:-len('.jw-tmpl')]) - self.___config_paths = sorted(ret) + self.___target_paths = sorted(ret) warm = ['/'] - warm += [f'/{p}{SECRET_SUFFIX}' for p in self.___config_paths] - warm += [f'/{p}{BLOB_SUFFIX}' for p in self.___config_paths] + warm += [f'/{p}{SECRET_SUFFIX}' for p in self.___target_paths] + warm += [f'/{p}{BLOB_SUFFIX}' for p in self.___target_paths] dirs: set[str] = set() - for p in self.___config_paths: + for p in self.___target_paths: parts = p.split('/') for i in range(1, len(parts)): dirs.add('/'.join(parts[:i])) for d in sorted(dirs): warm += [f'/{d}', f'/{d}{SECRET_SUFFIX}', f'/{d}{BLOB_SUFFIX}'] await self.__ctx.warm(warm) - assert self.___config_paths is not None - return self.___config_paths + assert self.___target_paths is not None + return self.___target_paths - async def __compound_kv(self, config_path: str) -> dict[str, str]: - path = f'/{config_path.lstrip("/")}{SECRET_SUFFIX}' + async def __compound_kv(self, target_path: str) -> dict[str, str]: + path = f'/{target_path.lstrip("/")}{SECRET_SUFFIX}' if not await self.__ctx.file_exists(path): - raise FileNotFoundError(config_path) + raise FileNotFoundError(target_path) ret = await self.__ctx.get(path) return parse_kv(ret.stdout) - async def __is_compound(self, config_path: str) -> bool: - if not config_path: + async def __is_compound(self, target_path: str) -> bool: + if not target_path: return False - return await self.__ctx.file_exists(f'/{config_path}{SECRET_SUFFIX}') + return await self.__ctx.file_exists(f'/{target_path}{SECRET_SUFFIX}') @override async def _stat(self, path: str, follow_symlinks: bool) -> StatResult: path = self.__host_path(path) - config_path, is_blob = self.__strip_suffix(path) + target_path, is_blob = self.__strip_suffix(path) async def __stat_of(host_path: str, ftype: FileType) -> StatResult: st = await self.__ctx.stat(host_path, follow_symlinks) @@ -149,16 +149,16 @@ class KvFile(Base): size = st.size, ) - if not config_path: + if not target_path: return await __stat_of('/', FT_DIR) if is_blob: - secret_path = f'/{config_path}{BLOB_SUFFIX}' + secret_path = f'/{target_path}{BLOB_SUFFIX}' if not await self.__ctx.file_exists(secret_path): raise FileNotFoundError(errno.ENOENT, f'stat: {path}') return await __stat_of(secret_path, FT_SECRET_FILE) - if await self.__is_compound(config_path): - return await __stat_of(f'/{config_path}{SECRET_SUFFIX}', FT_SECRET) - parent, sep, key = config_path.rpartition('/') + if await self.__is_compound(target_path): + return await __stat_of(f'/{target_path}{SECRET_SUFFIX}', FT_SECRET) + parent, sep, key = target_path.rpartition('/') if sep and key: parent, _ = self.__strip_suffix(parent) if await self.__is_compound(parent) and \ @@ -171,41 +171,41 @@ class KvFile(Base): FT_SECRET_KEY, mode = st.mode, ) - secret_path = f'/{config_path}{BLOB_SUFFIX}' + secret_path = f'/{target_path}{BLOB_SUFFIX}' if await self.__ctx.file_exists(secret_path): return await __stat_of(secret_path, FT_SECRET_FILE) - if await self.__ctx.is_dir(f'/{config_path}'): - return await __stat_of(f'/{config_path}', FT_DIR) + if await self.__ctx.is_dir(f'/{target_path}'): + return await __stat_of(f'/{target_path}', FT_DIR) raise FileNotFoundError(errno.ENOENT, f'stat: {path}') @override async def _is_dir(self, path: str, follow_symlinks: bool) -> bool: path = self.__host_path(path) - config_path, is_blob = self.__strip_suffix(path) - if not config_path: + target_path, is_blob = self.__strip_suffix(path) + if not target_path: return True - parent, sep, _ = config_path.rpartition('/') + parent, sep, _ = target_path.rpartition('/') if sep: parent, _ = self.__strip_suffix(parent) if await self.__is_compound(parent): return False - if await self.__is_compound(config_path): + if await self.__is_compound(target_path): return True if is_blob: return False - return await self.__ctx.is_dir(f'/{config_path}') + return await self.__ctx.is_dir(f'/{target_path}') @override async def _readdir(self, path: str) -> Iterable[str]: path = self.__host_path(path) - config_path, is_blob = self.__strip_suffix(path) - if config_path and await self.__is_compound(config_path): - return (await self.__compound_kv(config_path)).keys() - if is_blob and await self.__ctx.file_exists(f'/{config_path}{BLOB_SUFFIX}'): + target_path, is_blob = self.__strip_suffix(path) + if target_path and await self.__is_compound(target_path): + return (await self.__compound_kv(target_path)).keys() + if is_blob and await self.__ctx.file_exists(f'/{target_path}{BLOB_SUFFIX}'): raise NotADirectoryError(path) children: set[str] = set() - prefix = f'{config_path}/' if config_path else '' - for cfg in await self.__config_paths(): + prefix = f'{target_path}/' if target_path else '' + for cfg in await self.__target_paths(): if not cfg.startswith(prefix): continue rest = cfg[len(prefix):] @@ -219,8 +219,8 @@ class KvFile(Base): children.add(f'{label}{SECRET_SUFFIX}') if await self.__ctx.file_exists(f'/{cfg}{BLOB_SUFFIX}'): children.add(f'{label}{BLOB_SUFFIX}') - if config_path and not children: - if not await self.__ctx.is_dir(f'/{config_path}'): + if target_path and not children: + if not await self.__ctx.is_dir(f'/{target_path}'): raise FileNotFoundError(path) return children @@ -229,23 +229,23 @@ class KvFile(Base): self, path: str, wd: str | None, throw: bool, verbose: bool | None, title: str ) -> Result: path = self.__host_path(path) - config_path, is_blob = self.__strip_suffix(path) + target_path, is_blob = self.__strip_suffix(path) if is_blob: - secret_path = f'/{config_path}{BLOB_SUFFIX}' + secret_path = f'/{target_path}{BLOB_SUFFIX}' if not await self.__ctx.file_exists(secret_path): raise FileNotFoundError(path) return await self.__ctx.get(secret_path) - secret_path = f'/{config_path}{SECRET_SUFFIX}' + secret_path = f'/{target_path}{SECRET_SUFFIX}' if await self.__ctx.file_exists(secret_path): return await self.__ctx.get(secret_path) - secret_path = f'/{config_path}{BLOB_SUFFIX}' + secret_path = f'/{target_path}{BLOB_SUFFIX}' if await self.__ctx.file_exists(secret_path): return await self.__ctx.get(secret_path) - if await self.__ctx.is_dir(f'/{config_path}'): + if await self.__ctx.is_dir(f'/{target_path}'): raise IsADirectoryError(errno.EISDIR, f'get: {path}') - if '/' not in config_path: + if '/' not in target_path: raise FileNotFoundError(path) - compound, key = config_path.rsplit('/', 1) + compound, key = target_path.rsplit('/', 1) compound, _ = self.__strip_suffix(compound) kv = await self.__compound_kv(compound) try: @@ -256,8 +256,8 @@ class KvFile(Base): @override async def _mkdir(self, path: str, mode: int, ftype: FileType) -> None: path = self.__host_path(path) - config_path, _ = self.__strip_suffix(path) - host_path = f'/{config_path}' + target_path, _ = self.__strip_suffix(path) + host_path = f'/{target_path}' if ftype.is_subtype(FT_COMPOUND): if await self.__ctx.file_exists(host_path + SECRET_SUFFIX): return @@ -295,7 +295,7 @@ class KvFile(Base): ftype: FileType, ) -> Result: path = self.__host_path(path) - config_path, is_blob = self.__strip_suffix(path) + target_path, is_blob = self.__strip_suffix(path) if ftype.is_subtype(FT_SECRET): if is_blob: raise ValueError( @@ -303,7 +303,7 @@ class KvFile(Base): ) m = 0o400 if mode is None else int(mode, 8) return await self.__ctx.put( - f'/{config_path}{SECRET_SUFFIX}', + f'/{target_path}{SECRET_SUFFIX}', content, owner = owner, group = group, @@ -313,14 +313,14 @@ class KvFile(Base): if ftype.is_subtype(FT_SECRET_FILE): m = 0o400 if mode is None else int(mode, 8) return await self.__ctx.put( - f'/{config_path}{BLOB_SUFFIX}', + f'/{target_path}{BLOB_SUFFIX}', content, owner = owner, group = group, mode = m, atomic = True, ) - compound, sep, key = config_path.rpartition('/') + compound, sep, key = target_path.rpartition('/') if not sep or not compound or not key or '/' in key: raise ValueError(f'put: "{path}" is not a compound/key path') compound, _ = self.__strip_suffix(compound) diff --git a/src/python/jw/pkg/lib/ec/secret_store/layout.py b/src/python/jw/pkg/lib/ec/secret_store/layout.py index 67956350..ba8b54cd 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/layout.py +++ b/src/python/jw/pkg/lib/ec/secret_store/layout.py @@ -12,6 +12,9 @@ from ...file_types import FT_COMPOUND, FT_REG, file_types # # Host-specific entries take precedence over default ones. +# Suffix of the template file accompanying a compiled target +TMPL_SUFFIX = '.jw-tmpl' + # Suffix of the key-value secret file accompanying a compiled target SECRET_SUFFIX = '.jw-secret' @@ -20,11 +23,11 @@ BLOB_SUFFIX = '.jw-secret-file' DEFAULT_PREFIX = 'default' -def content_name(name: str) -> str | None: - # -- The config path of an on-host secret file name: the name - # with its content suffix removed, or None if the name - # carries neither suffix - for suffix in (SECRET_SUFFIX, BLOB_SUFFIX): +def target_name(name: str) -> str | None: + # -- The target path of a store or template file name: the + # name with its content suffix removed, or None if the + # name carries no suffix + for suffix in (TMPL_SUFFIX, SECRET_SUFFIX, BLOB_SUFFIX): if name.endswith(suffix): return name.removesuffix(suffix) return None diff --git a/test/unit/python/jw/pkg/lib/ec/secret_store/layout/test.py b/test/unit/python/jw/pkg/lib/ec/secret_store/layout/test.py index 17b8d90e..1ca50ad0 100644 --- a/test/unit/python/jw/pkg/lib/ec/secret_store/layout/test.py +++ b/test/unit/python/jw/pkg/lib/ec/secret_store/layout/test.py @@ -5,7 +5,7 @@ from jw.pkg.lib.ec.secret_store.layout import ( FT_SECRET_FILE, FT_SECRET_KEY, SECRET_SUFFIX, - content_name, + target_name, host_prefix, ) from jw.pkg.lib.file_types import FT_COMPOUND, FT_DIR, FT_REG @@ -15,11 +15,11 @@ assert DEFAULT_PREFIX == 'default' assert SECRET_SUFFIX == '.jw-secret' assert BLOB_SUFFIX == '.jw-secret-file' -# content_name strips the content suffix, and names without a +# target_name strips the content suffix, and names without a # content suffix are not store content -assert content_name('etc/a.jw-secret') == 'etc/a' -assert content_name('etc/c.pem.jw-secret-file') == 'etc/c.pem' -assert content_name('etc/README.md') is None +assert target_name('etc/a.jw-secret') == 'etc/a' +assert target_name('etc/c.pem.jw-secret-file') == 'etc/c.pem' +assert target_name('etc/README.md') is None # An FQDN maps to its reversed, dot-split host root assert host_prefix('host.example.com') == 'com/example/host' -- 2.56.1 From 2416257cba7fea5afd60f2c96d4129a471d1e3bd Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Wed, 11 Nov 2026 13:16:54 +0100 Subject: [PATCH 7/9] 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') -- 2.56.1 From fc79545c305c04f8fe4c0761205395474827f352 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Thu, 12 Nov 2026 17:22:19 +0100 Subject: [PATCH 8/9] lib.ec.secret_store.KvFile: Use PkgSecrets.target_paths() .jw-secret and .jw-secret-file detection on a distro's packages should happend in a central place. PkgSecrets.distro_target_paths() is that place, use it, instead of rolling our own detection loop. .target_paths() is a welcome performance-enhancement, reusing PkgSecret's cache. Signed-off-by: Jan Lindemann --- src/python/jw/pkg/lib/ec/secret_store/KvFile.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py index 2154594e..72d96a30 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py +++ b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py @@ -101,12 +101,14 @@ class KvFile(Base): async def __target_paths(self) -> list[str]: if self.___target_paths is None: - ret: set[str] = set() - for f in await (await self.__distro()).pkg_paths(): - if not f.endswith('.jw-tmpl'): - continue - ret.add(f.lstrip('/')[:-len('.jw-tmpl')]) - self.___target_paths = sorted(ret) + pf = self.path_filter + if isinstance(pf, PkgSecrets): + ret = await pf.target_paths() + else: + ret = await PkgSecrets.distro_target_paths( + await self.__distro(), filter = pf + ) + self.___target_paths = ret warm = ['/'] warm += [f'/{p}{SECRET_SUFFIX}' for p in self.___target_paths] warm += [f'/{p}{BLOB_SUFFIX}' for p in self.___target_paths] -- 2.56.1 From f717fe2174838473a9376dda8658c78e7ee21896 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Wed, 11 Nov 2026 19:09:29 +0100 Subject: [PATCH 9/9] lib.ec.secret_store.KvFile: Use lib.pf.PkgSecrets Do the filtering outside of KvFile, in a standard way. KvFile currently instantiates its backend distro with a self-instantiated backend filter, and doesn't propagate the filter passed to its ctor up to its base class. This arrangement makes it hard to ensure the class behaves in a standardish way. Allowing the base class filter to do its work, and not pass any filter to the backend context, is the more straightforward architecture, this is what this commit does. The base class still has some freedom to create a filter. Override the base class's _create_path_filter() to make sure that filter is a PkgSecrets / pkg-secrets: filter, anything else is not thought through at this point. Signed-off-by: Jan Lindemann --- .../jw/pkg/lib/ec/secret_store/KvFile.py | 50 +++--- .../jw/pkg/lib/ec/secret_store/KvFile/test.py | 155 +++++++++++++----- 2 files changed, 139 insertions(+), 66 deletions(-) diff --git a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py index 72d96a30..afce76e5 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py +++ b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py @@ -18,6 +18,7 @@ from ...file_types import FT_COMPOUND, FT_DIR from ...FileContext import FileContext from ...kv import parse_kv, serialize_kv from ...PathFilter import PathFilter +from ...pf.PkgSecrets import PkgSecrets from ...Result import Result from .Base import Base from .layout import BLOB_SUFFIX, FT_SECRET, FT_SECRET_FILE, FT_SECRET_KEY, SECRET_SUFFIX @@ -32,27 +33,9 @@ class KvFile(Base): default_path_filter: str | PathFilter | None | Literal[False] = None, **kwargs: Any, ) -> None: - - def __create_backend_path_filter() -> PathFilter | None: - - def __spec() -> str | None: - if isinstance(default_path_filter, str): - return default_path_filter - d = self.uri.query_dict - if d is None: - return None - return d.get('path-filter') - - if default_path_filter is False: - return None - if isinstance(default_path_filter, PathFilter): - return default_path_filter - spec: str | None = __spec() - if spec is None: - return None - return PathFilter.create(spec = spec, file_context = self.__inner) - - super().__init__(uri, *args, default_path_filter = False, **kwargs) + super().__init__( + uri, *args, default_path_filter = default_path_filter, **kwargs + ) kwargs.pop('chroot', None) scheme = 'ssh' if self.uri.hostname else 'local' self.__inner: ExecContext = cast( @@ -61,12 +44,31 @@ class KvFile(Base): f'{scheme}://{self.uri.authority}', chroot = False, **kwargs ), ) - self.__backend_path_filter = __create_backend_path_filter() self.___distro: Distro | None = None self.___target_paths: list[str] | None = None self.__root = self.uri.path.lstrip('/') self.__ctx = FcCache(self.__inner) + @override + def _create_path_filter( + self, candidate: str | PathFilter | Literal[False] | None + ) -> PathFilter | Literal[False]: + # -- The address space is scoped by a pkg-secrets filter + # backed by the inner connection, which alone knows the + # distribution; this context is a virtual layer over it + if candidate is None or candidate is False: + return False + if isinstance(candidate, PathFilter): + ret = candidate + else: + ret = PathFilter.create(spec = candidate, file_context = self.__inner) + if not isinstance(ret, PkgSecrets): + raise Exception( + f'A kvfile address space is scoped by a pkg-secrets ' + f'filter, not by {ret!r}' + ) + return ret + @override async def _open(self) -> None: await self.__inner.open() @@ -94,9 +96,7 @@ class KvFile(Base): async def __distro(self) -> Distro: if self.___distro is None: from ...Distro import Distro - self.___distro = await Distro.instantiate( - ec = self.__inner, default_path_filter = self.__backend_path_filter - ) + self.___distro = await Distro.instantiate(ec = self.__inner) return self.___distro async def __target_paths(self) -> list[str]: diff --git a/test/unit/python/jw/pkg/lib/ec/secret_store/KvFile/test.py b/test/unit/python/jw/pkg/lib/ec/secret_store/KvFile/test.py index c511b641..9da182fe 100644 --- a/test/unit/python/jw/pkg/lib/ec/secret_store/KvFile/test.py +++ b/test/unit/python/jw/pkg/lib/ec/secret_store/KvFile/test.py @@ -15,6 +15,7 @@ from jw.pkg.lib.ec.secret_store.layout import FT_SECRET, FT_SECRET_FILE, FT_SECR from jw.pkg.lib.file_types import FT_DIR from jw.pkg.lib.FileContext import FileContext from jw.pkg.lib.Package import Package +from jw.pkg.lib.pf.PkgSecrets import PkgSecrets async def run_tests() -> None: with tempfile.TemporaryDirectory() as tmp: @@ -346,49 +347,121 @@ async def run_tests() -> None: assert not os.path.exists(os.path.join(tree, 'etc', 'sub', 'conf.jw-secret')) await sstore.close() - # -- The autodetected distro applies the app's documented - # filter fallback: JW_DEFAULT_PATH_FILTER reaches - # Distro.instantiate() as the default path filter - astore = KvFile('kvfile://', default_path_filter = 'pkg:url=~jw.dev') - assert set(await astore.readdir('')) == {'tmp'} - flt = captured['kwargs'].get('default_path_filter') - assert flt is not None - assert flt.match_pkg(Package('fixture', url = 'https://jw.dev/fixture.rpm')) - assert not flt.match_pkg(Package('other', url = 'https://elsewhere/other.rpm')) - - # -- The backend filter also comes from the store URI's - # query's path-filter parameter; the constructor - # parameter wins - async def __flt_matches(flt: Any) -> None: - assert flt.match_pkg(Package('fixture', url = 'https://jw.dev/fixture.rpm')) - assert not flt.match_pkg( - Package('other', url = 'https://elsewhere/other.rpm') - ) - - # No query, no parameter: no filter - s = KvFile('kvfile://') - await s.readdir('') - assert captured['kwargs'].get('default_path_filter') is None - # The query's path-filter parameter - s = KvFile('kvfile://?path-filter=pkg%3Aurl%3D~jw.dev') - await s.readdir('') - await __flt_matches(captured['kwargs'].get('default_path_filter')) - # An unrelated query parameter is not a filter spec - s = KvFile('kvfile://?foo=bar') - await s.readdir('') - assert captured['kwargs'].get('default_path_filter') is None - # The constructor parameter wins over the query - s = KvFile( - 'kvfile://?path-filter=pkg%3Aurl%3D~jw.dev', - default_path_filter = 'pkg:url=~zzz-nomatch', - ) - await s.readdir('') - flt = captured['kwargs'].get('default_path_filter') - assert flt is not None - assert not flt.match_pkg(Package('fixture', url = 'https://jw.dev/fixture.rpm')) - patcher.stop() + # -- The address space is scoped by a pkg-secrets filter, + # explicit or from the store URI's query: it scopes the + # operations and the enumeration alike, and a foreign + # filter kind is refused + class FilteredFake(SuseDistro): + + def __init__(self, pkgs: list[tuple[str, str, list[str]]]) -> None: + super().__init__(Local(), id = 'suse') + self.pkgs = pkgs + + # -- The package enumeration seam: Distro.paths() goes + # through _select(), which bottoms out here + @override + async def _select_by_name(self, names: Any) -> list[Package]: + ret = [Package(name = n, url = u) for n, u, _ in self.pkgs] + if names: + ret = [p for p in ret if p.name in names] + return ret + + @override + async def _pkg_paths(self, names: list[str] | None) -> list[str]: + ret: list[str] = [] + for n, _, files in self.pkgs: + if names is None or n in names: + ret.extend(files) + return ret + + ffake = FilteredFake( + [ + ( + 'fixture', + 'https://jw.dev/fixture.rpm', + [ + f'{tree}/etc/foo.conf.jw-tmpl', + f'{tree}/etc/cert.pem.jw-tmpl', + f'{tree}/etc/ghost.conf.jw-tmpl', + ], + ), + ( + 'other', + 'https://elsewhere.org/other.rpm', + [f'{tree}/etc/zzz.conf.jw-tmpl'], + ), + ] + ) + captured2: dict[str, Any] = {} + + async def __instantiate2(*args: Any, **kwargs: Any) -> FilteredFake: + captured2['kwargs'] = kwargs + return ffake + + patcher2 = mock.patch.object( + Distro, 'instantiate', new = classmethod(__instantiate2) + ) + patcher2.start() + with open(os.path.join(tree, 'etc', 'zzz.conf.jw-secret'), 'w') as f: + f.write('z=1\n') + + # -- Raw: no filter, every installed template is a config + # path, and the distro derivation carries no filter + rstore = KvFile('kvfile://') + assert rstore.path_filter is None + assert set(await rstore.readdir(f'{base}/etc')) == { + 'cert.pem.jw-secret-file', 'foo.conf.jw-secret', 'zzz.conf.jw-secret' + } + # -- The distro derivation carries no filter of its own + assert captured2['kwargs'].get('default_path_filter') is None + + # -- Scoped: only the matching packages back the address + # space; an unbacked entry is invisible and unwritable + fstore = KvFile('kvfile://', default_path_filter = 'pkg-secrets:url=~jw.dev') + assert isinstance(fstore.path_filter, PkgSecrets) + assert set(await fstore.readdir(f'{base}/etc')) == \ + {'cert.pem.jw-secret-file', 'foo.conf.jw-secret'} + try: + await fstore.get(f'{base}/etc/zzz.conf') + raise AssertionError('expected FileNotFoundError') + except FileNotFoundError: + pass + await fstore.put(f'{base}/etc/zzz.conf', b'z=2\n', ftype = FT_SECRET) + with open(os.path.join(tree, 'etc', 'zzz.conf.jw-secret')) as f: + assert f.read() == 'z=1\n' + # -- A backed address writes through + await fstore.put(f'{base}/etc/foo.conf/k9', b'v9', ftype = FT_SECRET_KEY) + assert (await fstore.get(f'{base}/etc/foo.conf/k9')).stdout == b'v9' + + # -- The query's path-filter parameter + qstore = KvFile('kvfile://?path-filter=pkg-secrets%3Aurl%3D~elsewhere') + assert isinstance(qstore.path_filter, PkgSecrets) + assert set(await qstore.readdir(f'{base}/etc')) == {'zzz.conf.jw-secret'} + + # -- An unrelated query parameter is not a filter spec + s = KvFile('kvfile://?foo=bar') + assert s.path_filter is None + + # -- The query wins over the constructor parameter + wstore = KvFile( + 'kvfile://?path-filter=pkg-secrets%3Aurl%3D~jw.dev', + default_path_filter = 'pkg-secrets:url=~elsewhere', + ) + assert set(await wstore.readdir(f'{base}/etc') + ) == {'cert.pem.jw-secret-file', 'foo.conf.jw-secret'} + + # -- A foreign filter kind is refused at resolution + xstore = KvFile('kvfile://', default_path_filter = 'pkg:url=~jw.dev') + try: + xstore.path_filter + raise AssertionError('expected Exception') + except Exception as e: + assert 'pkg-secrets' in str(e) + + patcher2.stop() + # -- The lifecycle propagates to the host context: an # open() pin on the store keeps the host's transport # open for its duration, and the run()s within it share -- 2.56.1