diff --git a/src/python/jw/pkg/App.py b/src/python/jw/pkg/App.py index 4e20fcda..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.pkg_filter, + default_path_filter = self.exec_context.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..ca4ccd15 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,6 +20,15 @@ class CmdSelect(Cmd): # export @override async def _run(self, args: Namespace) -> None: - filter = PackageFilterString(args.filter) if args.filter else None + filter = PathFilter.create( + spec = args.filter, file_context = self.app.exec_context + ) if args.filter else None + if filter is not None: + from ...lib.pf.Pkg 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/cmds/posix/CmdCopy.py b/src/python/jw/pkg/cmds/posix/CmdCopy.py index 96014c79..afa7c4ff 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.exec_context.path_filter, ) diff --git a/src/python/jw/pkg/lib/CopyContext.py b/src/python/jw/pkg/lib/CopyContext.py index 3690d7b7..ef78dcbf 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,28 @@ 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) + # -- 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, + ) await self.__dst.open() return self diff --git a/src/python/jw/pkg/lib/Distro.py b/src/python/jw/pkg/lib/Distro.py index cc8327d9..b1f911c5 100644 --- a/src/python/jw/pkg/lib/Distro.py +++ b/src/python/jw/pkg/lib/Distro.py @@ -19,7 +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): @@ -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_path_filter: PathFilter | None = None, ) -> None: if id is None: raise ValueError('Tried to instantiate Distro without id') @@ -39,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 @@ -61,7 +62,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( @@ -329,8 +330,8 @@ class Distro(abc.ABC): return self.__exec_context @property - def default_pkg_filter(self) -> PackageFilter | 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) @@ -381,7 +382,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, @@ -389,7 +390,17 @@ class Distro(abc.ABC): filter: PackageFilter | None = None ) -> Iterable[Package]: if not filter: - filter = self.__default_pkg_filter + from .pf.Pkg import PackageFilter + + default = self.__default_path_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) @@ -508,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 1c282893..f84d85b1 100644 --- a/src/python/jw/pkg/lib/ExecApp.py +++ b/src/python/jw/pkg/lib/ExecApp.py @@ -3,7 +3,7 @@ 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 @@ -12,7 +12,6 @@ if TYPE_CHECKING: from argparse import ArgumentParser from .ExecContext import ExecContext - from .PackageFilter import PackageFilter class ExecApp(Base): # export @@ -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.__pkg_filter: PackageFilter | None | Literal[False] = None @override async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None: @@ -51,8 +49,9 @@ class ExecApp(Base): # export '--target', default = 'local', help = 'Run commands on this host' ) parser.add_argument( - '--pkg-filter', - help = 'Default filter for all distribution package-related operations', + '--path-filter', + 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 pkg_filter(self) -> PackageFilter | None: - if self.__pkg_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 - else: - from .PackageFilter import PackageFilterString - - self.__pkg_filter = PackageFilterString(spec) - if not self.__pkg_filter: - return None - return self.__pkg_filter - @property def exec_context(self) -> ExecContext: if self.__exec_context is None: from .ExecContext import ExecContext + spec = self.args.path_filter + if spec is None: + spec = os.getenv('JW_DEFAULT_PATH_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/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/PackageFilter.py b/src/python/jw/pkg/lib/PackageFilter.py deleted file mode 100644 index c0b7eb51..00000000 --- a/src/python/jw/pkg/lib/PackageFilter.py +++ /dev/null @@ -1,34 +0,0 @@ -from __future__ import annotations - -import abc -import re - -from typing import TYPE_CHECKING, override - -if TYPE_CHECKING: - from .Package import Package - -class PackageFilter(abc.ABC): - - @abc.abstractmethod - def _match(self, package: Package) -> bool: - raise NotImplementedError() - - def match(self, package: Package) -> bool: - return self._match(package) - -class PackageFilterString(PackageFilter): - - def __init__(self, definition: str) -> None: - # -- 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 - - @override - def _match(self, package: Package) -> bool: - url = package.url - if url is None: - return False - return re.search(self.__definition, url) is not None 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/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/src/python/jw/pkg/lib/ec/secret_store/KvFile.py b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py index 498ecb92..afcca673 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,21 +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_path_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 ...PackageFilter import PackageFilterString - - pkg_filter_str = os.environ.get('JW_DEFAULT_PKG_FILTER') - self.__distro = await Distro.instantiate( - ec = self.__inner, - default_pkg_filter = ( - PackageFilterString(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/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/src/python/jw/pkg/lib/pf/Pkg.py b/src/python/jw/pkg/lib/pf/Pkg.py new file mode 100644 index 00000000..b45dff44 --- /dev/null +++ b/src/python/jw/pkg/lib/pf/Pkg.py @@ -0,0 +1,90 @@ +from __future__ import annotations + +import abc +import os +import re + +from pathlib import Path +from typing import TYPE_CHECKING, override + +from ..PathFilter import PathFilter + +if TYPE_CHECKING: + 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: + 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 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 diff --git a/test/integration/jw_pkg/help/test-expected.txt b/test/integration/jw_pkg/help/test-expected.txt index efa2cbe1..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,9 +25,9 @@ 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 - Default filter for all distribution package-related - operations (default: None) + --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) --topdir-format TOPDIR_FORMAT Output references to topdir as one of "make: 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()) diff --git a/test/unit/python/jw/pkg/lib/PackageFilter/test.py b/test/unit/python/jw/pkg/lib/PackageFilter/test.py deleted file mode 100644 index f7c985bd..00000000 --- a/test/unit/python/jw/pkg/lib/PackageFilter/test.py +++ /dev/null @@ -1,34 +0,0 @@ -from jw.pkg.lib.Package import Package -from jw.pkg.lib.PackageFilter import PackageFilterString - -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) -# A package without a url never matches -assert not f.match(pkg_nourl) - -# Whitespace around the operator is tolerated -f = PackageFilterString(' url =~ example') -assert f.match(pkg) - -# An unanchored regex matches anywhere in the url -f = PackageFilterString('url=~jw-core$') -assert f.match(pkg) -assert not f.match(pkg_other) - -# -- Unsupported definitions raise -- - -for definition in ('', 'url=example.com', 'name=jw-core', 'url ~ example'): - try: - PackageFilterString(definition) - assert False, f'Should have raised for "{definition}"' - except Exception: - pass - -print('All PackageFilter tests passed') 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()) 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 594dd9cc..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,18 +347,45 @@ 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 - os.environ['JW_DEFAULT_PKG_FILTER'] = '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')) - finally: - del os.environ['JW_DEFAULT_PKG_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_path_filter') + assert flt is not None + assert flt.match_pkg(Package('fixture', url = 'https://jw.dev/fixture.rpm')) + assert not flt.match_pkg(Package('other', url = 'https://elsewhere/other.rpm')) + + # -- The backend filter also comes from the store URI's + # query's path-filter parameter; the constructor + # parameter wins + async def __flt_matches(flt: Any) -> None: + assert flt.match_pkg(Package('fixture', url = 'https://jw.dev/fixture.rpm')) + assert not flt.match_pkg( + Package('other', url = 'https://elsewhere/other.rpm') + ) + + # No query, no parameter: no filter + s = KvFile('kvfile://') + await s.readdir('') + assert captured['kwargs'].get('default_path_filter') is None + # The query's path-filter parameter + s = KvFile('kvfile://?path-filter=pkg%3Aurl%3D~jw.dev') + await s.readdir('') + await __flt_matches(captured['kwargs'].get('default_path_filter')) + # An unrelated query parameter is not a filter spec + s = KvFile('kvfile://?foo=bar') + await s.readdir('') + assert captured['kwargs'].get('default_path_filter') is None + # The constructor parameter wins over the query + s = KvFile( + 'kvfile://?path-filter=pkg%3Aurl%3D~jw.dev', + default_path_filter = 'pkg:url=~zzz-nomatch', + ) + await s.readdir('') + flt = captured['kwargs'].get('default_path_filter') + assert flt is not None + assert not flt.match_pkg(Package('fixture', url = 'https://jw.dev/fixture.rpm')) patcher.stop() 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/pf/Pkg/Makefile b/test/unit/python/jw/pkg/lib/pf/Pkg/Makefile new file mode 100644 index 00000000..49c7c21f --- /dev/null +++ b/test/unit/python/jw/pkg/lib/pf/Pkg/Makefile @@ -0,0 +1,7 @@ +TOPDIR = ../../../../../../../../ + +include $(TOPDIR)/make/proj.mk +include $(JWBDIR)/make/py-run.mk + +all: +test: run diff --git a/test/unit/python/jw/pkg/lib/pf/Pkg/test.py b/test/unit/python/jw/pkg/lib/pf/Pkg/test.py new file mode 100644 index 00000000..ad10bde0 --- /dev/null +++ b/test/unit/python/jw/pkg/lib/pf/Pkg/test.py @@ -0,0 +1,132 @@ +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.pf.Pkg import Pkg + +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 = 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 = Pkg(file_context = fc, spec = 'pkg: url =~ example') +assert f.match_pkg(pkg) + +# An unanchored regex matches anywhere in the url +f = Pkg(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', + 'pkg:url=example.com'): + try: + Pkg(file_context = fc, spec = definition) + assert False, f'Should have raised for "{definition}"' + except Exception: + pass + +# -- __repr__ -- + +f = Pkg(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 = Pkg(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 = 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' + except Exception as e: + assert 'backed by distributions' in str(e) + +asyncio.run(__run_tests()) + +print('All lib.pf.Pkg tests passed')