Compare commits

..
29 changed files with 241 additions and 559 deletions
+2 -7
View File
@@ -307,14 +307,9 @@ class ApprovalStore:
return record return record
def require_operator_policy(self): def require_operator_policy(self):
require(callable(self.operator_policy), "Trusted migration operator policy loader required") require(isinstance(self.operator_policy, OperatorApprovalPolicy),
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 policy return self.operator_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)
+11 -19
View File
@@ -56,18 +56,6 @@ def provenance_fingerprint(data):
}) })
def is_laravel_migration_path(value):
"""Match files Laravel discovers in supported registered directories."""
path = PurePosixPath(value)
parts = path.parts
application = len(parts) == 3 and parts[:2] == ("database", "migrations")
module = (
len(parts) == 5 and parts[0].lower() == "modules"
and tuple(part.lower() for part in parts[2:4]) == ("database", "migrations")
)
return (application or module) and "_" in path.stem and path.suffix == ".php"
def validate_migration_path(value, *, modular=False): def validate_migration_path(value, *, modular=False):
require( require(
@@ -82,8 +70,17 @@ def validate_migration_path(value, *, modular=False):
and path.as_posix() == value and path.as_posix() == value
and ".." not in path.parts and ".." not in path.parts
and len(path.parts) >= 3 and len(path.parts) >= 3
and (is_laravel_migration_path(value) if modular and (
else path.parts[:2] == ("database", "migrations")) path.parts[:2] == ("database", "migrations")
or (
modular and len(path.parts) >= 5 and (
(path.parts[0] == "Modules"
and path.parts[2:4] == ("Database", "Migrations"))
or (path.parts[0] == "modules"
and path.parts[2:4] == ("database", "migrations"))
)
)
)
and path.suffix == ".php" and path.suffix == ".php"
and all( and all(
re.fullmatch( re.fullmatch(
@@ -122,14 +119,9 @@ def validate_provenance(data):
"Invalid dependency inventory", "Invalid dependency inventory",
) )
basenames = set()
for name, digest in data["migrations"].items(): for name, digest in data["migrations"].items():
validate_migration_path(name, modular=version == 2) validate_migration_path(name, modular=version == 2)
if version == 2:
basename = PurePosixPath(name).stem
require(basename not in basenames, "Duplicate migration basename")
basenames.add(basename)
require( require(
valid_hash(digest, 64), valid_hash(digest, 64),
+8 -7
View File
@@ -5,9 +5,7 @@ import os
import stat import stat
from pathlib import Path from pathlib import Path
from core.compatibility import ( from core.compatibility import canonical_hash, provenance_fingerprint, validate_provenance
canonical_hash, is_laravel_migration_path, provenance_fingerprint, validate_provenance,
)
from core.provenance import ProvenanceVerifier, require from core.provenance import ProvenanceVerifier, require
@@ -60,10 +58,13 @@ class CompleteProvenance(ProvenanceVerifier):
expected = {**tracked, **self.generated, "REVISION": marker} expected = {**tracked, **self.generated, "REVISION": marker}
require(inventory(release) == expected, require(inventory(release) == expected,
"Full release tree differs from authorised source or generated artifacts") "Full release tree differs from authorised source or generated artifacts")
evidence["migrations"] = { for name, (digest, _) in tracked.items():
name: digest for name, (digest, _) in tracked.items() parts = Path(name).parts
if is_laravel_migration_path(name) if (len(parts) >= 5 and name.endswith(".php") and
} (parts[0], parts[2], parts[3]) in (
("Modules", "Database", "Migrations"), ("modules", "database", "migrations")
)):
evidence["migrations"][name] = digest
evidence.update(format_version=2, source_tree=canonical_hash(expected)) evidence.update(format_version=2, source_tree=canonical_hash(expected))
evidence["fingerprint"] = provenance_fingerprint(evidence) evidence["fingerprint"] = provenance_fingerprint(evidence)
validate_provenance(evidence) validate_provenance(evidence)
-47
View File
@@ -1,14 +1,10 @@
"""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,
@@ -86,46 +82,3 @@ 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"]))
-61
View File
@@ -1,61 +0,0 @@
"""Read site-scoped credentials from a trusted local provisioner."""
import os
import re
import stat
from pathlib import Path
from core.site_secrets import SiteSecretError, SiteSecrets
class FileSecretBackend:
"""A root-provisioned store with per-site OS group access."""
def __init__(self, directory, site, group):
self.directory = Path(directory)
if (not self.directory.is_absolute() or self.directory.resolve() != self.directory
or not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,62}", site)
or type(group) is not int or group <= 0):
raise SiteSecretError("Invalid file secret backend binding")
self.site = site
self.group = group
@staticmethod
def _require_metadata(descriptor, *, mode, group=None, directory=False):
info = os.fstat(descriptor)
valid_type = stat.S_ISDIR(info.st_mode) if directory else stat.S_ISREG(info.st_mode)
if (not valid_type or info.st_uid != 0 or stat.S_IMODE(info.st_mode) != mode
or (group is not None and info.st_gid != group)
or (not directory and info.st_nlink != 1)):
raise SiteSecretError("Unsafe file secret backend entry")
def read(self, filename):
if filename not in SiteSecrets.FILENAMES:
raise SiteSecretError("Unsupported credential filename")
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC
try:
root = os.open(self.directory, os.O_PATH | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC)
try:
self._require_metadata(root, mode=0o711, directory=True)
site = os.open(self.site, flags, dir_fd=root)
try:
self._require_metadata(site, mode=0o750, group=self.group, directory=True)
item = os.open(filename, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC
| os.O_NONBLOCK, dir_fd=site)
with os.fdopen(item, "rb") as source:
self._require_metadata(source.fileno(), mode=0o440, group=self.group)
data = source.read(65537)
finally:
os.close(site)
finally:
os.close(root)
except OSError:
raise SiteSecretError("Unable to read managed backend credential") from None
if not 0 < len(data) <= 65536:
raise SiteSecretError("Invalid backend credential size")
return data
def deliver(self, delivery, service, filename):
if not isinstance(delivery, SiteSecrets) or delivery.site != self.site:
raise SiteSecretError("Backend and delivery must bind the same site")
delivery.rotate(service, filename, self.read(filename))
+2 -28
View File
@@ -4,14 +4,12 @@ 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
from pathlib import Path, PurePosixPath from pathlib import Path, PurePosixPath
from core.backup import sync_directory from core.backup import sync_directory
from core.site_secrets import SiteSecrets
from core.configuration import ( from core.configuration import (
ConfigurationError, ConfigurationError,
@@ -36,9 +34,6 @@ class ServiceLifecycle:
config, config,
runner, runner,
stop_timeout=90, stop_timeout=90,
*,
site_secrets=None,
topology_runner=None,
): ):
require( require(
@@ -79,17 +74,11 @@ class ServiceLifecycle:
str(root / "compose.yaml"), str(root / "compose.yaml"),
) )
if site_secrets is not None:
require(isinstance(site_secrets, SiteSecrets), "Invalid managed site secrets")
self._prefix += ("--file", str(site_secrets.compose_file(validated)))
self._php = docker["php_service"] self._php = docker["php_service"]
self._web = docker["web_service"] self._web = docker["web_service"]
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
@@ -118,18 +107,6 @@ 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(
@@ -146,7 +123,6 @@ class ServiceLifecycle:
def restart_php(self): def restart_php(self):
self._require_project_backend()
self._execute( self._execute(
"restart PHP", "restart PHP",
( (
@@ -198,7 +174,6 @@ class ServiceLifecycle:
def resume(self): def resume(self):
self._require_project_backend()
self._execute( self._execute(
"resume workers", "resume workers",
( (
@@ -221,9 +196,8 @@ 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, topology_runner=None): worker_running, stop_timeout=90):
super().__init__(config, runner, stop_timeout, site_secrets=site_secrets, super().__init__(config, runner, stop_timeout)
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)
-102
View File
@@ -1,102 +0,0 @@
"""Trusted per-site credential file delivery for Docker Compose services."""
import json
import os
import re
import stat
import tempfile
from pathlib import Path
from core.backup import sync_directory
from core.configuration import validate_config
class SiteSecretError(RuntimeError):
"""Invalid or unsafe site secret configuration."""
class SiteSecrets:
"""Manage one credential bundle per explicitly configured Compose service."""
FILENAMES = frozenset({"absdev-client.cnf", "absdev-pgpass"})
def __init__(self, config, directory, consumers):
config = validate_config(config)
self.site = config["site"]["identifier"]
self.project = config["docker"]["project"]
self.project_root = config["site"]["root"]
self.directory = Path(directory)
self.uid = os.geteuid()
self.consumers = dict(consumers)
if not self.consumers or any(
not isinstance(service, str) or not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_-]*", service)
or type(uid) is not int or uid <= 0
for service, uid in self.consumers.items()
):
raise SiteSecretError("Compose consumers require valid service names and non-root UIDs")
self._check_directory(self.directory, 0o700)
self.site_directory = self.directory / self.site
self._ensure_directory(self.site_directory, 0o700)
def _check_directory(self, path, mode):
info = path.lstat()
if (path.resolve() != path or not stat.S_ISDIR(info.st_mode)
or info.st_uid != self.uid or stat.S_IMODE(info.st_mode) != mode):
raise SiteSecretError("Unsafe managed secret directory")
def _ensure_directory(self, path, mode):
try:
path.mkdir(mode=mode)
except FileExistsError:
pass
else:
# Explicit mode remains correct under a restrictive operator umask.
path.chmod(mode)
sync_directory(path.parent)
self._check_directory(path, mode)
def _service_directory(self, service):
self._check_directory(self.directory, 0o700)
self._check_directory(self.site_directory, 0o700)
path = self.site_directory / service
self._ensure_directory(path, 0o711)
return path
@staticmethod
def _replace(path, data, owner=None):
with tempfile.NamedTemporaryFile(dir=path.parent, prefix=".pending-", delete=False) as handle:
temporary = Path(handle.name)
try:
# The unfinished file is visible only to the provisioning account.
handle.write(data)
handle.flush()
if owner is not None:
os.fchown(handle.fileno(), owner, -1)
os.fsync(handle.fileno())
os.replace(temporary, path)
sync_directory(path.parent)
finally:
temporary.unlink(missing_ok=True)
def rotate(self, service, filename, data):
if (service not in self.consumers or filename not in self.FILENAMES
or not isinstance(data, bytes) or not 0 < len(data) <= 65536):
raise SiteSecretError("Invalid managed credential")
path = self._service_directory(service) / filename
self._replace(path, data, self.consumers[service])
def compose_file(self, config):
if (config["site"]["identifier"], config["docker"]["project"], config["site"]["root"]) != (
self.site, self.project, self.project_root
):
raise SiteSecretError("Managed secrets are bound to a different site or Compose project")
services = {}
for service in self.consumers:
directory = self._service_directory(service)
services[service] = {"volumes": [{
"type": "bind", "source": str(directory), "target": "/run/secrets",
"read_only": True, "bind": {"create_host_path": False},
}]}
override = self.site_directory / "compose-secrets.json"
self._replace(override, json.dumps({"services": services}, sort_keys=True).encode())
return override
-44
View File
@@ -1,44 +0,0 @@
# Managed site secrets for Docker Compose
Create a canonical private directory owned by the trusted provisioning account
with mode 0700, outside all application source trees. Use a
`SiteSecrets(config, directory, consumers)` instance for the site and pass it
as `site_secrets` to `ServiceLifecycle` or `ContainedServiceLifecycle`.
The consumer mapping specifies Compose service names and their non-root
numeric UIDs. The provisioning process needs authority to assign those file
owners. The Compose project, base file and Docker daemon must be trusted.
Services must run without Docker access, privileged mode or extra host mounts
that bypass the per-site directory boundary.
Call `rotate(service, filename, data)` with the complete client credential file
as bytes from the trusted provisioning source. Supported filenames are
`absdev-client.cnf` and `absdev-pgpass`. Bind the matching service to the
database adapter's configured client container when using that adapter.
Credential bytes are stored in owner-only files. The Compose override contains
paths only and mounts each service's directory read-only at `/run/secrets`.
Keep that mount target reserved in the base Compose file. Unlisted services
receive no managed mount.
The containing directory stays mounted when the provisioner atomically
replaces a file. New reads observe the replacement. Use server-side password
rotation and reconnect clients for new authentication. Existing connections
and programs that cache credentials require their own cutover. This runtime
accepts credential material from a trusted caller and does not operate a
production secret backend. Production execution remains disabled.
## Local file backend
A trusted provisioner can use `FileSecretBackend(directory, site, group)`
and call `backend.deliver(site_secrets, service, filename)` to refresh the
runtime credential from the selected site. Place the store under
administrator-controlled ancestors. The root directory is root-owned mode
0711. Each site directory is root-owned mode 0750 with a dedicated site
group. Credential files are root-owned mode 0440 with that same group. Use
distinct groups for sites and grant each site identity only its own group.
The privileged provisioner is trusted across sites. Keep backend files out
of containers and use the read-only runtime mounts for delivery.
Publish replacements atomically in the backend, then trigger a fresh
delivery for the site. A failed backend read leaves the current delivery
unchanged. Any server-side update and client reconnect are managed by the
caller. Production execution remains disabled.
+5 -18
View File
@@ -1,8 +1,8 @@
# Local migration operator authorisation # Local migration operator authorisation
The supported development composition accepts a policy loader through The supported development composition accepts an `OperatorApprovalPolicy`
`SiteOperations(operator_policy=...)`. The loader must return a fresh through `SiteOperations(operator_policy=...)`. Configure the policy in trusted
`OperatorApprovalPolicy` on each call. Configure the policy in trusted runtime code with a one-to-one mapping from dedicated OS accounts to operator 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,20 +24,7 @@ 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
Use `FileOperatorAuthority(path, group=...)` for a local authority source. Place further execution when grants are revoked or changed. The approved account
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.
-8
View File
@@ -34,11 +34,3 @@ 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 @@
# ABSDEV-CI command environment and credential rotation
ABSDEV-CI qualified commit `a60a33012be7f5cfb7062c47f8706f9216f3405a`. All 16 qualification checks and 898 framework tests passed.
The command runner excludes ambient credentials and runtime overrides. Disposable MySQL and PostgreSQL clients authenticated using owner-only files. Missing, world-writable and retired credential files failed authentication. Atomic replacement restored authentication after server-side rotation. The qualification removed both containers and their disposable volumes.
Production execution remained disabled. This evidence covers the disposable credential-file workflow. Production secret delivery remains unqualified.
@@ -0,0 +1,8 @@
934a04b5d6ec9aa62cb991fb2f57256c439bac4b2ac110cabd524ad456e59491 ./capabilities-after.json
934a04b5d6ec9aa62cb991fb2f57256c439bac4b2ac110cabd524ad456e59491 ./capabilities-before.json
13929b9643b7138f61b0944e2a6cb18b3f19208e53c2f279dd63b2a06893d752 ./checks.jsonl
25c26158a66f1f284b83ec26de1a554fb10a7d8ee4e57a351e211a8313d484ed ./framework-ci.txt
9e5008fb18bbbe95a2c54b0dbb327bb57804ce2faf34863105ce8ab326f3a437 ./scope.txt
36e510bef6e2627c790206650688dc8148ecd486340a8a75e1aff439c22bd7cf probe.py
4ad1a4783d14024047ff7638ae1cba27a1aeec2bcf971d7387aa1728fc25548c run.sh
6c44598e7812f4bd454814cc863c20e676f5195bf1bd5347088255996fa4f0c7 README.md
@@ -0,0 +1,16 @@
{"engine": "framework", "result": "PASS", "check": "approved child receives fixed PATH and locale only"}
{"engine": "mysql", "result": "PASS", "check": "disposable container has no external network, host mounts or published ports"}
{"engine": "mysql", "result": "PASS", "check": "missing credential file rejects authentication without publishing output"}
{"engine": "mysql", "result": "PASS", "check": "adapter authenticates with mode 0600 credential file and unrelated UID cannot read it"}
{"engine": "mysql", "result": "PASS", "check": "database client rejects world-writable credential file"}
{"engine": "mysql", "result": "PASS", "check": "old credential file is rejected after server-side rotation"}
{"engine": "mysql", "result": "PASS", "check": "atomic credential replacement restores authentication"}
{"engine": "mysql", "result": "PASS", "check": "rolling file back to retired credential does not restore access"}
{"engine": "pgsql", "result": "PASS", "check": "disposable container has no external network, host mounts or published ports"}
{"engine": "pgsql", "result": "PASS", "check": "missing credential file rejects authentication without publishing output"}
{"engine": "pgsql", "result": "PASS", "check": "adapter authenticates with mode 0600 credential file and unrelated UID cannot read it"}
{"engine": "pgsql", "result": "PASS", "check": "database client rejects world-writable credential file"}
{"engine": "pgsql", "result": "PASS", "check": "old credential file is rejected after server-side rotation"}
{"engine": "pgsql", "result": "PASS", "check": "atomic credential replacement restores authentication"}
{"engine": "pgsql", "result": "PASS", "check": "rolling file back to retired credential does not restore access"}
{"engine": "framework", "result": "PASS", "check": "all disposable containers and their anonymous volumes removed"}
@@ -2,12 +2,12 @@
Python 3.14.4 Python 3.14.4
=== PYTHON SYNTAX VALIDATION === === PYTHON SYNTAX VALIDATION ===
PASS: 88 Python sources compiled PASS: 86 Python sources compiled
=== COMPLETE UNIT REGRESSION SUITE === === COMPLETE UNIT REGRESSION SUITE ===
........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................ ..................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
---------------------------------------------------------------------- ----------------------------------------------------------------------
Ran 904 tests in 17.685s Ran 898 tests in 18.400s
OK OK
@@ -0,0 +1,167 @@
import io
import json
import os
import secrets
import subprocess
import sys
import time
from pathlib import Path
from core.database import get_adapter
from core.execution import CommandRunner, ExecutionError
IMAGES = {
"mysql": "sha256:8c233bad33d520a7aae1c1e619c3a9775f4a1ba2d463d692fada04ec7f40be00",
"pgsql": "sha256:e742a2668255221388004f3a42b6150a2103f5054ab3a4a93ae9e4f01e551c35",
}
KEY_PATHS = {"mysql": "/run/secrets/absdev-client.cnf", "pgsql": "/run/secrets/absdev-pgpass"}
containers = []
event_count = 0
def docker(*args, input_data=None):
return subprocess.run(("docker", *args), input=input_data, capture_output=True,
text=True, timeout=120)
def good(*args, input_data=None):
result = docker(*args, input_data=input_data)
if result.returncode:
raise RuntimeError(f"Docker {args[0]} failed with status {result.returncode}")
return result.stdout.strip()
def record(engine, check):
global event_count
event_count += 1
print(json.dumps(dict(engine=engine, result="PASS", check=check)), flush=True)
def start(engine):
name = "absdev-secret-" + engine + "-" + secrets.token_hex(5)
variable = "MYSQL_ROOT_PASSWORD" if engine == "mysql" else "POSTGRES_PASSWORD"
environment = Path.cwd().parent / (name + ".env")
environment.write_text(variable + "=" + secrets.token_hex(24) + "\n")
environment.chmod(0o600)
with environment.open("a") as handle:
if engine == "pgsql":
handle.write("POSTGRES_INITDB_ARGS=--auth-host=scram-sha-256\n")
try:
cid = good("create", "--pull", "never", "--name", name, "--network", "none",
"--security-opt", "no-new-privileges", "--cap-drop", "NET_RAW",
"--memory", "1g", "--pids-limit", "256", "--env-file", str(environment),
IMAGES[engine])
finally:
environment.unlink()
containers.append(cid)
good("start", cid)
details = json.loads(good("inspect", "--format", "{{json .HostConfig}}", cid))
assert details["NetworkMode"] == "none" and not details["Privileged"]
assert not details["PortBindings"] and not details["Binds"]
record(engine, "disposable container has no external network, host mounts or published ports")
return name, cid
def admin(engine, cid, sql):
if engine == "mysql":
return docker("exec", "-i", cid, "sh", "-c",
'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" exec mysql --no-defaults -uroot --batch',
input_data=sql)
return docker("exec", "-i", "--user", "postgres", cid, "psql", "-X", "-U", "postgres",
"-d", "postgres", "-v", "ON_ERROR_STOP=1", input_data=sql)
def ready(engine, cid):
for _ in range(90):
if engine == "pgsql":
status = docker("exec", cid, "pg_isready", "-h", "127.0.0.1", "-U", "postgres")
if status.returncode:
time.sleep(1)
continue
else:
status = docker("exec", cid, "sh", "-c",
'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" mysql --no-defaults --protocol=TCP -h127.0.0.1 -uroot -e "SELECT 1"')
if status.returncode:
time.sleep(1)
continue
if admin(engine, cid, "SELECT 1;").returncode == 0:
return
time.sleep(1)
raise RuntimeError(f"{engine} did not become ready")
def write_key(engine, cid, password):
path = KEY_PATHS[engine]
data = ("[client]\npassword=" + password + "\n" if engine == "mysql"
else "127.0.0.1:5432:fixture:fixture:" + password + "\n")
good("exec", "-i", cid, "sh", "-ceu",
'mkdir -p /run/secrets; umask 077; tmp=$(mktemp "$1.XXXXXX"); cat > "$tmp"; mv -f "$tmp" "$1"',
"sh", path, input_data=data)
assert good("exec", cid, "stat", "-c", "%a:%u", path) == "600:0"
def check_command(runner, command, success):
output = io.BytesIO()
try:
runner(command, output)
except ExecutionError:
assert not success and not output.getvalue()
else:
assert success and output.getvalue().strip() == b"1"
def qualify(engine):
name, cid = start(engine)
ready(engine, cid)
original, rotated = secrets.token_hex(24), secrets.token_hex(24)
if engine == "mysql":
setup = ("CREATE DATABASE fixture; "
f"CREATE USER 'fixture'@'127.0.0.1' IDENTIFIED BY '{original}'; "
"GRANT SELECT ON fixture.* TO 'fixture'@'127.0.0.1';")
change = f"ALTER USER 'fixture'@'127.0.0.1' IDENTIFIED BY '{rotated}';"
else:
setup = f"CREATE ROLE fixture LOGIN PASSWORD '{original}';\nCREATE DATABASE fixture OWNER fixture;"
change = f"ALTER ROLE fixture PASSWORD '{rotated}';"
assert admin(engine, cid, setup).returncode == 0, f"{engine} fixture setup failed"
config = json.loads(Path("config/site.example.json").read_text())
config["database"].update(driver=engine, container=name, host="127.0.0.1",
port=3306 if engine == "mysql" else 5432,
name="fixture", username="fixture")
command = get_adapter(config).ping_command()
assert not any(value in arg for arg in command for value in (original, rotated))
runner = CommandRunner([command], timeout=15)
check_command(runner, command, False)
record(engine, "missing credential file rejects authentication without publishing output")
write_key(engine, cid, original)
path = KEY_PATHS[engine]
assert docker("exec", "--user", "65534:65534", cid, "cat", path).returncode != 0
check_command(runner, command, True)
record(engine, "adapter authenticates with mode 0600 credential file and unrelated UID cannot read it")
good("exec", cid, "chmod", "0666", path)
check_command(runner, command, False)
record(engine, "database client rejects world-writable credential file")
good("exec", cid, "chmod", "0600", path)
assert admin(engine, cid, change).returncode == 0, f"{engine} password rotation failed"
check_command(runner, command, False)
record(engine, "old credential file is rejected after server-side rotation")
write_key(engine, cid, rotated)
check_command(runner, command, True)
record(engine, "atomic credential replacement restores authentication")
write_key(engine, cid, original)
check_command(runner, command, False)
record(engine, "rolling file back to retired credential does not restore access")
try:
os.environ.update(PATH="/untrusted", ABSDEV_TEST_SECRET="synthetic", DOCKER_HOST="synthetic",
PGPASSWORD="synthetic", MYSQL_PWD="synthetic")
argv = [sys.executable, "-I", "-c", "import json, os; print(json.dumps(dict(os.environ)))"]
output = io.BytesIO()
CommandRunner([argv])(argv, output)
assert json.loads(output.getvalue()) == {"PATH": os.defpath, "LC_ALL": "C"}
record("framework", "approved child receives fixed PATH and locale only")
# The qualification controller needs its own trusted Docker environment.
for name in ("ABSDEV_TEST_SECRET", "DOCKER_HOST", "PGPASSWORD", "MYSQL_PWD"):
os.environ.pop(name)
os.environ["PATH"] = os.defpath
for engine in IMAGES:
qualify(engine)
finally:
cleanup_failed = False
for cid in reversed(containers):
command = docker("rm", "-fv", cid)
if command.returncode:
cleanup_failed = True
if cleanup_failed:
raise RuntimeError("Disposable container cleanup failed")
record("framework", "all disposable containers and their anonymous volumes removed")
@@ -1,17 +1,17 @@
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-modular-fix.XXXXXX) stage=$(mktemp -d /var/tmp/absdev-secret-fix.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"
cd "$stage/source" cd "$stage/source"
export TMPDIR="$stage/tmp" export TMPDIR="$stage/tmp"
out="$stage/evidence" out="$stage/evidence"
printf 'host=%s\nrevision=5d3ea0d536ee00e4b235f3a195ea39aaf3224b47\n' "$(hostname -s)" > "$out/scope.txt" printf 'host=%s\nrevision=a60a33012be7f5cfb7062c47f8706f9216f3405a\n' "$(hostname -s)" > "$out/scope.txt"
python3 -B bin/absdev-deploy capabilities > "$out/capabilities-before.json" python3 -B bin/absdev-deploy capabilities > "$out/capabilities-before.json"
python3 -B -c 'import json,sys; d=json.load(open(sys.argv[1])); f=[v for k,v in d.items() if k.endswith("_enabled") or k=="production_ready"]; assert len(f)==6 and all(v is False for v in f)' "$out/capabilities-before.json" python3 -B -c 'import json,sys; d=json.load(open(sys.argv[1])); f=[v for k,v in d.items() if k.endswith("_enabled") or k=="production_ready"]; assert len(f)==6 and all(v is False for v in f)' "$out/capabilities-before.json"
python3 -B probe.py > "$out/laravel-inventory.json" || { cat "$out/laravel-inventory.json" >&2; exit 1; } python3 -B probe.py > "$out/checks.jsonl" || { cat "$out/checks.jsonl" >&2; exit 1; }
bash scripts/ci-check.sh > "$out/framework-ci.txt" 2>&1 || { tail -80 "$out/framework-ci.txt" >&2; exit 1; } bash scripts/ci-check.sh > "$out/framework-ci.txt" 2>&1 || { tail -80 "$out/framework-ci.txt" >&2; exit 1; }
python3 -B bin/absdev-deploy capabilities > "$out/capabilities-after.json" python3 -B bin/absdev-deploy capabilities > "$out/capabilities-after.json"
cmp "$out/capabilities-before.json" "$out/capabilities-after.json" cmp "$out/capabilities-before.json" "$out/capabilities-after.json"
@@ -0,0 +1,2 @@
host=absdev-ci
revision=a60a33012be7f5cfb7062c47f8706f9216f3405a
@@ -1,8 +0,0 @@
934a04b5d6ec9aa62cb991fb2f57256c439bac4b2ac110cabd524ad456e59491 ./capabilities-after.json
934a04b5d6ec9aa62cb991fb2f57256c439bac4b2ac110cabd524ad456e59491 ./capabilities-before.json
bc04e0a24a001d2ef37d4094f5528b70b244ea8fa4261e3ba5d9f43ad8d00b14 ./framework-ci.txt
4afcae0a0d3824b06cbbc2762d974c26b5b18df0c3a3c90956c177c594c32d48 ./laravel-inventory.json
4e788c450803b53914390e85812231c5c1405d6ccd69a2f5aba4910068426c0f ./scope.txt
54f8a44945572514c3c6416c4a09aa0297adca7da2296dfe5bb27a8161642683 run.sh
dc8cd7dc91e7bd20c766c5c7e6613aec2cdf4e2eae3d899d77a1118eb77d7a9f probe.py
41b745079ac469f8134f3f010a457bc689dbac0750fcf3426a23199b693f0ec1 inventory.php
@@ -1,16 +0,0 @@
<?php
require '/deps/vendor/autoload.php';
use Illuminate\Database\Migrations\Migrator;
use Illuminate\Filesystem\Filesystem;
$reflection = new ReflectionClass(Migrator::class);
$migrator = $reflection->newInstanceWithoutConstructor();
$reflection->getProperty('files')->setValue($migrator, new Filesystem());
$paths = array_map(fn ($path) => '/release/'.$path, array_slice($argv, 1));
$files = $migrator->getMigrationFiles($paths);
$relative = array_map(fn ($file) => substr($file, strlen('/release/')), $files);
echo json_encode([
'version' => Composer\InstalledVersions::getPrettyVersion('laravel/framework'),
'migrations' => $relative,
], JSON_THROW_ON_ERROR);
@@ -1,23 +0,0 @@
{
"host": "ABSDEV-CI",
"laravel_version": "v13.44.1",
"laravel_inventory": {
"0001_create_users": "database/migrations/0001_create_users.php",
"0002_create_orders": "database/migrations/0002_create_orders.php",
"0003_add_order_details": "Modules/Orders/Database/Migrations/0003_add_order_details.php",
"0004_add_product_details": "modules/products/database/migrations/0004_add_product_details.php",
"0005_add_billing_details": "Modules/Billing/database/Migrations/0005_add_billing_details.php"
},
"framework_inventory": {
"Modules/Billing/database/Migrations/0005_add_billing_details.php": "7492c4624ace05175e795841a2a1f9d91e46af66f0d0b6f5990387b4da32a756",
"Modules/Orders/Database/Migrations/0003_add_order_details.php": "7492c4624ace05175e795841a2a1f9d91e46af66f0d0b6f5990387b4da32a756",
"database/migrations/0001_create_users.php": "6b1c4722e1ab3ac3588b0a75a4a29e0a29da049e0db7feaf92d1405a7569b18d",
"database/migrations/0002_create_orders.php": "098b1d49c2865a6c7dc1a918821404abd5acedc013482572a2b764147f56051f",
"modules/products/database/migrations/0004_add_product_details.php": "7492c4624ace05175e795841a2a1f9d91e46af66f0d0b6f5990387b4da32a756"
},
"mixed_case_and_standard_paths_match_laravel": true,
"nonmatching_and_nested_files_excluded": true,
"laravel_collision_collapses_to_one_basename": true,
"framework_rejected_duplicate_basename": true,
"migrations_executed": false
}
@@ -1,87 +0,0 @@
import hashlib
import json
import subprocess
import sys
from pathlib import Path
sys.path.insert(0, str(Path("tests/unit").resolve()))
from test_provenance import ProvenanceTests
from core.compatibility import CompatibilityError
from core.dev3.provenance import CompleteProvenance
IMAGE = "sha256:cac70f6c4aa761a1c04c6813c03a7678b9a5c061cc67a413a12736253e7128ee"
DEPS = "/var/tmp/absdev-dev3-ci.8yBxcV/public-fixture"
DIRS = [
"database/migrations",
"Modules/Orders/Database/Migrations",
"modules/products/database/migrations",
"Modules/Billing/database/Migrations",
]
fixture = ProvenanceTests()
def write(path):
for root in (fixture.repository, fixture.release):
entry = root / path
entry.parent.mkdir(parents=True, exist_ok=True)
entry.write_text("<?php // disposable migration inventory fixture\n")
def commit():
fixture.git("add", ".")
fixture.git("commit", "-qm", "Update disposable Laravel fixture")
revision = fixture.git("rev-parse", "HEAD").strip()
(fixture.release / "REVISION").write_text(revision + "\n")
return CompleteProvenance(fixture.repository, [revision], {})
def laravel_inventory():
result = subprocess.run([
"docker", "run", "--rm", "--pull", "never", "--network", "none",
"--read-only", "--cap-drop", "ALL", "--cap-add", "DAC_OVERRIDE", "--security-opt", "no-new-privileges",
"-v", f"{DEPS}:/deps:ro", "-v", f"{fixture.release}:/release:ro",
"-v", f"{Path('inventory.php').resolve()}:/fixture.php:ro",
"--entrypoint", "php", IMAGE, "/fixture.php", *DIRS,
], timeout=60, capture_output=True)
if result.returncode:
raise RuntimeError((result.stdout + result.stderr).decode(errors="replace")[:1500])
return json.loads(result.stdout)
try:
fixture.setUp()
declared = [
DIRS[1] + "/0003_add_order_details.php",
DIRS[2] + "/0004_add_product_details.php",
DIRS[3] + "/0005_add_billing_details.php",
]
ignored = [DIRS[3] + "/README.php", DIRS[3] + "/nested/0006_ignored.php",
DIRS[0] + "/nested/0007_ignored.php"]
for path in declared + ignored:
write(path)
provenance = commit().verify(fixture.release)["migrations"]
observed = laravel_inventory()
expected = {path: hashlib.sha256((fixture.release / path).read_bytes()).hexdigest()
for path in observed["migrations"].values()}
assert provenance == expected and set(declared) <= set(expected)
assert not set(ignored) & set(expected)
duplicate = DIRS[3] + "/0003_add_order_details.php"
write(duplicate)
collision = commit()
overwritten = laravel_inventory()
assert overwritten["migrations"]["0003_add_order_details"] == duplicate
try:
collision.verify(fixture.release)
except CompatibilityError as error:
assert "Duplicate migration basename" in str(error)
else:
raise AssertionError("Duplicate migration accepted")
print(json.dumps({
"host": "ABSDEV-CI",
"laravel_version": observed["version"],
"laravel_inventory": observed["migrations"],
"framework_inventory": provenance,
"mixed_case_and_standard_paths_match_laravel": True,
"nonmatching_and_nested_files_excluded": True,
"laravel_collision_collapses_to_one_basename": True,
"framework_rejected_duplicate_basename": True,
"migrations_executed": False,
}, indent=2))
finally:
fixture.doCleanups()
@@ -1,2 +0,0 @@
host=absdev-ci
revision=5d3ea0d536ee00e4b235f3a195ea39aaf3224b47
+5 -26
View File
@@ -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=lambda: self.policy) self.store = ApprovalStore(self.root, operator_policy=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=lambda: self.policy) self.store = ApprovalStore(self.root, operator_policy=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 loader required"): with self.assertRaisesRegex(ApprovalStoreError, "policy 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.policy = OperatorApprovalPolicy(other_account, sealing_key=self.key) self.store.operator_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.policy = OperatorApprovalPolicy([grant], sealing_key=self.key) self.store.operator_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,26 +522,5 @@ 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()
-3
View File
@@ -24,9 +24,6 @@ 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):
-18
View File
@@ -20,21 +20,3 @@ class InventoryTests(unittest.TestCase):
(root / "link").symlink_to(script) (root / "link").symlink_to(script)
with self.assertRaises(ProvenanceError): with self.assertRaises(ProvenanceError):
inventory(root) inventory(root)
class LaravelMigrationPathTests(unittest.TestCase):
def test_inventory_matches_registered_directory_globs(self):
from core.compatibility import is_laravel_migration_path
for path in (
"Modules/Billing/database/Migrations/0001_add_invoice.php",
"modules/Orders/Database/migrations/0002_add_order.php",
"database/migrations/0003_add_user.php",
):
self.assertTrue(is_laravel_migration_path(path), path)
for path in (
"Modules/Billing/database/Migrations/nested/0001_add_invoice.php",
"database/migrations/README.php",
"database/migrations/nested/0003_add_user.php",
):
self.assertFalse(is_laravel_migration_path(path), path)
+2 -2
View File
@@ -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=lambda: self.fixture.policy) self.ops = SiteOperations(self.fixture.root, operator_policy=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.policy = OperatorApprovalPolicy( self.fixture.store.operator_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):
-27
View File
@@ -19,14 +19,10 @@ 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 = [
@@ -78,26 +74,6 @@ 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()
@@ -172,7 +148,6 @@ 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()
@@ -189,7 +164,6 @@ 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()
@@ -207,7 +181,6 @@ class ServiceTests(unittest.TestCase):
manager = ServiceLifecycle( manager = ServiceLifecycle(
self.config, self.config,
self.runner, self.runner,
topology_runner=self.topology,
) )
manager.quiesce() manager.quiesce()