From ca56f38daa8a6252fba6fca24e5f7822a7c77fc1 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Thu, 5 Nov 2026 19:05:31 +0100 Subject: [PATCH 1/4] lib.ec.secret_store.KvFile: Remove comments KvFile works but is up for a major refactoring: It features an unnecessary amount of special cases, and its private method names are not self-explanatory enough. First thing to remove are the code comments, because they would account for much churn and would be obsolete afterwards anyway. This commit does it now in the expectation that the move from package- to path-based filters will also touch KvFile. Signed-off-by: Jan Lindemann --- .../jw/pkg/lib/ec/secret_store/KvFile.py | 99 +------------------ 1 file changed, 1 insertion(+), 98 deletions(-) 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 2edea5d3..d4a747e4 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py +++ b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py @@ -20,44 +20,7 @@ from .Base import Base from .layout import BLOB_SUFFIX, FT_SECRET, FT_SECRET_FILE, FT_SECRET_KEY, SECRET_SUFFIX class KvFile(Base): - """The on-host store of a host's package secrets. - - A config path X is either an entry, the file X.jw-secret with - KEY=VALUE lines, whose children in the address space are its - keys, or a blob, the file X.jw-secret-file, whose content is the - file itself, a leaf. Any other path is a branch: a real - directory on the host, with no file of its own. - - Rooted at the host: addresses are config paths relative to the - host root, absolute on the host with the leading slash. A URI - may root the store at a subtree of the host tree; its path is - composed into every address, and the URI is the store's - identity. A suffixed address names the on-host file of its - config path, the suffix picking the kind: .jw-secret the - entry, .jw-secret-file the blob. - - get reads a key below an entry or the blob at its config path; - put writes a key into its entry file, or a blob as a - .jw-secret-file at its config path, and accepts entry, key, and - blob content only; unlink drops the file the address names. No - default fallback. - - An entry lists its keys. A branch lists the config paths below - it, the root included: the host's package set is the bounded - base, the .jw-tmpl files of the installed packages, presence- - checked on the host. The distro is autodetected from the host - on first use, or given in the constructor; the autodetected - distro applies the JW_DEFAULT_PKG_FILTER package filter, if - set, so a URI-built context honors the app's documented - filter fallback. is_dir() answers from the entry file and the - host tree, so the write path never pays for the enumeration. - - The on-host tree is a precondition: mkdir materializes a missing - entry file below an existing directory, and mkdir and put fail - with EROFS below a missing one. KvFile never creates - directories. Entry and blob files are mode 0400; - owner and group follow the put request, if given. - """ + """The on-host store of a host's package secrets. """ def __init__( self, @@ -65,10 +28,6 @@ class KvFile(Base): uri: str | Uri | None = None, distro: Distro | None = None, ) -> None: - # -- The URI roots the namespace at the host tree's root, or - # at a subtree of it: its path is composed into every - # address, and it is the store's identity. A direct - # construction names the context's host if uri is None: uri = f'kvfile://{ctx.uri.hostname or "target"}' super().__init__(uri = uri) @@ -76,17 +35,10 @@ class KvFile(Base): self.__distro: Distro | None = distro self.___config_paths: list[str] | None = None self.__subtree = self.uri.path.lstrip('/') - # -- The context is read through a cache: the read path - # probes the same handful of paths again and again, and - # the cache pays the transport once per path self.__ctx = FcCache(ctx) @override async def _open(self) -> None: - # -- The lifecycle propagates to the host context: an - # open() pin on the store, the CopyContext of a copy - # walk, keeps the host's transport open for its - # duration, and the run()s within it share it await self.__raw.open() @override @@ -94,8 +46,6 @@ class KvFile(Base): await self.__raw.close() def __addr(self, path: str) -> str: - # -- The host-relative address: the subtree the URI roots - # the store at, then the address relative to it path = self._unchroot(path) if not path: return self.__subtree @@ -105,10 +55,6 @@ class KvFile(Base): @staticmethod def __resolve(path: str) -> tuple[str, bool]: - # -- The config path of the address, and whether the address - # names a blob file: a suffixed address is the on-host - # file name of its config path, the suffix picking the - # kind if path.endswith(SECRET_SUFFIX): return path[:-len(SECRET_SUFFIX)], False if path.endswith(BLOB_SUFFIX): @@ -116,27 +62,16 @@ class KvFile(Base): return path, False async def __config_paths(self) -> list[str]: - # -- The config paths of the host's package secrets: the - # templates of the installed packages, relative to the - # host root. The package database is the bounded base, a - # filesystem scan is not. Computed once: the package set - # is stable for the lifetime of the session if self.___config_paths is None: if self.__distro is None: from ...Distro import Distro from ...ExecContext import ExecContext - # -- The distro probes the host through the raw - # context: the cache is a plain file context, no - # exec of its own if not isinstance(self.__raw, ExecContext): raise ValueError( 'KvFile: a distro must be given when the host' ' context is not an exec context' ) - # -- A URI-built context has no app distro to - # inherit the package filter from: apply the - # app's documented fallback from ...PackageFilter import PackageFilterString pkg_filter_str = os.environ.get('JW_DEFAULT_PKG_FILTER') @@ -146,7 +81,6 @@ class KvFile(Base): PackageFilterString(pkg_filter_str) if pkg_filter_str else None ), ) - # -- The packages' file paths, filtered to the templates ret: set[str] = set() for f in await self.__distro.pkg_files(): if not f.endswith('.jw-tmpl'): @@ -189,11 +123,6 @@ class KvFile(Base): @override async def _stat(self, path: str, follow_symlinks: bool) -> StatResult: - # -- The metadata of the host file behind the node, the type - # overridden: an entry is a file that enumerates its - # keys, a key a leaf below it; a branch is a plain - # directory. A key has no file of its own, so it keeps - # the size 0 path = self.__addr(path) config, is_blob = self.__resolve(path) @@ -240,12 +169,6 @@ class KvFile(Base): @override async def _is_dir(self, path: str, follow_symlinks: bool) -> bool: - # -- An entry is a directory of its keys, a key below an - # entry is a leaf: the entry is a file on the host, so - # there is no host path below it to stat. A branch is a - # real directory on the host. The package set is not - # consulted: the write path never pays for the - # enumeration path = self.__addr(path) config, is_blob = self.__resolve(path) if not config: @@ -263,10 +186,6 @@ class KvFile(Base): @override async def _readdir(self, path: str) -> Iterable[str]: - # -- An entry lists its keys; a branch, the root included, - # lists the config paths below it, presence-checked on - # the host, under the on-host file name of the file that - # backs it path = self.__addr(path) config, is_blob = self.__resolve(path) if config and await self.__is_entry(config): @@ -315,7 +234,6 @@ class KvFile(Base): return await self.__ctx.get(real) real = f'/{config}' if await self.__ctx.file_exists(real + SECRET_SUFFIX): - # -- The entry file is the serialized entry return await self.__ctx.get(real + SECRET_SUFFIX) if await self.__ctx.file_exists(real + BLOB_SUFFIX): return await self.__ctx.get(real + BLOB_SUFFIX) @@ -331,11 +249,6 @@ class KvFile(Base): @override async def _mkdir(self, path: str, mode: int, ftype: FileType) -> None: - # -- The address space has no directories of its own: a node - # is a branch (a real directory) or an entry (a suffixed - # file); the type says which to build. Below a missing - # branch, mkdir fails with EROFS: the caller creates the - # levels path = self.__addr(path) config, _ = self.__resolve(path) real = f'/{config}' @@ -378,9 +291,6 @@ class KvFile(Base): path = self.__addr(path) config, is_blob = self.__resolve(path) if ftype.is_subtype(FT_SECRET): - # -- The whole entry: the content is the serialized - # entry, written over the entry file; the branch is - # a precondition, as for a blob if is_blob: raise ValueError( f'put: "{path}" names a blob file, but the ftype is an entry' @@ -412,10 +322,6 @@ class KvFile(Base): entry, _ = self.__resolve(entry) real_entry = f'/{entry}' if ftype.is_subtype(FT_SECRET_KEY): - # -- A key: merge into the entry file, which must exist; - # mkdir() is the materialization. The put is atomic, - # so it also overwrites an existing entry file, which - # is mode 0400 if not await self.__ctx.file_exists(f'{real_entry}{SECRET_SUFFIX}'): raise OSError(errno.EROFS, f'put: "{entry}" has no entry file') kv = await self.__entry_kv(entry) @@ -433,7 +339,4 @@ class KvFile(Base): @override async def _unlink(self, path: str) -> None: - # -- Unlink the file the address names: the address is the - # on-host file name below the subtree, so the host path - # is the composed address itself await self.__ctx.unlink(f'/{self.__addr(path)}') -- 2.56.1 From 1c27a40d4873273d2d1d7a525aff51f207d8b92a Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Sat, 7 Nov 2026 10:53:15 +0100 Subject: [PATCH 2/4] lib.ec.secret_store.KvFile: Rename private symbols KvFile contains symbol names "addr" or "entry" which look better defined than they are. I prefer sticking to well-defined names like "path". "path" in itself is ambiguous and makes it necessary to understand its context, but so be it: At least it's used uniformly throughout the codebase and makes it even more obvious that the function it's used in needs to bear a meaningful name. Which is what this commit does, along with renaming some member variables to more self-explanatory variants. In detail, __addr() composes a host path from the URI path and the store's relpath, __resolve() strips the store's suffixes, __entry_kv() and __is_entry() operate on a config path that has a .jw-secret file, __subtree holds the path component of the URI, and __raw holds the context under the FcCache. The local variables config, entry, real, and blob do not name the things they hold either. - The __addr() method becomes __host_path(), its parameter is named relpath. - The __resolve() method becomes __strip_suffix(). - The __entry_kv() and __is_entry() methods become __compound_kv() and __is_compound(), their parameters are named config_path. - The __subtree and __raw members become __root and __inner. - The locals config, entry, real, and blob become config_path, compound, host_path, and secret_path. Update the error messages and the comments that name the old symbols to use the new ones. Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.0 Signed-off-by: Jan Lindemann --- .../jw/pkg/lib/ec/secret_store/KvFile.py | 202 +++++++++--------- 1 file changed, 103 insertions(+), 99 deletions(-) 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 d4a747e4..45d2091a 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py +++ b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py @@ -31,30 +31,30 @@ class KvFile(Base): if uri is None: uri = f'kvfile://{ctx.uri.hostname or "target"}' super().__init__(uri = uri) - self.__raw = ctx + self.__inner = ctx self.__distro: Distro | None = distro self.___config_paths: list[str] | None = None - self.__subtree = self.uri.path.lstrip('/') - self.__ctx = FcCache(ctx) + self.__root = self.uri.path.lstrip('/') + self.__ctx = FcCache(self.__inner) @override async def _open(self) -> None: - await self.__raw.open() + await self.__inner.open() @override async def _close(self) -> None: - await self.__raw.close() + await self.__inner.close() - def __addr(self, path: str) -> str: - path = self._unchroot(path) - if not path: - return self.__subtree - if not self.__subtree: - return path - return f'{self.__subtree}/{path}' + def __host_path(self, relpath: str) -> str: + relpath = self._unchroot(relpath) + if not relpath: + return self.__root + if not self.__root: + return relpath + return f'{self.__root}/{relpath}' @staticmethod - def __resolve(path: str) -> tuple[str, bool]: + def __strip_suffix(path: str) -> tuple[str, bool]: if path.endswith(SECRET_SUFFIX): return path[:-len(SECRET_SUFFIX)], False if path.endswith(BLOB_SUFFIX): @@ -67,7 +67,7 @@ class KvFile(Base): from ...Distro import Distro from ...ExecContext import ExecContext - if not isinstance(self.__raw, ExecContext): + if not isinstance(self.__inner, ExecContext): raise ValueError( 'KvFile: a distro must be given when the host' ' context is not an exec context' @@ -76,7 +76,7 @@ class KvFile(Base): pkg_filter_str = os.environ.get('JW_DEFAULT_PKG_FILTER') self.__distro = await Distro.instantiate( - ec = self.__raw, + ec = self.__inner, default_pkg_filter = ( PackageFilterString(pkg_filter_str) if pkg_filter_str else None ), @@ -91,7 +91,7 @@ class KvFile(Base): # 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 address would probe those + # names a suffixed path would probe those # directories by warm = ['/'] warm += [f'/{p}{SECRET_SUFFIX}' for p in self.___config_paths] @@ -107,27 +107,27 @@ class KvFile(Base): assert self.___config_paths is not None return self.___config_paths - async def __entry_kv(self, entry: str) -> dict[str, str]: - path = f'/{entry.lstrip("/")}{SECRET_SUFFIX}' + async def __compound_kv(self, config_path: str) -> dict[str, str]: + path = f'/{config_path.lstrip("/")}{SECRET_SUFFIX}' if not await self.__ctx.file_exists(path): - raise FileNotFoundError(entry) + raise FileNotFoundError(config_path) ret = await self.__ctx.get(path) return parse_kv(ret.stdout) - async def __is_entry(self, path: str) -> bool: - # -- The entry file on the host; KvFile has no default tree. - # The path is host-relative, as from __addr() - if not path: + 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'/{path}{SECRET_SUFFIX}') + return await self.__ctx.file_exists(f'/{config_path}{SECRET_SUFFIX}') @override async def _stat(self, path: str, follow_symlinks: bool) -> StatResult: - path = self.__addr(path) - config, is_blob = self.__resolve(path) + path = self.__host_path(path) + config_path, is_blob = self.__strip_suffix(path) - async def __stat_of(real: str, ftype: FileType) -> StatResult: - st = await self.__ctx.stat(real, follow_symlinks) + async def __stat_of(host_path: str, ftype: FileType) -> StatResult: + st = await self.__ctx.stat(host_path, follow_symlinks) return self._stat_result( st.owner, st.group, @@ -137,21 +137,22 @@ class KvFile(Base): size = st.size, ) - if not config: + if not config_path: return await __stat_of('/', FT_DIR) if is_blob: - real = f'/{config}{BLOB_SUFFIX}' - if not await self.__ctx.file_exists(real): + secret_path = f'/{config_path}{BLOB_SUFFIX}' + if not await self.__ctx.file_exists(secret_path): raise FileNotFoundError(errno.ENOENT, f'stat: {path}') - return await __stat_of(real, FT_SECRET_FILE) - if await self.__is_entry(config): - return await __stat_of(f'/{config}{SECRET_SUFFIX}', FT_SECRET) - parent, sep, key = config.rpartition('/') + 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 sep and key: - parent, _ = self.__resolve(parent) - if await self.__is_entry(parent) and key in await self.__entry_kv(parent): + 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 entry file + # the compound file st = await self.__ctx.stat(f'/{parent}{SECRET_SUFFIX}', follow_symlinks) return self._stat_result( st.owner, @@ -160,40 +161,40 @@ class KvFile(Base): FT_SECRET_KEY, mode = st.mode, ) - blob = f'/{config}{BLOB_SUFFIX}' - if await self.__ctx.file_exists(blob): - return await __stat_of(blob, FT_SECRET_FILE) - if await self.__ctx.is_dir(f'/{config}'): - return await __stat_of(f'/{config}', FT_DIR) + secret_path = f'/{config_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) raise FileNotFoundError(errno.ENOENT, f'stat: {path}') @override async def _is_dir(self, path: str, follow_symlinks: bool) -> bool: - path = self.__addr(path) - config, is_blob = self.__resolve(path) - if not config: + path = self.__host_path(path) + config_path, is_blob = self.__strip_suffix(path) + if not config_path: return True - parent, sep, _ = config.rpartition('/') + parent, sep, _ = config_path.rpartition('/') if sep: - parent, _ = self.__resolve(parent) - if await self.__is_entry(parent): + parent, _ = self.__strip_suffix(parent) + if await self.__is_compound(parent): return False - if await self.__is_entry(config): + if await self.__is_compound(config_path): return True if is_blob: return False - return await self.__ctx.is_dir(f'/{config}') + return await self.__ctx.is_dir(f'/{config_path}') @override async def _readdir(self, path: str) -> Iterable[str]: - path = self.__addr(path) - config, is_blob = self.__resolve(path) - if config and await self.__is_entry(config): - return (await self.__entry_kv(config)).keys() - if is_blob and await self.__ctx.file_exists(f'/{config}{BLOB_SUFFIX}'): + 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}'): raise NotADirectoryError(path) children: set[str] = set() - prefix = f'{config}/' if config else '' + prefix = f'{config_path}/' if config_path else '' for cfg in await self.__config_paths(): if not cfg.startswith(prefix): continue @@ -209,15 +210,15 @@ class KvFile(Base): children.add(label) continue # -- A direct child lists under the on-host file name of - # the file that backs it, entry and blob alike + # 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 and not children: + 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}'): + if not await self.__ctx.is_dir(f'/{config_path}'): raise FileNotFoundError(path) return children @@ -225,23 +226,24 @@ class KvFile(Base): async def _get( self, path: str, wd: str | None, throw: bool, verbose: bool | None, title: str ) -> Result: - path = self.__addr(path) - config, is_blob = self.__resolve(path) + path = self.__host_path(path) + config_path, is_blob = self.__strip_suffix(path) if is_blob: - real = f'/{config}{BLOB_SUFFIX}' - if not await self.__ctx.file_exists(real): + secret_path = f'/{config_path}{BLOB_SUFFIX}' + if not await self.__ctx.file_exists(secret_path): raise FileNotFoundError(path) - return await self.__ctx.get(real) - real = f'/{config}' - if await self.__ctx.file_exists(real + SECRET_SUFFIX): - return await self.__ctx.get(real + SECRET_SUFFIX) - if await self.__ctx.file_exists(real + BLOB_SUFFIX): - return await self.__ctx.get(real + BLOB_SUFFIX) - if '/' not in config: + return await self.__ctx.get(secret_path) + secret_path = f'/{config_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}' + if await self.__ctx.file_exists(secret_path): + return await self.__ctx.get(secret_path) + if '/' not in config_path: raise FileNotFoundError(path) - entry, key = config.rsplit('/', 1) - entry, _ = self.__resolve(entry) - kv = await self.__entry_kv(entry) + compound, key = config_path.rsplit('/', 1) + compound, _ = self.__strip_suffix(compound) + kv = await self.__compound_kv(compound) try: return Result(stdout = kv[key].encode()) except KeyError: @@ -249,27 +251,29 @@ class KvFile(Base): @override async def _mkdir(self, path: str, mode: int, ftype: FileType) -> None: - path = self.__addr(path) - config, _ = self.__resolve(path) - real = f'/{config}' + path = self.__host_path(path) + config_path, _ = self.__strip_suffix(path) + host_path = f'/{config_path}' if ftype.is_subtype(FT_COMPOUND): - # -- An entry: materialize the empty entry file - if await self.__ctx.file_exists(real + SECRET_SUFFIX): + # -- 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(real)): + if not await self.__ctx.is_dir(os.path.dirname(host_path)): raise OSError( errno.EROFS, f'mkdir: "{path}" is below a missing directory' ) - await self.__ctx.put(real + SECRET_SUFFIX, b'', mode = 0o400, atomic = True) + await self.__ctx.put( + 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(real): + if await self.__ctx.is_dir(host_path): return - if not await self.__ctx.is_dir(os.path.dirname(real)): + if not await self.__ctx.is_dir(os.path.dirname(host_path)): raise OSError( errno.EROFS, f'mkdir: "{path}" is below a missing directory' ) - await self.__ctx.mkdir(real, mode) + await self.__ctx.mkdir(host_path, mode) else: raise ValueError(f'mkdir: "{path}" is not a directory type') @@ -288,16 +292,16 @@ class KvFile(Base): atomic: bool, ftype: FileType, ) -> Result: - path = self.__addr(path) - config, is_blob = self.__resolve(path) + path = self.__host_path(path) + config_path, is_blob = self.__strip_suffix(path) if ftype.is_subtype(FT_SECRET): if is_blob: raise ValueError( - f'put: "{path}" names a blob file, but the ftype is an entry' + f'put: "{path}" names a blob file, but the ftype is a compound' ) m = 0o400 if mode is None else int(mode, 8) return await self.__ctx.put( - f'/{config}{SECRET_SUFFIX}', + f'/{config_path}{SECRET_SUFFIX}', content, owner = owner, group = group, @@ -309,26 +313,26 @@ class KvFile(Base): # on-host file name m = 0o400 if mode is None else int(mode, 8) return await self.__ctx.put( - f'/{config}{BLOB_SUFFIX}', + f'/{config_path}{BLOB_SUFFIX}', content, owner = owner, group = group, mode = m, atomic = True, ) - entry, sep, key = config.rpartition('/') - if not sep or not entry or not key or '/' in key: - raise ValueError(f'put: "{path}" is not an entry/key path') - entry, _ = self.__resolve(entry) - real_entry = f'/{entry}' + compound, sep, key = config_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) + real_compound = f'/{compound}' if ftype.is_subtype(FT_SECRET_KEY): - if not await self.__ctx.file_exists(f'{real_entry}{SECRET_SUFFIX}'): - raise OSError(errno.EROFS, f'put: "{entry}" has no entry file') - kv = await self.__entry_kv(entry) + if not await self.__ctx.file_exists(f'{real_compound}{SECRET_SUFFIX}'): + raise OSError(errno.EROFS, f'put: "{compound}" has no compound file') + kv = await self.__compound_kv(compound) kv[key] = content.decode() m = 0o400 if mode is None else int(mode, 8) return await self.__ctx.put( - f'{real_entry}{SECRET_SUFFIX}', + f'{real_compound}{SECRET_SUFFIX}', serialize_kv(kv), owner = owner, group = group, @@ -339,4 +343,4 @@ class KvFile(Base): @override async def _unlink(self, path: str) -> None: - await self.__ctx.unlink(f'/{self.__addr(path)}') + await self.__ctx.unlink(f'/{self.__host_path(path)}') -- 2.56.1 From e96bfca0e159bd9de901aa6bc0e8ac32bcf317ce Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Sat, 7 Nov 2026 10:54:15 +0100 Subject: [PATCH 3/4] 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) == { -- 2.56.1 From fae3390a500eef5a8a01a935935237b1767b05c8 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Sat, 7 Nov 2026 06:54:16 +0100 Subject: [PATCH 4/4] lib.ec.secret_store.KvFile: Fail get() on directories A directory node of the store, the root included, stats as a directory, but a get on it falls through to the key lookup below its parent and fails with a FileNotFoundError naming a path the caller never asked for: get() on the root fails with an empty name, get() on a branch with its parent's compound path. Raise IsADirectoryError from _get() when the path is a directory on the host, after the compound and the blob lookups, so get() and stat() agree: a directory stats as FT_DIR and refuses a get. Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.0 Signed-off-by: Jan Lindemann --- src/python/jw/pkg/lib/ec/secret_store/KvFile.py | 2 ++ .../python/jw/pkg/lib/ec/secret_store/KvFile/test.py | 11 +++++++++++ 2 files changed, 13 insertions(+) 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 fb7d954c..498ecb92 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py +++ b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py @@ -215,6 +215,8 @@ class KvFile(Base): secret_path = f'/{config_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}'): + raise IsADirectoryError(errno.EISDIR, f'get: {path}') if '/' not in config_path: raise FileNotFoundError(path) compound, key = config_path.rsplit('/', 1) 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 6313f998..594dd9cc 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 @@ -82,6 +82,17 @@ async def run_tests() -> None: except FileNotFoundError: pass + # -- A directory refuses a get: stat() answers a directory, + # get() raises IsADirectoryError, the two agree + for path in ('', os.path.dirname(target)): + st = await store.stat(path) + assert st.ftype is FT_DIR + try: + await store.get(path) + raise AssertionError(f'expected IsADirectoryError for {path}') + except IsADirectoryError: + pass + # put writes a key into the entry file, merging with the # existing keys await store.put(f'{target}/key4', b'value4', ftype = FT_SECRET_KEY) -- 2.56.1