103 lines
4.1 KiB
Python
103 lines
4.1 KiB
Python
"""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", "absdev-db-password", "absdev-redis-password"})
|
|
|
|
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
|