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 <jan@janware.com>
This commit is contained in:
Jan Lindemann 2026-11-07 10:54:15 +01:00
commit e96bfca0e1
Signed by: Jan Lindemann
GPG key ID: 3750640C9E25DD61
6 changed files with 103 additions and 108 deletions

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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