diff --git a/src/python/jw/pkg/cmds/pkg/CmdLs.py b/src/python/jw/pkg/cmds/pkg/CmdLs.py index b3a74d6f..c162eda8 100644 --- a/src/python/jw/pkg/cmds/pkg/CmdLs.py +++ b/src/python/jw/pkg/cmds/pkg/CmdLs.py @@ -21,4 +21,4 @@ class CmdLs(NamedPkgsCmd): # export @override async def _run(self, args: Namespace) -> None: for name in args.names: - print('\n'.join(await self.distro.pkg_files(name))) + print('\n'.join(await self.distro.pkg_paths(name))) diff --git a/src/python/jw/pkg/cmds/secrets/lib/DistroContext.py b/src/python/jw/pkg/cmds/secrets/lib/DistroContext.py index 8f5b8cf4..3006a1a2 100644 --- a/src/python/jw/pkg/cmds/secrets/lib/DistroContext.py +++ b/src/python/jw/pkg/cmds/secrets/lib/DistroContext.py @@ -35,7 +35,7 @@ class DistroContext(FilesContext): async def match_files(self, pkg_names: Collection[str], pattern: str) -> list[str]: ret: list[str] = [] for pkg_name in pkg_names: - for path in await self.__distro.pkg_files(pkg_name): + for path in await self.__distro.pkg_paths(pkg_name): if re.match(pattern, path): ret.append(path) return ret diff --git a/src/python/jw/pkg/lib/Distro.py b/src/python/jw/pkg/lib/Distro.py index b1f911c5..2352be5a 100644 --- a/src/python/jw/pkg/lib/Distro.py +++ b/src/python/jw/pkg/lib/Distro.py @@ -10,6 +10,8 @@ from typing import TYPE_CHECKING, Any from .base import InputMode from .log import ERR, INFO, WARNING, log +from .PathFilter import Verdict +from .pf.Pkg import PackageFilter if TYPE_CHECKING: from collections.abc import Collection @@ -20,7 +22,6 @@ if TYPE_CHECKING: from .FlaggedFile import FlaggedFile from .Package import Package from .PathFilter import PathFilter - from .pf.Pkg import PackageFilter class Distro(abc.ABC): @@ -504,13 +505,13 @@ class Distro(abc.ABC): return return await self._delete(names) - # -- pkg_files + # -- pkg_paths @abc.abstractmethod - async def _pkg_files(self, names: list[str] | None) -> Iterable[str]: + async def _pkg_paths(self, names: list[str] | None) -> Iterable[str]: pass - async def pkg_files(self, names: str | list[str] | None = None) -> Iterable[str]: + async def pkg_paths(self, names: str | list[str] | None = None) -> Iterable[str]: # -- The file paths of the packages selected by the # argument: None, the default selection, filtered to the # app's packages when a filter is set, all installed @@ -519,9 +520,49 @@ class Distro(abc.ABC): # compatibility with the single-package call if isinstance(names, str): names = [names] - if names is None and self.default_path_filter is not None: + elif names is None and self.default_path_filter is not None: names = [p.name for p in await self.select()] - return await self._pkg_files(names) + return await self._pkg_paths(names) + + # -- paths + + async def _paths( + self, + filter: PathFilter | None = None, + pkg_names: Collection[str] = [], + ) -> Iterable[str]: + if filter and pkg_names and not isinstance(filter, PackageFilter): + raise Exception( + f'Tried to select files from {self} with non-package-filter {filter} ' + f'and package list {", ".join(pkg_names)}' + ) + if not filter: + filter = self.__default_path_filter + # -- pkg_names follows the select() convention: an empty + # list selects every package, which is listed in one + # whole-system query instead of by name + if isinstance(filter, PackageFilter): + pkg_names = [p.name for p in await self._select(pkg_names, filter)] + ret: list[str] = [ + path for path in await self.pkg_paths(names = list(pkg_names)) + ] + elif pkg_names: + pkg_names = [p.name for p in await self._select_by_name(pkg_names)] + ret = [path for path in await self.pkg_paths(names = list(pkg_names))] + else: + # -- _pkg_paths() directly: pkg_paths() would re-resolve + # the default filter, which _paths() already did + ret = [path for path in await self._pkg_paths(None)] + if filter and not isinstance(filter, PackageFilter): + ret = [path for path in ret if await filter.run(path) == Verdict.ALLOW] + return ret + + async def paths( + self, + filter: PathFilter | None = None, + pkg_names: Collection[str] = [], + ) -> Iterable[str]: + return await self._paths(filter, pkg_names) # -- verify diff --git a/src/python/jw/pkg/lib/FileContext.py b/src/python/jw/pkg/lib/FileContext.py index 2caa26f9..e5ced518 100644 --- a/src/python/jw/pkg/lib/FileContext.py +++ b/src/python/jw/pkg/lib/FileContext.py @@ -124,29 +124,31 @@ class FileContext(abc.ABC): def chroot(self) -> bool: return self.__chroot + def _create_path_filter( + self, candidate: str | PathFilter | Literal[False] | None + ) -> PathFilter | Literal[False]: + if candidate is None or candidate is False: + return False + if isinstance(candidate, PathFilter): + return candidate + return PathFilter.create(spec = candidate, file_context = self) + @property def path_filter(self) -> PathFilter | None: - - def __create_path_filter( - candidate: str | None | PathFilter | Literal[False] - ) -> PathFilter | Literal[False]: - if candidate is None or candidate is False: - return False - if isinstance(candidate, PathFilter): - return candidate - return PathFilter.create(spec = candidate, file_context = self) - if self.__path_filter is None: query = self.__uri.query_dict if self.__uri.query_dict else {} candidate: str | PathFilter | Literal[False] | None = \ query.get('path-filter') if candidate is None: candidate = self.__default_path_filter - self.__path_filter = __create_path_filter(candidate) + self.__path_filter = self._create_path_filter(candidate) return self.__path_filter or None @path_filter.setter def path_filter(self, value: str | PathFilter | None | Literal[False]) -> None: + self._set_path_filter(value) + + def _set_path_filter(self, value: str | PathFilter | None | Literal[False]) -> None: self.__path_filter = None self.__default_path_filter = value diff --git a/src/python/jw/pkg/lib/PathFilter.py b/src/python/jw/pkg/lib/PathFilter.py index dd1148aa..6f0b43c4 100644 --- a/src/python/jw/pkg/lib/PathFilter.py +++ b/src/python/jw/pkg/lib/PathFilter.py @@ -54,7 +54,9 @@ class PathFilter(abc.ABC): f'Unsupported filter spec "{spec}": expected a "name:spec" ' 'form, where the name picks the filter class' ) - class_name = name.capitalize() + from .util import kebab_to_pascal + + class_name = kebab_to_pascal(name) module_name = 'jw.pkg.lib.pf.' + class_name filter_classes: LoadTypes[PathFilter] = LoadTypes( [module_name], diff --git a/src/python/jw/pkg/lib/distros/arch/Distro.py b/src/python/jw/pkg/lib/distros/arch/Distro.py index cc31b9c4..362c5708 100644 --- a/src/python/jw/pkg/lib/distros/arch/Distro.py +++ b/src/python/jw/pkg/lib/distros/arch/Distro.py @@ -67,7 +67,7 @@ class Distro(Base): ) @override - async def _pkg_files(self, names: list[str] | None) -> Iterable[str]: + async def _pkg_paths(self, names: list[str] | None) -> Iterable[str]: raise NotImplementedError( 'distro pkg ls yet implemented for Arch-like distributions' ) diff --git a/src/python/jw/pkg/lib/distros/debian/Distro.py b/src/python/jw/pkg/lib/distros/debian/Distro.py index b6f472d0..a9d73fa9 100644 --- a/src/python/jw/pkg/lib/distros/debian/Distro.py +++ b/src/python/jw/pkg/lib/distros/debian/Distro.py @@ -156,7 +156,7 @@ class Distro(Base): await self.dpkg(['-P', *names], sudo = True) @override - async def _pkg_files(self, names: list[str] | None) -> Iterable[str]: + async def _pkg_paths(self, names: list[str] | None) -> Iterable[str]: return await list_files(names, ec = self.ctx) @override diff --git a/src/python/jw/pkg/lib/distros/redhat/Distro.py b/src/python/jw/pkg/lib/distros/redhat/Distro.py index b365c3ad..c8f6b77a 100644 --- a/src/python/jw/pkg/lib/distros/redhat/Distro.py +++ b/src/python/jw/pkg/lib/distros/redhat/Distro.py @@ -88,7 +88,7 @@ class Distro(Base): await self.rpm(['-e', *names], sudo = True) @override - async def _pkg_files(self, names: list[str] | None) -> Iterable[str]: + async def _pkg_paths(self, names: list[str] | None) -> Iterable[str]: return await list_files(names, ec = self.ctx) @override diff --git a/src/python/jw/pkg/lib/distros/suse/Distro.py b/src/python/jw/pkg/lib/distros/suse/Distro.py index b143d839..aae12133 100644 --- a/src/python/jw/pkg/lib/distros/suse/Distro.py +++ b/src/python/jw/pkg/lib/distros/suse/Distro.py @@ -107,7 +107,7 @@ class Distro(Base): await self.rpm(['-e', *names], sudo = True) @override - async def _pkg_files(self, names: list[str] | None) -> Iterable[str]: + async def _pkg_paths(self, names: list[str] | None) -> Iterable[str]: return await list_files(names, ec = self.ctx) @override diff --git a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py index afcca673..afce76e5 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py +++ b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py @@ -18,6 +18,7 @@ from ...file_types import FT_COMPOUND, FT_DIR from ...FileContext import FileContext from ...kv import parse_kv, serialize_kv from ...PathFilter import PathFilter +from ...pf.PkgSecrets import PkgSecrets from ...Result import Result from .Base import Base from .layout import BLOB_SUFFIX, FT_SECRET, FT_SECRET_FILE, FT_SECRET_KEY, SECRET_SUFFIX @@ -32,27 +33,9 @@ class KvFile(Base): default_path_filter: str | PathFilter | None | Literal[False] = None, **kwargs: Any, ) -> None: - - def __create_backend_path_filter() -> PathFilter | None: - - def __spec() -> str | None: - if isinstance(default_path_filter, str): - return default_path_filter - d = self.uri.query_dict - if d is None: - return None - return d.get('path-filter') - - if default_path_filter is False: - return None - if isinstance(default_path_filter, PathFilter): - return default_path_filter - spec: str | None = __spec() - if spec is None: - return None - return PathFilter.create(spec = spec, file_context = self.__inner) - - super().__init__(uri, *args, default_path_filter = False, **kwargs) + super().__init__( + uri, *args, default_path_filter = default_path_filter, **kwargs + ) kwargs.pop('chroot', None) scheme = 'ssh' if self.uri.hostname else 'local' self.__inner: ExecContext = cast( @@ -61,12 +44,31 @@ class KvFile(Base): f'{scheme}://{self.uri.authority}', chroot = False, **kwargs ), ) - self.__backend_path_filter = __create_backend_path_filter() self.___distro: Distro | None = None - self.___config_paths: list[str] | None = None + self.___target_paths: list[str] | None = None self.__root = self.uri.path.lstrip('/') self.__ctx = FcCache(self.__inner) + @override + def _create_path_filter( + self, candidate: str | PathFilter | Literal[False] | None + ) -> PathFilter | Literal[False]: + # -- The address space is scoped by a pkg-secrets filter + # backed by the inner connection, which alone knows the + # distribution; this context is a virtual layer over it + if candidate is None or candidate is False: + return False + if isinstance(candidate, PathFilter): + ret = candidate + else: + ret = PathFilter.create(spec = candidate, file_context = self.__inner) + if not isinstance(ret, PkgSecrets): + raise Exception( + f'A kvfile address space is scoped by a pkg-secrets ' + f'filter, not by {ret!r}' + ) + return ret + @override async def _open(self) -> None: await self.__inner.open() @@ -94,49 +96,49 @@ class KvFile(Base): async def __distro(self) -> Distro: if self.___distro is None: from ...Distro import Distro - self.___distro = await Distro.instantiate( - ec = self.__inner, default_path_filter = self.__backend_path_filter - ) + self.___distro = await Distro.instantiate(ec = self.__inner) return self.___distro - async def __config_paths(self) -> list[str]: - if self.___config_paths is None: - ret: set[str] = set() - for f in await (await self.__distro()).pkg_files(): - if not f.endswith('.jw-tmpl'): - continue - ret.add(f.lstrip('/')[:-len('.jw-tmpl')]) - self.___config_paths = sorted(ret) + async def __target_paths(self) -> list[str]: + if self.___target_paths is None: + pf = self.path_filter + if isinstance(pf, PkgSecrets): + ret = await pf.target_paths() + else: + ret = await PkgSecrets.distro_target_paths( + await self.__distro(), filter = pf + ) + self.___target_paths = ret warm = ['/'] - warm += [f'/{p}{SECRET_SUFFIX}' for p in self.___config_paths] - warm += [f'/{p}{BLOB_SUFFIX}' for p in self.___config_paths] + warm += [f'/{p}{SECRET_SUFFIX}' for p in self.___target_paths] + warm += [f'/{p}{BLOB_SUFFIX}' for p in self.___target_paths] dirs: set[str] = set() - for p in self.___config_paths: + for p in self.___target_paths: parts = p.split('/') for i in range(1, len(parts)): dirs.add('/'.join(parts[:i])) for d in sorted(dirs): warm += [f'/{d}', f'/{d}{SECRET_SUFFIX}', f'/{d}{BLOB_SUFFIX}'] await self.__ctx.warm(warm) - assert self.___config_paths is not None - return self.___config_paths + assert self.___target_paths is not None + return self.___target_paths - async def __compound_kv(self, config_path: str) -> dict[str, str]: - path = f'/{config_path.lstrip("/")}{SECRET_SUFFIX}' + async def __compound_kv(self, target_path: str) -> dict[str, str]: + path = f'/{target_path.lstrip("/")}{SECRET_SUFFIX}' if not await self.__ctx.file_exists(path): - raise FileNotFoundError(config_path) + raise FileNotFoundError(target_path) ret = await self.__ctx.get(path) return parse_kv(ret.stdout) - async def __is_compound(self, config_path: str) -> bool: - if not config_path: + async def __is_compound(self, target_path: str) -> bool: + if not target_path: return False - return await self.__ctx.file_exists(f'/{config_path}{SECRET_SUFFIX}') + return await self.__ctx.file_exists(f'/{target_path}{SECRET_SUFFIX}') @override async def _stat(self, path: str, follow_symlinks: bool) -> StatResult: path = self.__host_path(path) - config_path, is_blob = self.__strip_suffix(path) + target_path, is_blob = self.__strip_suffix(path) async def __stat_of(host_path: str, ftype: FileType) -> StatResult: st = await self.__ctx.stat(host_path, follow_symlinks) @@ -149,16 +151,16 @@ class KvFile(Base): size = st.size, ) - if not config_path: + if not target_path: return await __stat_of('/', FT_DIR) if is_blob: - secret_path = f'/{config_path}{BLOB_SUFFIX}' + secret_path = f'/{target_path}{BLOB_SUFFIX}' if not await self.__ctx.file_exists(secret_path): raise FileNotFoundError(errno.ENOENT, f'stat: {path}') return await __stat_of(secret_path, FT_SECRET_FILE) - if await self.__is_compound(config_path): - return await __stat_of(f'/{config_path}{SECRET_SUFFIX}', FT_SECRET) - parent, sep, key = config_path.rpartition('/') + if await self.__is_compound(target_path): + return await __stat_of(f'/{target_path}{SECRET_SUFFIX}', FT_SECRET) + parent, sep, key = target_path.rpartition('/') if sep and key: parent, _ = self.__strip_suffix(parent) if await self.__is_compound(parent) and \ @@ -171,41 +173,41 @@ class KvFile(Base): FT_SECRET_KEY, mode = st.mode, ) - secret_path = f'/{config_path}{BLOB_SUFFIX}' + secret_path = f'/{target_path}{BLOB_SUFFIX}' if await self.__ctx.file_exists(secret_path): return await __stat_of(secret_path, FT_SECRET_FILE) - if await self.__ctx.is_dir(f'/{config_path}'): - return await __stat_of(f'/{config_path}', FT_DIR) + if await self.__ctx.is_dir(f'/{target_path}'): + return await __stat_of(f'/{target_path}', FT_DIR) raise FileNotFoundError(errno.ENOENT, f'stat: {path}') @override async def _is_dir(self, path: str, follow_symlinks: bool) -> bool: path = self.__host_path(path) - config_path, is_blob = self.__strip_suffix(path) - if not config_path: + target_path, is_blob = self.__strip_suffix(path) + if not target_path: return True - parent, sep, _ = config_path.rpartition('/') + parent, sep, _ = target_path.rpartition('/') if sep: parent, _ = self.__strip_suffix(parent) if await self.__is_compound(parent): return False - if await self.__is_compound(config_path): + if await self.__is_compound(target_path): return True if is_blob: return False - return await self.__ctx.is_dir(f'/{config_path}') + return await self.__ctx.is_dir(f'/{target_path}') @override async def _readdir(self, path: str) -> Iterable[str]: path = self.__host_path(path) - config_path, is_blob = self.__strip_suffix(path) - if config_path and await self.__is_compound(config_path): - return (await self.__compound_kv(config_path)).keys() - if is_blob and await self.__ctx.file_exists(f'/{config_path}{BLOB_SUFFIX}'): + target_path, is_blob = self.__strip_suffix(path) + if target_path and await self.__is_compound(target_path): + return (await self.__compound_kv(target_path)).keys() + if is_blob and await self.__ctx.file_exists(f'/{target_path}{BLOB_SUFFIX}'): raise NotADirectoryError(path) children: set[str] = set() - prefix = f'{config_path}/' if config_path else '' - for cfg in await self.__config_paths(): + prefix = f'{target_path}/' if target_path else '' + for cfg in await self.__target_paths(): if not cfg.startswith(prefix): continue rest = cfg[len(prefix):] @@ -219,8 +221,8 @@ class KvFile(Base): children.add(f'{label}{SECRET_SUFFIX}') if await self.__ctx.file_exists(f'/{cfg}{BLOB_SUFFIX}'): children.add(f'{label}{BLOB_SUFFIX}') - if config_path and not children: - if not await self.__ctx.is_dir(f'/{config_path}'): + if target_path and not children: + if not await self.__ctx.is_dir(f'/{target_path}'): raise FileNotFoundError(path) return children @@ -229,23 +231,23 @@ class KvFile(Base): self, path: str, wd: str | None, throw: bool, verbose: bool | None, title: str ) -> Result: path = self.__host_path(path) - config_path, is_blob = self.__strip_suffix(path) + target_path, is_blob = self.__strip_suffix(path) if is_blob: - secret_path = f'/{config_path}{BLOB_SUFFIX}' + secret_path = f'/{target_path}{BLOB_SUFFIX}' if not await self.__ctx.file_exists(secret_path): raise FileNotFoundError(path) return await self.__ctx.get(secret_path) - secret_path = f'/{config_path}{SECRET_SUFFIX}' + secret_path = f'/{target_path}{SECRET_SUFFIX}' if await self.__ctx.file_exists(secret_path): return await self.__ctx.get(secret_path) - secret_path = f'/{config_path}{BLOB_SUFFIX}' + secret_path = f'/{target_path}{BLOB_SUFFIX}' if await self.__ctx.file_exists(secret_path): return await self.__ctx.get(secret_path) - if await self.__ctx.is_dir(f'/{config_path}'): + if await self.__ctx.is_dir(f'/{target_path}'): raise IsADirectoryError(errno.EISDIR, f'get: {path}') - if '/' not in config_path: + if '/' not in target_path: raise FileNotFoundError(path) - compound, key = config_path.rsplit('/', 1) + compound, key = target_path.rsplit('/', 1) compound, _ = self.__strip_suffix(compound) kv = await self.__compound_kv(compound) try: @@ -256,8 +258,8 @@ class KvFile(Base): @override async def _mkdir(self, path: str, mode: int, ftype: FileType) -> None: path = self.__host_path(path) - config_path, _ = self.__strip_suffix(path) - host_path = f'/{config_path}' + target_path, _ = self.__strip_suffix(path) + host_path = f'/{target_path}' if ftype.is_subtype(FT_COMPOUND): if await self.__ctx.file_exists(host_path + SECRET_SUFFIX): return @@ -295,7 +297,7 @@ class KvFile(Base): ftype: FileType, ) -> Result: path = self.__host_path(path) - config_path, is_blob = self.__strip_suffix(path) + target_path, is_blob = self.__strip_suffix(path) if ftype.is_subtype(FT_SECRET): if is_blob: raise ValueError( @@ -303,7 +305,7 @@ class KvFile(Base): ) m = 0o400 if mode is None else int(mode, 8) return await self.__ctx.put( - f'/{config_path}{SECRET_SUFFIX}', + f'/{target_path}{SECRET_SUFFIX}', content, owner = owner, group = group, @@ -313,14 +315,14 @@ class KvFile(Base): if ftype.is_subtype(FT_SECRET_FILE): m = 0o400 if mode is None else int(mode, 8) return await self.__ctx.put( - f'/{config_path}{BLOB_SUFFIX}', + f'/{target_path}{BLOB_SUFFIX}', content, owner = owner, group = group, mode = m, atomic = True, ) - compound, sep, key = config_path.rpartition('/') + compound, sep, key = target_path.rpartition('/') if not sep or not compound or not key or '/' in key: raise ValueError(f'put: "{path}" is not a compound/key path') compound, _ = self.__strip_suffix(compound) diff --git a/src/python/jw/pkg/lib/ec/secret_store/layout.py b/src/python/jw/pkg/lib/ec/secret_store/layout.py index 67956350..ba8b54cd 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/layout.py +++ b/src/python/jw/pkg/lib/ec/secret_store/layout.py @@ -12,6 +12,9 @@ from ...file_types import FT_COMPOUND, FT_REG, file_types # # Host-specific entries take precedence over default ones. +# Suffix of the template file accompanying a compiled target +TMPL_SUFFIX = '.jw-tmpl' + # Suffix of the key-value secret file accompanying a compiled target SECRET_SUFFIX = '.jw-secret' @@ -20,11 +23,11 @@ BLOB_SUFFIX = '.jw-secret-file' DEFAULT_PREFIX = 'default' -def content_name(name: str) -> str | None: - # -- The config path of an on-host secret file name: the name - # with its content suffix removed, or None if the name - # carries neither suffix - for suffix in (SECRET_SUFFIX, BLOB_SUFFIX): +def target_name(name: str) -> str | None: + # -- The target path of a store or template file name: the + # name with its content suffix removed, or None if the + # name carries no suffix + for suffix in (TMPL_SUFFIX, SECRET_SUFFIX, BLOB_SUFFIX): if name.endswith(suffix): return name.removesuffix(suffix) return None diff --git a/src/python/jw/pkg/lib/pf/Pkg.py b/src/python/jw/pkg/lib/pf/Pkg.py index b45dff44..a11e9a0c 100644 --- a/src/python/jw/pkg/lib/pf/Pkg.py +++ b/src/python/jw/pkg/lib/pf/Pkg.py @@ -65,25 +65,33 @@ class PackageFilter(FileContextFilter): # export async def _access(self, path: str, mode: int = os.F_OK) -> bool: if self.__space is None: distro = await self.distro() - names = [p.name for p in await distro.select([], filter = self)] - self.__space = set(self.__add_parent_paths(await distro.pkg_files(names))) + self.__space = set( + self.__add_parent_paths(await distro.paths(filter = self)) + ) 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 + self.__criterion, self.__rx = self._parse_spec(spec) + + def _parse_spec(self, spec: str) -> tuple[str | None, re.Pattern[str] | None]: + # -- Poor man's parsing for now: "pkg:criterion=~regex", + # where the criterion picks the package attribute to + # match m = re.match(r'^\s*pkg\s*:\s*(\S+?)\s*=~\s*(.+?)\s*$', spec) if m is None: raise Exception(f'Unsupported filter string "{spec}"') - self.__criterion = m.group(1) - self.__rx = re.compile(m.group(2)) + return m.group(1), re.compile(m.group(2)) @override def _match_pkg(self, package: Package) -> bool: - if self.__criterion != 'url': + # -- A None criterion or regex matches every package + if self.__criterion not in (None, 'url'): return False + if self.__rx is None: + return True url = package.url if url is None: return False diff --git a/src/python/jw/pkg/lib/pf/PkgSecrets.py b/src/python/jw/pkg/lib/pf/PkgSecrets.py new file mode 100644 index 00000000..15703dc3 --- /dev/null +++ b/src/python/jw/pkg/lib/pf/PkgSecrets.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +import os +import re + +from pathlib import Path +from typing import TYPE_CHECKING, Any, override + +from ..ec.secret_store.layout import TMPL_SUFFIX, target_name +from .Pkg import Pkg + +if TYPE_CHECKING: + from ..Distro import Distro + from ..FileContext import FileContext + from ..PathFilter import PathFilter + +class PkgSecrets(Pkg): # export + + def __init__(self, *, spec: str, file_context: FileContext, **kwargs: Any) -> None: + super().__init__(spec = spec, file_context = file_context, **kwargs) + self.___targets: list[str] | None = None + self.___targets_set: set[str] | None = None + self.___targets_and_parents: set[str] | None = None + + @override + def _parse_spec(self, spec: str) -> tuple[str | None, re.Pattern[str] | None]: + # -- "pkg-secrets:criterion=~regex", following Pkg; a bare + # spec (no criterion) matches every installed package + m = re.match(r'^\s*pkg-secrets\s*:\s*(?:(\S+?)\s*=~\s*(.+?))?\s*$', spec) + if m is None: + raise Exception(f'Unsupported filter string "{spec}"') + criterion = m.group(1) + if criterion is not None and criterion != 'url': + raise Exception(f'Unsupported criterion "{criterion}" in "{spec}"') + rx = re.compile(m.group(2)) if m.group(2) is not None else None + return criterion, rx + + async def __targets(self) -> list[str]: + if self.___targets is None: + self.___targets = await self.distro_target_paths( + await self.distro(), filter = self + ) + return self.___targets + + async def __targets_set(self) -> set[str]: + if self.___targets_set is None: + self.___targets_set = set(await self.__targets()) + return self.___targets_set + + async def __targets_and_parents(self) -> set[str]: + if self.___targets_and_parents is None: + ret: set[str] = set() + cfgs = await self.__targets() + for p in cfgs: + item = Path(p) + for i in (item, *item.parents): + ret.add(str(i)) + self.___targets_and_parents = ret + return self.___targets_and_parents + + @override + async def _access(self, path: str, mode: int = os.F_OK) -> bool: + p = path.lstrip('/') + targets = target_name(p) + if targets is not None: + return targets in await self.__targets_and_parents() + if '/' in p: + parent = p.rpartition('/')[0] + ptargets = target_name(parent) + if ptargets is not None and ptargets in \ + await self.__targets_and_parents(): + return True + if parent in await self.__targets_set(): + return True + # -- A directory, a plain file, the root + return (p or '.') in await self.__targets_and_parents() + + @classmethod + async def distro_target_paths( + cls, + distro: Distro, + filter: PathFilter | None, + ) -> list[str]: + return sorted( + path.lstrip('/')[:-len(TMPL_SUFFIX)] + for path in await distro.paths(filter = filter) + if path.endswith(TMPL_SUFFIX) + ) + + async def target_paths(self) -> list[str]: + return await self.__targets() diff --git a/src/python/jw/pkg/lib/util.py b/src/python/jw/pkg/lib/util.py index ab06270c..f8eb78bd 100644 --- a/src/python/jw/pkg/lib/util.py +++ b/src/python/jw/pkg/lib/util.py @@ -2,6 +2,7 @@ from __future__ import annotations import json import os +import re import sys from enum import Enum, auto @@ -38,6 +39,15 @@ def pretty_cmd(cmd: list[str] | None = None, wd: str | None = None) -> str: ret += f' in {wd}' return ret +def kebab_to_pascal(value: str) -> str: + return ''.join(part.capitalize() for part in value.split('-')) + +def pascal_to_kebab(value: str) -> str: + # Handles normal CamelCase / PascalCase, including many acronym cases + s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1-\2', value) + s2 = re.sub(r'([a-z0-9])([A-Z])', r'\1-\2', s1) + return s2.lower() + # See ExecContext.run() for what this function does async def run_cmd( *args: Any, diff --git a/test/integration/jw_pkg/secrets/test.py b/test/integration/jw_pkg/secrets/test.py index 3daed322..b61ed17d 100644 --- a/test/integration/jw_pkg/secrets/test.py +++ b/test/integration/jw_pkg/secrets/test.py @@ -72,7 +72,7 @@ class FakeDistro(SuseDistro): return [Package(name) for name in names if name in self.__files] @override - async def _pkg_files(self, names: list[str] | None) -> list[str]: + async def _pkg_paths(self, names: list[str] | None) -> list[str]: if names is None: names = list(self.__files) ret: list[str] = [] diff --git a/test/unit/python/jw/pkg/lib/Distro/test.py b/test/unit/python/jw/pkg/lib/Distro/test.py index 6af6c125..0ec1ef89 100644 --- a/test/unit/python/jw/pkg/lib/Distro/test.py +++ b/test/unit/python/jw/pkg/lib/Distro/test.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +import os from typing import TYPE_CHECKING, Iterable, cast, override @@ -8,6 +9,7 @@ from jw.pkg.lib.Distro import Distro from jw.pkg.lib.distros.suse.Distro import Distro as SuseDistro from jw.pkg.lib.ec.Local import Local from jw.pkg.lib.Package import Package +from jw.pkg.lib.PathFilter import Handle, PathFilter from jw.pkg.lib.pf.Pkg import Pkg from jw.pkg.lib.Result import Result @@ -63,7 +65,7 @@ class DummyDistro(Distro): pass @override - async def _pkg_files(self, names: list[str] | None) -> Iterable[str]: + async def _pkg_paths(self, names: list[str] | None) -> Iterable[str]: return [] @override @@ -97,7 +99,7 @@ vd.verified = None assert asyncio.run(vd.verify()) == [] assert vd.verified is None -# -- pkg_files -- +# -- pkg_paths -- # -- Without a filter, the selection is passed through as the # whole system; the paths come back unfiltered @@ -113,7 +115,7 @@ class TmplDistro(DummyDistro): return [Package(n) for n in self.files] @override - async def _pkg_files(self, names: list[str] | None) -> list[str]: + async def _pkg_paths(self, names: list[str] | None) -> list[str]: if names is None: names = list(self.files) ret: list[str] = [] @@ -126,12 +128,12 @@ t.files = { 'a': ['/usr/share/a/a.conf.jw-tmpl', '/usr/bin/a'], 'b': ['/etc/b/b.conf.jw-tmpl'], } -assert sorted(asyncio.run(t.pkg_files())) == [ +assert sorted(asyncio.run(t.pkg_paths())) == [ '/etc/b/b.conf.jw-tmpl', '/usr/bin/a', '/usr/share/a/a.conf.jw-tmpl' ] # -- A single package name as a str is accepted for compatibility -assert sorted(asyncio.run(t.pkg_files('a'))) == [ +assert sorted(asyncio.run(t.pkg_paths('a'))) == [ '/usr/bin/a', '/usr/share/a/a.conf.jw-tmpl', ] @@ -252,7 +254,9 @@ class CannedRpmLocal(Local): ) -> Result: self.cmds.append(cmd) if '-qal' in cmd: - out = '/usr/bin/x\n/etc/a/a.conf.jw-tmpl\n' + out = ('/usr/bin/x\n' + '/etc/a/a.conf.jw-tmpl\n' + '/etc/b/b.conf.jw-tmpl\n') elif '-ql' in cmd: out = '/etc/a/a.conf.jw-tmpl\n/etc/b/b.conf.jw-tmpl\n' else: @@ -261,9 +265,10 @@ class CannedRpmLocal(Local): cl = CannedRpmLocal() sd = SuseDistro(cl, id = 'suse', os_release_str = OS_RELEASE_SUSE) -assert asyncio.run(sd.pkg_files()) == [ +assert asyncio.run(sd.pkg_paths()) == [ '/usr/bin/x', '/etc/a/a.conf.jw-tmpl', + '/etc/b/b.conf.jw-tmpl', ] assert cl.cmds[-1] == ['/usr/bin/rpm', '-qal'] @@ -273,7 +278,7 @@ sdf = SuseDistro( os_release_str = OS_RELEASE_SUSE, default_path_filter = Pkg(spec = 'pkg:url=~jw.dev', file_context = cl) ) -assert asyncio.run(sdf.pkg_files()) == \ +assert asyncio.run(sdf.pkg_paths()) == \ ['/etc/a/a.conf.jw-tmpl', '/etc/b/b.conf.jw-tmpl'] assert cl.cmds[-1] == ['/usr/bin/rpm', '-ql', 'a', 'b'] @@ -283,9 +288,48 @@ sde = SuseDistro( os_release_str = OS_RELEASE_SUSE, default_path_filter = Pkg(spec = 'pkg:url=~zzz-nomatch', file_context = cl) ) -assert asyncio.run(sde.pkg_files()) == [] +assert asyncio.run(sde.pkg_paths()) == [] assert '--queryformat' in cl.cmds[-1] +# -- paths() -- + +# -- No filter and a bare path filter take the one-shot +# whole-system query, the second then checking the files one by +# one; a package filter selects the backing packages and lists +# their files by name; a path filter with package names is +# refused +class _AllowList(PathFilter): + + def __init__(self, allowed: set[str]) -> None: + super().__init__(spec = 'test:allow', handle = Handle(0)) + self.allowed = allowed + + @override + async def _access(self, path: str, mode: int = os.F_OK) -> bool: + return path in self.allowed + +allow = _AllowList({'/etc/b/b.conf.jw-tmpl'}) + +assert sorted(asyncio.run(sd.paths())) == \ + ['/etc/a/a.conf.jw-tmpl', '/etc/b/b.conf.jw-tmpl', '/usr/bin/x'] +assert cl.cmds[-1] == ['/usr/bin/rpm', '-qal'] + +assert sorted( + asyncio.run(sd.paths(filter = Pkg(spec = 'pkg:url=~jw.dev', file_context = cl))) +) == ['/etc/a/a.conf.jw-tmpl', '/etc/b/b.conf.jw-tmpl'] +assert cl.cmds[-1] == ['/usr/bin/rpm', '-ql', 'a', 'b'] + +assert asyncio.run(sd.paths(filter = allow)) == ['/etc/b/b.conf.jw-tmpl'] +assert cl.cmds[-1] == ['/usr/bin/rpm', '-qal'] + +try: + asyncio.run(sd.paths(filter = allow, pkg_names = ['a'])) + assert False, 'Should have raised' +except AssertionError: + raise +except Exception: + pass + # -- _install_local_files -- # -- With dependency resolution, the files go to the package manager; diff --git a/test/unit/python/jw/pkg/lib/ec/secret_store/KvFile/test.py b/test/unit/python/jw/pkg/lib/ec/secret_store/KvFile/test.py index 7cbaebbc..9da182fe 100644 --- a/test/unit/python/jw/pkg/lib/ec/secret_store/KvFile/test.py +++ b/test/unit/python/jw/pkg/lib/ec/secret_store/KvFile/test.py @@ -15,6 +15,7 @@ from jw.pkg.lib.ec.secret_store.layout import FT_SECRET, FT_SECRET_FILE, FT_SECR from jw.pkg.lib.file_types import FT_DIR from jw.pkg.lib.FileContext import FileContext from jw.pkg.lib.Package import Package +from jw.pkg.lib.pf.PkgSecrets import PkgSecrets async def run_tests() -> None: with tempfile.TemporaryDirectory() as tmp: @@ -212,7 +213,7 @@ async def run_tests() -> None: self.queries = 0 @override - async def _pkg_files(self, names: list[str] | None) -> list[str]: + async def _pkg_paths(self, names: list[str] | None) -> list[str]: self.queries += 1 return self.files @@ -346,49 +347,121 @@ async def run_tests() -> None: assert not os.path.exists(os.path.join(tree, 'etc', 'sub', 'conf.jw-secret')) await sstore.close() - # -- The autodetected distro applies the app's documented - # filter fallback: JW_DEFAULT_PATH_FILTER reaches - # Distro.instantiate() as the default path filter - astore = KvFile('kvfile://', default_path_filter = 'pkg:url=~jw.dev') - assert set(await astore.readdir('')) == {'tmp'} - flt = captured['kwargs'].get('default_path_filter') - assert flt is not None - assert flt.match_pkg(Package('fixture', url = 'https://jw.dev/fixture.rpm')) - assert not flt.match_pkg(Package('other', url = 'https://elsewhere/other.rpm')) - - # -- The backend filter also comes from the store URI's - # query's path-filter parameter; the constructor - # parameter wins - async def __flt_matches(flt: Any) -> None: - assert flt.match_pkg(Package('fixture', url = 'https://jw.dev/fixture.rpm')) - assert not flt.match_pkg( - Package('other', url = 'https://elsewhere/other.rpm') - ) - - # No query, no parameter: no filter - s = KvFile('kvfile://') - await s.readdir('') - assert captured['kwargs'].get('default_path_filter') is None - # The query's path-filter parameter - s = KvFile('kvfile://?path-filter=pkg%3Aurl%3D~jw.dev') - await s.readdir('') - await __flt_matches(captured['kwargs'].get('default_path_filter')) - # An unrelated query parameter is not a filter spec - s = KvFile('kvfile://?foo=bar') - await s.readdir('') - assert captured['kwargs'].get('default_path_filter') is None - # The constructor parameter wins over the query - s = KvFile( - 'kvfile://?path-filter=pkg%3Aurl%3D~jw.dev', - default_path_filter = 'pkg:url=~zzz-nomatch', - ) - await s.readdir('') - flt = captured['kwargs'].get('default_path_filter') - assert flt is not None - assert not flt.match_pkg(Package('fixture', url = 'https://jw.dev/fixture.rpm')) - patcher.stop() + # -- The address space is scoped by a pkg-secrets filter, + # explicit or from the store URI's query: it scopes the + # operations and the enumeration alike, and a foreign + # filter kind is refused + class FilteredFake(SuseDistro): + + def __init__(self, pkgs: list[tuple[str, str, list[str]]]) -> None: + super().__init__(Local(), id = 'suse') + self.pkgs = pkgs + + # -- The package enumeration seam: Distro.paths() goes + # through _select(), which bottoms out here + @override + async def _select_by_name(self, names: Any) -> list[Package]: + ret = [Package(name = n, url = u) for n, u, _ in self.pkgs] + if names: + ret = [p for p in ret if p.name in names] + return ret + + @override + async def _pkg_paths(self, names: list[str] | None) -> list[str]: + ret: list[str] = [] + for n, _, files in self.pkgs: + if names is None or n in names: + ret.extend(files) + return ret + + ffake = FilteredFake( + [ + ( + 'fixture', + 'https://jw.dev/fixture.rpm', + [ + f'{tree}/etc/foo.conf.jw-tmpl', + f'{tree}/etc/cert.pem.jw-tmpl', + f'{tree}/etc/ghost.conf.jw-tmpl', + ], + ), + ( + 'other', + 'https://elsewhere.org/other.rpm', + [f'{tree}/etc/zzz.conf.jw-tmpl'], + ), + ] + ) + captured2: dict[str, Any] = {} + + async def __instantiate2(*args: Any, **kwargs: Any) -> FilteredFake: + captured2['kwargs'] = kwargs + return ffake + + patcher2 = mock.patch.object( + Distro, 'instantiate', new = classmethod(__instantiate2) + ) + patcher2.start() + with open(os.path.join(tree, 'etc', 'zzz.conf.jw-secret'), 'w') as f: + f.write('z=1\n') + + # -- Raw: no filter, every installed template is a config + # path, and the distro derivation carries no filter + rstore = KvFile('kvfile://') + assert rstore.path_filter is None + assert set(await rstore.readdir(f'{base}/etc')) == { + 'cert.pem.jw-secret-file', 'foo.conf.jw-secret', 'zzz.conf.jw-secret' + } + # -- The distro derivation carries no filter of its own + assert captured2['kwargs'].get('default_path_filter') is None + + # -- Scoped: only the matching packages back the address + # space; an unbacked entry is invisible and unwritable + fstore = KvFile('kvfile://', default_path_filter = 'pkg-secrets:url=~jw.dev') + assert isinstance(fstore.path_filter, PkgSecrets) + assert set(await fstore.readdir(f'{base}/etc')) == \ + {'cert.pem.jw-secret-file', 'foo.conf.jw-secret'} + try: + await fstore.get(f'{base}/etc/zzz.conf') + raise AssertionError('expected FileNotFoundError') + except FileNotFoundError: + pass + await fstore.put(f'{base}/etc/zzz.conf', b'z=2\n', ftype = FT_SECRET) + with open(os.path.join(tree, 'etc', 'zzz.conf.jw-secret')) as f: + assert f.read() == 'z=1\n' + # -- A backed address writes through + await fstore.put(f'{base}/etc/foo.conf/k9', b'v9', ftype = FT_SECRET_KEY) + assert (await fstore.get(f'{base}/etc/foo.conf/k9')).stdout == b'v9' + + # -- The query's path-filter parameter + qstore = KvFile('kvfile://?path-filter=pkg-secrets%3Aurl%3D~elsewhere') + assert isinstance(qstore.path_filter, PkgSecrets) + assert set(await qstore.readdir(f'{base}/etc')) == {'zzz.conf.jw-secret'} + + # -- An unrelated query parameter is not a filter spec + s = KvFile('kvfile://?foo=bar') + assert s.path_filter is None + + # -- The query wins over the constructor parameter + wstore = KvFile( + 'kvfile://?path-filter=pkg-secrets%3Aurl%3D~jw.dev', + default_path_filter = 'pkg-secrets:url=~elsewhere', + ) + assert set(await wstore.readdir(f'{base}/etc') + ) == {'cert.pem.jw-secret-file', 'foo.conf.jw-secret'} + + # -- A foreign filter kind is refused at resolution + xstore = KvFile('kvfile://', default_path_filter = 'pkg:url=~jw.dev') + try: + xstore.path_filter + raise AssertionError('expected Exception') + except Exception as e: + assert 'pkg-secrets' in str(e) + + patcher2.stop() + # -- The lifecycle propagates to the host context: an # open() pin on the store keeps the host's transport # open for its duration, and the run()s within it share diff --git a/test/unit/python/jw/pkg/lib/ec/secret_store/Sops/test.py b/test/unit/python/jw/pkg/lib/ec/secret_store/Sops/test.py index a6d163cd..a8f4c8fd 100644 --- a/test/unit/python/jw/pkg/lib/ec/secret_store/Sops/test.py +++ b/test/unit/python/jw/pkg/lib/ec/secret_store/Sops/test.py @@ -336,7 +336,7 @@ async def run_tests() -> None: self.files = files @override - async def _pkg_files(self, names: list[str] | None) -> list[str]: + async def _pkg_paths(self, names: list[str] | None) -> list[str]: return self.files fake = FakeDistro( diff --git a/test/unit/python/jw/pkg/lib/ec/secret_store/TarGpg/test.py b/test/unit/python/jw/pkg/lib/ec/secret_store/TarGpg/test.py index b202b15a..b89de064 100644 --- a/test/unit/python/jw/pkg/lib/ec/secret_store/TarGpg/test.py +++ b/test/unit/python/jw/pkg/lib/ec/secret_store/TarGpg/test.py @@ -321,7 +321,7 @@ async def run_tests() -> None: self.files = files @override - async def _pkg_files(self, names: list[str] | None) -> list[str]: + async def _pkg_paths(self, names: list[str] | None) -> list[str]: return self.files fake = FakeDistro( diff --git a/test/unit/python/jw/pkg/lib/ec/secret_store/Vault/test.py b/test/unit/python/jw/pkg/lib/ec/secret_store/Vault/test.py index ff3892b6..1ae661a6 100644 --- a/test/unit/python/jw/pkg/lib/ec/secret_store/Vault/test.py +++ b/test/unit/python/jw/pkg/lib/ec/secret_store/Vault/test.py @@ -351,7 +351,7 @@ async def run_tests() -> None: self.files = files @override - async def _pkg_files(self, names: list[str] | None) -> list[str]: + async def _pkg_paths(self, names: list[str] | None) -> list[str]: return self.files fake = FakeDistro( diff --git a/test/unit/python/jw/pkg/lib/ec/secret_store/layout/test.py b/test/unit/python/jw/pkg/lib/ec/secret_store/layout/test.py index 17b8d90e..1ca50ad0 100644 --- a/test/unit/python/jw/pkg/lib/ec/secret_store/layout/test.py +++ b/test/unit/python/jw/pkg/lib/ec/secret_store/layout/test.py @@ -5,7 +5,7 @@ from jw.pkg.lib.ec.secret_store.layout import ( FT_SECRET_FILE, FT_SECRET_KEY, SECRET_SUFFIX, - content_name, + target_name, host_prefix, ) from jw.pkg.lib.file_types import FT_COMPOUND, FT_DIR, FT_REG @@ -15,11 +15,11 @@ assert DEFAULT_PREFIX == 'default' assert SECRET_SUFFIX == '.jw-secret' assert BLOB_SUFFIX == '.jw-secret-file' -# content_name strips the content suffix, and names without a +# target_name strips the content suffix, and names without a # content suffix are not store content -assert content_name('etc/a.jw-secret') == 'etc/a' -assert content_name('etc/c.pem.jw-secret-file') == 'etc/c.pem' -assert content_name('etc/README.md') is None +assert target_name('etc/a.jw-secret') == 'etc/a' +assert target_name('etc/c.pem.jw-secret-file') == 'etc/c.pem' +assert target_name('etc/README.md') is None # An FQDN maps to its reversed, dot-split host root assert host_prefix('host.example.com') == 'com/example/host' diff --git a/test/unit/python/jw/pkg/lib/pf/Pkg/test.py b/test/unit/python/jw/pkg/lib/pf/Pkg/test.py index ad10bde0..16656998 100644 --- a/test/unit/python/jw/pkg/lib/pf/Pkg/test.py +++ b/test/unit/python/jw/pkg/lib/pf/Pkg/test.py @@ -6,6 +6,7 @@ from typing import TYPE_CHECKING, Any, override from jw.pkg.lib.FileContext import FileContext from jw.pkg.lib.Package import Package +from jw.pkg.lib.PathFilter import PathFilter from jw.pkg.lib.pf.Pkg import Pkg if TYPE_CHECKING: @@ -65,6 +66,13 @@ for definition in ('', f = Pkg(file_context = fc, spec = 'pkg:url=~example\\.com') assert repr(f) == 'filter:pkg:url=~example\\.com' +# -- PathFilter.create() resolves the name kebab-to-pascal -- + +f3 = PathFilter.create(spec = 'pkg:url=~example\\.com', file_context = fc) +assert isinstance(f3, Pkg) +assert f3.match_pkg(pkg) +assert not f3.match_pkg(pkg_other) + class _FakeDistro: def __init__(self, pkgs: list[tuple[str, str | None, list[str]]]) -> None: @@ -77,13 +85,23 @@ class _FakeDistro: filter: Any = None) -> list[Package]: return [p for p, _ in self.__pkgs if filter is None or filter.match_pkg(p)] - async def pkg_files(self, names: list[str] | None = None) -> list[str]: + async def pkg_paths(self, names: list[str] | None = None) -> list[str]: ret: list[str] = [] for p, files in self.__pkgs: if names is None or p.name in names: ret.extend(files) return ret + async def paths(self, filter: Any = None, pkg_names: Any = []) -> list[str]: + ret: list[str] = [] + for p, files in self.__pkgs: + if filter is not None and not filter.match_pkg(p): + continue + if pkg_names and p.name not in pkg_names: + continue + ret.extend(files) + return ret + fake = _FakeDistro( [ ( diff --git a/test/unit/python/jw/pkg/lib/pf/PkgSecrets/Makefile b/test/unit/python/jw/pkg/lib/pf/PkgSecrets/Makefile new file mode 100644 index 00000000..49c7c21f --- /dev/null +++ b/test/unit/python/jw/pkg/lib/pf/PkgSecrets/Makefile @@ -0,0 +1,7 @@ +TOPDIR = ../../../../../../../../ + +include $(TOPDIR)/make/proj.mk +include $(JWBDIR)/make/py-run.mk + +all: +test: run diff --git a/test/unit/python/jw/pkg/lib/pf/PkgSecrets/test.py b/test/unit/python/jw/pkg/lib/pf/PkgSecrets/test.py new file mode 100644 index 00000000..35d706f7 --- /dev/null +++ b/test/unit/python/jw/pkg/lib/pf/PkgSecrets/test.py @@ -0,0 +1,138 @@ +from __future__ import annotations + +import asyncio + +from typing import TYPE_CHECKING, Any, override + +from jw.pkg.lib.FileContext import FileContext +from jw.pkg.lib.Package import Package +from jw.pkg.lib.PathFilter import PathFilter, Verdict +from jw.pkg.lib.pf.PkgSecrets import PkgSecrets + +if TYPE_CHECKING: + from jw.pkg.lib.Result import Result + +class _StubFC(FileContext): + + def __init__(self) -> None: + super().__init__(uri = 'file:///') + + @override + async def _get( + self, path: str, wd: str | None, throw: bool, verbose: bool | None, title: str + ) -> Result: + raise NotImplementedError() + +# -- Unsupported specs raise at construction -- + +for bad in ['pkg-secrets', 'pkg-secrets:uri', 'pkg-secrets:name=~x']: + try: + PkgSecrets(spec = bad, file_context = _StubFC()) + assert False, f'Should have raised for "{bad}"' + except Exception: + pass + +class _FakeDistro: + + def __init__(self, pkgs: list[tuple[str, str | None, list[str]]]) -> None: + self.__pkgs = [ + (Package(name = name, url = url), files) for name, url, files in pkgs + ] + + async def select(self, + names: list[str] | None = None, + filter: Any = None) -> list[Package]: + return [p for p, _ in self.__pkgs if filter is None or filter.match_pkg(p)] + + async def pkg_paths(self, names: list[str] | None = None) -> list[str]: + ret: list[str] = [] + for p, files in self.__pkgs: + if names is None or p.name in names: + ret.extend(files) + return ret + + async def paths(self, filter: Any = None, pkg_names: Any = []) -> list[str]: + ret: list[str] = [] + for p, files in self.__pkgs: + if filter is not None and not filter.match_pkg(p): + continue + if pkg_names and p.name not in pkg_names: + continue + ret.extend(files) + return ret + +fake = _FakeDistro( + [ + ( + 'fixture', + 'https://example.com/fixture.rpm', + ['/etc/foo.conf.jw-tmpl', '/etc/fixture.conf', '/opt/jw-x/app.ini.jw-tmpl'], + ), + ('other', 'https://elsewhere.org/other.rpm', ['/etc/bar.conf.jw-tmpl']), + ] +) + +async def __run_tests() -> None: + from unittest import mock + + from jw.pkg.lib.Distro import Distro + from jw.pkg.lib.ec.Local import Local + + async def __instantiate(*args: Any, **kwargs: Any) -> _FakeDistro: + return fake + + with mock.patch.object(Distro, 'instantiate', new = classmethod(__instantiate)): + # -- Unscoped: every installed package backs + f = PkgSecrets(spec = 'pkg-secrets:', file_context = Local('local')) + # A compound, a key below it, and a blob are all addressable + assert await f.run('etc/foo.conf.jw-secret') == Verdict.ALLOW + assert await f.run('etc/foo.conf.jw-secret/key') == Verdict.ALLOW + # -- A key below the compound, its name unsuffixed + assert await f.run('etc/foo.conf/key') == Verdict.ALLOW + assert await f.run('opt/jw-x/app.ini/key') == Verdict.ALLOW + assert await f.run('etc/plain/key') == Verdict.IGNORE + assert await f.run('etc/foo.conf.jw-secret-file') == Verdict.ALLOW + # A deep target path + assert await f.run('opt/jw-x/app.ini.jw-secret') == Verdict.ALLOW + # The other package backs too, unscoped + assert await f.run('etc/bar.conf.jw-secret-file') == Verdict.ALLOW + # A plain file is not a target path + assert await f.run('etc/fixture.conf') == Verdict.IGNORE + # No template for this target path: the orphan case + assert await f.run('etc/fixture.conf.jw-secret') == Verdict.IGNORE + assert await f.run('nope.jw-secret') == Verdict.IGNORE + # Directories leading to target paths, and the root + assert await f.run('etc') == Verdict.ALLOW + assert await f.run('opt/jw-x') == Verdict.ALLOW + assert await f.run('') == Verdict.ALLOW + + # -- The backing set, as the filter computes it + assert await f.target_paths() == [ + 'etc/bar.conf', 'etc/foo.conf', 'opt/jw-x/app.ini' + ] + + # -- Scoped: only the matching packages back + f2 = PkgSecrets( + spec = 'pkg-secrets:url=~example\\.com', file_context = Local('local') + ) + assert await f2.run('etc/foo.conf.jw-secret') == Verdict.ALLOW + assert await f2.run('etc/bar.conf.jw-secret') == Verdict.IGNORE + assert await f2.target_paths() == ['etc/foo.conf', 'opt/jw-x/app.ini'] + + # -- PathFilter.create() resolves the kebab name + f3 = PathFilter.create( + spec = 'pkg-secrets:url=~example\\.com', file_context = Local('local') + ) + assert isinstance(f3, PkgSecrets) + + # -- A context that cannot be probed rejects + f4 = PkgSecrets(spec = 'pkg-secrets:', file_context = _StubFC()) + try: + await f4.run('etc/foo.conf.jw-secret') + assert False, 'An unbacked context should reject path queries' + except Exception as e: + assert 'backed by distributions' in str(e) + +asyncio.run(__run_tests()) + +print('All lib.pf.PkgSecrets tests passed') diff --git a/test/unit/python/jw/pkg/lib/util/test.py b/test/unit/python/jw/pkg/lib/util/test.py index 8771a905..aaf65cbc 100644 --- a/test/unit/python/jw/pkg/lib/util/test.py +++ b/test/unit/python/jw/pkg/lib/util/test.py @@ -4,12 +4,19 @@ import stat import tempfile from jw.pkg.lib.ec.Local import Local -from jw.pkg.lib.util import copy +from jw.pkg.lib.util import copy, kebab_to_pascal, pascal_to_kebab def uri(path: str) -> str: return 'local://localhost' + path async def run_tests() -> None: + # -- kebab <-> pascal: the name conversion behind the dynamic + # loading of filters and, later, file contexts + assert kebab_to_pascal('pkg') == 'Pkg' + assert kebab_to_pascal('pkg-secrets') == 'PkgSecrets' + assert pascal_to_kebab('Pkg') == 'pkg' + assert pascal_to_kebab('PkgSecrets') == 'pkg-secrets' + with tempfile.TemporaryDirectory() as tmp: # -- Source tree #