Files
absdev-deployment/core/configuration.py
T
Mark Gregory a2ad086ccc
ABSDEV Framework CI / framework-ci (pull_request) Successful in 19s
Represent dedicated backend networks and inspection-only sites
2026-11-30 23:39:21 +00:00

457 lines
11 KiB
Python

"""Strict, non-secret deployment configuration validation."""
import copy
import json
import re
from pathlib import Path, PurePosixPath
class ConfigurationError(ValueError):
"""Invalid deployment configuration."""
def require(condition, message):
if not condition:
raise ConfigurationError(message)
def object_fields(value, fields, location):
require(
isinstance(value, dict),
f"{location} must be an object",
)
require(
set(value) == set(fields),
f"{location} contains missing or unknown fields",
)
def string_pattern(value, pattern, location):
require(
isinstance(value, str)
and re.fullmatch(pattern, value) is not None,
f"Invalid {location}",
)
def integer(value, minimum, maximum, location):
require(
type(value) is int
and minimum <= value <= maximum,
f"Invalid {location}",
)
def required_true(value, location):
require(
value is True,
f"{location} must be enabled",
)
def absolute_path(value, location):
require(
isinstance(value, str)
and re.fullmatch(
r"/[A-Za-z0-9._/-]+", value
) is not None,
f"Invalid {location}",
)
path = PurePosixPath(value)
require(
path.is_absolute()
and str(path) == value
and ".." not in path.parts
and value != "/",
f"Unsafe {location}",
)
def domain(value):
require(
isinstance(value, str)
and len(value) <= 253,
"Invalid site domain",
)
parts = value.split(".")
require(
len(parts) >= 2,
"Invalid site domain",
)
for part in parts:
string_pattern(
part,
r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",
"domain label",
)
def repository_url(value):
require(
isinstance(value, str),
"Invalid repository URL",
)
patterns = (
r"(?:[A-Za-z0-9_-]+@)?"
r"[A-Za-z0-9.-]+:"
r"[A-Za-z0-9_./-]+\.git",
r"https://[A-Za-z0-9.-]+"
r"(?::[0-9]+)?"
r"/[A-Za-z0-9_./-]+\.git",
r"ssh://(?:[A-Za-z0-9_-]+@)?"
r"[A-Za-z0-9.-]+"
r"(?::[0-9]+)?"
r"/[A-Za-z0-9_./-]+\.git",
)
require(
any(
re.fullmatch(pattern, value)
for pattern in patterns
)
and ".." not in value,
"Unsafe or unsupported repository URL",
)
def docker_workers(docker):
return tuple(docker[key] for key in ("queue_service", "scheduler_service") if docker[key] is not None)
def docker_backend_keys(docker):
if "private_backends" in docker:
return tuple(docker["private_backends"])
return (docker["backend_network"],)
def validate_config(data):
object_fields(
data,
{
"schema_version",
"site",
"repository",
"database",
"docker",
"retention",
"migration",
"backup",
"health",
},
"Configuration",
)
require(
type(data["schema_version"]) is int
and data["schema_version"] == 1,
"Unsupported configuration schema",
)
identifier = r"[a-z0-9][a-z0-9-]{0,62}"
service_name = r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}"
database_name = r"[A-Za-z_][A-Za-z0-9_]{0,62}"
site = data["site"]
require(isinstance(site, dict), "site must be an object")
site_fields = {"identifier", "domain", "root", "origin_port"}
if "checkout_layout" in site:
site_fields.add("checkout_layout")
require(site["checkout_layout"] == "in-place", "Unsupported checkout layout")
object_fields(site, site_fields, "site")
string_pattern(
site["identifier"], identifier, "site identifier"
)
domain(site["domain"])
absolute_path(site["root"], "site root")
integer(
site["origin_port"], 1024, 65535, "origin port"
)
repository = data["repository"]
object_fields(
repository,
{"url", "branch"},
"repository",
)
repository_url(repository["url"])
branch = repository["branch"]
string_pattern(
branch,
r"[A-Za-z0-9][A-Za-z0-9_./-]{0,127}",
"repository branch",
)
require(
".." not in branch
and all(
part
and not part.startswith(".")
and not part.endswith(".lock")
and not part.endswith(".")
for part in branch.split("/")
),
"Unsafe repository branch",
)
database = data["database"]
require(isinstance(database, dict), "database must be an object")
sqlite = database.get("driver") == "sqlite"
if sqlite:
object_fields(database, {"driver", "path"}, "database")
absolute_path(database["path"], "SQLite path")
require(site.get("checkout_layout") == "in-place", "SQLite requires the in-place inspection layout")
else:
require("checkout_layout" not in site, "In-place checkout requires SQLite")
object_fields(
database,
{
"driver",
"container",
"host",
"port",
"name",
"username",
},
"database",
)
require(
database["driver"] in ("mysql", "pgsql"),
"Unsupported database driver",
)
string_pattern(
database["container"],
service_name,
"database container",
)
string_pattern(
database["host"],
r"[A-Za-z0-9][A-Za-z0-9.-]{0,252}",
"database host",
)
string_pattern(
database["name"],
database_name,
"database name",
)
string_pattern(
database["username"],
database_name,
"database username",
)
integer(
database["port"], 1, 65535, "database port"
)
docker = data["docker"]
require(isinstance(docker, dict), "docker must be an object")
fields = {"project", "application_path", "php_service", "web_service",
"queue_service", "scheduler_service", "proxy_network"}
backend_field = "private_backends" if "private_backends" in docker else "backend_network"
optional = {"compose_override"} if "compose_override" in docker else set()
object_fields(docker, fields | {backend_field} | optional, "docker")
absolute_path(docker["application_path"], "container application path")
if sqlite:
require(PurePosixPath(database["path"]).is_relative_to(docker["application_path"]),
"SQLite path must be within the container application path")
require(backend_field == "private_backends" and docker["private_backends"] == {}
and not docker_workers(docker), "SQLite inspection must use site-local services")
for key in ("project", "php_service", "web_service", "proxy_network"):
string_pattern(docker[key], service_name, f"docker.{key}")
for worker in docker_workers(docker):
string_pattern(worker, service_name, "Docker worker service")
services = (docker["php_service"], docker["web_service"], *docker_workers(docker))
require(len(set(services)) == len(services), "Docker service names must be distinct")
if "compose_override" in docker:
string_pattern(docker["compose_override"], r"compose\.[a-z0-9-]+\.yaml", "Compose override filename")
if backend_field == "backend_network":
string_pattern(docker["backend_network"], service_name, "docker.backend_network")
else:
backends = docker["private_backends"]
require(isinstance(backends, dict) and (sqlite or 1 <= len(backends) <= 8), "Invalid private backend inventory")
for network, binding in backends.items():
string_pattern(network, service_name, "Compose backend network key")
object_fields(binding, {"name", "container"}, "private backend")
string_pattern(binding["name"], service_name, "private Docker network name")
string_pattern(binding["container"], service_name, "private backend container")
require(len({item["name"] for item in backends.values()}) == len(backends),
"Duplicate private Docker network name")
require(sqlite or any(item["container"] == database["container"] for item in backends.values()),
"The database container must have a declared private backend")
retention = data["retention"]
object_fields(
retention,
{"keep_releases", "automatic_deletion"},
"retention",
)
integer(
retention["keep_releases"],
1, 100,
"retention count",
)
require(
retention["automatic_deletion"] is False,
"Automatic destructive cleanup is prohibited",
)
migration = data["migration"]
object_fields(
migration,
{
"require_approval",
"require_rehearsal",
"approval_ttl_hours",
},
"migration",
)
required_true(
migration["require_approval"], "migration approval"
)
required_true(
migration["require_rehearsal"], "migration rehearsal"
)
integer(
migration["approval_ttl_hours"],
1, 72,
"migration approval TTL",
)
backup = data["backup"]
object_fields(
backup,
{"required", "verify_checksum"},
"backup",
)
required_true(backup["required"], "database backup")
required_true(
backup["verify_checksum"], "backup checksum"
)
health = data["health"]
object_fields(
health,
{"endpoints", "timeout_seconds"},
"health",
)
endpoints = health["endpoints"]
require(
isinstance(endpoints, list)
and 1 <= len(endpoints) <= 20,
"Invalid health endpoint list",
)
for endpoint in endpoints:
string_pattern(
endpoint,
r"/[A-Za-z0-9/_-]*",
"health endpoint",
)
require(
not endpoint.startswith("//"),
"External health endpoints are prohibited",
)
require(
len(set(endpoints)) == len(endpoints),
"Duplicate health endpoints",
)
integer(
health["timeout_seconds"],
1, 120,
"health timeout",
)
return copy.deepcopy(data)
def unique_json_object(pairs):
result = {}
for key, value in pairs:
require(
key not in result,
"Duplicate JSON configuration field",
)
result[key] = value
return result
def load_config(path):
try:
with Path(path).open(
"r", encoding="utf-8"
) as handle:
data = json.load(
handle,
object_pairs_hook=unique_json_object,
)
except (OSError, UnicodeError, ValueError) as error:
raise ConfigurationError(
"Unable to read valid configuration"
) from error
return validate_config(data)