fix: harden preprocessing state and child capabilities

This commit is contained in:
2026-08-11 14:30:16 +02:00
parent a5916f6177
commit ee5ac381b3
12 changed files with 323 additions and 104 deletions
+67 -17
View File
@@ -1,22 +1,26 @@
"""Capability verifier for mutating workspace children.
"""Fail-closed verifier for the backend-owned writer capability.
The backend passes writer.lock as fd 3 and the retained workspace directory as fd 4.
This module intentionally has no path fallback: callers either run with the capability
or fail closed before touching artifacts.
FD 3 is the inherited writer open file description and FD 4 is the retained
workspace-root directory. Environment values are descriptive identity only;
they never authorize a direct invocation.
"""
from __future__ import annotations
import errno
import fcntl
import os
import re
import stat
from dataclasses import dataclass
class WorkspaceWriterConflict(RuntimeError):
"preprocessing_conflict"
def __init__(self, message: str = "preprocessing_conflict") -> None:
super().__init__(message)
@dataclass(frozen=True)
class WorkspaceCapability:
workspace_id: str
@@ -26,26 +30,72 @@ class WorkspaceCapability:
writer_device: int
writer_inode: int
def _identity(env: dict[str, str]) -> tuple[str, str, int, int]:
wid, rev = env.get("THOTH_WORKSPACE_ID"), env.get("THOTH_WORKSPACE_REVISION")
if not wid or not rev or not __import__("re").fullmatch(r"[a-z][a-z0-9-]{2,62}", wid) or not __import__("re").fullmatch(r"[0-9a-f]{40}", rev):
if not wid or not rev or not re.fullmatch(r"[a-z][a-z0-9-]{2,62}", wid) or not re.fullmatch(r"[0-9a-f]{40}", rev):
raise WorkspaceWriterConflict()
try:
device, inode = int(env["THOTH_WORKSPACE_DEVICE"]), int(env["THOTH_WORKSPACE_INODE"])
except (KeyError, ValueError):
raise WorkspaceWriterConflict() from None
if device < 0 or inode <= 0:
raise WorkspaceWriterConflict()
try: device, inode = int(env["THOTH_WORKSPACE_DEVICE"]), int(env["THOTH_WORKSPACE_INODE"])
except (KeyError, ValueError): raise WorkspaceWriterConflict()
return wid, rev, device, inode
def _fstat(fd: int) -> os.stat_result:
try:
return os.fstat(fd)
except OSError:
raise WorkspaceWriterConflict() from None
def _open_lock(root_fd: int) -> int:
# The lock is opened relative to the retained root and cannot be substituted
# by a symlink between validation and open. No path fallback is permitted.
try:
return os.open("writer.lock", os.O_RDWR | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=root_fd)
except OSError:
raise WorkspaceWriterConflict() from None
def verify_workspace_writer_fds(*, writer_fd: int = 3, root_fd: int = 4, env: dict[str, str] | None = None) -> WorkspaceCapability:
env = dict(os.environ if env is None else env)
wid, rev, device, inode = _identity(env)
try: root = os.fstat(root_fd); writer = os.fstat(writer_fd)
except OSError as exc: raise WorkspaceWriterConflict() from exc
if not stat.S_ISDIR(root.st_mode) or root.st_uid != os.getuid() or (root.st_mode & 0o777) != 0o700 or (root.st_dev, root.st_ino) != (device, inode): raise WorkspaceWriterConflict()
if not stat.S_ISREG(writer.st_mode) or writer.st_uid != os.getuid() or (writer.st_mode & 0o777) != 0o600: raise WorkspaceWriterConflict()
try: fcntl.flock(writer_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError as exc: raise WorkspaceWriterConflict() from exc
# Keep the OFD locked. A lock check is necessarily best effort on some BSDs; identity and
# descriptor ownership remain mandatory and no path-based lock is accepted.
if writer_fd == root_fd or writer_fd < 0 or root_fd < 0:
raise WorkspaceWriterConflict()
root, writer = _fstat(root_fd), _fstat(writer_fd)
uid = os.getuid()
if not stat.S_ISDIR(root.st_mode) or root.st_uid != uid or (root.st_mode & 0o777) != 0o700 or (root.st_dev, root.st_ino) != (device, inode):
raise WorkspaceWriterConflict()
if not stat.S_ISREG(writer.st_mode) or writer.st_uid != uid or (writer.st_mode & 0o777) != 0o600 or writer.st_nlink != 1:
raise WorkspaceWriterConflict()
lock_fd = _open_lock(root_fd)
try:
lock = _fstat(lock_fd)
if (lock.st_dev, lock.st_ino) != (writer.st_dev, writer.st_ino) or not stat.S_ISREG(lock.st_mode) or lock.st_uid != uid or (lock.st_mode & 0o777) != 0o600 or lock.st_nlink != 1:
raise WorkspaceWriterConflict()
# A duplicate of the locked open description is re-lockable. An
# independently-opened description receives EWOULDBLOCK.
try:
fcntl.flock(writer_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError as exc:
if exc.errno in (errno.EACCES, errno.EAGAIN, errno.EWOULDBLOCK):
raise WorkspaceWriterConflict() from None
raise WorkspaceWriterConflict() from exc
finally:
try:
os.close(lock_fd)
except OSError:
pass
return WorkspaceCapability(wid, rev, root.st_dev, root.st_ino, writer.st_dev, writer.st_ino)
def require_workspace_writer_capability() -> WorkspaceCapability:
return verify_workspace_writer_fds()
def require_workspace_writer_capability(*, workspace_id: str | None = None, revision: str | None = None) -> WorkspaceCapability:
cap = verify_workspace_writer_fds()
if workspace_id is not None and cap.workspace_id != workspace_id:
raise WorkspaceWriterConflict()
if revision is not None and cap.revision != revision:
raise WorkspaceWriterConflict()
return cap