Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c400b3a37 | ||
|
|
89418ea21a | ||
|
|
2719378f67 |
@@ -307,9 +307,14 @@ class ApprovalStore:
|
|||||||
return record
|
return record
|
||||||
|
|
||||||
def require_operator_policy(self):
|
def require_operator_policy(self):
|
||||||
require(isinstance(self.operator_policy, OperatorApprovalPolicy),
|
require(callable(self.operator_policy), "Trusted migration operator policy loader required")
|
||||||
|
try:
|
||||||
|
policy = self.operator_policy()
|
||||||
|
except Exception:
|
||||||
|
raise ApprovalStoreError("Unable to verify current migration operator authority") from None
|
||||||
|
require(isinstance(policy, OperatorApprovalPolicy),
|
||||||
"Trusted migration operator policy required")
|
"Trusted migration operator policy required")
|
||||||
return self.operator_policy
|
return policy
|
||||||
|
|
||||||
def verify_execution(self, approval, context, *, confirmation, now):
|
def verify_execution(self, approval, context, *, confirmation, now):
|
||||||
verify_approval(approval, context, confirmation=confirmation, now=now)
|
verify_approval(approval, context, confirmation=confirmation, now=now)
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
"""Local operator identity and scoped migration approval policy."""
|
"""Local operator identity and scoped migration approval policy."""
|
||||||
|
|
||||||
import hmac
|
import hmac
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import stat
|
||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from os import geteuid
|
from os import geteuid
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from core.approval import (
|
from core.approval import (
|
||||||
ApprovalError,
|
ApprovalError,
|
||||||
@@ -82,3 +86,46 @@ class OperatorApprovalPolicy:
|
|||||||
def verify_execution(self, approval, now):
|
def verify_execution(self, approval, now):
|
||||||
self.verify_seal(approval)
|
self.verify_seal(approval)
|
||||||
self.authorise(approval, "execute", now)
|
self.authorise(approval, "execute", now)
|
||||||
|
|
||||||
|
|
||||||
|
class FileOperatorAuthority:
|
||||||
|
"""Load a fresh, atomic authority snapshot from a trusted local provisioner."""
|
||||||
|
|
||||||
|
MAX_BYTES = 65536
|
||||||
|
|
||||||
|
def __init__(self, path, *, group):
|
||||||
|
self.path = Path(path)
|
||||||
|
self.group = group
|
||||||
|
require(self.path.is_absolute() and self.path.parent.resolve() == self.path.parent
|
||||||
|
and type(group) is int and group > 0, "Invalid operator authority binding")
|
||||||
|
|
||||||
|
def __call__(self):
|
||||||
|
# The parent and its ancestors are trusted, and the final entry cannot
|
||||||
|
# be replaced by the reader or resolved through a symbolic link.
|
||||||
|
directory = os.open(self.path.parent, os.O_RDONLY | os.O_DIRECTORY
|
||||||
|
| os.O_NOFOLLOW | os.O_CLOEXEC)
|
||||||
|
try:
|
||||||
|
info = os.fstat(directory)
|
||||||
|
require(info.st_uid == 0 and info.st_gid == self.group
|
||||||
|
and stat.S_IMODE(info.st_mode) == 0o750,
|
||||||
|
"Unsafe operator authority directory")
|
||||||
|
descriptor = os.open(self.path.name, os.O_RDONLY | os.O_NOFOLLOW
|
||||||
|
| os.O_NONBLOCK | os.O_CLOEXEC, dir_fd=directory)
|
||||||
|
with os.fdopen(descriptor, "rb") as stream:
|
||||||
|
info = os.fstat(stream.fileno())
|
||||||
|
require(stat.S_ISREG(info.st_mode) and info.st_uid == 0
|
||||||
|
and info.st_gid == self.group and info.st_nlink == 1
|
||||||
|
and stat.S_IMODE(info.st_mode) == 0o440,
|
||||||
|
"Unsafe operator authority file")
|
||||||
|
data = stream.read(self.MAX_BYTES + 1)
|
||||||
|
finally:
|
||||||
|
os.close(directory)
|
||||||
|
require(0 < len(data) <= self.MAX_BYTES, "Invalid operator authority size")
|
||||||
|
snapshot = json.loads(data)
|
||||||
|
require(isinstance(snapshot, dict) and set(snapshot) == {"grants", "sealing_key"}
|
||||||
|
and isinstance(snapshot["grants"], list), "Invalid operator authority snapshot")
|
||||||
|
grants = [
|
||||||
|
OperatorGrant(**dict(grant, expires_at=datetime.fromisoformat(grant["expires_at"])))
|
||||||
|
for grant in snapshot["grants"]
|
||||||
|
]
|
||||||
|
return OperatorApprovalPolicy(grants, sealing_key=bytes.fromhex(snapshot["sealing_key"]))
|
||||||
|
|||||||
+21
-2
@@ -4,6 +4,7 @@ The command runner must be supplied by the caller.
|
|||||||
This module does not execute subprocesses directly.
|
This module does not execute subprocesses directly.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
import os
|
import os
|
||||||
import stat
|
import stat
|
||||||
import tempfile
|
import tempfile
|
||||||
@@ -37,6 +38,7 @@ class ServiceLifecycle:
|
|||||||
stop_timeout=90,
|
stop_timeout=90,
|
||||||
*,
|
*,
|
||||||
site_secrets=None,
|
site_secrets=None,
|
||||||
|
topology_runner=None,
|
||||||
):
|
):
|
||||||
|
|
||||||
require(
|
require(
|
||||||
@@ -86,6 +88,8 @@ class ServiceLifecycle:
|
|||||||
self._queue = docker["queue_service"]
|
self._queue = docker["queue_service"]
|
||||||
self._scheduler = docker["scheduler_service"]
|
self._scheduler = docker["scheduler_service"]
|
||||||
|
|
||||||
|
self._backend_network = docker["backend_network"]
|
||||||
|
self._topology_runner = topology_runner
|
||||||
self._runner = runner
|
self._runner = runner
|
||||||
self._stop_timeout = stop_timeout
|
self._stop_timeout = stop_timeout
|
||||||
|
|
||||||
@@ -114,6 +118,18 @@ class ServiceLifecycle:
|
|||||||
f"Service operation failed: {operation}",
|
f"Service operation failed: {operation}",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def _require_project_backend(self):
|
||||||
|
require(callable(self._topology_runner), "Trusted Compose topology runner required")
|
||||||
|
command = (*self._prefix, "config", "--format", "json")
|
||||||
|
try:
|
||||||
|
model = json.loads(self._topology_runner(command, timeout=30))
|
||||||
|
backend = model["networks"][self._backend_network]
|
||||||
|
except Exception:
|
||||||
|
raise ServiceError("Unable to verify Compose backend network") from None
|
||||||
|
require(isinstance(backend, dict), "Invalid Compose backend network")
|
||||||
|
require(backend.get("external", False) is False,
|
||||||
|
"External Compose backend networks are prohibited")
|
||||||
|
|
||||||
def quiesce(self):
|
def quiesce(self):
|
||||||
|
|
||||||
self._execute(
|
self._execute(
|
||||||
@@ -130,6 +146,7 @@ class ServiceLifecycle:
|
|||||||
|
|
||||||
def restart_php(self):
|
def restart_php(self):
|
||||||
|
|
||||||
|
self._require_project_backend()
|
||||||
self._execute(
|
self._execute(
|
||||||
"restart PHP",
|
"restart PHP",
|
||||||
(
|
(
|
||||||
@@ -181,6 +198,7 @@ class ServiceLifecycle:
|
|||||||
|
|
||||||
def resume(self):
|
def resume(self):
|
||||||
|
|
||||||
|
self._require_project_backend()
|
||||||
self._execute(
|
self._execute(
|
||||||
"resume workers",
|
"resume workers",
|
||||||
(
|
(
|
||||||
@@ -203,8 +221,9 @@ class ContainedServiceLifecycle(ServiceLifecycle):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, config, runner, *, gate_directory, ingress_sealed,
|
def __init__(self, config, runner, *, gate_directory, ingress_sealed,
|
||||||
worker_running, stop_timeout=90, site_secrets=None):
|
worker_running, stop_timeout=90, site_secrets=None, topology_runner=None):
|
||||||
super().__init__(config, runner, stop_timeout, site_secrets=site_secrets)
|
super().__init__(config, runner, stop_timeout, site_secrets=site_secrets,
|
||||||
|
topology_runner=topology_runner)
|
||||||
require(callable(ingress_sealed) and callable(worker_running),
|
require(callable(ingress_sealed) and callable(worker_running),
|
||||||
"Containment probes are required")
|
"Containment probes are required")
|
||||||
self._gate_directory = Path(gate_directory)
|
self._gate_directory = Path(gate_directory)
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# Local migration operator authorisation
|
# Local migration operator authorisation
|
||||||
|
|
||||||
The supported development composition accepts an `OperatorApprovalPolicy`
|
The supported development composition accepts a policy loader through
|
||||||
through `SiteOperations(operator_policy=...)`. Configure the policy in trusted
|
`SiteOperations(operator_policy=...)`. The loader must return a fresh
|
||||||
runtime code with a one-to-one mapping from dedicated OS accounts to operator
|
`OperatorApprovalPolicy` on each call. Configure the policy in trusted runtime code with a one-to-one mapping from dedicated OS accounts to operator
|
||||||
principals. The policy authenticates the process's effective UID. The operator's
|
principals. The policy authenticates the process's effective UID. The operator's
|
||||||
login or service launcher must authenticate access to that account. A shared
|
login or service launcher must authenticate access to that account. A shared
|
||||||
service account cannot provide individual operator identity.
|
service account cannot provide individual operator identity.
|
||||||
@@ -24,7 +24,20 @@ for audit. Unsealed recovery evidence requires manual review. Recovery evidence
|
|||||||
verification requires access to the sealing key used for issuance.
|
verification requires access to the sealing key used for issuance.
|
||||||
|
|
||||||
The runtime process, its code, policy, key, clock and state directory are trusted.
|
The runtime process, its code, policy, key, clock and state directory are trusted.
|
||||||
The policy is constructed from a configuration snapshot. Reload it before
|
|
||||||
further execution when grants are revoked or changed. The approved account
|
Use `FileOperatorAuthority(path, group=...)` for a local authority source. Place
|
||||||
|
the root-owned mode 0440 JSON file in a root-owned mode 0750 directory whose
|
||||||
|
group matches the configured reader group, under administrator-controlled
|
||||||
|
ancestors. The JSON object contains `sealing_key` as hex and `grants` as a list
|
||||||
|
of objects with `uid`, `principal`, `operation`, `site`, `revision` and
|
||||||
|
`expires_at` (timezone-aware ISO 8601). Atomically replace the whole file when
|
||||||
|
removing grants or changing the key. The runtime reopens it for each authority
|
||||||
|
check, including consumption under the approval lock. Missing, unreadable,
|
||||||
|
unsafe or malformed state denies the operation. Key rotation invalidates
|
||||||
|
outstanding approvals and puts evidence sealed with the retired key into
|
||||||
|
manual review. Revocation is evaluated at the next authority read and cannot
|
||||||
|
recall an operation that already passed its final consumption check.
|
||||||
|
|
||||||
|
The approved account
|
||||||
must never be exposed as a shared application or arbitrary command identity.
|
must never be exposed as a shared application or arbitrary command identity.
|
||||||
The inspection CLI remains disabled for production execution.
|
The inspection CLI remains disabled for production execution.
|
||||||
|
|||||||
@@ -34,3 +34,11 @@ result record the activation and health outcome independently of reopening.
|
|||||||
|
|
||||||
These controls are available to the trusted runtime composition. The
|
These controls are available to the trusted runtime composition. The
|
||||||
operational production CLI remains disabled.
|
operational production CLI remains disabled.
|
||||||
|
|
||||||
|
Pass a trusted `topology_runner(command, *, timeout)` that returns stdout
|
||||||
|
from a successful Compose command as JSON bytes or text and raises on failure.
|
||||||
|
The runtime resolves the exact project and Compose files with
|
||||||
|
`config --format json` before starting workers or restarting PHP. Missing,
|
||||||
|
unverifiable, or external configured backend networks deny those operations.
|
||||||
|
Keep Compose inputs under trusted control across validation and execution.
|
||||||
|
Stopping workers remains available if topology validation fails.
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
934a04b5d6ec9aa62cb991fb2f57256c439bac4b2ac110cabd524ad456e59491 ./capabilities-after.json
|
||||||
|
934a04b5d6ec9aa62cb991fb2f57256c439bac4b2ac110cabd524ad456e59491 ./capabilities-before.json
|
||||||
|
cc4a6894db5d31b57a686cf8d23b86e1710388b9562df3f4b152fe03b9e1abf6 ./checks.jsonl
|
||||||
|
c692d9943cdf76339c82f6d77bf3e24d8f3b77ba70b8203e687e8104b9b351a1 ./framework-ci.txt
|
||||||
|
c25354dc469de95845d96f00548f745c62cd510e46cdf94ddcdaf139f918b5df ./scope.txt
|
||||||
|
ed2e7da48d89da2c217f5ada21465e98ed08f48d51915105fff5d5b9746f6033 run.sh
|
||||||
|
9d6b8cbf1b02abb9effee48d56dc136b5cb057f19fef33747fa23f299d51064b probe.py
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{"check": "each site used a distinct project-owned internal network with no published ports", "result": "PASS"}
|
||||||
|
{"check": "local service DNS worked and cross-project service DNS failed in both directions", "result": "PASS"}
|
||||||
|
{"check": "external backend rejected before worker start or PHP restart; no service command ran", "result": "PASS"}
|
||||||
|
{"check": "disposable Compose projects and networks removed", "result": "PASS"}
|
||||||
+2
-2
@@ -5,9 +5,9 @@ Python 3.14.4
|
|||||||
PASS: 88 Python sources compiled
|
PASS: 88 Python sources compiled
|
||||||
|
|
||||||
=== COMPLETE UNIT REGRESSION SUITE ===
|
=== COMPLETE UNIT REGRESSION SUITE ===
|
||||||
..................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
|
.......................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
|
||||||
----------------------------------------------------------------------
|
----------------------------------------------------------------------
|
||||||
Ran 898 tests in 18.300s
|
Ran 903 tests in 17.975s
|
||||||
|
|
||||||
OK
|
OK
|
||||||
|
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import copy
|
||||||
|
import json
|
||||||
|
import secrets
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
from core.services import ServiceError, ServiceLifecycle
|
||||||
|
|
||||||
|
base = json.loads(Path("config/site.example.json").read_text())
|
||||||
|
image_id = "sha256:e742a2668255221388004f3a42b6150a2103f5054ab3a4a93ae9e4f01e551c35"
|
||||||
|
run = secrets.token_hex(5)
|
||||||
|
projects = []
|
||||||
|
|
||||||
|
def cmd(*args):
|
||||||
|
return subprocess.check_output(args, timeout=60, text=True).strip()
|
||||||
|
|
||||||
|
def record(check):
|
||||||
|
print(json.dumps({"check": check, "result": "PASS"}), flush=True)
|
||||||
|
|
||||||
|
def setup(label, external=None):
|
||||||
|
name = f"absdev-topology-{label}-{run}"
|
||||||
|
root = Path.cwd().parent / label
|
||||||
|
root.mkdir()
|
||||||
|
config = copy.deepcopy(base)
|
||||||
|
config["site"].update(identifier=name, root=str(root))
|
||||||
|
config["docker"].update(project=name, backend_network="backend")
|
||||||
|
image = json.loads(cmd("docker", "image", "inspect", image_id))[0]
|
||||||
|
tag = next(t for t in image["RepoTags"] if t.startswith("postgres:"))
|
||||||
|
assert json.loads(cmd("docker", "image", "inspect", tag))[0]["Id"] == image_id
|
||||||
|
topology = {
|
||||||
|
"services": {
|
||||||
|
svc: {"image": tag, "pull_policy": "never", "entrypoint": ["sleep", "300"],
|
||||||
|
"user": "10001:10001", "read_only": True, "cap_drop": ["ALL"],
|
||||||
|
"security_opt": ["no-new-privileges:true"],
|
||||||
|
"networks": {"backend": {"aliases": [name + "-" + svc]}}}
|
||||||
|
for svc in ("queue", "scheduler")
|
||||||
|
},
|
||||||
|
"networks": {"backend": ({"external": True, "name": external} if external
|
||||||
|
else {"internal": True})},
|
||||||
|
}
|
||||||
|
spec = root / "compose.yaml"
|
||||||
|
spec.write_text(json.dumps(topology))
|
||||||
|
prefix = ("docker", "compose", "--project-name", name, "--project-directory", str(root),
|
||||||
|
"--file", str(spec))
|
||||||
|
actions = []
|
||||||
|
def runner(argv, *, timeout):
|
||||||
|
assert argv[:len(prefix)] == prefix
|
||||||
|
actions.append(argv[len(prefix)])
|
||||||
|
return subprocess.run(argv, timeout=timeout, stdout=subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.DEVNULL).returncode
|
||||||
|
def topology_runner(argv, *, timeout):
|
||||||
|
assert argv == (*prefix, "config", "--format", "json")
|
||||||
|
return subprocess.check_output(argv, timeout=timeout)
|
||||||
|
lifecycle = ServiceLifecycle(config, runner, topology_runner=topology_runner)
|
||||||
|
if external:
|
||||||
|
resolved = json.loads(topology_runner((*prefix, "config", "--format", "json"), timeout=30))
|
||||||
|
assert resolved["networks"]["backend"]["external"] is True
|
||||||
|
for operation in (lifecycle.resume, lifecycle.restart_php):
|
||||||
|
try:
|
||||||
|
operation()
|
||||||
|
except ServiceError as error:
|
||||||
|
assert "External Compose backend networks" in str(error)
|
||||||
|
else:
|
||||||
|
raise AssertionError("External backend accepted")
|
||||||
|
assert not actions
|
||||||
|
assert not cmd("docker", "ps", "-aq", "--filter", "label=com.docker.compose.project=" + name)
|
||||||
|
return None
|
||||||
|
projects.append(prefix)
|
||||||
|
lifecycle.resume()
|
||||||
|
ids = [cmd(*prefix, "ps", "-q", svc) for svc in ("queue", "scheduler")]
|
||||||
|
network = name + "_backend"
|
||||||
|
details = json.loads(cmd("docker", "network", "inspect", network))[0]
|
||||||
|
assert details["Internal"] and details["Labels"]["com.docker.compose.project"] == name
|
||||||
|
for cid in ids:
|
||||||
|
info = json.loads(cmd("docker", "inspect", cid))[0]
|
||||||
|
assert set(info["NetworkSettings"]["Networks"]) == {network}
|
||||||
|
assert not info["HostConfig"]["PortBindings"] and not info["HostConfig"]["Privileged"]
|
||||||
|
return name, network, ids[0]
|
||||||
|
|
||||||
|
def lookup(cid, host):
|
||||||
|
return subprocess.run(("docker", "exec", cid, "getent", "hosts", host),
|
||||||
|
capture_output=True, timeout=15)
|
||||||
|
|
||||||
|
try:
|
||||||
|
a, anet, ac = setup("alpha")
|
||||||
|
b, bnet, bc = setup("beta")
|
||||||
|
assert anet != bnet
|
||||||
|
record("each site used a distinct project-owned internal network with no published ports")
|
||||||
|
for name, other, cid in ((a, b, ac), (b, a, bc)):
|
||||||
|
assert lookup(cid, name + "-scheduler").returncode == 0
|
||||||
|
denied = lookup(cid, other + "-scheduler")
|
||||||
|
assert denied.returncode == 2 and not denied.stdout
|
||||||
|
record("local service DNS worked and cross-project service DNS failed in both directions")
|
||||||
|
setup("shared-model", external=anet)
|
||||||
|
record("external backend rejected before worker start or PHP restart; no service command ran")
|
||||||
|
finally:
|
||||||
|
for prefix in reversed(projects):
|
||||||
|
cmd(*prefix, "down", "--volumes", "--timeout", "1")
|
||||||
|
record("disposable Compose projects and networks removed")
|
||||||
+2
-4
@@ -1,17 +1,15 @@
|
|||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
umask 077
|
umask 077
|
||||||
test "$(hostname -s | tr A-Z a-z)" = absdev-ci
|
test "$(hostname -s | tr A-Z a-z)" = absdev-ci
|
||||||
stage=$(mktemp -d /var/tmp/absdev-secret-backend.XXXXXX)
|
stage=$(mktemp -d /var/tmp/absdev-backend-network.XXXXXX)
|
||||||
trap 'rm -rf -- "$stage"' EXIT
|
trap 'rm -rf -- "$stage"' EXIT
|
||||||
mkdir "$stage/source" "$stage/evidence" "$stage/tmp"
|
mkdir "$stage/source" "$stage/evidence" "$stage/tmp"
|
||||||
tar -xm -f - -C "$stage/source"
|
tar -xm -f - -C "$stage/source"
|
||||||
chmod 0711 "$stage"
|
|
||||||
chmod -R a+rX "$stage/source"
|
|
||||||
cd "$stage/source"
|
cd "$stage/source"
|
||||||
export TMPDIR="$stage/tmp"
|
export TMPDIR="$stage/tmp"
|
||||||
export DOCKER_CONFIG=/var/tmp/absdev-supported-containment.L6qYEi/docker-config
|
export DOCKER_CONFIG=/var/tmp/absdev-supported-containment.L6qYEi/docker-config
|
||||||
out="$stage/evidence"
|
out="$stage/evidence"
|
||||||
printf 'host=%s\nrevision=1c3df42a68d75b825993f9e5b9a774e5eeacff4b\n' "$(hostname -s)" > "$out/scope.txt"
|
printf 'host=%s\nrevision=89418ea21ad3d307eff3cbadc978687a48e572ce\n' "$(hostname -s)" > "$out/scope.txt"
|
||||||
docker compose version >> "$out/scope.txt"
|
docker compose version >> "$out/scope.txt"
|
||||||
sha256sum "$DOCKER_CONFIG/cli-plugins/docker-compose" >> "$out/scope.txt"
|
sha256sum "$DOCKER_CONFIG/cli-plugins/docker-compose" >> "$out/scope.txt"
|
||||||
python3 -B bin/absdev-deploy capabilities > "$out/capabilities-before.json"
|
python3 -B bin/absdev-deploy capabilities > "$out/capabilities-before.json"
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
host=absdev-ci
|
host=absdev-ci
|
||||||
revision=1c3df42a68d75b825993f9e5b9a774e5eeacff4b
|
revision=89418ea21ad3d307eff3cbadc978687a48e572ce
|
||||||
Docker Compose version 2.40.3+ds1-0ubuntu1
|
Docker Compose version 2.40.3+ds1-0ubuntu1
|
||||||
93226cc2ea191353641921350ad87d96cb942e29a21c7c68c430adfd9954af34 /var/tmp/absdev-supported-containment.L6qYEi/docker-config/cli-plugins/docker-compose
|
93226cc2ea191353641921350ad87d96cb942e29a21c7c68c430adfd9954af34 /var/tmp/absdev-supported-containment.L6qYEi/docker-config/cli-plugins/docker-compose
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
934a04b5d6ec9aa62cb991fb2f57256c439bac4b2ac110cabd524ad456e59491 ./capabilities-after.json
|
|
||||||
934a04b5d6ec9aa62cb991fb2f57256c439bac4b2ac110cabd524ad456e59491 ./capabilities-before.json
|
|
||||||
499359ffe91cf40ff270d33416162d1252b679d58e43f143d111eba37b2d4532 ./checks.jsonl
|
|
||||||
15c818e408d8b710ccf5c341b1d48b839e5f8e6c52ff0f6d8f0835c53a3e9c8a ./framework-ci.txt
|
|
||||||
fcbcfb1fd1737afb7f9663aaceebf76720583b05c0830285b3ae8db2e3ff9193 ./scope.txt
|
|
||||||
c3454343f7e7b582256cf41288abdfe5a194baec9b3edcc30a5091d628b429ee probe.py
|
|
||||||
707f621628fbdebd112b33d00e92318ec32eb4cd49cdc8e99831dd26300b0089 run.sh
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
{"check": "both supported Compose lifecycle instances started with independent read-only credential mounts", "result": "PASS"}
|
|
||||||
{"check": "same-UID services cannot read the other site's credentials or access their own site's ungranted mount", "result": "PASS"}
|
|
||||||
{"check": "read-only mount rejects writes and runtime rejects mismatched site bindings", "result": "PASS"}
|
|
||||||
{"check": "dedicated OS identities can access only their own backend namespace; cross-site delivery rejected", "result": "PASS"}
|
|
||||||
{"check": "unsafe backend file permissions deny refresh and preserve current delivery", "result": "PASS"}
|
|
||||||
{"check": "atomic rotation reaches the existing container without affecting the other site", "result": "PASS"}
|
|
||||||
{"check": "disposable Compose projects, volumes and backend accounts removed", "result": "PASS"}
|
|
||||||
@@ -1,172 +0,0 @@
|
|||||||
import copy
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import secrets
|
|
||||||
import stat
|
|
||||||
import subprocess
|
|
||||||
import tempfile
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from core.secret_backend import FileSecretBackend
|
|
||||||
from core.services import ServiceLifecycle
|
|
||||||
from core.site_secrets import SiteSecretError, SiteSecrets
|
|
||||||
|
|
||||||
IMAGE = "sha256:e742a2668255221388004f3a42b6150a2103f5054ab3a4a93ae9e4f01e551c35"
|
|
||||||
root = Path(tempfile.mkdtemp(dir=Path.cwd().parent))
|
|
||||||
store = root / "credentials"
|
|
||||||
store.mkdir(mode=0o700)
|
|
||||||
base = json.loads(Path("config/site.example.json").read_text())
|
|
||||||
run = secrets.token_hex(5)
|
|
||||||
projects = []
|
|
||||||
accounts = []
|
|
||||||
backend_root = root / "backend"
|
|
||||||
root.chmod(0o711)
|
|
||||||
backend_root.mkdir()
|
|
||||||
backend_root.chmod(0o711)
|
|
||||||
|
|
||||||
def publish(site_root, gid, filename, data):
|
|
||||||
with tempfile.NamedTemporaryFile(dir=site_root, delete=False) as stream:
|
|
||||||
stream.write(data)
|
|
||||||
stream.flush()
|
|
||||||
os.fchown(stream.fileno(), 0, gid)
|
|
||||||
os.fchmod(stream.fileno(), 0o440)
|
|
||||||
os.fsync(stream.fileno())
|
|
||||||
os.replace(stream.name, site_root / filename)
|
|
||||||
|
|
||||||
|
|
||||||
def cmd(*args, allow_failure=False):
|
|
||||||
result = subprocess.run(args, capture_output=True, timeout=90)
|
|
||||||
if result.returncode and args[:2] == ("docker", "compose"):
|
|
||||||
import sys
|
|
||||||
print(result.stderr.decode(errors="replace")[:800], file=sys.stderr)
|
|
||||||
if result.returncode and not allow_failure:
|
|
||||||
raise RuntimeError(f"Command failed: {args[:3]}: {result.stderr.decode(errors='replace')[:800]}")
|
|
||||||
return result
|
|
||||||
|
|
||||||
def passcheck(text):
|
|
||||||
print(json.dumps({"check": text, "result": "PASS"}), flush=True)
|
|
||||||
|
|
||||||
def create(label, filename):
|
|
||||||
config = copy.deepcopy(base)
|
|
||||||
name = "absdev-secret-" + label + "-" + run
|
|
||||||
project_root = root / label
|
|
||||||
project_root.mkdir()
|
|
||||||
config["site"].update(identifier=name, root=str(project_root))
|
|
||||||
config["docker"]["project"] = name
|
|
||||||
container_image = json.loads(cmd("docker", "image", "inspect", IMAGE).stdout)[0]
|
|
||||||
image = next(tag for tag in container_image["RepoTags"] if tag.startswith("postgres:"))
|
|
||||||
assert json.loads(cmd("docker", "image", "inspect", image).stdout)[0]["Id"] == IMAGE
|
|
||||||
services = {service: {"image": image, "pull_policy": "never", "entrypoint": ["sleep", "300"],
|
|
||||||
"user": "10001:10001", "network_mode": "none", "read_only": True,
|
|
||||||
"cap_drop": ["ALL"], "security_opt": ["no-new-privileges:true"]}
|
|
||||||
for service in ("queue", "scheduler")}
|
|
||||||
(project_root / "compose.yaml").write_text(json.dumps({"services": services}))
|
|
||||||
site = SiteSecrets(config, store, {"queue": 10001})
|
|
||||||
data = secrets.token_bytes(32).hex().encode() + b"\n"
|
|
||||||
account = "absec" + label[0] + run
|
|
||||||
cmd("useradd", "-U", "-M", "-d", "/nonexistent", "-s", "/usr/sbin/nologin", account)
|
|
||||||
accounts.append(account)
|
|
||||||
gid = int(cmd("id", "-g", account).stdout)
|
|
||||||
area = backend_root / name
|
|
||||||
area.mkdir()
|
|
||||||
os.chown(area, 0, gid)
|
|
||||||
area.chmod(0o750)
|
|
||||||
publish(area, gid, filename, data)
|
|
||||||
backend = FileSecretBackend(backend_root, name, gid)
|
|
||||||
backend.deliver(site, "queue", filename)
|
|
||||||
path = store / name / "queue" / filename
|
|
||||||
assert stat.S_IMODE(path.stat().st_mode) == 0o600 and path.stat().st_uid == 10001
|
|
||||||
def runner(args, *, timeout):
|
|
||||||
assert args[:2] == ("docker", "compose")
|
|
||||||
return cmd(*args).returncode
|
|
||||||
lifecycle = ServiceLifecycle(config, runner, site_secrets=site)
|
|
||||||
compose = ("docker", "compose", "--project-name", name, "--project-directory", str(project_root),
|
|
||||||
"--file", str(project_root / "compose.yaml"), "--file", str(site.compose_file(config)))
|
|
||||||
projects.append(compose)
|
|
||||||
lifecycle.resume()
|
|
||||||
queue = cmd(*compose, "ps", "-q", "queue").stdout.decode().strip()
|
|
||||||
scheduler = cmd(*compose, "ps", "-q", "scheduler").stdout.decode().strip()
|
|
||||||
info = json.loads(cmd("docker", "inspect", queue).stdout)[0]
|
|
||||||
mount = [m for m in info["Mounts"] if m["Destination"] == "/run/secrets"]
|
|
||||||
assert len(mount) == 1 and mount[0]["Source"] == str(path.parent) and not mount[0]["RW"]
|
|
||||||
assert info["Image"] == IMAGE and info["HostConfig"]["NetworkMode"] == "none"
|
|
||||||
return config, site, queue, scheduler, data, backend, account
|
|
||||||
|
|
||||||
def read(cid, file, expected=None):
|
|
||||||
result = cmd("docker", "exec", cid, "cat", "/run/secrets/" + file, allow_failure=True)
|
|
||||||
if expected is None:
|
|
||||||
assert result.returncode and not result.stdout
|
|
||||||
else:
|
|
||||||
assert not result.returncode and result.stdout == expected
|
|
||||||
|
|
||||||
try:
|
|
||||||
a_config, a_site, a, a_other, first, a_backend, a_account = create("alpha", "absdev-client.cnf")
|
|
||||||
b_config, b_site, b, b_other, second, b_backend, b_account = create("beta", "absdev-pgpass")
|
|
||||||
passcheck("both supported Compose lifecycle instances started with independent read-only credential mounts")
|
|
||||||
read(a, "absdev-client.cnf", first)
|
|
||||||
read(b, "absdev-pgpass", second)
|
|
||||||
read(a, "absdev-pgpass")
|
|
||||||
read(b, "absdev-client.cnf")
|
|
||||||
read(a_other, "absdev-client.cnf")
|
|
||||||
read(b_other, "absdev-pgpass")
|
|
||||||
passcheck("same-UID services cannot read the other site's credentials or access their own site's ungranted mount")
|
|
||||||
assert cmd("docker", "exec", a, "sh", "-c",
|
|
||||||
"printf invalid > /run/secrets/absdev-client.cnf", allow_failure=True).returncode
|
|
||||||
try:
|
|
||||||
a_site.compose_file(b_config)
|
|
||||||
except SiteSecretError:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
raise AssertionError("Cross-site override accepted")
|
|
||||||
passcheck("read-only mount rejects writes and runtime rejects mismatched site bindings")
|
|
||||||
identity_probe = """from core.secret_backend import FileSecretBackend
|
|
||||||
from core.site_secrets import SiteSecretError
|
|
||||||
import sys
|
|
||||||
|
|
||||||
backend = FileSecretBackend(sys.argv[1], sys.argv[2], int(sys.argv[3]))
|
|
||||||
try:
|
|
||||||
backend.read(sys.argv[4])
|
|
||||||
except SiteSecretError:
|
|
||||||
sys.exit(3)
|
|
||||||
"""
|
|
||||||
for allowed, denied, backend, filename in (
|
|
||||||
(a_account, b_account, a_backend, "absdev-client.cnf"),
|
|
||||||
(b_account, a_account, b_backend, "absdev-pgpass"),
|
|
||||||
):
|
|
||||||
args = ("python3", "-B", "-c", identity_probe, str(backend_root),
|
|
||||||
backend.site, str(backend.group), filename)
|
|
||||||
assert cmd("runuser", "-u", allowed, "--", *args).returncode == 0
|
|
||||||
assert cmd("runuser", "-u", denied, "--", *args, allow_failure=True).returncode == 3
|
|
||||||
try:
|
|
||||||
a_backend.deliver(b_site, "queue", "absdev-client.cnf")
|
|
||||||
except SiteSecretError:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
raise AssertionError("Backend delivered across site bindings")
|
|
||||||
passcheck("dedicated OS identities can access only their own backend namespace; cross-site delivery rejected")
|
|
||||||
file = backend_root / a_backend.site / "absdev-client.cnf"
|
|
||||||
file.chmod(0o444)
|
|
||||||
try:
|
|
||||||
a_backend.deliver(a_site, "queue", "absdev-client.cnf")
|
|
||||||
except SiteSecretError:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
raise AssertionError("Backend accepted unsafe mode")
|
|
||||||
read(a, "absdev-client.cnf", first)
|
|
||||||
passcheck("unsafe backend file permissions deny refresh and preserve current delivery")
|
|
||||||
rotated = secrets.token_hex(32).encode() + b"\n"
|
|
||||||
publish(file.parent, a_backend.group, file.name, rotated)
|
|
||||||
a_backend.deliver(a_site, "queue", file.name)
|
|
||||||
read(a, "absdev-client.cnf", rotated)
|
|
||||||
read(b, "absdev-pgpass", second)
|
|
||||||
read(b, "absdev-client.cnf")
|
|
||||||
assert cmd(*projects[0], "ps", "-q", "queue").stdout.decode().strip() == a
|
|
||||||
passcheck("atomic rotation reaches the existing container without affecting the other site")
|
|
||||||
finally:
|
|
||||||
failures = [project for project in reversed(projects)
|
|
||||||
if cmd(*project, "down", "--volumes", allow_failure=True).returncode]
|
|
||||||
failures.extend(account for account in reversed(accounts)
|
|
||||||
if cmd("userdel", account, allow_failure=True).returncode)
|
|
||||||
if failures:
|
|
||||||
raise RuntimeError("Disposable Compose cleanup failed")
|
|
||||||
passcheck("disposable Compose projects, volumes and backend accounts removed")
|
|
||||||
@@ -96,7 +96,7 @@ class ApprovalStoreTests(unittest.TestCase):
|
|||||||
for operation in ("issue", "execute")
|
for operation in ("issue", "execute")
|
||||||
]
|
]
|
||||||
self.policy = OperatorApprovalPolicy(self.grants, sealing_key=self.key)
|
self.policy = OperatorApprovalPolicy(self.grants, sealing_key=self.key)
|
||||||
self.store = ApprovalStore(self.root, operator_policy=self.policy)
|
self.store = ApprovalStore(self.root, operator_policy=lambda: self.policy)
|
||||||
|
|
||||||
def save(self):
|
def save(self):
|
||||||
|
|
||||||
@@ -171,7 +171,7 @@ class ApprovalStoreTests(unittest.TestCase):
|
|||||||
self.save()
|
self.save()
|
||||||
self.consume()
|
self.consume()
|
||||||
|
|
||||||
self.store = ApprovalStore(self.root, operator_policy=self.policy)
|
self.store = ApprovalStore(self.root, operator_policy=lambda: self.policy)
|
||||||
|
|
||||||
with self.assertRaisesRegex(ApprovalStoreError, "already consumed"):
|
with self.assertRaisesRegex(ApprovalStoreError, "already consumed"):
|
||||||
self.consume()
|
self.consume()
|
||||||
@@ -483,13 +483,13 @@ class ApprovalStoreTests(unittest.TestCase):
|
|||||||
|
|
||||||
def test_missing_policy_denies_issuance(self):
|
def test_missing_policy_denies_issuance(self):
|
||||||
self.store = ApprovalStore(self.root)
|
self.store = ApprovalStore(self.root)
|
||||||
with self.assertRaisesRegex(ApprovalStoreError, "policy required"):
|
with self.assertRaisesRegex(ApprovalStoreError, "policy loader required"):
|
||||||
self.save()
|
self.save()
|
||||||
self.assertFalse(self.store.approval_path(self.identifier).exists())
|
self.assertFalse(self.store.approval_path(self.identifier).exists())
|
||||||
|
|
||||||
def test_unrecognised_os_identity_denies_issuance(self):
|
def test_unrecognised_os_identity_denies_issuance(self):
|
||||||
other_account = [replace(grant, uid=self.uid + 1) for grant in self.grants]
|
other_account = [replace(grant, uid=self.uid + 1) for grant in self.grants]
|
||||||
self.store.operator_policy = OperatorApprovalPolicy(other_account, sealing_key=self.key)
|
self.policy = OperatorApprovalPolicy(other_account, sealing_key=self.key)
|
||||||
with self.assertRaisesRegex(ApprovalStoreError, "not authorised"):
|
with self.assertRaisesRegex(ApprovalStoreError, "not authorised"):
|
||||||
self.save()
|
self.save()
|
||||||
self.assertFalse(self.store.approval_path(self.identifier).exists())
|
self.assertFalse(self.store.approval_path(self.identifier).exists())
|
||||||
@@ -502,7 +502,7 @@ class ApprovalStoreTests(unittest.TestCase):
|
|||||||
replace(execute, principal="other-operator"),
|
replace(execute, principal="other-operator"),
|
||||||
replace(execute, expires_at=self.now)):
|
replace(execute, expires_at=self.now)):
|
||||||
with self.subTest(grant=grant):
|
with self.subTest(grant=grant):
|
||||||
self.store.operator_policy = OperatorApprovalPolicy([grant], sealing_key=self.key)
|
self.policy = OperatorApprovalPolicy([grant], sealing_key=self.key)
|
||||||
with self.assertRaises(ApprovalStoreError):
|
with self.assertRaises(ApprovalStoreError):
|
||||||
self.consume()
|
self.consume()
|
||||||
self.assertFalse(self.store.consumed_path(self.identifier).exists())
|
self.assertFalse(self.store.consumed_path(self.identifier).exists())
|
||||||
@@ -522,5 +522,26 @@ class ApprovalStoreTests(unittest.TestCase):
|
|||||||
self.consume()
|
self.consume()
|
||||||
self.assertFalse(self.store.consumed_path(self.identifier).exists())
|
self.assertFalse(self.store.consumed_path(self.identifier).exists())
|
||||||
|
|
||||||
|
|
||||||
|
def test_static_authority_is_rejected(self):
|
||||||
|
self.store.operator_policy = self.policy
|
||||||
|
with self.assertRaisesRegex(ApprovalStoreError, "policy loader required"):
|
||||||
|
self.save()
|
||||||
|
|
||||||
|
def test_unavailable_authority_fails_closed_after_issuance(self):
|
||||||
|
self.save()
|
||||||
|
with patch.object(self.store, "operator_policy", side_effect=OSError("unavailable")):
|
||||||
|
with self.assertRaises(ApprovalStoreError):
|
||||||
|
self.consume()
|
||||||
|
self.assertFalse(self.store.consumed_path(self.identifier).exists())
|
||||||
|
|
||||||
|
def test_running_store_rejects_retired_sealing_key(self):
|
||||||
|
self.save()
|
||||||
|
self.policy = OperatorApprovalPolicy(self.grants, sealing_key=os.urandom(32))
|
||||||
|
with self.assertRaises(ApprovalStoreError):
|
||||||
|
self.consume()
|
||||||
|
self.assertFalse(self.store.consumed_path(self.identifier).exists())
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -24,6 +24,9 @@ class ContainedServiceTests(unittest.TestCase):
|
|||||||
self.config, self.run_command, gate_directory=self.directory,
|
self.config, self.run_command, gate_directory=self.directory,
|
||||||
ingress_sealed=lambda: self.gate.is_file() and self.probe_ok,
|
ingress_sealed=lambda: self.gate.is_file() and self.probe_ok,
|
||||||
worker_running=lambda _name: self.running,
|
worker_running=lambda _name: self.running,
|
||||||
|
topology_runner=lambda _command, **_options: json.dumps({
|
||||||
|
"networks": {self.config["docker"]["backend_network"]: {"internal": True}},
|
||||||
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
def run_command(self, args, *, timeout):
|
def run_command(self, args, *, timeout):
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ class MigrationTests(unittest.TestCase):
|
|||||||
self.fixture = test_approval_store.ApprovalStoreTests()
|
self.fixture = test_approval_store.ApprovalStoreTests()
|
||||||
self.addCleanup(self.fixture.doCleanups)
|
self.addCleanup(self.fixture.doCleanups)
|
||||||
self.fixture.setUp()
|
self.fixture.setUp()
|
||||||
self.ops = SiteOperations(self.fixture.root, operator_policy=self.fixture.policy)
|
self.ops = SiteOperations(self.fixture.root, operator_policy=lambda: self.fixture.policy)
|
||||||
self.fixture.store = self.ops.approvals
|
self.fixture.store = self.ops.approvals
|
||||||
self.fixture.save()
|
self.fixture.save()
|
||||||
|
|
||||||
@@ -367,7 +367,7 @@ class MigrationTests(unittest.TestCase):
|
|||||||
def test_missing_execution_authority_blocks_before_containment(self):
|
def test_missing_execution_authority_blocks_before_containment(self):
|
||||||
from core.operator_approval import OperatorApprovalPolicy
|
from core.operator_approval import OperatorApprovalPolicy
|
||||||
|
|
||||||
self.fixture.store.operator_policy = OperatorApprovalPolicy(
|
self.fixture.policy = OperatorApprovalPolicy(
|
||||||
self.fixture.grants[:1], sealing_key=self.fixture.key,
|
self.fixture.grants[:1], sealing_key=self.fixture.key,
|
||||||
)
|
)
|
||||||
with self.assertRaises(MigrationError):
|
with self.assertRaises(MigrationError):
|
||||||
|
|||||||
@@ -19,10 +19,14 @@ class ServiceTests(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
|
|
||||||
self.runner = Mock(return_value=0)
|
self.runner = Mock(return_value=0)
|
||||||
|
self.topology = Mock(return_value=json.dumps({
|
||||||
|
"networks": {self.config["docker"]["backend_network"]: {"internal": True}},
|
||||||
|
}))
|
||||||
|
|
||||||
self.manager = ServiceLifecycle(
|
self.manager = ServiceLifecycle(
|
||||||
self.config,
|
self.config,
|
||||||
self.runner,
|
self.runner,
|
||||||
|
topology_runner=self.topology,
|
||||||
)
|
)
|
||||||
|
|
||||||
self.prefix = [
|
self.prefix = [
|
||||||
@@ -74,6 +78,26 @@ class ServiceTests(unittest.TestCase):
|
|||||||
],
|
],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def test_external_backend_blocks_start_and_restart(self):
|
||||||
|
self.topology.return_value = json.dumps({
|
||||||
|
"networks": {self.config["docker"]["backend_network"]: {"external": True}},
|
||||||
|
})
|
||||||
|
for operation in (self.manager.resume, self.manager.restart_php):
|
||||||
|
with self.assertRaisesRegex(ServiceError, "External Compose backend"):
|
||||||
|
operation()
|
||||||
|
self.runner.assert_not_called()
|
||||||
|
self.topology.assert_called_with(
|
||||||
|
(*self.prefix, "config", "--format", "json"), timeout=30,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_unverifiable_backend_fails_closed(self):
|
||||||
|
for model in ("invalid json", '{"networks": {}}', '{"networks": null}'):
|
||||||
|
with self.subTest(model=model):
|
||||||
|
self.topology.return_value = model
|
||||||
|
with self.assertRaisesRegex(ServiceError, "Unable to verify"):
|
||||||
|
self.manager.resume()
|
||||||
|
self.runner.assert_not_called()
|
||||||
|
|
||||||
def test_validate_nginx(self):
|
def test_validate_nginx(self):
|
||||||
|
|
||||||
self.manager.validate_nginx()
|
self.manager.validate_nginx()
|
||||||
@@ -148,6 +172,7 @@ class ServiceTests(unittest.TestCase):
|
|||||||
manager = ServiceLifecycle(
|
manager = ServiceLifecycle(
|
||||||
self.config,
|
self.config,
|
||||||
self.runner,
|
self.runner,
|
||||||
|
topology_runner=self.topology,
|
||||||
)
|
)
|
||||||
|
|
||||||
manager.restart_php()
|
manager.restart_php()
|
||||||
@@ -164,6 +189,7 @@ class ServiceTests(unittest.TestCase):
|
|||||||
manager = ServiceLifecycle(
|
manager = ServiceLifecycle(
|
||||||
self.config,
|
self.config,
|
||||||
self.runner,
|
self.runner,
|
||||||
|
topology_runner=self.topology,
|
||||||
)
|
)
|
||||||
|
|
||||||
manager.validate_nginx()
|
manager.validate_nginx()
|
||||||
@@ -181,6 +207,7 @@ class ServiceTests(unittest.TestCase):
|
|||||||
manager = ServiceLifecycle(
|
manager = ServiceLifecycle(
|
||||||
self.config,
|
self.config,
|
||||||
self.runner,
|
self.runner,
|
||||||
|
topology_runner=self.topology,
|
||||||
)
|
)
|
||||||
|
|
||||||
manager.quiesce()
|
manager.quiesce()
|
||||||
|
|||||||
Reference in New Issue
Block a user