From 013636fa38af2cb2371db48ba11cc9470a97636e Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Wed, 4 Nov 2026 18:20:49 +0100 Subject: [PATCH 01/12] lib.PathFilter / lib.pf: Add class + module Add the abstract PathFilter class, designed to be attached to a FileContext in later commits. This is the first commit of a series that generalizes the JW_DEFAULT_PKG_FILTER / --pkg-filter framework into loadable path filters that can be attached to any FileContext. A filter answers an access check, _access(), with a bool. run() turns the answer into a verdict: ALLOW when the check passes, otherwise ABORT or IGNORE according to the filter's deny action, LOG or ABORT. The verdict is handled by the filter's handle, a pair of per-verdict gates: with the ABORT gate set, an ABORT verdict raises PermissionError; with the LOG gate set, an IGNORE verdict is logged and returned. A verdict whose gate is not set passes through unhandled. Also add the lib.pf module that hosts the concrete filters. A filter spec of the form foo:something is loaded by PathFilter.create() as the Foo class from the jw.pkg.lib.pf.Foo module. A spec without the name prefix, or a name that no module provides, is rejected with an error that names the expected class and module. Signed-off-by: Jan Lindemann Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.0 --- src/python/jw/pkg/lib/PathFilter.py | 95 +++++++++++++++++++ src/python/jw/pkg/lib/pf/Makefile | 4 + .../python/jw/pkg/lib/PathFilter/Makefile | 8 ++ .../unit/python/jw/pkg/lib/PathFilter/test.py | 94 ++++++++++++++++++ 4 files changed, 201 insertions(+) create mode 100644 src/python/jw/pkg/lib/PathFilter.py create mode 100644 src/python/jw/pkg/lib/pf/Makefile create mode 100644 test/unit/python/jw/pkg/lib/PathFilter/Makefile create mode 100644 test/unit/python/jw/pkg/lib/PathFilter/test.py diff --git a/src/python/jw/pkg/lib/PathFilter.py b/src/python/jw/pkg/lib/PathFilter.py new file mode 100644 index 00000000..dd1148aa --- /dev/null +++ b/src/python/jw/pkg/lib/PathFilter.py @@ -0,0 +1,95 @@ +from __future__ import annotations + +import abc +import os + +from enum import Enum, Flag, auto +from typing import TYPE_CHECKING, override + +from .log import WARNING, get_caller_pos, log +from .Types import LoadTypes + +if TYPE_CHECKING: + from typing import Any + +class DenyAction(Enum): + LOG = auto() + ABORT = auto() + +class Handle(Flag): + LOG = auto() + ABORT = auto() + +class Verdict(Enum): + ALLOW = auto() + IGNORE = auto() + ABORT = auto() + +class PathFilter(abc.ABC): + + def __init__( + self, + *, + spec: str, + deny_action: DenyAction = DenyAction.LOG, + handle: Handle = Handle.LOG | Handle.ABORT, + ) -> None: + self.__spec = spec + self.__deny_action = deny_action + self.__handle = handle + + @override + def __repr__(self) -> str: + return f'filter:{self.__spec}' + + @property + def deny_action(self) -> DenyAction: + return self.__deny_action + + @classmethod + def create(cls, *, spec: str, **kwargs: Any) -> PathFilter: + name, sep, _ = spec.partition(':') + if not sep: + raise Exception( + f'Unsupported filter spec "{spec}": expected a "name:spec" ' + 'form, where the name picks the filter class' + ) + class_name = name.capitalize() + module_name = 'jw.pkg.lib.pf.' + class_name + filter_classes: LoadTypes[PathFilter] = LoadTypes( + [module_name], + type_name_filter = class_name, + type_filter = [PathFilter], + ) + try: + filter_class = next(iter(filter_classes)) + except (StopIteration, ModuleNotFoundError) as e: + raise Exception( + f'No PathFilter class "{class_name}" in module {module_name}' + ) from e + return filter_class(spec = spec, **kwargs) + + @abc.abstractmethod + async def _access(self, path: str, mode: int = os.F_OK) -> bool: + raise NotImplementedError() + + async def run( + self, + path: str, + mode: int = os.F_OK, + msg: str | None = None, + caller: tuple[str, str, int] | None = None, + ) -> Verdict: + if await self._access(path, mode): + return Verdict.ALLOW + ret = Verdict.ABORT if self.__deny_action == DenyAction.ABORT \ + else Verdict.IGNORE + if not (self.__handle & (Handle.LOG | Handle.ABORT)): + return ret + if msg is None: + msg = f'"{path}" is filtered' + if self.__handle & Handle.ABORT and ret == Verdict.ABORT: + raise PermissionError(msg + ', aborting') + if self.__handle & Handle.LOG and ret == Verdict.IGNORE: + log(WARNING, msg + ', ignoring', caller = caller or get_caller_pos()) + return ret diff --git a/src/python/jw/pkg/lib/pf/Makefile b/src/python/jw/pkg/lib/pf/Makefile new file mode 100644 index 00000000..7a83c333 --- /dev/null +++ b/src/python/jw/pkg/lib/pf/Makefile @@ -0,0 +1,4 @@ +TOPDIR = ../../../../../.. + +include $(TOPDIR)/make/proj.mk +include $(JWBDIR)/make/py-mod.mk diff --git a/test/unit/python/jw/pkg/lib/PathFilter/Makefile b/test/unit/python/jw/pkg/lib/PathFilter/Makefile new file mode 100644 index 00000000..3d3138c5 --- /dev/null +++ b/test/unit/python/jw/pkg/lib/PathFilter/Makefile @@ -0,0 +1,8 @@ +TOPDIR = ../../../../../../.. + +include $(TOPDIR)/make/proj.mk +include $(JWBDIR)/make/py-run.mk + +all: + +test: run diff --git a/test/unit/python/jw/pkg/lib/PathFilter/test.py b/test/unit/python/jw/pkg/lib/PathFilter/test.py new file mode 100644 index 00000000..ad1fe353 --- /dev/null +++ b/test/unit/python/jw/pkg/lib/PathFilter/test.py @@ -0,0 +1,94 @@ +import asyncio +import io +import os + +from contextlib import redirect_stderr +from typing import override + +from jw.pkg.lib.PathFilter import DenyAction, Handle, PathFilter, Verdict + +class ConstFilter(PathFilter): + + def __init__( + self, + allow: bool, + deny_action: DenyAction = DenyAction.LOG, + handle: Handle = Handle.LOG | Handle.ABORT, + ) -> None: + super().__init__( + spec = 'const:test', + deny_action = deny_action, + handle = handle, + ) + self.__allow = allow + + @override + async def _access(self, path: str, mode: int = os.F_OK) -> bool: + return self.__allow + +async def run_tests() -> None: + # -- An allowed address passes through, unhandled + assert await ConstFilter(True).run('p') is Verdict.ALLOW + + # -- Default handle: a LOG denial is returned and logged, an ABORT + # denial raises + buf = io.StringIO() + with redirect_stderr(buf): + assert await ConstFilter( + False, deny_action = DenyAction.LOG + ).run('p') is Verdict.IGNORE + assert 'is filtered, ignoring' in buf.getvalue() + try: + await ConstFilter(False, deny_action = DenyAction.ABORT).run('p') + raise AssertionError('default handle: ABORT should raise') + except PermissionError: + pass + + # -- ABORT only: a LOG denial passes through without logging, an + # ABORT denial raises + buf = io.StringIO() + with redirect_stderr(buf): + assert await ConstFilter( + False, + deny_action = DenyAction.LOG, + handle = Handle.ABORT, + ).run('p') is Verdict.IGNORE + assert 'filtered' not in buf.getvalue() + try: + await ConstFilter( + False, + deny_action = DenyAction.ABORT, + handle = Handle.ABORT, + ).run('p') + raise AssertionError('ABORT handle: ABORT should raise') + except PermissionError: + pass + + # -- LOG only: both denials are returned unraised; the LOG denial is + # logged with the ignoring suffix, the ABORT denial is not logged + buf = io.StringIO() + with redirect_stderr(buf): + assert await ConstFilter( + False, + deny_action = DenyAction.LOG, + handle = Handle.LOG, + ).run('p') is Verdict.IGNORE + assert 'is filtered, ignoring' in buf.getvalue() + buf = io.StringIO() + with redirect_stderr(buf): + assert await ConstFilter( + False, + deny_action = DenyAction.ABORT, + handle = Handle.LOG, + ).run('p') is Verdict.ABORT + assert 'is filtered' not in buf.getvalue() + + # -- No handle: denials pass through, unhandled + buf = io.StringIO() + with redirect_stderr(buf): + assert await ConstFilter( + False, deny_action = DenyAction.ABORT, handle = Handle(0) + ).run('p') is Verdict.ABORT + assert 'filtered' not in buf.getvalue() + +asyncio.run(run_tests()) -- 2.56.1 From c2c8db2737d1df646aa2d02681d54acac15cd4d8 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Wed, 4 Nov 2026 18:24:14 +0100 Subject: [PATCH 02/12] lib.FileContext: Limit accessible addresses Allow to attach a default path filter to a FileContext, given in the constructor as default_path_filter, or in the URI query as "path-filter". Passing False as default_path_filter will make the FileContext ignore any path-filter in the query. The filter is created lazily on first use through PathFilter.create(), so a string spec is loaded from the lib.pf module like any other filter. Every path based action evaluates the filter before it is carried out. An IGNORE verdict is logged and the action is skipped: reads and stats raise FileNotFoundError, writes, unlinks, erases, renames, and mkdirs are no-ops, and readdir() drops the filtered entries. An ABORT verdict raises PermissionError. Every path-driven method also takes a flag parameter, "filtered", defaulting to True, so a caller that must work regardless of the context's filter can opt out of the check. Add a unit test that exercises the verdicts, the filtered bypass, and the distribution probe on a Local context. Signed-off-by: Jan Lindemann Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.0 --- src/python/jw/pkg/lib/Distro.py | 2 +- src/python/jw/pkg/lib/FileContext.py | 116 ++++++++++++++-- src/python/jw/pkg/lib/ec/secret_store/Base.py | 2 + .../python/jw/pkg/lib/FileContext/Makefile | 8 ++ .../python/jw/pkg/lib/FileContext/test.py | 131 ++++++++++++++++++ 5 files changed, 247 insertions(+), 12 deletions(-) create mode 100644 test/unit/python/jw/pkg/lib/FileContext/Makefile create mode 100644 test/unit/python/jw/pkg/lib/FileContext/test.py diff --git a/src/python/jw/pkg/lib/Distro.py b/src/python/jw/pkg/lib/Distro.py index cc8327d9..705d136d 100644 --- a/src/python/jw/pkg/lib/Distro.py +++ b/src/python/jw/pkg/lib/Distro.py @@ -61,7 +61,7 @@ class Distro(abc.ABC): async def read_os_release_str(cls, ec: ExecContext) -> str: release_file = '/etc/os-release' try: - result = await ec.get(release_file, throw = True) + result = await ec.get(release_file, throw = True, filtered = False) return result.stdout_str except Exception as e: log( diff --git a/src/python/jw/pkg/lib/FileContext.py b/src/python/jw/pkg/lib/FileContext.py index 6228fe98..2caa26f9 100644 --- a/src/python/jw/pkg/lib/FileContext.py +++ b/src/python/jw/pkg/lib/FileContext.py @@ -1,18 +1,21 @@ from __future__ import annotations import abc +import os from enum import Enum, auto from functools import cached_property -from typing import TYPE_CHECKING, Any, Iterable, override +from typing import TYPE_CHECKING, Any, Iterable, Literal, override +from .base import Result from .file_types import FT_DIR, FT_REG -from .log import DEBUG, ERR, log +from .log import DEBUG, ERR, get_caller_pos, log +from .PathFilter import PathFilter, Verdict from .ProcFilter import ProcPipeline from .Uri import Uri if TYPE_CHECKING: - from .base import Result, StatResult + from .base import StatResult from .file_types import FileType from .ProcFilter import ProcFilter @@ -30,6 +33,7 @@ class FileContext(abc.ABC): chroot: bool = False, in_pipe: ProcPipeline | None = None, out_pipe: ProcPipeline | None = None, + default_path_filter: str | PathFilter | None | Literal[False] = None, ): self.__uri = Uri.pimp(uri) self.__chroot = chroot @@ -39,6 +43,10 @@ class FileContext(abc.ABC): self.__in_pipe = in_pipe self.__out_pipe = out_pipe self.__open_count = 0 + self.__default_path_filter: str | PathFilter | Literal[ + False] | None = default_path_filter + self.__path_filter: PathFilter | Literal[ + False] | None = False if default_path_filter is False else None if verbose_default not in [True, False]: raise ValueError( 'Tried to instantiate FileContext with verbose_default ' @@ -116,6 +124,49 @@ class FileContext(abc.ABC): def chroot(self) -> bool: return self.__chroot + @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) + return self.__path_filter or None + + @path_filter.setter + def path_filter(self, value: str | PathFilter | None | Literal[False]) -> None: + self.__path_filter = None + self.__default_path_filter = value + + async def check_filtered( + self, + path: str, + mode: int = os.F_OK, + action: str = '', + caller: tuple[str, str, int] | None = None, + ) -> Verdict: + path_filter = self.path_filter + if path_filter is None: + return Verdict.ALLOW + return await path_filter.run( + path, + mode = mode, + msg = f'[{self.log_name}] {action}("{path}") is filtered', + caller = caller or get_caller_pos(), + ) + @property def username(self) -> str | None: return self.__uri.username @@ -145,7 +196,11 @@ class FileContext(abc.ABC): throw: bool = True, verbose: bool | None = None, title: str | None = None, + filtered: bool = True, ) -> Result: + if filtered and await self.check_filtered(path, mode = os.R_OK, + action = 'get') == Verdict.IGNORE: + raise FileNotFoundError(path) ret = await self._get( self._chroot(path), wd = wd, @@ -184,7 +239,11 @@ class FileContext(abc.ABC): mode: int | None = None, atomic: bool = False, ftype: FileType = FT_REG, + filtered: bool = True, ) -> Result: + if filtered and await self.check_filtered(path, mode = os.W_OK, + action = 'put') == Verdict.IGNORE: + return Result() mode_str = None if mode is None else oct(mode).replace('0o', '0') if self.__out_pipe is not None: content = (await self.__out_pipe.run(content)).stdout @@ -207,7 +266,10 @@ class FileContext(abc.ABC): f'{self.log_name}: unlink("{path}") is not implemented' ) - async def unlink(self, path: str) -> None: + async def unlink(self, path: str, filtered: bool = True) -> None: + if filtered and await self.check_filtered( + path, mode = os.W_OK, action = 'unlink') == Verdict.IGNORE: + return return await self._unlink(self._chroot(path)) async def _erase(self, path: str) -> None: @@ -215,7 +277,10 @@ class FileContext(abc.ABC): f'{self.log_name}: erase("{path}") is not implemented' ) - async def erase(self, path: str) -> None: + async def erase(self, path: str, filtered: bool = True) -> None: + if filtered and await self.check_filtered( + path, mode = os.W_OK, action = 'erase') == Verdict.IGNORE: + return return await self._erase(self._chroot(path)) async def _rename(self, src: str, dst: str) -> None: @@ -223,15 +288,28 @@ class FileContext(abc.ABC): f'{self.log_name}: rename("{src}" -> "{dst}") is not implemented' ) - async def rename(self, src: str, dst: str) -> None: - return await self._rename(src, dst) + async def rename(self, src: str, dst: str, filtered: bool = True) -> None: + if filtered and await self.check_filtered( + src, mode = os.R_OK, action = 'rename') == Verdict.IGNORE: + return + if filtered and await self.check_filtered( + dst, mode = os.W_OK, action = 'rename') == Verdict.IGNORE: + return + return await self._rename(self._chroot(src), self._chroot(dst)) async def _mkdir(self, path: str, mode: int, ftype: FileType) -> None: raise NotImplementedError(f'{self.log_name}: mkdir({path}) is not implemented') async def mkdir( - self, path: str, mode: int = 0o777, ftype: FileType = FT_DIR + self, + path: str, + mode: int = 0o777, + ftype: FileType = FT_DIR, + filtered: bool = True, ) -> None: + if filtered and await self.check_filtered( + path, mode = os.W_OK, action = 'mkdir') == Verdict.IGNORE: + return return await self._mkdir(self._chroot(path), mode, ftype) async def _mktemp(self, tmpl: str, directory: bool) -> str: @@ -269,9 +347,17 @@ class FileContext(abc.ABC): f'{self.log_name}: lstat("{path}") is not implemented' ) - async def stat(self, path: str, follow_symlinks: bool = True) -> StatResult: + async def stat( + self, + path: str, + follow_symlinks: bool = True, + filtered: bool = True + ) -> StatResult: if not isinstance(path, str): raise TypeError(f'path must be str, got {type(path).__name__}') + if filtered and await self.check_filtered(path, mode = os.F_OK, + action = 'stat') == Verdict.IGNORE: + raise FileNotFoundError(path) return await self._stat(self._chroot(path), follow_symlinks) async def _file_exists(self, path: str) -> bool: @@ -341,8 +427,16 @@ class FileContext(abc.ABC): f'{self.log_name}: readdir("{path}") is not implemented' ) - async def readdir(self, path: str) -> Iterable[str]: - return await self._readdir(self._chroot(path)) + async def readdir(self, path: str, filtered: bool = True) -> Iterable[str]: + base = path.rstrip('/') + ret: list[str] = [] + for entry in await self._readdir(self._chroot(path)): + full = f'{base}/{entry}' if base else entry + if filtered and await self.check_filtered( + full, mode = os.R_OK, action = 'readdir') == Verdict.IGNORE: + continue + ret.append(entry) + return ret @classmethod def create(cls, uri: str | Uri, *args: Any, **kwargs: Any) -> 'FileContext': diff --git a/src/python/jw/pkg/lib/ec/secret_store/Base.py b/src/python/jw/pkg/lib/ec/secret_store/Base.py index 967c1da3..2fff26a0 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/Base.py +++ b/src/python/jw/pkg/lib/ec/secret_store/Base.py @@ -141,6 +141,7 @@ class Base(FileContext): mode: int | None = None, atomic: bool = False, ftype: FileType = FT_REG, + filtered: bool = True, ) -> Result: # -- A put that changes nothing is a no-op: the pre-read is # fallback-aware, so a value already represented, below @@ -171,6 +172,7 @@ class Base(FileContext): mode, atomic, ftype, + filtered, ) def _put_is_noop(self, existing: bytes, content: bytes, ftype: FileType) -> bool: diff --git a/test/unit/python/jw/pkg/lib/FileContext/Makefile b/test/unit/python/jw/pkg/lib/FileContext/Makefile new file mode 100644 index 00000000..3d3138c5 --- /dev/null +++ b/test/unit/python/jw/pkg/lib/FileContext/Makefile @@ -0,0 +1,8 @@ +TOPDIR = ../../../../../../.. + +include $(TOPDIR)/make/proj.mk +include $(JWBDIR)/make/py-run.mk + +all: + +test: run diff --git a/test/unit/python/jw/pkg/lib/FileContext/test.py b/test/unit/python/jw/pkg/lib/FileContext/test.py new file mode 100644 index 00000000..8fbd8b3f --- /dev/null +++ b/test/unit/python/jw/pkg/lib/FileContext/test.py @@ -0,0 +1,131 @@ +import asyncio +import os +import tempfile + +from typing import Any, override + +from jw.pkg.lib.Distro import Distro +from jw.pkg.lib.ec.Local import Local +from jw.pkg.lib.PathFilter import DenyAction, PathFilter + +class BlockedFilter(PathFilter): + + def __init__(self, *, spec: str, blocked: str, **kwargs: Any) -> None: + super().__init__(spec = spec, **kwargs) + self.__blocked = blocked + + @override + async def _access(self, path: str, mode: int = os.F_OK) -> bool: + return not (path == self.__blocked or path.startswith(self.__blocked + '/')) + +class AllIgnoreFilter(PathFilter): + + def __init__(self, *, spec: str, **kwargs: Any) -> None: + super().__init__(spec = spec, **kwargs) + + @override + async def _access(self, path: str, mode: int = os.F_OK) -> bool: + return False + +class AbortingFilter(PathFilter): + + def __init__(self, *, spec: str, abort: str, **kwargs: Any) -> None: + super().__init__(spec = spec, deny_action = DenyAction.ABORT, **kwargs) + self.__abort = abort + + @override + async def _access(self, path: str, mode: int = os.F_OK) -> bool: + return not (path == self.__abort or path.startswith(self.__abort + '/')) + +async def run_tests() -> None: + with tempfile.TemporaryDirectory() as tmp: + for name in ('a/x', 'b/y'): + p = os.path.join(tmp, name) + os.makedirs(os.path.dirname(p), exist_ok = True) + with open(p, 'w') as f: + f.write('v\n') + + fc = Local( + f'local://{tmp}', + chroot = True, + default_path_filter = BlockedFilter(spec = 'test:b', blocked = 'b') + ) + assert isinstance(fc.path_filter, BlockedFilter) + + # -- An unfiltered address passes through + assert (await fc.get('a/x')).stdout == b'v\n' + + # -- A filtered address is not visible to reads + try: + await fc.get('b/y') + raise AssertionError('filtered get() should not pass') + except FileNotFoundError: + pass + try: + await fc.stat('b/y') + raise AssertionError('filtered stat() should not pass') + except FileNotFoundError: + pass + + # -- A filtered write is a no-op, an unfiltered one lands + await fc.put('b/z', b'v\n') + assert not os.path.exists(os.path.join(tmp, 'b', 'z')) + await fc.put('a/z', b'v\n') + assert os.path.exists(os.path.join(tmp, 'a', 'z')) + + # -- A filtered unlink leaves the file in place + await fc.unlink('b/y') + assert os.path.exists(os.path.join(tmp, 'b', 'y')) + await fc.unlink('a/z') + assert not os.path.exists(os.path.join(tmp, 'a', 'z')) + + # -- A filtered rename is a no-op, in either direction + await fc.rename('b/y', 'a/moved') + assert os.path.exists(os.path.join(tmp, 'b', 'y')) + assert not os.path.exists(os.path.join(tmp, 'a', 'moved')) + await fc.rename('a/x', 'a/moved') + assert os.path.exists(os.path.join(tmp, 'a', 'moved')) + + # -- A filtered mkdir and erase are no-ops + await fc.mkdir('b/d') + assert not os.path.exists(os.path.join(tmp, 'b', 'd')) + await fc.erase('b/y') + assert os.path.exists(os.path.join(tmp, 'b', 'y')) + + # -- readdir() drops the filtered entries + assert set(await fc.readdir('')) == {'a'} + assert set(await fc.readdir('a')) == {'moved'} + + # -- filtered=False bypasses the filter + assert (await fc.get('b/y', filtered = False)).stdout == b'v\n' + assert (await fc.stat('b/y', filtered = False)) is not None + await fc.put('b/w', b'v\n', filtered = False) + assert os.path.exists(os.path.join(tmp, 'b', 'w')) + + # -- An aborting verdict denies the operation outright + ac = Local( + f'local://{tmp}', + chroot = True, + default_path_filter = AbortingFilter(spec = 'test:b', abort = 'b') + ) + try: + await ac.get('b/y') + raise AssertionError('aborted get() should not pass') + except PermissionError: + pass + + # -- Without a filter, everything is visible + plain = Local(f'local://{tmp}', chroot = True) + assert set(await plain.readdir('')) == {'a', 'b'} + + # -- The distribution probe reads /etc/os-release even on a + # context whose filter ignores every path + if os.path.exists('/etc/os-release'): + ec = Local( + 'local', default_path_filter = AllIgnoreFilter(spec = 'test:all') + ) + with open('/etc/os-release') as f: + expected = f.read() + assert await Distro.read_os_release_str(ec) == expected + +asyncio.run(run_tests()) -- 2.56.1 From 4117143c051dc6c4712efac36ebb417668d92ae1 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Tue, 3 Nov 2026 11:18:34 +0100 Subject: [PATCH 03/12] lib.CopyContext: Add optional default_path_filter CopyContext creates its src and dst contexts from URIs when they are not given as instances. Pass an optional default_path_filter into that creation, so a copy made under a filter limits the addresses it reads and writes. A context given as an instance keeps the filter it already carries. Signed-off-by: Jan Lindemann Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.0 --- src/python/jw/pkg/lib/CopyContext.py | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/python/jw/pkg/lib/CopyContext.py b/src/python/jw/pkg/lib/CopyContext.py index 3690d7b7..649a9614 100644 --- a/src/python/jw/pkg/lib/CopyContext.py +++ b/src/python/jw/pkg/lib/CopyContext.py @@ -1,8 +1,13 @@ -from typing import Any, Self +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Self from .FileContext import FileContext from .Uri import Uri +if TYPE_CHECKING: + from .PathFilter import PathFilter + class CopyContext: def __init__( @@ -10,6 +15,7 @@ class CopyContext: src: Uri | str | FileContext, dst: Uri | str | FileContext, chroot: bool = False, + default_path_filter: str | PathFilter | None = None, ) -> None: def __uri(ctx: FileContext | Uri | str) -> Uri | str: @@ -29,17 +35,26 @@ class CopyContext: self.__src, self.__src_uri = __info(src) self.__dst, self.__dst_uri = __info(dst) self.__chroot = chroot + self.__default_path_filter = default_path_filter async def __aenter__(self) -> Self: if self.__src is None: if self.__src_uri is None: raise Exception('Tried to create source context without URI') - self.__src = FileContext.create(self.__src_uri, chroot = self.__chroot) + self.__src = FileContext.create( + self.__src_uri, + chroot = self.__chroot, + default_path_filter = self.__default_path_filter, + ) await self.__src.open() if self.__dst is None: if self.__dst_uri is None: raise Exception('Tried to create destination context without URI') - self.__dst = FileContext.create(self.__dst_uri, chroot = self.__chroot) + self.__dst = FileContext.create( + self.__dst_uri, + chroot = self.__chroot, + default_path_filter = self.__default_path_filter, + ) await self.__dst.open() return self -- 2.56.1 From d27bf01714fad8528b3856504fa8012ee82b9c54 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Tue, 3 Nov 2026 11:29:45 +0100 Subject: [PATCH 04/12] lib.util.copy(): Add optional default_path_filter Hand the new default_path_filter parameter to the CopyContext copy() opens, and to the recursive calls it makes for a list of URIs, so an app can limit the addresses a copy touches the same way it limits its own contexts. Signed-off-by: Jan Lindemann Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.0 --- src/python/jw/pkg/lib/util.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/python/jw/pkg/lib/util.py b/src/python/jw/pkg/lib/util.py index 8f108da9..ab06270c 100644 --- a/src/python/jw/pkg/lib/util.py +++ b/src/python/jw/pkg/lib/util.py @@ -16,6 +16,7 @@ if TYPE_CHECKING: from argparse import Namespace from .ExecContext import ExecContext + from .PathFilter import PathFilter from .ProcFilter import ProcFilter, ProcPipeline T = TypeVar('T') @@ -177,6 +178,7 @@ async def copy( throw: bool = True, recursive: bool = False, parents: bool = False, + default_path_filter: str | PathFilter | None = None, ) -> Exception | str | list[str]: async def __copy_tree(src_path: str, dst_path: str) -> list[str]: @@ -211,7 +213,17 @@ async def copy( if not isinstance(src, (str, FileContext)): ret = [] for uri in src: # TODO: Group identical netlocs into one CopyContext - rr = await copy(uri, dst, owner, group, mode, throw, recursive, parents) + rr = await copy( + uri, + dst, + owner, + group, + mode, + throw, + recursive, + parents, + default_path_filter, + ) if isinstance(rr, Exception): return rr if isinstance(rr, list): @@ -226,7 +238,8 @@ async def copy( from .CopyContext import CopyContext - async with CopyContext(src, dst) as ctx: + async with CopyContext(src, dst, + default_path_filter = default_path_filter) as ctx: src_uri = src.uri if isinstance(src, FileContext) else Uri(src) ret = '' if ctx.dst.chroot else ctx.dst.root -- 2.56.1 From f74dca5a454e2c61a3d94d0134ba6057e4c8cd68 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Sat, 7 Nov 2026 11:17:34 +0100 Subject: [PATCH 05/12] lib.PackageFilter: Derive from PathFilter This commit moves package-based filtering from the package level to the path level, using the new path filter framework. Derive PackageFilter from a new FileContextFilter base, which binds a PathFilter to the FileContext it guards, and implements _access(). The filter's space is the file list of the packages it selects, taken from the backing distro's pkg_files(). An address is allowed only if it names one of those files. The backing distro is taken from the file context, if the context carries one, and is otherwise autodetected from the host the context executes on, so the filter also works on a bare exec context. A context that is not an exec context and carries no distro rejects path queries with an error. The filter string now follows the loader syntax, pkg:url=~ regex, and a bare url=~regex like the old url=~jw.dev form is rejected; update JW_DEFAULT_PKG_FILTER values accordingly. PackageFilter's match() is renamed match_pkg(), to make clear that it matches packages, and Distro._select() calls the new name. ExecApp.path_filter builds the filter through PathFilter.create() and binds it to the exec context. CmdSelect passes its argument to the new constructor, CmdCopy hands the app's filter to the copy, and the App distro picks it up as the default package filter. Extend the unit test to cover the space membership and the distro lookup. Signed-off-by: Jan Lindemann Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.0 --- src/python/jw/pkg/App.py | 2 +- src/python/jw/pkg/cmds/pkg/CmdSelect.py | 4 +- src/python/jw/pkg/cmds/posix/CmdCopy.py | 1 + src/python/jw/pkg/lib/Distro.py | 2 +- src/python/jw/pkg/lib/ExecApp.py | 20 +-- src/python/jw/pkg/lib/PackageFilter.py | 69 ++++++++-- .../jw/pkg/lib/ec/secret_store/KvFile.py | 3 +- test/unit/python/jw/pkg/lib/Distro/test.py | 8 +- .../python/jw/pkg/lib/PackageFilter/test.py | 122 ++++++++++++++++-- .../jw/pkg/lib/ec/secret_store/KvFile/test.py | 8 +- 10 files changed, 198 insertions(+), 41 deletions(-) diff --git a/src/python/jw/pkg/App.py b/src/python/jw/pkg/App.py index 4e20fcda..fad60663 100644 --- a/src/python/jw/pkg/App.py +++ b/src/python/jw/pkg/App.py @@ -389,7 +389,7 @@ class App(Base): self.__distro = await Distro.instantiate( ec = self.exec_context, id = self.args.distro_id, - default_pkg_filter = self.pkg_filter, + default_pkg_filter = self.path_filter, ) @override diff --git a/src/python/jw/pkg/cmds/pkg/CmdSelect.py b/src/python/jw/pkg/cmds/pkg/CmdSelect.py index 0432f0cd..f8b05423 100644 --- a/src/python/jw/pkg/cmds/pkg/CmdSelect.py +++ b/src/python/jw/pkg/cmds/pkg/CmdSelect.py @@ -20,6 +20,8 @@ class CmdSelect(Cmd): # export @override async def _run(self, args: Namespace) -> None: - filter = PackageFilterString(args.filter) if args.filter else None + filter = PackageFilterString( + file_context = self.app.exec_context, spec = args.filter + ) if args.filter else None for p in await self.distro.select(filter = filter): print(p.name) diff --git a/src/python/jw/pkg/cmds/posix/CmdCopy.py b/src/python/jw/pkg/cmds/posix/CmdCopy.py index 96014c79..142a8f4d 100644 --- a/src/python/jw/pkg/cmds/posix/CmdCopy.py +++ b/src/python/jw/pkg/cmds/posix/CmdCopy.py @@ -67,4 +67,5 @@ class CmdCopy(Cmd): # export mode = int(args.mode, 0) if args.mode is not None else None, recursive = args.recursive, parents = args.parents, + default_path_filter = self.app.path_filter, ) diff --git a/src/python/jw/pkg/lib/Distro.py b/src/python/jw/pkg/lib/Distro.py index 705d136d..2be551fe 100644 --- a/src/python/jw/pkg/lib/Distro.py +++ b/src/python/jw/pkg/lib/Distro.py @@ -381,7 +381,7 @@ class Distro(abc.ABC): async def _select(self, names: Collection[str], filter: PackageFilter) -> Iterable[Package]: - return [p for p in await self._select_by_name(names) if filter.match(p)] + return [p for p in await self._select_by_name(names) if filter.match_pkg(p)] async def select( self, diff --git a/src/python/jw/pkg/lib/ExecApp.py b/src/python/jw/pkg/lib/ExecApp.py index 1c282893..a733c057 100644 --- a/src/python/jw/pkg/lib/ExecApp.py +++ b/src/python/jw/pkg/lib/ExecApp.py @@ -6,13 +6,13 @@ import sys from typing import TYPE_CHECKING, Any, Literal, override from .App import App as Base +from .PathFilter import PathFilter if TYPE_CHECKING: from argparse import ArgumentParser from .ExecContext import ExecContext - from .PackageFilter import PackageFilter class ExecApp(Base): # export @@ -21,7 +21,7 @@ class ExecApp(Base): # export self.__opt_interactive: bool | None = None self.__opt_verbose: bool | None = None self.__exec_context: ExecContext | None = None - self.__pkg_filter: PackageFilter | None | Literal[False] = None + self.__path_filter: PathFilter | None | Literal[False] = None @override async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None: @@ -82,20 +82,20 @@ class ExecApp(Base): # export return self.__opt_verbose @property - def pkg_filter(self) -> PackageFilter | None: - if self.__pkg_filter is None: + def path_filter(self) -> PathFilter | None: + if self.__path_filter is None: spec = self.args.pkg_filter if spec is None: spec = os.getenv('JW_DEFAULT_PKG_FILTER') if spec is None: - self.__pkg_filter = False + self.__path_filter = False else: - from .PackageFilter import PackageFilterString - - self.__pkg_filter = PackageFilterString(spec) - if not self.__pkg_filter: + self.__path_filter = PathFilter.create( + spec = spec, file_context = self.exec_context + ) + if not self.__path_filter: return None - return self.__pkg_filter + return self.__path_filter @property def exec_context(self) -> ExecContext: diff --git a/src/python/jw/pkg/lib/PackageFilter.py b/src/python/jw/pkg/lib/PackageFilter.py index c0b7eb51..610da9f1 100644 --- a/src/python/jw/pkg/lib/PackageFilter.py +++ b/src/python/jw/pkg/lib/PackageFilter.py @@ -1,34 +1,81 @@ from __future__ import annotations import abc +import os import re from typing import TYPE_CHECKING, override +from .PathFilter import PathFilter + if TYPE_CHECKING: + from typing import Any + + from .Distro import Distro + from .FileContext import FileContext from .Package import Package -class PackageFilter(abc.ABC): +class FileContextFilter(PathFilter): + + def __init__(self, *, spec: str, file_context: FileContext, **kwargs: Any) -> None: + super().__init__(spec = spec, **kwargs) + self.__file_context = file_context + + @property + def file_context(self) -> FileContext: + return self.__file_context + +class PackageFilter(FileContextFilter): + + def __init__(self, *, spec: str, file_context: FileContext, **kwargs: Any) -> None: + super().__init__(spec = spec, file_context = file_context, **kwargs) + self.__space: set[str] | None = None + self.___distro: Distro | None = None + + async def distro(self) -> Distro: + if self.___distro is None: + from .Distro import Distro + from .ExecContext import ExecContext + + if not isinstance(self.file_context, ExecContext): + raise Exception( + 'Package-based filters need to be backed by ' + f'distributions, but "{self}" isn\'t' + ) + self.___distro = await Distro.instantiate(ec = self.file_context) + return self.___distro @abc.abstractmethod - def _match(self, package: Package) -> bool: + def _match_pkg(self, package: Package) -> bool: raise NotImplementedError() - def match(self, package: Package) -> bool: - return self._match(package) + def match_pkg(self, package: Package) -> bool: + return self._match_pkg(package) + + @override + 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(await distro.pkg_files(names)) + return path in self.__space class PackageFilterString(PackageFilter): - def __init__(self, definition: str) -> None: + def __init__(self, *, spec: str, file_context: FileContext) -> None: + super().__init__(spec = spec, file_context = file_context) # -- Poor man's parsing for now - url_rx_str = re.sub(r'^\s*url\s*=~\s*', '', definition) - if url_rx_str == definition: - raise Exception(f'Unsupported filter string "{definition}"') - self.__definition = url_rx_str + 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)) @override - def _match(self, package: Package) -> bool: + def _match_pkg(self, package: Package) -> bool: + if self.__criterion != 'url': + return False url = package.url if url is None: return False - return re.search(self.__definition, url) is not None + return self.__rx.search(url) is not None 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 498ecb92..1fbc06f9 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py +++ b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py @@ -72,7 +72,8 @@ class KvFile(Base): self.__distro = await Distro.instantiate( ec = self.__inner, default_pkg_filter = ( - PackageFilterString(pkg_filter_str) if pkg_filter_str else None + PackageFilterString(file_context = self, spec = pkg_filter_str) + if pkg_filter_str else None ), ) ret: set[str] = set() diff --git a/test/unit/python/jw/pkg/lib/Distro/test.py b/test/unit/python/jw/pkg/lib/Distro/test.py index 1725d5de..95d9ec50 100644 --- a/test/unit/python/jw/pkg/lib/Distro/test.py +++ b/test/unit/python/jw/pkg/lib/Distro/test.py @@ -271,7 +271,9 @@ sdf = SuseDistro( cl, id = 'suse', os_release_str = OS_RELEASE_SUSE, - default_pkg_filter = PackageFilterString('url=~jw.dev') + default_pkg_filter = PackageFilterString( + spec = 'pkg:url=~jw.dev', file_context = cl + ) ) assert asyncio.run(sdf.pkg_files()) == \ ['/etc/a/a.conf.jw-tmpl', '/etc/b/b.conf.jw-tmpl'] @@ -281,7 +283,9 @@ sde = SuseDistro( cl, id = 'suse', os_release_str = OS_RELEASE_SUSE, - default_pkg_filter = PackageFilterString('url=~zzz-nomatch') + default_pkg_filter = PackageFilterString( + spec = 'pkg:url=~zzz-nomatch', file_context = cl + ) ) assert asyncio.run(sde.pkg_files()) == [] assert '--queryformat' in cl.cmds[-1] diff --git a/test/unit/python/jw/pkg/lib/PackageFilter/test.py b/test/unit/python/jw/pkg/lib/PackageFilter/test.py index f7c985bd..835243d0 100644 --- a/test/unit/python/jw/pkg/lib/PackageFilter/test.py +++ b/test/unit/python/jw/pkg/lib/PackageFilter/test.py @@ -1,34 +1,134 @@ +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.PackageFilter import PackageFilterString +if TYPE_CHECKING: + from jw.pkg.lib.Result import Result + +# -- A minimal file context; the match_pkg() role never touches its distro -- + +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() + +fc = _StubFC() + pkg = Package(name = 'jw-core', url = 'https://example.com/jw-core') pkg_other = Package(name = 'jw-base', url = 'https://other.org/jw-base') pkg_nourl = Package(name = 'no-url') # -- url=~ filters -- -f = PackageFilterString('url=~example\\.com') -assert f.match(pkg) -assert not f.match(pkg_other) +f = PackageFilterString(file_context = fc, spec = 'pkg:url=~example\\.com') +assert f.match_pkg(pkg) +assert not f.match_pkg(pkg_other) # A package without a url never matches -assert not f.match(pkg_nourl) +assert not f.match_pkg(pkg_nourl) # Whitespace around the operator is tolerated -f = PackageFilterString(' url =~ example') -assert f.match(pkg) +f = PackageFilterString(file_context = fc, spec = 'pkg: url =~ example') +assert f.match_pkg(pkg) # An unanchored regex matches anywhere in the url -f = PackageFilterString('url=~jw-core$') -assert f.match(pkg) -assert not f.match(pkg_other) +f = PackageFilterString(file_context = fc, spec = 'pkg:url=~jw-core$') +assert f.match_pkg(pkg) +assert not f.match_pkg(pkg_other) # -- Unsupported definitions raise -- -for definition in ('', 'url=example.com', 'name=jw-core', 'url ~ example'): +for definition in ('', + 'url=example.com', + 'name=jw-core', + 'url ~ example', + 'pkg:url=example.com'): try: - PackageFilterString(definition) + PackageFilterString(file_context = fc, spec = definition) assert False, f'Should have raised for "{definition}"' except Exception: pass +# -- __repr__ -- + +f = PackageFilterString(file_context = fc, spec = 'pkg:url=~example\\.com') +assert repr(f) == 'filter:pkg:url=~example\\.com' + +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_files(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 + +fake = _FakeDistro( + [ + ( + 'fixture', + 'https://example.com/fixture.rpm', + ['/etc/foo.conf.jw-tmpl', '/etc/fixture.conf'], + ), + ('other', 'https://elsewhere.org/other.rpm', ['/etc/bar.conf']), + ] +) + +# -- _access(): the space is the selected packages' file list, and +# the context's distro is probed on first use -- +async def __run_tests() -> None: + from unittest import mock + + from jw.pkg.lib.Distro import Distro + from jw.pkg.lib.ec.Local import Local + from jw.pkg.lib.PathFilter import Verdict + + f2 = PackageFilterString( + spec = 'pkg:url=~example\\.com', file_context = Local('local') + ) + + async def __instantiate(*args: Any, **kwargs: Any) -> _FakeDistro: + return fake + + with mock.patch.object(Distro, 'instantiate', new = classmethod(__instantiate)): + # The files of the selected package are in the space, + # template and plain alike + assert await f2.run('/etc/foo.conf.jw-tmpl') == Verdict.ALLOW + assert await f2.run('/etc/fixture.conf') == Verdict.ALLOW + # An address of a non-selected package is out of the space + assert await f2.run('/etc/bar.conf') == Verdict.IGNORE + # An address that is not a package file is out of the space + assert await f2.run('/etc/foo.conf') == Verdict.IGNORE + + # -- A context that cannot be probed rejects + f4 = PackageFilterString(spec = 'pkg:url=~example\\.com', file_context = _StubFC()) + try: + await f4.run('/etc/foo.conf') + 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 PackageFilter tests passed') 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 594dd9cc..b9b11437 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 @@ -349,14 +349,16 @@ async def run_tests() -> None: # -- The autodetected distro applies the app's documented # filter fallback: JW_DEFAULT_PKG_FILTER reaches # Distro.instantiate() as the default package filter - os.environ['JW_DEFAULT_PKG_FILTER'] = 'url=~jw.dev' + os.environ['JW_DEFAULT_PKG_FILTER'] = 'pkg:url=~jw.dev' try: astore = KvFile('kvfile://') assert set(await astore.readdir('')) == {'tmp'} flt = captured['kwargs'].get('default_pkg_filter') assert flt is not None - assert flt.match(Package('fixture', url = 'https://jw.dev/fixture.rpm')) - assert not flt.match(Package('other', url = 'https://elsewhere/other.rpm')) + assert flt.match_pkg(Package('fixture', url = 'https://jw.dev/fixture.rpm')) + assert not flt.match_pkg( + Package('other', url = 'https://elsewhere/other.rpm') + ) finally: del os.environ['JW_DEFAULT_PKG_FILTER'] -- 2.56.1 From 774ab215dee98cad5627c7d27511e4b75e48eb2f Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Tue, 3 Nov 2026 14:00:14 +0100 Subject: [PATCH 06/12] lib.pf.Pkg: Add module Add the Pkg path filter to the lib.pf module, the loader-visible home of the package filter spec. A spec of the form pkg:criterion=~regex instantiates Pkg through PathFilter.create(). The parsing duplicates the one of PackageFilterString for now; a later commit consolidates the two. Signed-off-by: Jan Lindemann Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.0 --- src/python/jw/pkg/lib/pf/Pkg.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/python/jw/pkg/lib/pf/Pkg.py diff --git a/src/python/jw/pkg/lib/pf/Pkg.py b/src/python/jw/pkg/lib/pf/Pkg.py new file mode 100644 index 00000000..f9f86ecd --- /dev/null +++ b/src/python/jw/pkg/lib/pf/Pkg.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +import re + +from typing import TYPE_CHECKING, override + +from ..PackageFilter import PackageFilter + +if TYPE_CHECKING: + from typing import Any + + from ..FileContext import FileContext + from ..Package import Package + +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 + 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)) + + @override + def _match_pkg(self, package: Package) -> bool: + if self.__criterion != 'url': + return False + url = package.url + if url is None: + return False + return self.__rx.search(url) is not None -- 2.56.1 From 9197e51439dc3e728b3a6bdf56d84383ae6c80d2 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Wed, 4 Nov 2026 18:34:08 +0100 Subject: [PATCH 07/12] lib.Distro: Widen the package filter to PathFilter The default package filter is typed PackageFilter, but it is handed over from file contexts that carry a PathFilter. Widen the default_pkg_filter parameter. Signed-off-by: Jan Lindemann Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.0 --- src/python/jw/pkg/cmds/pkg/CmdSelect.py | 7 +++++++ src/python/jw/pkg/lib/Distro.py | 17 ++++++++++++++--- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/python/jw/pkg/cmds/pkg/CmdSelect.py b/src/python/jw/pkg/cmds/pkg/CmdSelect.py index f8b05423..9cc38776 100644 --- a/src/python/jw/pkg/cmds/pkg/CmdSelect.py +++ b/src/python/jw/pkg/cmds/pkg/CmdSelect.py @@ -23,5 +23,12 @@ class CmdSelect(Cmd): # export filter = PackageFilterString( file_context = self.app.exec_context, spec = args.filter ) if args.filter else None + if filter is not None: + from ...lib.PackageFilter import PackageFilter + if not isinstance(filter, PackageFilter): + raise Exception( + 'Use a package filter for selecting packages, this ' + f'is not a package filter: "{args.filter}"' + ) for p in await self.distro.select(filter = filter): print(p.name) diff --git a/src/python/jw/pkg/lib/Distro.py b/src/python/jw/pkg/lib/Distro.py index 2be551fe..3f35630a 100644 --- a/src/python/jw/pkg/lib/Distro.py +++ b/src/python/jw/pkg/lib/Distro.py @@ -20,6 +20,7 @@ if TYPE_CHECKING: from .FlaggedFile import FlaggedFile from .Package import Package from .PackageFilter import PackageFilter + from .PathFilter import PathFilter class Distro(abc.ABC): @@ -28,7 +29,7 @@ class Distro(abc.ABC): ec: ExecContext, id: str | None = None, os_release_str: str | None = None, - default_pkg_filter: PackageFilter | None = None, + default_pkg_filter: PathFilter | None = None, ) -> None: if id is None: raise ValueError('Tried to instantiate Distro without id') @@ -329,7 +330,7 @@ class Distro(abc.ABC): return self.__exec_context @property - def default_pkg_filter(self) -> PackageFilter | None: + def default_pkg_filter(self) -> PathFilter | None: return self.__default_pkg_filter async def run(self, *args: Any, **kwargs: Any) -> Result: @@ -389,7 +390,17 @@ class Distro(abc.ABC): filter: PackageFilter | None = None ) -> Iterable[Package]: if not filter: - filter = self.__default_pkg_filter + from .PackageFilter import PackageFilter + + default = self.__default_pkg_filter + if default is not None and not isinstance(default, PackageFilter): + log( + WARNING, + f'The default path filter is not a package filter, ' + f'selecting all packages: "{default}"', + ) + return await self._select_by_name(names) + filter = default if not filter: return await self._select_by_name(names) return await self._select(names, filter) -- 2.56.1 From 685ed51935ffa2f2b38d4dd1d9a469da388d0863 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Tue, 3 Nov 2026 15:21:29 +0100 Subject: [PATCH 08/12] cmds.pkg.CmdSelect: Load path filter dynamically The select command names PackageFilterString directly, but the filter is a spec string and the class is resolved dynamically by the loader. Build the filter through PathFilter.create() so the concrete class no longer appears at the call site. Signed-off-by: Jan Lindemann Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.0 --- src/python/jw/pkg/cmds/pkg/CmdSelect.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/python/jw/pkg/cmds/pkg/CmdSelect.py b/src/python/jw/pkg/cmds/pkg/CmdSelect.py index 9cc38776..f4ee4298 100644 --- a/src/python/jw/pkg/cmds/pkg/CmdSelect.py +++ b/src/python/jw/pkg/cmds/pkg/CmdSelect.py @@ -2,7 +2,7 @@ from __future__ import annotations from typing import TYPE_CHECKING, override -from ...lib.PackageFilter import PackageFilterString +from ...lib.PathFilter import PathFilter from .Cmd import Cmd, Parent if TYPE_CHECKING: @@ -20,8 +20,8 @@ class CmdSelect(Cmd): # export @override async def _run(self, args: Namespace) -> None: - filter = PackageFilterString( - file_context = self.app.exec_context, spec = args.filter + filter = PathFilter.create( + spec = args.filter, file_context = self.app.exec_context ) if args.filter else None if filter is not None: from ...lib.PackageFilter import PackageFilter -- 2.56.1 From 09d76249f38de75aeb635113f4f5234787573c3e Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Tue, 3 Nov 2026 17:37:49 +0100 Subject: [PATCH 09/12] lib.ExecApp: Move .path_filter into the app's ExecContext Create an app's exec context with the user-specified path filter, and drop the ExecApp.path_filter property, now a duplicate of exec_context.path_filter. Use the latter in the two call sites. Signed-off-by: Jan Lindemann Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.0 --- src/python/jw/pkg/App.py | 2 +- src/python/jw/pkg/cmds/posix/CmdCopy.py | 2 +- src/python/jw/pkg/lib/ExecApp.py | 27 +++++-------------- .../integration/jw_pkg/help/test-expected.txt | 4 +-- 4 files changed, 11 insertions(+), 24 deletions(-) diff --git a/src/python/jw/pkg/App.py b/src/python/jw/pkg/App.py index fad60663..fa315a90 100644 --- a/src/python/jw/pkg/App.py +++ b/src/python/jw/pkg/App.py @@ -389,7 +389,7 @@ class App(Base): self.__distro = await Distro.instantiate( ec = self.exec_context, id = self.args.distro_id, - default_pkg_filter = self.path_filter, + default_pkg_filter = self.exec_context.path_filter, ) @override diff --git a/src/python/jw/pkg/cmds/posix/CmdCopy.py b/src/python/jw/pkg/cmds/posix/CmdCopy.py index 142a8f4d..afa7c4ff 100644 --- a/src/python/jw/pkg/cmds/posix/CmdCopy.py +++ b/src/python/jw/pkg/cmds/posix/CmdCopy.py @@ -67,5 +67,5 @@ class CmdCopy(Cmd): # export mode = int(args.mode, 0) if args.mode is not None else None, recursive = args.recursive, parents = args.parents, - default_path_filter = self.app.path_filter, + default_path_filter = self.app.exec_context.path_filter, ) diff --git a/src/python/jw/pkg/lib/ExecApp.py b/src/python/jw/pkg/lib/ExecApp.py index a733c057..932a5d45 100644 --- a/src/python/jw/pkg/lib/ExecApp.py +++ b/src/python/jw/pkg/lib/ExecApp.py @@ -3,10 +3,9 @@ from __future__ import annotations import os import sys -from typing import TYPE_CHECKING, Any, Literal, override +from typing import TYPE_CHECKING, Any, override from .App import App as Base -from .PathFilter import PathFilter if TYPE_CHECKING: @@ -21,7 +20,6 @@ class ExecApp(Base): # export self.__opt_interactive: bool | None = None self.__opt_verbose: bool | None = None self.__exec_context: ExecContext | None = None - self.__path_filter: PathFilter | None | Literal[False] = None @override async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None: @@ -52,7 +50,8 @@ class ExecApp(Base): # export ) parser.add_argument( '--pkg-filter', - help = 'Default filter for all distribution package-related operations', + help = 'Default path filter for the exec context, ' + 'as a name:spec loader string', ) @property @@ -81,30 +80,18 @@ class ExecApp(Base): # export assert self.__opt_verbose is not None return self.__opt_verbose - @property - def path_filter(self) -> PathFilter | None: - if self.__path_filter is None: - spec = self.args.pkg_filter - if spec is None: - spec = os.getenv('JW_DEFAULT_PKG_FILTER') - if spec is None: - self.__path_filter = False - else: - self.__path_filter = PathFilter.create( - spec = spec, file_context = self.exec_context - ) - if not self.__path_filter: - return None - return self.__path_filter - @property def exec_context(self) -> ExecContext: if self.__exec_context is None: from .ExecContext import ExecContext + spec = self.args.pkg_filter + if spec is None: + spec = os.getenv('JW_DEFAULT_PKG_FILTER') self.__exec_context = ExecContext.create( self.args.target, interactive = self.interactive, verbose_default = self.verbose, + default_path_filter = spec, ) return self.__exec_context diff --git a/test/integration/jw_pkg/help/test-expected.txt b/test/integration/jw_pkg/help/test-expected.txt index efa2cbe1..33745f7a 100644 --- a/test/integration/jw_pkg/help/test-expected.txt +++ b/test/integration/jw_pkg/help/test-expected.txt @@ -26,8 +26,8 @@ options: distro level (default: False) --target TARGET Run commands on this host (default: local) --pkg-filter PKG_FILTER - Default filter for all distribution package-related - operations (default: None) + Default path filter for the exec context, as a + name:spec loader string (default: None) -t, --topdir TOPDIR Project Path (default: None) --topdir-format TOPDIR_FORMAT Output references to topdir as one of "make: Date: Sat, 7 Nov 2026 11:23:52 +0100 Subject: [PATCH 10/12] lib.pf.Pkg: Consolidate PackageFilter, drop PackageFilterString PackageFilterString and Pkg are duplicates. The PackageFilter and FileContextFilter base classes live in lib/PackageFilter.py, imported by Pkg, Distro, and the tests. Move the two base classes into lib/pf/Pkg.py (where Pkg already lives), drop PackageFilterString, delete lib/PackageFilter.py, and repoint Distro and the tests to the new location. Move the test suite with the module to test/.../pf/Pkg/. Signed-off-by: Jan Lindemann Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.0 --- src/python/jw/pkg/cmds/pkg/CmdSelect.py | 2 +- src/python/jw/pkg/lib/Distro.py | 4 +- src/python/jw/pkg/lib/PackageFilter.py | 81 ------------------- .../jw/pkg/lib/ec/secret_store/KvFile.py | 4 +- src/python/jw/pkg/lib/pf/Pkg.py | 61 +++++++++++++- test/unit/python/jw/pkg/lib/Distro/test.py | 10 +-- test/unit/python/jw/pkg/lib/pf/Makefile | 4 + .../lib/{PackageFilter => pf/Pkg}/Makefile | 2 +- .../pkg/lib/{PackageFilter => pf/Pkg}/test.py | 20 +++-- 9 files changed, 81 insertions(+), 107 deletions(-) delete mode 100644 src/python/jw/pkg/lib/PackageFilter.py create mode 100644 test/unit/python/jw/pkg/lib/pf/Makefile rename test/unit/python/jw/pkg/lib/{PackageFilter => pf/Pkg}/Makefile (70%) rename test/unit/python/jw/pkg/lib/{PackageFilter => pf/Pkg}/test.py (85%) diff --git a/src/python/jw/pkg/cmds/pkg/CmdSelect.py b/src/python/jw/pkg/cmds/pkg/CmdSelect.py index f4ee4298..ca4ccd15 100644 --- a/src/python/jw/pkg/cmds/pkg/CmdSelect.py +++ b/src/python/jw/pkg/cmds/pkg/CmdSelect.py @@ -24,7 +24,7 @@ class CmdSelect(Cmd): # export spec = args.filter, file_context = self.app.exec_context ) if args.filter else None if filter is not None: - from ...lib.PackageFilter import PackageFilter + from ...lib.pf.Pkg import PackageFilter if not isinstance(filter, PackageFilter): raise Exception( 'Use a package filter for selecting packages, this ' diff --git a/src/python/jw/pkg/lib/Distro.py b/src/python/jw/pkg/lib/Distro.py index 3f35630a..e58427b8 100644 --- a/src/python/jw/pkg/lib/Distro.py +++ b/src/python/jw/pkg/lib/Distro.py @@ -19,8 +19,8 @@ if TYPE_CHECKING: from .ExecContext import ExecContext from .FlaggedFile import FlaggedFile from .Package import Package - from .PackageFilter import PackageFilter from .PathFilter import PathFilter + from .pf.Pkg import PackageFilter class Distro(abc.ABC): @@ -390,7 +390,7 @@ class Distro(abc.ABC): filter: PackageFilter | None = None ) -> Iterable[Package]: if not filter: - from .PackageFilter import PackageFilter + from .pf.Pkg import PackageFilter default = self.__default_pkg_filter if default is not None and not isinstance(default, PackageFilter): diff --git a/src/python/jw/pkg/lib/PackageFilter.py b/src/python/jw/pkg/lib/PackageFilter.py deleted file mode 100644 index 610da9f1..00000000 --- a/src/python/jw/pkg/lib/PackageFilter.py +++ /dev/null @@ -1,81 +0,0 @@ -from __future__ import annotations - -import abc -import os -import re - -from typing import TYPE_CHECKING, override - -from .PathFilter import PathFilter - -if TYPE_CHECKING: - from typing import Any - - from .Distro import Distro - from .FileContext import FileContext - from .Package import Package - -class FileContextFilter(PathFilter): - - def __init__(self, *, spec: str, file_context: FileContext, **kwargs: Any) -> None: - super().__init__(spec = spec, **kwargs) - self.__file_context = file_context - - @property - def file_context(self) -> FileContext: - return self.__file_context - -class PackageFilter(FileContextFilter): - - def __init__(self, *, spec: str, file_context: FileContext, **kwargs: Any) -> None: - super().__init__(spec = spec, file_context = file_context, **kwargs) - self.__space: set[str] | None = None - self.___distro: Distro | None = None - - async def distro(self) -> Distro: - if self.___distro is None: - from .Distro import Distro - from .ExecContext import ExecContext - - if not isinstance(self.file_context, ExecContext): - raise Exception( - 'Package-based filters need to be backed by ' - f'distributions, but "{self}" isn\'t' - ) - self.___distro = await Distro.instantiate(ec = self.file_context) - return self.___distro - - @abc.abstractmethod - def _match_pkg(self, package: Package) -> bool: - raise NotImplementedError() - - def match_pkg(self, package: Package) -> bool: - return self._match_pkg(package) - - @override - 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(await distro.pkg_files(names)) - return path in self.__space - -class PackageFilterString(PackageFilter): - - def __init__(self, *, spec: str, file_context: FileContext) -> None: - super().__init__(spec = spec, file_context = file_context) - # -- Poor man's parsing for now - 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)) - - @override - def _match_pkg(self, package: Package) -> bool: - if self.__criterion != 'url': - return False - url = package.url - if url is None: - return False - return self.__rx.search(url) is not None 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 1fbc06f9..87a0afe0 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py +++ b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py @@ -66,13 +66,13 @@ class KvFile(Base): if self.___config_paths is None: if self.__distro is None: from ...Distro import Distro - from ...PackageFilter import PackageFilterString + from ...pf.Pkg import Pkg pkg_filter_str = os.environ.get('JW_DEFAULT_PKG_FILTER') self.__distro = await Distro.instantiate( ec = self.__inner, default_pkg_filter = ( - PackageFilterString(file_context = self, spec = pkg_filter_str) + Pkg(file_context = self, spec = pkg_filter_str) if pkg_filter_str else None ), ) diff --git a/src/python/jw/pkg/lib/pf/Pkg.py b/src/python/jw/pkg/lib/pf/Pkg.py index f9f86ecd..b45dff44 100644 --- a/src/python/jw/pkg/lib/pf/Pkg.py +++ b/src/python/jw/pkg/lib/pf/Pkg.py @@ -1,17 +1,74 @@ from __future__ import annotations +import abc +import os import re +from pathlib import Path from typing import TYPE_CHECKING, override -from ..PackageFilter import PackageFilter +from ..PathFilter import PathFilter if TYPE_CHECKING: - from typing import Any + from typing import Any, Iterable + from ..Distro import Distro from ..FileContext import FileContext from ..Package import Package +class FileContextFilter(PathFilter): + + def __init__(self, *, spec: str, file_context: FileContext, **kwargs: Any) -> None: + super().__init__(spec = spec, **kwargs) + self.__file_context = file_context + + @property + def file_context(self) -> FileContext: + return self.__file_context + +class PackageFilter(FileContextFilter): # export + + def __add_parent_paths(self, paths: Iterable[str]) -> Iterable[str]: + seen: dict[str, None] = {} + for value in paths: + path = Path(value) + for item in (path, *path.parents): + seen.setdefault(str(item), None) + return list(seen) + + def __init__(self, *, spec: str, file_context: FileContext, **kwargs: Any) -> None: + super().__init__(spec = spec, file_context = file_context, **kwargs) + self.__space: set[str] | None = None + self.___distro: Distro | None = None + + async def distro(self) -> Distro: + if self.___distro is None: + from ..Distro import Distro + from ..ExecContext import ExecContext + + if not isinstance(self.file_context, ExecContext): + raise Exception( + 'Package-based filters need to be backed by ' + f'distributions, but "{self}" isn\'t' + ) + self.___distro = await Distro.instantiate(ec = self.file_context) + return self.___distro + + @abc.abstractmethod + def _match_pkg(self, package: Package) -> bool: + raise NotImplementedError() + + def match_pkg(self, package: Package) -> bool: + return self._match_pkg(package) + + @override + 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_files(names))) + return path in self.__space + class Pkg(PackageFilter): # export def __init__(self, *, spec: str, file_context: FileContext, **kwargs: Any) -> None: diff --git a/test/unit/python/jw/pkg/lib/Distro/test.py b/test/unit/python/jw/pkg/lib/Distro/test.py index 95d9ec50..3292a81a 100644 --- a/test/unit/python/jw/pkg/lib/Distro/test.py +++ b/test/unit/python/jw/pkg/lib/Distro/test.py @@ -8,7 +8,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.PackageFilter import PackageFilterString +from jw.pkg.lib.pf.Pkg import Pkg from jw.pkg.lib.Result import Result if TYPE_CHECKING: @@ -271,9 +271,7 @@ sdf = SuseDistro( cl, id = 'suse', os_release_str = OS_RELEASE_SUSE, - default_pkg_filter = PackageFilterString( - spec = 'pkg:url=~jw.dev', file_context = cl - ) + default_pkg_filter = Pkg(spec = 'pkg:url=~jw.dev', file_context = cl) ) assert asyncio.run(sdf.pkg_files()) == \ ['/etc/a/a.conf.jw-tmpl', '/etc/b/b.conf.jw-tmpl'] @@ -283,9 +281,7 @@ sde = SuseDistro( cl, id = 'suse', os_release_str = OS_RELEASE_SUSE, - default_pkg_filter = PackageFilterString( - spec = 'pkg:url=~zzz-nomatch', file_context = cl - ) + default_pkg_filter = Pkg(spec = 'pkg:url=~zzz-nomatch', file_context = cl) ) assert asyncio.run(sde.pkg_files()) == [] assert '--queryformat' in cl.cmds[-1] diff --git a/test/unit/python/jw/pkg/lib/pf/Makefile b/test/unit/python/jw/pkg/lib/pf/Makefile new file mode 100644 index 00000000..c87020cb --- /dev/null +++ b/test/unit/python/jw/pkg/lib/pf/Makefile @@ -0,0 +1,4 @@ +TOPDIR = ../../../../../../.. + +include $(TOPDIR)/make/proj.mk +include $(JWBDIR)/make/dirs.mk diff --git a/test/unit/python/jw/pkg/lib/PackageFilter/Makefile b/test/unit/python/jw/pkg/lib/pf/Pkg/Makefile similarity index 70% rename from test/unit/python/jw/pkg/lib/PackageFilter/Makefile rename to test/unit/python/jw/pkg/lib/pf/Pkg/Makefile index de693650..49c7c21f 100644 --- a/test/unit/python/jw/pkg/lib/PackageFilter/Makefile +++ b/test/unit/python/jw/pkg/lib/pf/Pkg/Makefile @@ -1,4 +1,4 @@ -TOPDIR = ../../../../../../.. +TOPDIR = ../../../../../../../../ include $(TOPDIR)/make/proj.mk include $(JWBDIR)/make/py-run.mk diff --git a/test/unit/python/jw/pkg/lib/PackageFilter/test.py b/test/unit/python/jw/pkg/lib/pf/Pkg/test.py similarity index 85% rename from test/unit/python/jw/pkg/lib/PackageFilter/test.py rename to test/unit/python/jw/pkg/lib/pf/Pkg/test.py index 835243d0..ad10bde0 100644 --- a/test/unit/python/jw/pkg/lib/PackageFilter/test.py +++ b/test/unit/python/jw/pkg/lib/pf/Pkg/test.py @@ -6,7 +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.PackageFilter import PackageFilterString +from jw.pkg.lib.pf.Pkg import Pkg if TYPE_CHECKING: from jw.pkg.lib.Result import Result @@ -32,18 +32,18 @@ pkg_nourl = Package(name = 'no-url') # -- url=~ filters -- -f = PackageFilterString(file_context = fc, spec = 'pkg:url=~example\\.com') +f = Pkg(file_context = fc, spec = 'pkg:url=~example\\.com') assert f.match_pkg(pkg) assert not f.match_pkg(pkg_other) # A package without a url never matches assert not f.match_pkg(pkg_nourl) # Whitespace around the operator is tolerated -f = PackageFilterString(file_context = fc, spec = 'pkg: url =~ example') +f = Pkg(file_context = fc, spec = 'pkg: url =~ example') assert f.match_pkg(pkg) # An unanchored regex matches anywhere in the url -f = PackageFilterString(file_context = fc, spec = 'pkg:url=~jw-core$') +f = Pkg(file_context = fc, spec = 'pkg:url=~jw-core$') assert f.match_pkg(pkg) assert not f.match_pkg(pkg_other) @@ -55,14 +55,14 @@ for definition in ('', 'url ~ example', 'pkg:url=example.com'): try: - PackageFilterString(file_context = fc, spec = definition) + Pkg(file_context = fc, spec = definition) assert False, f'Should have raised for "{definition}"' except Exception: pass # -- __repr__ -- -f = PackageFilterString(file_context = fc, spec = 'pkg:url=~example\\.com') +f = Pkg(file_context = fc, spec = 'pkg:url=~example\\.com') assert repr(f) == 'filter:pkg:url=~example\\.com' class _FakeDistro: @@ -104,9 +104,7 @@ async def __run_tests() -> None: from jw.pkg.lib.ec.Local import Local from jw.pkg.lib.PathFilter import Verdict - f2 = PackageFilterString( - spec = 'pkg:url=~example\\.com', file_context = Local('local') - ) + f2 = Pkg(spec = 'pkg:url=~example\\.com', file_context = Local('local')) async def __instantiate(*args: Any, **kwargs: Any) -> _FakeDistro: return fake @@ -122,7 +120,7 @@ async def __run_tests() -> None: assert await f2.run('/etc/foo.conf') == Verdict.IGNORE # -- A context that cannot be probed rejects - f4 = PackageFilterString(spec = 'pkg:url=~example\\.com', file_context = _StubFC()) + f4 = Pkg(spec = 'pkg:url=~example\\.com', file_context = _StubFC()) try: await f4.run('/etc/foo.conf') assert False, 'An unbacked context should reject path queries' @@ -131,4 +129,4 @@ async def __run_tests() -> None: asyncio.run(__run_tests()) -print('All PackageFilter tests passed') +print('All lib.pf.Pkg tests passed') -- 2.56.1 From bc54e4f3b2d5c884568d339d30d1b2aec17f1932 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Sat, 7 Nov 2026 18:52:37 +0100 Subject: [PATCH 11/12] lib.ec.secret_store.KvFile: Init filter in FC-style Drop the re-read of JW_DEFAULT_PKG_FILTER, and derive the filter from the ctor and URI like all other FileContext instances would. Use that to filter the backend for the packages provinding secrets. Signed-off-by: Jan Lindemann Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.0 --- src/python/jw/pkg/lib/CopyContext.py | 4 +- .../jw/pkg/lib/ec/secret_store/KvFile.py | 61 +++++++++++++------ .../jw/pkg/lib/ec/secret_store/KvFile/test.py | 41 ++++++++++--- 3 files changed, 79 insertions(+), 27 deletions(-) diff --git a/src/python/jw/pkg/lib/CopyContext.py b/src/python/jw/pkg/lib/CopyContext.py index 649a9614..ef78dcbf 100644 --- a/src/python/jw/pkg/lib/CopyContext.py +++ b/src/python/jw/pkg/lib/CopyContext.py @@ -50,10 +50,12 @@ class CopyContext: if self.__dst is None: if self.__dst_uri is None: raise Exception('Tried to create destination context without URI') + # -- The destination is the target of the copy, not part + # of the source's address space: the filter bounds the + # source only self.__dst = FileContext.create( self.__dst_uri, chroot = self.__chroot, - default_path_filter = self.__default_path_filter, ) await self.__dst.open() return self 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 87a0afe0..6985aef3 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py +++ b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py @@ -3,19 +3,21 @@ from __future__ import annotations import errno import os -from typing import TYPE_CHECKING, Any, Iterable, cast, override +from typing import TYPE_CHECKING, cast, override if TYPE_CHECKING: - from ...Distro import Distro + from typing import Any, Iterable, Literal from ...ExecContext import ExecContext from ...Uri import Uri from ...base import StatResult from ...file_types import FileType + from ...Distro import Distro from ...FcCache import FcCache from ...file_types import FT_COMPOUND, FT_DIR from ...FileContext import FileContext from ...kv import parse_kv, serialize_kv +from ...PathFilter import PathFilter from ...Result import Result from .Base import Base from .layout import BLOB_SUFFIX, FT_SECRET, FT_SECRET_FILE, FT_SECRET_KEY, SECRET_SUFFIX @@ -23,8 +25,34 @@ from .layout import BLOB_SUFFIX, FT_SECRET, FT_SECRET_FILE, FT_SECRET_KEY, SECRE class KvFile(Base): """The on-host store of a host's package secrets. """ - def __init__(self, uri: str | Uri, *args: Any, **kwargs: Any) -> None: - super().__init__(uri, *args, **kwargs) + def __init__( + self, + uri: str | Uri, + *args: Any, + 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) kwargs.pop('chroot', None) scheme = 'ssh' if self.uri.hostname else 'local' self.__inner: ExecContext = cast( @@ -33,7 +61,8 @@ class KvFile(Base): f'{scheme}://{self.uri.authority}', chroot = False, **kwargs ), ) - self.__distro: Distro | None = None + self.__backend_path_filter = __create_backend_path_filter() + self.___distro: Distro | None = None self.___config_paths: list[str] | None = None self.__root = self.uri.path.lstrip('/') self.__ctx = FcCache(self.__inner) @@ -62,22 +91,18 @@ class KvFile(Base): return path[:-len(BLOB_SUFFIX)], True return path, False + async def __distro(self) -> Distro: + if self.___distro is None: + from ...Distro import Distro + self.___distro = await Distro.instantiate( + ec = self.__inner, default_pkg_filter = self.__backend_path_filter + ) + return self.___distro + async def __config_paths(self) -> list[str]: if self.___config_paths is None: - if self.__distro is None: - from ...Distro import Distro - from ...pf.Pkg import Pkg - - pkg_filter_str = os.environ.get('JW_DEFAULT_PKG_FILTER') - self.__distro = await Distro.instantiate( - ec = self.__inner, - default_pkg_filter = ( - Pkg(file_context = self, spec = pkg_filter_str) - if pkg_filter_str else None - ), - ) ret: set[str] = set() - for f in await self.__distro.pkg_files(): + for f in await (await self.__distro()).pkg_files(): if not f.endswith('.jw-tmpl'): continue ret.add(f.lstrip('/')[:-len('.jw-tmpl')]) 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 b9b11437..5e2830a9 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 @@ -349,18 +349,43 @@ async def run_tests() -> None: # -- The autodetected distro applies the app's documented # filter fallback: JW_DEFAULT_PKG_FILTER reaches # Distro.instantiate() as the default package filter - os.environ['JW_DEFAULT_PKG_FILTER'] = 'pkg:url=~jw.dev' - try: - astore = KvFile('kvfile://') - assert set(await astore.readdir('')) == {'tmp'} - flt = captured['kwargs'].get('default_pkg_filter') - assert flt is not None + astore = KvFile('kvfile://', default_path_filter = 'pkg:url=~jw.dev') + assert set(await astore.readdir('')) == {'tmp'} + flt = captured['kwargs'].get('default_pkg_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') ) - finally: - del os.environ['JW_DEFAULT_PKG_FILTER'] + + # No query, no parameter: no filter + s = KvFile('kvfile://') + await s.readdir('') + assert captured['kwargs'].get('default_pkg_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_pkg_filter')) + # An unrelated query parameter is not a filter spec + s = KvFile('kvfile://?foo=bar') + await s.readdir('') + assert captured['kwargs'].get('default_pkg_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_pkg_filter') + assert flt is not None + assert not flt.match_pkg(Package('fixture', url = 'https://jw.dev/fixture.rpm')) patcher.stop() -- 2.56.1 From 0373ae3134a0a9a994d31d18416775a25e0fa992 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Sat, 7 Nov 2026 11:36:49 +0100 Subject: [PATCH 12/12] lib.ExecApp: Rename --pkg-filter to --path-filter The exec context's default filter selects paths, not just packages, so the pkg spelling of the option and environment variable that set it no longer fit. Rename both and some variables accordingly: - ExecApp: --pkg-filter becomes --path-filter, and the fallback environment variable JW_DEFAULT_PKG_FILTER becomes JW_DEFAULT_PATH_FILTER - Distro: the default_pkg_filter constructor argument and property become default_path_filter, matching FileContext, ExecContext, and CopyContext; App and KvFile pass the renamed argument - Adapt the help test's expected output and the unit tests Signed-off-by: Jan Lindemann Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.0 --- src/python/jw/pkg/App.py | 2 +- src/python/jw/pkg/lib/Distro.py | 12 ++++++------ src/python/jw/pkg/lib/ExecApp.py | 6 +++--- src/python/jw/pkg/lib/ec/secret_store/KvFile.py | 2 +- test/integration/jw_pkg/help/test-expected.txt | 4 ++-- test/unit/python/jw/pkg/lib/Distro/test.py | 4 ++-- test/unit/python/jw/pkg/lib/Uri/test.py | 16 ++++++++-------- .../jw/pkg/lib/ec/secret_store/KvFile/test.py | 14 +++++++------- 8 files changed, 30 insertions(+), 30 deletions(-) diff --git a/src/python/jw/pkg/App.py b/src/python/jw/pkg/App.py index fa315a90..07c6f807 100644 --- a/src/python/jw/pkg/App.py +++ b/src/python/jw/pkg/App.py @@ -389,7 +389,7 @@ class App(Base): self.__distro = await Distro.instantiate( ec = self.exec_context, id = self.args.distro_id, - default_pkg_filter = self.exec_context.path_filter, + default_path_filter = self.exec_context.path_filter, ) @override diff --git a/src/python/jw/pkg/lib/Distro.py b/src/python/jw/pkg/lib/Distro.py index e58427b8..b1f911c5 100644 --- a/src/python/jw/pkg/lib/Distro.py +++ b/src/python/jw/pkg/lib/Distro.py @@ -29,7 +29,7 @@ class Distro(abc.ABC): ec: ExecContext, id: str | None = None, os_release_str: str | None = None, - default_pkg_filter: PathFilter | None = None, + default_path_filter: PathFilter | None = None, ) -> None: if id is None: raise ValueError('Tried to instantiate Distro without id') @@ -40,7 +40,7 @@ class Distro(abc.ABC): self.__exec_context = ec self.__id: str | None = None self.__os_release_str: str | None = os_release_str - self.__default_pkg_filter = default_pkg_filter + self.__default_path_filter = default_path_filter # Names that can be used by code outside this class to retrieve # distribution properties by @@ -330,8 +330,8 @@ class Distro(abc.ABC): return self.__exec_context @property - def default_pkg_filter(self) -> PathFilter | None: - return self.__default_pkg_filter + def default_path_filter(self) -> PathFilter | None: + return self.__default_path_filter async def run(self, *args: Any, **kwargs: Any) -> Result: return await self.__exec_context.run(*args, **kwargs) @@ -392,7 +392,7 @@ class Distro(abc.ABC): if not filter: from .pf.Pkg import PackageFilter - default = self.__default_pkg_filter + default = self.__default_path_filter if default is not None and not isinstance(default, PackageFilter): log( WARNING, @@ -519,7 +519,7 @@ class Distro(abc.ABC): # compatibility with the single-package call if isinstance(names, str): names = [names] - if names is None and self.default_pkg_filter is not None: + 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) diff --git a/src/python/jw/pkg/lib/ExecApp.py b/src/python/jw/pkg/lib/ExecApp.py index 932a5d45..f84d85b1 100644 --- a/src/python/jw/pkg/lib/ExecApp.py +++ b/src/python/jw/pkg/lib/ExecApp.py @@ -49,7 +49,7 @@ class ExecApp(Base): # export '--target', default = 'local', help = 'Run commands on this host' ) parser.add_argument( - '--pkg-filter', + '--path-filter', help = 'Default path filter for the exec context, ' 'as a name:spec loader string', ) @@ -85,9 +85,9 @@ class ExecApp(Base): # export if self.__exec_context is None: from .ExecContext import ExecContext - spec = self.args.pkg_filter + spec = self.args.path_filter if spec is None: - spec = os.getenv('JW_DEFAULT_PKG_FILTER') + spec = os.getenv('JW_DEFAULT_PATH_FILTER') self.__exec_context = ExecContext.create( self.args.target, interactive = self.interactive, 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 6985aef3..afcca673 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py +++ b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py @@ -95,7 +95,7 @@ class KvFile(Base): if self.___distro is None: from ...Distro import Distro self.___distro = await Distro.instantiate( - ec = self.__inner, default_pkg_filter = self.__backend_path_filter + ec = self.__inner, default_path_filter = self.__backend_path_filter ) return self.___distro diff --git a/test/integration/jw_pkg/help/test-expected.txt b/test/integration/jw_pkg/help/test-expected.txt index 33745f7a..975b67bb 100644 --- a/test/integration/jw_pkg/help/test-expected.txt +++ b/test/integration/jw_pkg/help/test-expected.txt @@ -3,7 +3,7 @@ usage: jw-pkg.py [--log-flags LOG_FLAGS] [--log-level LOG_LEVEL] [--log-file LOG_FILE] [--backtrace] [--write-profile WRITE_PROFILE] [--interactive {true,false,auto}] [--verbose] - [--target TARGET] [--pkg-filter PKG_FILTER] [-t TOPDIR] + [--target TARGET] [--path-filter PATH_FILTER] [-t TOPDIR] [--topdir-format TOPDIR_FORMAT] [-p PREFIX] [--distro-id DISTRO_ID] [-h] ... @@ -25,7 +25,7 @@ options: --verbose Be verbose on stderr about what's being done on the distro level (default: False) --target TARGET Run commands on this host (default: local) - --pkg-filter PKG_FILTER + --path-filter PATH_FILTER Default path filter for the exec context, as a name:spec loader string (default: None) -t, --topdir TOPDIR Project Path (default: None) diff --git a/test/unit/python/jw/pkg/lib/Distro/test.py b/test/unit/python/jw/pkg/lib/Distro/test.py index 3292a81a..6af6c125 100644 --- a/test/unit/python/jw/pkg/lib/Distro/test.py +++ b/test/unit/python/jw/pkg/lib/Distro/test.py @@ -271,7 +271,7 @@ sdf = SuseDistro( cl, id = 'suse', os_release_str = OS_RELEASE_SUSE, - default_pkg_filter = Pkg(spec = 'pkg:url=~jw.dev', file_context = cl) + default_path_filter = Pkg(spec = 'pkg:url=~jw.dev', file_context = cl) ) assert asyncio.run(sdf.pkg_files()) == \ ['/etc/a/a.conf.jw-tmpl', '/etc/b/b.conf.jw-tmpl'] @@ -281,7 +281,7 @@ sde = SuseDistro( cl, id = 'suse', os_release_str = OS_RELEASE_SUSE, - default_pkg_filter = Pkg(spec = 'pkg:url=~zzz-nomatch', file_context = cl) + default_path_filter = Pkg(spec = 'pkg:url=~zzz-nomatch', file_context = cl) ) assert asyncio.run(sde.pkg_files()) == [] assert '--queryformat' in cl.cmds[-1] diff --git a/test/unit/python/jw/pkg/lib/Uri/test.py b/test/unit/python/jw/pkg/lib/Uri/test.py index 60a958c3..2afa9656 100644 --- a/test/unit/python/jw/pkg/lib/Uri/test.py +++ b/test/unit/python/jw/pkg/lib/Uri/test.py @@ -98,21 +98,21 @@ assert '' in str(u) # The query is identity, not path: it is exposed, it survives a # path change, and it shows in the full form -u = Uri('kvfile://host/?pkg-filter=url=~jw.dev') -assert u.query == 'pkg-filter=url=~jw.dev' +u = Uri('kvfile://host/?path-filter=url=~jw.dev') +assert u.query == 'path-filter=url=~jw.dev' assert u.path == '/' assert u.new_replace_path('etc/foo.conf').to_string == \ - 'kvfile://host/etc/foo.conf?pkg-filter=url=~jw.dev' -u = Uri('kvfile:///?pkg-filter=url=~jw.dev') + 'kvfile://host/etc/foo.conf?path-filter=url=~jw.dev' +u = Uri('kvfile:///?path-filter=url=~jw.dev') assert u.new_replace_path('etc').to_string == \ - 'kvfile:///etc?pkg-filter=url=~jw.dev' -assert 'pkg-filter=url=~jw.dev' in u.full + 'kvfile:///etc?path-filter=url=~jw.dev' +assert 'path-filter=url=~jw.dev' in u.full assert Uri('ssh://host/path').query == '' # query_dict is None without a query and a key/value dict with one assert Uri('ssh://host/path').query_dict is None -u = Uri('kvfile://host/?pkg-filter=url=~jw.dev') -assert u.query_dict == {'pkg-filter': 'url=~jw.dev'} +u = Uri('kvfile://host/?path-filter=url=~jw.dev') +assert u.query_dict == {'path-filter': 'url=~jw.dev'} u = Uri('https://example.com/?a=1&b=two') assert u.query_dict == {'a': '1', 'b': 'two'} 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 5e2830a9..7cbaebbc 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 @@ -347,11 +347,11 @@ async def run_tests() -> None: await sstore.close() # -- The autodetected distro applies the app's documented - # filter fallback: JW_DEFAULT_PKG_FILTER reaches - # Distro.instantiate() as the default package filter + # 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_pkg_filter') + 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')) @@ -368,22 +368,22 @@ async def run_tests() -> None: # No query, no parameter: no filter s = KvFile('kvfile://') await s.readdir('') - assert captured['kwargs'].get('default_pkg_filter') is None + 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_pkg_filter')) + 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_pkg_filter') is None + 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_pkg_filter') + 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')) -- 2.56.1