From e96bfca0e159bd9de901aa6bc0e8ac32bcf317ce Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Sat, 7 Nov 2026 10:54:15 +0100 Subject: [PATCH] lib.ec.secret_store.KvFile: Construct from a URI KvFile.__init__() accepts a host FileContext plus an optional Distro, and the two may live on different hosts. In effect, files are read from one host based on another host's package set, which may have its use cases but is generally undesirable. The context parameter also breaks the uniformity of the store constructors: Sops, TarGpg, and Vault are constructed from a URI alone, and FileContext.create() needs a special case that builds the kvfile store's inner context before handing it to the constructor. This commit has KvFile constructed from a URI alone like the other stores. The URI's authority names the host, no authority means "local", and the constructor builds the inner context through FileContext.create() with chroot off, forwarding the store's constructor parameters to it. The inner context is always an exec context, which the distro derivation needs: it is lazy, Distro.instantiate() runs on the first file listing, with the JW_DEFAULT_PKG_FILTER environment variable as the default package filter, as before. Adapt all call sites: - FileContext.create(): the kvfile case returns KvFile(uri) directly. - FilesContext: the distro parameter goes; the store URI is derived from the exec context's scheme, authority, and path, so a local context with a hostname in its URI stays local. - DistroContext.install(): the kvfile source wrap goes; the compounds read directly through the source context with parse_kv(). - The store tests monkey-patch Distro.instantiate() for the stores that list something Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.0 Signed-off-by: Jan Lindemann --- .../jw/pkg/cmds/secrets/lib/DistroContext.py | 26 ++++----- .../jw/pkg/cmds/secrets/lib/FilesContext.py | 18 +++--- src/python/jw/pkg/cmds/secrets/lib/util.py | 4 +- src/python/jw/pkg/lib/FileContext.py | 6 +- src/python/jw/pkg/lib/ec/secret_store/Base.py | 2 +- .../jw/pkg/lib/ec/secret_store/KvFile.py | 56 +++++------------- .../jw/pkg/lib/ec/secret_store/KvFile/test.py | 58 ++++++++++--------- .../jw/pkg/lib/ec/secret_store/Sops/test.py | 17 ++++-- .../jw/pkg/lib/ec/secret_store/TarGpg/test.py | 13 ++++- .../jw/pkg/lib/ec/secret_store/Vault/test.py | 11 +++- 10 files changed, 103 insertions(+), 108 deletions(-) diff --git a/src/python/jw/pkg/cmds/secrets/lib/DistroContext.py b/src/python/jw/pkg/cmds/secrets/lib/DistroContext.py index 8b5147f2..8f5b8cf4 100644 --- a/src/python/jw/pkg/cmds/secrets/lib/DistroContext.py +++ b/src/python/jw/pkg/cmds/secrets/lib/DistroContext.py @@ -8,7 +8,6 @@ from pathlib import Path from typing import TYPE_CHECKING from ....lib.ec.secret_store.Base import Base as SecretStore -from ....lib.ec.secret_store.KvFile import KvFile from ....lib.ec.secret_store.layout import ( DEFAULT_PREFIX, FT_SECRET, @@ -17,6 +16,7 @@ from ....lib.ec.secret_store.layout import ( host_prefix, ) from ....lib.FileContext import FileContext +from ....lib.kv import parse_kv from ....lib.log import DEBUG, ERR, NOTICE, WARNING, log from .FilesContext import FilesContext @@ -29,7 +29,7 @@ if TYPE_CHECKING: class DistroContext(FilesContext): def __init__(self, distro: Distro) -> None: - super().__init__(distro.ctx, distro = distro) + super().__init__(distro.ctx) self.__distro = distro async def match_files(self, pkg_names: Collection[str], pattern: str) -> list[str]: @@ -144,13 +144,10 @@ class DistroContext(FilesContext): f'src {src_uri} must name the whole store, not a ' f'rooted subtree' ) - src: FileContext = fc # -- Store candidates: the host tree, then the default # tree prefixes: tuple[str, ...] = (host_prefix(hostname), DEFAULT_PREFIX) else: - # -- A file tree in the on-host layout: wrap it in the kvfile store - src = KvFile(fc, distro = self.__distro) prefixes = ('', ) # -- The store and the kvfile source are alike addressed @@ -161,23 +158,26 @@ class DistroContext(FilesContext): # -- A present entry, even an empty one, wins over the # fallback entry_rel = f'{entry.lstrip("/")}{suffix}' - addr = entry_rel - keys: list[str] | None = None + pairs: list[tuple[str, bytes]] | None = None for pfx in prefixes: addr = f'{pfx}/{entry_rel}' if pfx else entry_rel try: - keys = list(await src.readdir(addr)) + if isinstance(fc, SecretStore): + keys = list(await fc.readdir(addr)) + pairs = [ + (key, (await fc.get(f'{addr}/{key}')).stdout) + for key in keys + ] + else: + kv = parse_kv((await fc.get(f'/{addr}')).stdout) + pairs = [(key, val.encode()) for key, val in kv.items()] break except FileNotFoundError: continue - if keys is None: + if pairs is None: log(NOTICE, f'not extracted: {entry}') continue log(NOTICE, f'extracted: {entry}') - pairs: list[tuple[str, bytes]] = [] - for key in keys: - val = await src.get(f'{addr}/{key}') - pairs.append((key, val.stdout)) dst = self.store with suppress(FileNotFoundError): await dst.unlink(entry_rel) diff --git a/src/python/jw/pkg/cmds/secrets/lib/FilesContext.py b/src/python/jw/pkg/cmds/secrets/lib/FilesContext.py index 0be62b5d..0f778df3 100644 --- a/src/python/jw/pkg/cmds/secrets/lib/FilesContext.py +++ b/src/python/jw/pkg/cmds/secrets/lib/FilesContext.py @@ -10,8 +10,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Iterable - from ....lib.Distro import Distro - from ....lib.FileContext import FileContext + from ....lib.ExecContext import ExecContext from ....lib.ec.secret_store.Base import Base from ....lib.ec.secret_store.KvFile import KvFile @@ -21,19 +20,18 @@ from .base import Attrs class FilesContext: - def __init__( - self, - ctx: FileContext, - store: Base | None = None, - distro: Distro | None = None, - ) -> None: + def __init__(self, ctx: ExecContext, store: Base | None = None) -> None: self.__ctx = ctx if store is None: - store = KvFile(ctx, distro = distro) + if ctx.uri.scheme in ('local', 'file'): + authority = '' + else: + authority = ctx.uri.authority + store = KvFile(f'kvfile://{authority}{ctx.uri.path}') self.__store = store @property - def ctx(self) -> FileContext: + def ctx(self) -> ExecContext: return self.__ctx @property diff --git a/src/python/jw/pkg/cmds/secrets/lib/util.py b/src/python/jw/pkg/cmds/secrets/lib/util.py index fcc32244..c9a1f27a 100644 --- a/src/python/jw/pkg/cmds/secrets/lib/util.py +++ b/src/python/jw/pkg/cmds/secrets/lib/util.py @@ -6,13 +6,13 @@ from ....lib.ec.Local import Local from .FilesContext import FilesContext if TYPE_CHECKING: - from ....lib.FileContext import FileContext + from ....lib.ExecContext import ExecContext from .base import Attrs async def compile_template_file( target_path: str, default_attrs: Attrs | None = None, - ctx: FileContext | None = None + ctx: ExecContext | None = None ) -> bool: if ctx is None: ctx = Local() diff --git a/src/python/jw/pkg/lib/FileContext.py b/src/python/jw/pkg/lib/FileContext.py index 3612ea75..6228fe98 100644 --- a/src/python/jw/pkg/lib/FileContext.py +++ b/src/python/jw/pkg/lib/FileContext.py @@ -371,11 +371,7 @@ class FileContext(abc.ABC): case 'kvfile': from .ec.secret_store.KvFile import KvFile - scheme = 'ssh' if uri.hostname else 'local' - inner = FileContext.create( - f'{scheme}://{uri.authority}', chroot = False - ) - return KvFile(inner, uri = uri) + return KvFile(uri, *args, **kwargs) case 'vault': from .ec.secret_store.Vault import Vault 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 83297ae7..967c1da3 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/Base.py +++ b/src/python/jw/pkg/lib/ec/secret_store/Base.py @@ -49,7 +49,7 @@ class Base(FileContext): The URI-addressable stores are created by FileContext.create() from their scheme. The kvfile store is the store of the on-host layout: its addresses are config paths of the host it is rooted - at, and it may be constructed directly over a host context. + at, and it is constructed from a URI naming that host. """ def __init__(self, uri: str | Uri, *args: Any, **kwargs: Any) -> None: diff --git a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py index 45d2091a..fb7d954c 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py +++ b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py @@ -3,17 +3,18 @@ from __future__ import annotations import errno import os -from typing import TYPE_CHECKING, Iterable, override +from typing import TYPE_CHECKING, Any, Iterable, cast, override if TYPE_CHECKING: from ...Distro import Distro - from ...FileContext import FileContext + from ...ExecContext import ExecContext from ...Uri import Uri from ...base import StatResult from ...file_types import FileType from ...FcCache import FcCache from ...file_types import FT_COMPOUND, FT_DIR +from ...FileContext import FileContext from ...kv import parse_kv, serialize_kv from ...Result import Result from .Base import Base @@ -22,17 +23,17 @@ 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, - ctx: FileContext, - uri: str | Uri | None = None, - distro: Distro | None = None, - ) -> None: - if uri is None: - uri = f'kvfile://{ctx.uri.hostname or "target"}' - super().__init__(uri = uri) - self.__inner = ctx - self.__distro: Distro | None = distro + def __init__(self, uri: str | Uri, *args: Any, **kwargs: Any) -> None: + super().__init__(uri, *args, **kwargs) + kwargs.pop('chroot', None) + scheme = 'ssh' if self.uri.hostname else 'local' + self.__inner: ExecContext = cast( + 'ExecContext', + FileContext.create( + f'{scheme}://{self.uri.authority}', chroot = False, **kwargs + ), + ) + self.__distro: Distro | None = None self.___config_paths: list[str] | None = None self.__root = self.uri.path.lstrip('/') self.__ctx = FcCache(self.__inner) @@ -65,13 +66,6 @@ class KvFile(Base): if self.___config_paths is None: if self.__distro is None: from ...Distro import Distro - from ...ExecContext import ExecContext - - if not isinstance(self.__inner, ExecContext): - raise ValueError( - 'KvFile: a distro must be given when the host' - ' context is not an exec context' - ) from ...PackageFilter import PackageFilterString pkg_filter_str = os.environ.get('JW_DEFAULT_PKG_FILTER') @@ -87,12 +81,6 @@ class KvFile(Base): continue ret.add(f.lstrip('/')[:-len('.jw-tmpl')]) self.___config_paths = sorted(ret) - # -- Warm the stat cache with one host command, so the - # per-level presence checks and the walk's node stats - # hit memory: the root, the candidate files of both - # kinds, the directories they live in, and the file - # names a suffixed path would probe those - # directories by warm = ['/'] warm += [f'/{p}{SECRET_SUFFIX}' for p in self.___config_paths] warm += [f'/{p}{BLOB_SUFFIX}' for p in self.___config_paths] @@ -115,8 +103,6 @@ class KvFile(Base): return parse_kv(ret.stdout) async def __is_compound(self, config_path: str) -> bool: - # -- The compound file on the host; KvFile has no default tree. - # The path is host-relative, as from __host_path() if not config_path: return False return await self.__ctx.file_exists(f'/{config_path}{SECRET_SUFFIX}') @@ -151,8 +137,6 @@ class KvFile(Base): parent, _ = self.__strip_suffix(parent) if await self.__is_compound(parent) and \ key in await self.__compound_kv(parent): - # -- The type is synthesized, the mode the one of - # the compound file st = await self.__ctx.stat(f'/{parent}{SECRET_SUFFIX}', follow_symlinks) return self._stat_result( st.owner, @@ -201,23 +185,15 @@ class KvFile(Base): rest = cfg[len(prefix):] label, sep, _ = rest.partition('/') if sep: - # -- A deeper candidate lists its branch label, if a - # secret is present below it: the label names a - # directory on the host, which a present secret - # below implies if await self.__ctx.file_exists(f'/{cfg}{SECRET_SUFFIX}') or \ await self.__ctx.file_exists(f'/{cfg}{BLOB_SUFFIX}'): children.add(label) continue - # -- A direct child lists under the on-host file name of - # the file that backs it, compound and blob alike if await self.__ctx.file_exists(f'/{cfg}{SECRET_SUFFIX}'): 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: - # -- A branch the host lacks is absent; a real directory - # with no secret children lists empty if not await self.__ctx.is_dir(f'/{config_path}'): raise FileNotFoundError(path) return children @@ -255,7 +231,6 @@ class KvFile(Base): config_path, _ = self.__strip_suffix(path) host_path = f'/{config_path}' if ftype.is_subtype(FT_COMPOUND): - # -- A compound: materialize the empty compound file if await self.__ctx.file_exists(host_path + SECRET_SUFFIX): return if not await self.__ctx.is_dir(os.path.dirname(host_path)): @@ -266,7 +241,6 @@ class KvFile(Base): host_path + SECRET_SUFFIX, b'', mode = 0o400, atomic = True ) elif ftype.is_subtype(FT_DIR): - # -- A branch: a real directory if await self.__ctx.is_dir(host_path): return if not await self.__ctx.is_dir(os.path.dirname(host_path)): @@ -309,8 +283,6 @@ class KvFile(Base): atomic = True, ) if ftype.is_subtype(FT_SECRET_FILE): - # -- A blob: the content is the file itself, at its - # on-host file name m = 0o400 if mode is None else int(mode, 8) return await self.__ctx.put( f'/{config_path}{BLOB_SUFFIX}', 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 8e084cd2..6313f998 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 @@ -5,7 +5,9 @@ import stat import tempfile from typing import Any, override +from unittest import mock +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.ec.secret_store.KvFile import KvFile @@ -30,7 +32,7 @@ async def run_tests() -> None: assert isinstance(created, KvFile) assert created.uri.scheme == 'kvfile' - store = KvFile(Local()) + store = KvFile('kvfile://') assert set(await store.readdir(target)) == {'key1', 'key2', 'key3'} assert (await store.get(f'{target}/key1')).stdout == b'value1' assert (await store.get(f'{target}/key3')).stdout == b'' @@ -224,8 +226,22 @@ async def run_tests() -> None: ) # -- The address space is rooted at the host root; the # package file list reports host-absolute paths, so the - # fixture tree sits at its path below the root - bstore = KvFile(Local(), distro = fake) + # fixture tree sits at its path below the root. The + # store derives its distro from the host context, so the + # derivation is patched to the fake for the sections + # below + captured: dict[str, Any] = {} + + async def __instantiate(*args: Any, **kwargs: Any) -> FakeDistro: + captured['kwargs'] = kwargs + return fake + + patcher = mock.patch.object( + Distro, 'instantiate', new = classmethod(__instantiate) + ) + patcher.start() + + bstore = KvFile('kvfile://') base = tree.lstrip('/') # -- is_dir answers from the host state, without consulting # the package set @@ -281,7 +297,7 @@ async def run_tests() -> None: # without a double path created = FileContext.create(f'kvfile://{tree}/etc') assert created.uri.path == f'{tree}/etc' - sstore = KvFile(Local(), uri = f'kvfile://{tree}/etc', distro = fake) + sstore = KvFile(f'kvfile://{tree}/etc') await sstore.open() assert set(await sstore.readdir('')) == \ {'cert.pem.jw-secret-file', 'foo.conf.jw-secret'} @@ -322,32 +338,19 @@ async def run_tests() -> None: # -- The autodetected distro applies the app's documented # filter fallback: JW_DEFAULT_PKG_FILTER reaches # Distro.instantiate() as the default package filter - from unittest import mock - - from jw.pkg.lib.Distro import Distro - - captured: dict[str, Any] = {} - - async def __instantiate(*args: Any, **kwargs: Any) -> FakeDistro: - captured['kwargs'] = kwargs - return fake - os.environ['JW_DEFAULT_PKG_FILTER'] = 'url=~jw.dev' try: - with mock.patch.object(Distro, - 'instantiate', - new = classmethod(__instantiate)): - astore = KvFile(Local()) - 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') - ) + 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'] + patcher.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 @@ -370,7 +373,10 @@ async def run_tests() -> None: await super()._close() cl = CountingLocal() - pstore = KvFile(cl) + with mock.patch.object(FileContext, + 'create', + new = classmethod(lambda *a, **k: cl)): + pstore = KvFile('kvfile://') await pstore.open() assert cl.opens == 1 await cl.run(['true']) 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 38968f97..d1a3a188 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 @@ -6,8 +6,10 @@ import subprocess import tempfile from glob import glob -from typing import override +from typing import Any, override +from unittest import mock +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.ec.secret_store.KvFile import KvFile @@ -343,11 +345,18 @@ async def run_tests() -> None: f'{host_tree}/etc/cert.pem.jw-tmpl', ] ) + # -- The package file list reports host-absolute paths, so - # the fixture tree sits at its path below the host root - src = KvFile(Local(), distro = fake) + # the fixture tree sits at its path below the host root. + # The store derives its distro from the host context, so + # the derivation is patched to the fake for the copy + async def __instantiate(*args: Any, **kwargs: Any) -> FakeDistro: + return fake + + src = KvFile('kvfile://') base = host_tree.lstrip('/') - ret = await copy(src, 'sops://fetch.example.com', recursive = True) + with mock.patch.object(Distro, 'instantiate', new = classmethod(__instantiate)): + ret = await copy(src, 'sops://fetch.example.com', recursive = True) assert isinstance(ret, list) # -- The copy transports the on-host file names unchanged assert set(ret) == { 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 a475cb89..b202b15a 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 @@ -7,8 +7,10 @@ import subprocess import tarfile import tempfile -from typing import override +from typing import Any, override +from unittest import mock +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.ec.secret_store.KvFile import KvFile @@ -328,9 +330,14 @@ async def run_tests() -> None: f'{host3}/etc/cert.pem.jw-tmpl', ] ) - src = KvFile(Local(), distro = fake) + + async def __instantiate(*args: Any, **kwargs: Any) -> FakeDistro: + return fake + + src = KvFile('kvfile://') base = host3.lstrip('/') - ret = await copy(src, 'targpg://host3.example.com', recursive = True) + with mock.patch.object(Distro, 'instantiate', new = classmethod(__instantiate)): + ret = await copy(src, 'targpg://host3.example.com', recursive = True) assert isinstance(ret, list) # -- The copy transports the on-host file names unchanged assert set(ret) == { 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 77b842be..ff3892b6 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 @@ -9,7 +9,9 @@ import uuid from pathlib import Path from typing import Any, override +from unittest import mock +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.ec.secret_store.KvFile import KvFile @@ -358,9 +360,14 @@ async def run_tests() -> None: f'{host_tree}/etc/cert.pem.jw-tmpl', ] ) - src = KvFile(Local(), distro = fake) + + async def __instantiate(*args: Any, **kwargs: Any) -> FakeDistro: + return fake + + src = KvFile('kvfile://') base = host_tree.lstrip('/') - ret = await copy(src, f'vault://{fetch_host}', recursive = True) + with mock.patch.object(Distro, 'instantiate', new = classmethod(__instantiate)): + ret = await copy(src, f'vault://{fetch_host}', recursive = True) assert isinstance(ret, list) # -- The copy transports the on-host file names unchanged assert set(ret) == {