lib.ec.secret_store.KvFile: Refactor and construct from a URI #167
10 changed files with 212 additions and 297 deletions
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -3,112 +3,59 @@ 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
|
||||
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.
|
||||
"""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.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ctx: FileContext,
|
||||
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)
|
||||
self.__raw = 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.__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)
|
||||
self.__root = self.uri.path.lstrip('/')
|
||||
self.__ctx = FcCache(self.__inner)
|
||||
|
||||
@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()
|
||||
await self.__inner.open()
|
||||
|
||||
@override
|
||||
async def _close(self) -> None:
|
||||
await self.__raw.close()
|
||||
await self.__inner.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
|
||||
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]:
|
||||
# -- 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
|
||||
def __strip_suffix(path: str) -> tuple[str, bool]:
|
||||
if path.endswith(SECRET_SUFFIX):
|
||||
return path[:-len(SECRET_SUFFIX)], False
|
||||
if path.endswith(BLOB_SUFFIX):
|
||||
|
|
@ -116,49 +63,24 @@ 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')
|
||||
self.__distro = await Distro.instantiate(
|
||||
ec = self.__raw,
|
||||
ec = self.__inner,
|
||||
default_pkg_filter = (
|
||||
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'):
|
||||
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 address 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]
|
||||
|
|
@ -173,32 +95,25 @@ 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:
|
||||
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:
|
||||
# -- 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)
|
||||
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,
|
||||
|
|
@ -208,21 +123,20 @@ 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):
|
||||
# -- The type is synthesized, the mode the one of
|
||||
# the entry file
|
||||
parent, _ = self.__strip_suffix(parent)
|
||||
if await self.__is_compound(parent) and \
|
||||
key in await self.__compound_kv(parent):
|
||||
st = await self.__ctx.stat(f'/{parent}{SECRET_SUFFIX}', follow_symlinks)
|
||||
return self._stat_result(
|
||||
st.owner,
|
||||
|
|
@ -231,74 +145,56 @@ 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:
|
||||
# -- 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:
|
||||
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]:
|
||||
# -- 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):
|
||||
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
|
||||
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, entry 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:
|
||||
# -- 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 config_path and not children:
|
||||
if not await self.__ctx.is_dir(f'/{config_path}'):
|
||||
raise FileNotFoundError(path)
|
||||
return children
|
||||
|
||||
|
|
@ -306,24 +202,26 @@ 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):
|
||||
# -- 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)
|
||||
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 await self.__ctx.is_dir(f'/{config_path}'):
|
||||
raise IsADirectoryError(errno.EISDIR, f'get: {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:
|
||||
|
|
@ -331,32 +229,27 @@ 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}'
|
||||
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):
|
||||
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')
|
||||
|
||||
|
|
@ -375,19 +268,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):
|
||||
# -- 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'
|
||||
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,
|
||||
|
|
@ -395,34 +285,28 @@ 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}{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):
|
||||
# -- 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)
|
||||
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,
|
||||
|
|
@ -433,7 +317,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)}')
|
||||
await self.__ctx.unlink(f'/{self.__host_path(path)}')
|
||||
|
|
|
|||
|
|
@ -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''
|
||||
|
|
@ -80,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)
|
||||
|
|
@ -224,8 +237,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 +308,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 +349,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 +384,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'])
|
||||
|
|
|
|||
|
|
@ -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) == {
|
||||
|
|
|
|||
|
|
@ -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) == {
|
||||
|
|
|
|||
|
|
@ -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) == {
|
||||
|
|
|
|||
Loading…
Reference in a new issue