112 lines
5.8 KiB
Python
112 lines
5.8 KiB
Python
"""Generate private, run-owned TLS material and actual P07 node bundle schemas."""
|
|
import base64
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
|
|
from rig import atomic_write_secret
|
|
|
|
|
|
def _openssl(*arguments):
|
|
result = subprocess.run(["openssl", *map(str, arguments)], capture_output=True, timeout=30)
|
|
if result.returncode:
|
|
# Paths and private key material never enter diagnostic output.
|
|
raise RuntimeError("run-local certificate generation failed")
|
|
return result.stdout
|
|
|
|
|
|
def _validate_nodes(nodes):
|
|
"""Create a new restricted directory, cleaning partial output on failure.
|
|
|
|
`nodes` is keyed by Docker service DNS and contains the deployed owner,
|
|
authoritative scope generation and consumer-specific credential entries.
|
|
Secret values remain exclusively in restricted node bundle files.
|
|
"""
|
|
if not isinstance(nodes, dict) or not nodes:
|
|
raise ValueError("at least one explicit node is required")
|
|
for node, scope in nodes.items():
|
|
if not isinstance(node, str) or not re.fullmatch(r"[a-z][a-z0-9-]{0,62}", node):
|
|
raise ValueError("invalid local node identity")
|
|
if not isinstance(scope, dict) or not re.fullmatch(r"[A-Z][A-Z0-9_-]{0,63}", scope.get("owner", "")):
|
|
raise ValueError("invalid cluster identity")
|
|
if type(scope.get("scope_version")) is not int or scope["scope_version"] <= 0:
|
|
raise ValueError("a deployed scope generation is required")
|
|
entries = scope.get("entries")
|
|
if not isinstance(entries, list) or len(entries) > 256:
|
|
raise ValueError("invalid credential scope")
|
|
seen = set()
|
|
for entry in entries:
|
|
if not isinstance(entry, dict) or not isinstance(entry.get("ConnectionId"), str) or not entry["ConnectionId"].strip():
|
|
raise ValueError("invalid connection identity")
|
|
identity = entry["ConnectionId"].upper()
|
|
reference = entry.get("SecretReference", "")
|
|
if identity in seen or not re.fullmatch(r"secret:data/[a-z0-9][a-z0-9._/-]*", reference) or ".." in reference:
|
|
raise ValueError("invalid secret scope")
|
|
if type(entry.get("Deleted")) is not bool or (not entry["Deleted"] and (not isinstance(entry.get("Value"), str) or not entry["Value"])):
|
|
raise ValueError("fixture requires an explicit active credential or deletion marker")
|
|
seen.add(identity)
|
|
|
|
|
|
def provision_tls(destination, nodes):
|
|
"""Create CA and SAN server certificates before any deployment exists."""
|
|
destination = Path(destination)
|
|
if destination.exists():
|
|
raise FileExistsError("credential directory already exists")
|
|
if not nodes or any(not re.fullmatch(r"[a-z][a-z0-9-]{0,62}", node) for node in nodes):
|
|
raise ValueError("invalid local node identity")
|
|
destination.mkdir(mode=0o700)
|
|
try:
|
|
ca_key, ca = destination / "ca.key", destination / "ca.pem"
|
|
_openssl("req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes",
|
|
"-keyout", ca_key, "-out", ca, "-days", "2", "-subj", "/CN=grpc-data-local-run",
|
|
"-addext", "basicConstraints=critical,CA:TRUE", "-addext", "keyUsage=critical,keyCertSign,cRLSign")
|
|
for node in nodes:
|
|
tls = destination / "tls" / node
|
|
tls.mkdir(parents=True, mode=0o700)
|
|
extension = tls / "extensions.cnf"
|
|
atomic_write_secret(extension, f"subjectAltName=DNS:{node}\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=serverAuth\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid,issuer\n")
|
|
_openssl("req", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes",
|
|
"-keyout", tls / "server.key", "-out", tls / "request.pem", "-subj", f"/CN={node}")
|
|
_openssl("x509", "-req", "-in", tls / "request.pem", "-CA", ca, "-CAkey", ca_key,
|
|
"-set_serial", str(int.from_bytes(os.urandom(16), "big")), "-out", tls / "server.pem",
|
|
"-days", "2", "-extfile", extension)
|
|
(tls / "request.pem").unlink()
|
|
extension.unlink()
|
|
for path in destination.rglob("*"):
|
|
path.chmod(0o700 if path.is_dir() else 0o600)
|
|
except BaseException:
|
|
shutil.rmtree(destination)
|
|
raise
|
|
|
|
|
|
def write_bundles(destination, nodes):
|
|
"""Atomically publish bundles only for an authoritative deployed scope."""
|
|
_validate_nodes(nodes)
|
|
destination = Path(destination)
|
|
root_der = base64.b64encode(_openssl("x509", "-in", destination / "ca.pem", "-outform", "DER")).decode("ascii")
|
|
(destination / "credentials").mkdir(exist_ok=True, mode=0o700)
|
|
for node, scope in nodes.items():
|
|
bundle_path = destination / "credentials" / node
|
|
bundle_path.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
common = {"OwnerCluster": scope["owner"], "ConsumerNode": node + ":4053", "ScopeVersion": scope["scope_version"]}
|
|
atomic_write_secret(bundle_path / "bundle.json", json.dumps({**common, "Version": scope.get("bundle_version", 1), "Entries": scope["entries"]}))
|
|
atomic_write_secret(bundle_path / "trust.json", json.dumps({**common, "Entries": [
|
|
{"ConnectionId": entry["ConnectionId"], "Version": scope.get("trust_version", 1), "Roots": scope.get("trust_roots", [root_der])} for entry in scope["entries"]]}))
|
|
|
|
|
|
def provision(destination, nodes):
|
|
"""Compatibility helper for callers that already hold a deployed scope."""
|
|
destination = Path(destination)
|
|
if destination.exists():
|
|
raise FileExistsError("credential directory already exists")
|
|
_validate_nodes(nodes)
|
|
provision_tls(destination, nodes)
|
|
try:
|
|
write_bundles(destination, nodes)
|
|
except BaseException:
|
|
shutil.rmtree(destination)
|
|
raise
|