forked from mtusi2026/mtusi2026lab7
feat: core func lab7
This commit is contained in:
@@ -0,0 +1,194 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Создаёт локальную PKI и bootstrap-данные сервисов."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SECRETS = ROOT / "secrets"
|
||||
OPERATOR = SECRETS / "operator"
|
||||
TLS = SECRETS / "tls"
|
||||
SERVERS = {
|
||||
"ingress": ("localhost", "nginx", "127.0.0.1"),
|
||||
"api-server": ("api", "api-short-ttl", "127.0.0.1"),
|
||||
"postgres": ("postgres",),
|
||||
"valkey": ("valkey",),
|
||||
"s3": ("s3",),
|
||||
"broker": ("broker",),
|
||||
"openbao": ("openbao", "localhost", "127.0.0.1"),
|
||||
"grafana-server": ("localhost", "grafana", "127.0.0.1"),
|
||||
"telemetry": ("otel-collector", "prometheus", "loki", "tempo"),
|
||||
}
|
||||
CLIENTS = (
|
||||
"lb", "health", "messenger_api", "messenger_worker", "messenger_dispatcher",
|
||||
"messenger_janitor", "messenger_owner", "collector", "prometheus",
|
||||
"grafana", "operator", "unauthorized",
|
||||
)
|
||||
S3_ROLES = ("bootstrap", "api", "worker", "janitor")
|
||||
|
||||
|
||||
def openssl(*args, capture=False):
|
||||
return subprocess.run(
|
||||
["openssl", *map(str, args)], check=True, stderr=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
|
||||
).stdout
|
||||
|
||||
|
||||
def write(path, content, mode=0o644):
|
||||
if path.is_file() and path.read_text() == content:
|
||||
path.chmod(mode)
|
||||
return
|
||||
temp = path.with_name(path.name + ".new")
|
||||
temp.write_text(content)
|
||||
temp.chmod(mode)
|
||||
temp.replace(path)
|
||||
|
||||
|
||||
def ca(directory, name):
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
cert = directory / "ca.crt"
|
||||
key = directory / "ca.key"
|
||||
if not cert.exists():
|
||||
config = directory / "openssl-ca.cnf"
|
||||
write(config, """[req]
|
||||
distinguished_name = subject
|
||||
x509_extensions = profile
|
||||
|
||||
[subject]
|
||||
|
||||
[profile]
|
||||
basicConstraints = critical,CA:TRUE,pathlen:0
|
||||
keyUsage = critical,keyCertSign,cRLSign
|
||||
subjectKeyIdentifier = hash
|
||||
authorityKeyIdentifier = keyid:always
|
||||
""", 0o600)
|
||||
try:
|
||||
openssl("req", "-x509", "-newkey", "rsa:3072", "-nodes", "-sha256",
|
||||
"-config", config, "-days", "365", "-subj", f"/CN={name}",
|
||||
"-keyout", key, "-out", cert)
|
||||
finally:
|
||||
config.unlink()
|
||||
elif b"CA:TRUE" not in openssl("x509", "-in", cert, "-noout", "-text", capture=True):
|
||||
raise RuntimeError("Локальный CA выпущен без basicConstraints CA:TRUE")
|
||||
return cert, key
|
||||
|
||||
|
||||
def issue(directory, identity, ca_files, addresses=(), renew=False):
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
directory.chmod(0o755)
|
||||
cert, key = directory / "tls.crt", directory / "tls.key"
|
||||
if cert.exists() and not renew:
|
||||
return
|
||||
san = ",".join(("IP:" if name == "127.0.0.1" else "DNS:") + name
|
||||
for name in (addresses or (identity,)))
|
||||
usage = "serverAuth" if addresses else "clientAuth"
|
||||
ext = directory / "extensions"
|
||||
write(ext, f"basicConstraints=critical,CA:FALSE\n"
|
||||
f"keyUsage=critical,digitalSignature,keyEncipherment\n"
|
||||
f"extendedKeyUsage={usage}\nsubjectAltName={san}\n")
|
||||
csr, next_cert, next_key = (directory / name for name in ("request.csr", "next.crt", "next.key"))
|
||||
try:
|
||||
openssl("req", "-new", "-newkey", "rsa:2048", "-nodes", "-subj",
|
||||
f"/CN={identity}", "-keyout", next_key, "-out", csr)
|
||||
openssl("x509", "-req", "-sha256", "-days", "30", "-in", csr,
|
||||
"-CA", ca_files[0], "-CAkey", ca_files[1], "-set_serial",
|
||||
"0x" + secrets.token_hex(16), "-extfile", ext, "-out", next_cert)
|
||||
for src, dst in ((next_cert, cert), (next_key, key)):
|
||||
src.chmod(0o644)
|
||||
src.replace(dst)
|
||||
finally:
|
||||
for path in (csr, next_cert, next_key, ext):
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def fingerprint(cert):
|
||||
return hashlib.sha256(openssl("x509", "-in", cert, "-outform", "DER", capture=True)).hexdigest()
|
||||
|
||||
|
||||
def initial_json(path, values):
|
||||
if path.is_file():
|
||||
return json.loads(path.read_text())
|
||||
data = {key: secrets.token_hex(size) for key, size in values.items()}
|
||||
write(path, json.dumps(data) + "\n", 0o600)
|
||||
return data
|
||||
|
||||
|
||||
def s3_configuration(bucket):
|
||||
identities = []
|
||||
for role in S3_ROLES:
|
||||
keys = initial_json(OPERATOR / f"s3-{role}.json", {"accessKey": 12, "secretKey": 24})
|
||||
if role == "bootstrap":
|
||||
actions = ["Admin"]
|
||||
for field, suffix in (("accessKey", "access_key_id"), ("secretKey", "secret_access_key")):
|
||||
write(SECRETS / f"s3_admin_{suffix}", keys[field])
|
||||
else:
|
||||
actions = {
|
||||
"api": [f"List:{bucket}", f"Read:{bucket}/originals/*", f"Write:{bucket}/staging/*"],
|
||||
"worker": [f"Read:{bucket}/staging/*", f"Write:{bucket}/originals/*"],
|
||||
"janitor": [f"List:{bucket}", f"Write:{bucket}/originals/*",
|
||||
f"Write:{bucket}/staging/*"],
|
||||
}[role]
|
||||
identities.append({"name": role, "credentials": [keys], "actions": actions})
|
||||
write(SECRETS / "s3_identities.json", json.dumps({"identities": identities}) + "\n")
|
||||
|
||||
|
||||
def grafana_provisioning(ca_cert):
|
||||
keypair = TLS / "grafana"
|
||||
text = (ROOT / "infra/grafana/provisioning/datasources/telemetry.yaml").read_text()
|
||||
for marker, path in (("@CA@", ca_cert), ("@CERT@", keypair / "tls.crt"),
|
||||
("@KEY@", keypair / "tls.key")):
|
||||
text = text.replace(marker, json.dumps(path.read_text()))
|
||||
directory = SECRETS / "grafana-datasources"
|
||||
directory.mkdir(exist_ok=True)
|
||||
directory.chmod(0o755)
|
||||
write(directory / "telemetry.yaml", text)
|
||||
|
||||
|
||||
def bootstrap():
|
||||
os.umask(0o077)
|
||||
SECRETS.mkdir(mode=0o700, exist_ok=True)
|
||||
SECRETS.chmod(0o700)
|
||||
OPERATOR.mkdir(mode=0o700, exist_ok=True)
|
||||
OPERATOR.chmod(0o700)
|
||||
TLS.mkdir(mode=0o755, exist_ok=True)
|
||||
public = ROOT / "certs"
|
||||
public.mkdir(mode=0o755, exist_ok=True)
|
||||
if not (ROOT / ".env").exists():
|
||||
shutil.copyfile(ROOT / ".env.example", ROOT / ".env")
|
||||
values = dict(line.split("=", 1) for line in (ROOT / ".env").read_text().splitlines()
|
||||
if line and not line.startswith("#") and "=" in line)
|
||||
ca_files = ca(OPERATOR, "Messenger lab7 local CA")
|
||||
foreign_ca = ca(OPERATOR / "foreign", "Messenger lab7 foreign CA")
|
||||
write(public / "ca.crt", ca_files[0].read_text())
|
||||
for identity, addresses in SERVERS.items():
|
||||
issue(TLS / identity, identity, ca_files, addresses)
|
||||
for identity in CLIENTS:
|
||||
issue(TLS / identity, identity, ca_files)
|
||||
issue(OPERATOR / "foreign-lb", "lb", foreign_ca)
|
||||
lb_pin = TLS / "api-server" / "lb-pins"
|
||||
if not lb_pin.exists():
|
||||
write(lb_pin, fingerprint(TLS / "lb" / "tls.crt") + "\n")
|
||||
telemetry = TLS / "telemetry"
|
||||
write(telemetry / "bundle.pem", (telemetry / "tls.crt").read_text() + (telemetry / "tls.key").read_text())
|
||||
s3_configuration(values.get("S3_BUCKET", "messenger-attachments"))
|
||||
cache = initial_json(OPERATOR / "valkey.json", {"password": 24})
|
||||
digest = hashlib.sha256(cache["password"].encode()).hexdigest()
|
||||
write(SECRETS / "valkey.acl", "user default off\n"
|
||||
f"user sessions on #{digest} ~session:* +get +set +del +ping +client|setinfo\n")
|
||||
password = initial_json(OPERATOR / "grafana.json", {"password": 24})
|
||||
write(SECRETS / "grafana_admin_password", password["password"] + "\n")
|
||||
grafana_provisioning(public / "ca.crt")
|
||||
print("Созданы локальная PKI и bootstrap-данные. CA: certs/ca.crt")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
bootstrap()
|
||||
except subprocess.CalledProcessError as error:
|
||||
sys.exit(f"OpenSSL: {error.stderr.decode().strip()}")
|
||||
Reference in New Issue
Block a user