From 013636fa38af2cb2371db48ba11cc9470a97636e Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Wed, 4 Nov 2026 18:20:49 +0100 Subject: [PATCH] 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())