Move from package-based to path-based secret-store filters #181

Merged
Jan Lindemann merged 9 commits from jan/feature/20261118-move-from-package-based-to-path-based-secret-store-filters into master 2026-11-18 19:24:59 +01:00 AGit
25 changed files with 620 additions and 174 deletions

View file

@ -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)))

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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],

View file

@ -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'
)

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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)

View file

@ -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

View file

@ -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

View file

@ -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()

View file

@ -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,

View file

@ -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] = []

View file

@ -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;

View file

@ -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

View file

@ -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(

View file

@ -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(

View file

@ -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(

Some files were not shown because too many files have changed in this diff Show more