156 lines
6.4 KiB
Python
156 lines
6.4 KiB
Python
import base64
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import secrets
|
|
import shutil
|
|
import subprocess
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
LOCAL = ROOT / "secrets"
|
|
PKI = LOCAL / "pki"
|
|
BUCKET = "messenger-attachments"
|
|
|
|
|
|
def write(path, value):
|
|
if not path.exists():
|
|
path.write_bytes((value + "\n").encode("ascii"))
|
|
else:
|
|
content = path.read_bytes()
|
|
if b"\r\n" in content:
|
|
path.write_bytes(content.replace(b"\r\n", b"\n"))
|
|
if os.name != "nt":
|
|
path.chmod(0o644)
|
|
return path.read_text(encoding="ascii").strip()
|
|
|
|
|
|
def openssl(*args):
|
|
env = {**os.environ, "OPENSSL_CONF": str(PKI / "openssl.cnf")}
|
|
command = ["openssl", *map(str, args)]
|
|
result = subprocess.run(command, cwd=PKI, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
|
if result.returncode:
|
|
raise RuntimeError(result.stderr.decode(errors="replace").strip())
|
|
|
|
|
|
def authority(name):
|
|
cert, key = f"{name}.crt", f"{name}.key"
|
|
if not (PKI / cert).exists():
|
|
openssl("req", "-new", "-x509", "-newkey", "rsa:2048", "-nodes", "-sha256", "-days", 365,
|
|
"-subj", f"/CN=MTUSI Lab 7 {name}", "-addext", "basicConstraints=critical,CA:TRUE",
|
|
"-addext", "keyUsage=critical,keyCertSign,cRLSign",
|
|
"-addext", "subjectKeyIdentifier=hash", "-keyout", key, "-out", cert)
|
|
|
|
|
|
def certificate(name, san, usage, ca="ca"):
|
|
cert, key = PKI / f"{name}.crt", PKI / f"{name}.key"
|
|
if not cert.exists():
|
|
csr, extensions = f"{name}.csr", PKI / f"{name}.ext"
|
|
openssl("req", "-new", "-newkey", "rsa:2048", "-nodes", "-subj", f"/CN={name}",
|
|
"-keyout", key.name, "-out", csr)
|
|
extensions.write_text(
|
|
"basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\n"
|
|
"authorityKeyIdentifier=keyid:always\nsubjectKeyIdentifier=hash\n"
|
|
f"extendedKeyUsage={usage}\nsubjectAltName={san}\n",
|
|
encoding="ascii",
|
|
)
|
|
try:
|
|
openssl("x509", "-req", "-in", csr, "-CA", f"{ca}.crt", "-CAkey", f"{ca}.key",
|
|
"-set_serial", f"0x{secrets.token_hex(16)}", "-out", cert.name, "-days", 30,
|
|
"-sha256", "-extfile", extensions.name)
|
|
finally:
|
|
(PKI / csr).unlink(missing_ok=True)
|
|
extensions.unlink(missing_ok=True)
|
|
if os.name != "nt":
|
|
# Only the individual key file is mounted to its non-root container.
|
|
key.chmod(0o644)
|
|
|
|
|
|
def rabbit_definitions(credentials):
|
|
users, perms = [], []
|
|
for role, password in credentials.items():
|
|
salt = secrets.token_bytes(4)
|
|
password_hash = base64.b64encode(salt + hashlib.sha256(salt + password.encode()).digest()).decode()
|
|
users.append({"name": role, "password_hash": password_hash,
|
|
"hashing_algorithm": "rabbit_password_hashing_sha256", "tags": []})
|
|
perms.append({"user": role, "vhost": "/", "configure": "^$",
|
|
"write": "^amq\\.default$" if role == "dispatch" else "^$",
|
|
"read": "^attachment\\.process\\.v1$" if role == "worker" else "^$"})
|
|
return json.dumps({
|
|
"users": users, "vhosts": [{"name": "/"}], "permissions": perms, "exchanges": [], "bindings": [],
|
|
"queues": [{"name": "attachment.process.v1", "vhost": "/", "durable": True,
|
|
"auto_delete": False, "arguments": {}}],
|
|
})
|
|
|
|
|
|
def main():
|
|
if not (ROOT / ".env").exists():
|
|
shutil.copyfile(ROOT / ".env.example", ROOT / ".env")
|
|
for folder in (LOCAL, PKI):
|
|
folder.mkdir(mode=0o700, exist_ok=True)
|
|
if os.name != "nt":
|
|
folder.chmod(0o700)
|
|
write(PKI / "openssl.cnf", "[req]\ndistinguished_name = request_dn\n[request_dn]")
|
|
authority("ca")
|
|
authority("other-ca")
|
|
for name in ("api1", "api2", "db", "s3", "broker", "otel-collector", "openbao", "telemetry-edge", "localhost"):
|
|
san = f"DNS:{name}"
|
|
if name in ("openbao", "telemetry-edge"):
|
|
san += ",DNS:localhost"
|
|
certificate(name, san, "serverAuth")
|
|
for name in ("lb-ingress", "other-role", "api-bao", "worker-bao", "dispatch-bao"):
|
|
certificate(name, f"DNS:{name}", "clientAuth")
|
|
certificate("foreign-role", "DNS:lb-ingress", "clientAuth", "other-ca")
|
|
for name in ("localhost", "lb-ingress", "telemetry-edge"):
|
|
write(PKI / f"{name}.pem", (PKI / f"{name}.crt").read_text().strip() + "\n"
|
|
+ (PKI / f"{name}.key").read_text().strip())
|
|
if os.name != "nt":
|
|
for key in ("ca.key", "other-ca.key"):
|
|
(PKI / key).chmod(0o600)
|
|
|
|
def random(name):
|
|
return write(LOCAL / name, secrets.token_hex(24))
|
|
|
|
db_passwords = {role: random("db_" + role) for role in ("postgres", "owner", "api", "worker", "dispatch")}
|
|
database = {
|
|
role: f"postgresql://messenger_{role}:{db_passwords[role]}@db:5432/messenger"
|
|
"?sslmode=verify-full&sslrootcert=/run/tls/ca.crt"
|
|
for role in ("owner", "api", "worker", "dispatch")
|
|
}
|
|
write(LOCAL / "database_url", database["owner"])
|
|
write(LOCAL / "minio_root_user", "lab7-root")
|
|
random("minio_root_password")
|
|
random("grafana_password")
|
|
objects = {
|
|
role: {"S3_ACCESS_KEY_ID_FILE": f"lab7-{role}",
|
|
"S3_SECRET_ACCESS_KEY_FILE": random("s3_" + role)}
|
|
for role in ("api", "worker")
|
|
}
|
|
rabbit = {role: random("rabbit_" + role) for role in ("dispatch", "worker")}
|
|
write(LOCAL / "rabbit_definitions.json", rabbit_definitions(rabbit))
|
|
for name in ("otel_ingest", "otel_write", "grafana_read"):
|
|
token = random(name)
|
|
if name != "otel_ingest":
|
|
write(LOCAL / (name + "_header"), f"Bearer {token}")
|
|
ingest = (LOCAL / "otel_ingest").read_text().strip()
|
|
cursor = random("cursor_key")
|
|
for role in ("api", "worker", "dispatch"):
|
|
values = {"DATABASE_URL_FILE": database[role]}
|
|
if role in objects:
|
|
values.update(objects[role])
|
|
values["OTEL_INGEST_TOKEN"] = ingest
|
|
if role == "api":
|
|
values["CURSOR_SECRET_FILE"] = cursor
|
|
if role in rabbit:
|
|
values["BROKER_URL_FILE"] = f"amqps://{role}:{rabbit[role]}@broker:5671/%2F"
|
|
path = LOCAL / f"bao_{role}.json"
|
|
write(path, json.dumps(values))
|
|
if os.name != "nt":
|
|
path.chmod(0o600)
|
|
print("Сертификаты и локальные файлы стенда подготовлены.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|