From 7c43d31dc78756d66d0c9f3e7700962d95c98e58 Mon Sep 17 00:00:00 2001 From: Alexey Bodanyuk <144894236+wfa22@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:09:46 +0300 Subject: [PATCH] =?UTF-8?q?lab7:=20=D0=BB=D0=BE=D0=BA=D0=B0=D0=BB=D1=8C?= =?UTF-8?q?=D0=BD=D0=B0=D1=8F=20PKI=20(public-ca=20=D0=B4=D0=BB=D1=8F=20in?= =?UTF-8?q?gress,=20internal-ca=20=D0=B4=D0=BB=D1=8F=20=D1=81=D0=B5=D1=80?= =?UTF-8?q?=D0=B2=D0=B8=D1=81=D0=BE=D0=B2),=20HTTPS=20ingress=20=D0=BD?= =?UTF-8?q?=D0=B0=208443,=20=D0=B1=D0=B5=D0=B7=20=D0=BE=D1=82=D0=BA=D1=80?= =?UTF-8?q?=D1=8B=D1=82=D0=BE=D0=B3=D0=BE=208080?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- compose.yaml | 30 ++++--- infra/haproxy/haproxy.cfg | 10 ++- scripts/bg.ps1 | 11 +++ scripts/init_pki.py | 170 ++++++++++++++++++++++++++++++++++++++ scripts/init_secrets.py | 5 +- 5 files changed, 210 insertions(+), 16 deletions(-) create mode 100644 scripts/bg.ps1 create mode 100644 scripts/init_pki.py diff --git a/compose.yaml b/compose.yaml index f1e254b..00fff4f 100644 --- a/compose.yaml +++ b/compose.yaml @@ -21,7 +21,7 @@ # every service gets only the secrets it needs. Only the LB publishes ports (loopback only). # Networks: `edge` (lb <-> api); internal (no route outside): `data` (postgres/valkey), # `storage` (s3), `queue` (broker). The API is NOT on `queue`: it never talks to the broker. -name: mtusi-lab6 +name: ${COMPOSE_PROJECT_NAME:-mtusi-lab7} x-api-env: &api-env APP_ENV: ${APP_ENV:-lab} @@ -231,7 +231,7 @@ services: context: . args: BUILD_REVISION: ${BUILD_REVISION:-dev} - image: ${API_IMAGE:-mtusi-messenger:lab6} + image: ${API_IMAGE:-mtusi-messenger:lab7} command: ["python", "-m", "messenger.migrate"] environment: DATABASE_URL_FILE: /run/secrets/database_url @@ -250,7 +250,7 @@ services: # One-shot, idempotent S3 bootstrap: both buckets, sentinel object, verification of the access # model (private buckets, least-privilege keys). The ONLY holder of the admin key pair besides s3. s3-init: - image: ${API_IMAGE:-mtusi-messenger:lab6} + image: ${API_IMAGE:-mtusi-messenger:lab7} command: ["python", "-m", "messenger.s3_bootstrap"] environment: S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333} @@ -292,7 +292,7 @@ services: context: . args: BUILD_REVISION: ${BUILD_REVISION:-dev} - image: ${API_IMAGE:-mtusi-messenger:lab6} + image: ${API_IMAGE:-mtusi-messenger:lab7} environment: <<: [*api-env, *otel-env] OTEL_SERVICE_NAME: messenger-api @@ -340,13 +340,15 @@ services: image: haproxy:3.2.26-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122 volumes: - ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + secrets: + - source: pki_ingress_pem # public-ca leaf + key, SAN localhost/127.0.0.1/::1 + target: ingress.pem ports: - # The ONLY public entry point, on the loopback interfaces only. Both IPv4 and IPv6: + # The ONLY public entry point: HTTPS, on the loopback interfaces only. Both IPv4 and IPv6: # on Windows `localhost` resolves to ::1 first, and a refused ::1 connection costs ~2 s # per request before the fallback to 127.0.0.1 (measured in lab 3: 2.0 s vs 0.007 s). - - "127.0.0.1:${APP_PUBLISH_PORT:-8080}:8080" - - "[::1]:${APP_PUBLISH_PORT:-8080}:8080" - - "127.0.0.1:${LB_STATS_PORT:-8404}:8404" # local status page (UP/DOWN of replicas) + - "127.0.0.1:${APP_PUBLISH_PORT:-8443}:8443" + - "[::1]:${APP_PUBLISH_PORT:-8443}:8443" healthcheck: # Config is valid and the process answers; whether any API is ready is the LB's own job. test: ["CMD-SHELL", "haproxy -c -q -f /usr/local/etc/haproxy/haproxy.cfg && wget -q -O /dev/null http://127.0.0.1:8404/"] @@ -365,7 +367,7 @@ services: # Lab 5: outbox relay + lease reaper (src/messenger/relay.py). One process; a second one would # be safe (SKIP LOCKED) but is not needed. Database + broker only, no S3 keys. relay: - image: ${API_IMAGE:-mtusi-messenger:lab6} + image: ${API_IMAGE:-mtusi-messenger:lab7} command: ["python", "-m", "messenger.relay"] environment: <<: [*pipeline-env, *otel-env] @@ -399,7 +401,7 @@ services: # Lab 5: image worker (src/messenger/worker.py). Scalable (`--scale worker=2`): competing # consumers of one queue; the database lease decides who works on a job. worker: - image: ${API_IMAGE:-mtusi-messenger:lab6} + image: ${API_IMAGE:-mtusi-messenger:lab7} command: ["python", "-m", "messenger.worker"] environment: <<: [*pipeline-env, *otel-env] @@ -452,7 +454,7 @@ services: # S3 auditor key: Read + List, no Write). On demand: docker compose run --rm auditor auditor: profiles: ["tools"] - image: ${API_IMAGE:-mtusi-messenger:lab6} + image: ${API_IMAGE:-mtusi-messenger:lab7} entrypoint: ["python", "-m", "messenger.audit"] command: [] environment: @@ -487,7 +489,7 @@ services: # docker compose run --rm jobctl replay --operator alice --reason "..." jobctl: profiles: ["tools"] - image: ${API_IMAGE:-mtusi-messenger:lab6} + image: ${API_IMAGE:-mtusi-messenger:lab7} entrypoint: ["python", "-m", "messenger.jobctl"] command: [] environment: @@ -681,3 +683,7 @@ secrets: file: ./secrets/broker_url_worker grafana_admin_password: file: ./secrets/grafana_admin_password + # Lab 7 PKI (scripts/init_pki.py). Each service mounts only its own certificate/key and the CA it + # verifies peers with; the CA private keys are mounted nowhere. + pki_ingress_pem: + file: ./secrets/pki/ingress.pem diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg index 13172af..2e01763 100644 --- a/infra/haproxy/haproxy.cfg +++ b/infra/haproxy/haproxy.cfg @@ -74,7 +74,9 @@ defaults http-error status 504 content-type application/json lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"API-реплика не ответила вовремя; повторите с тем же Idempotency-Key\",\"request_id\":\"%[var(txn.request_id)]\"}}" hdr X-Request-Id "%[var(txn.request_id)]" frontend public - bind :8080 + # Lab 7: the ONLY public listener is HTTPS. Certificate of the public CA (SAN localhost, + # 127.0.0.1, ::1; scripts/init_pki.py), TLS 1.2+. There is no plaintext listener to fall back to. + bind :8443 ssl crt /run/secrets/ingress.pem ssl-min-ver TLSv1.2 alpn http/1.1 # One request id end to end: keep a valid client X-Request-Id, otherwise create one; the # API echoes it, and errors generated by the LB itself carry the same value. http-request set-header X-Request-Id %[uuid()] unless { req.hdr(x-request-id) -m reg ^[A-Za-z0-9._:-]{1,128}$ } @@ -107,9 +109,11 @@ backend api_core default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4 maxconn 200 server-template core 8 api:8080 -# Local-only status page (127.0.0.1:8404 on the host): which replica is UP/DOWN right now. +# Status page for the container healthcheck only: bound to the container's own loopback and NOT +# published (lab 7: only the TLS ingress leaves the host). Operators use the admin socket +# (`docker compose exec lb ...`, scripts/lbctl.py). frontend stats - bind :8404 + bind 127.0.0.1:8404 stats enable stats uri / stats refresh 2s diff --git a/scripts/bg.ps1 b/scripts/bg.ps1 new file mode 100644 index 0000000..d3ce819 --- /dev/null +++ b/scripts/bg.ps1 @@ -0,0 +1,11 @@ +# Run a long command as a separate Windows process that survives the calling shell/session. +# powershell -File scripts/bg.ps1 -Log evidence/run.log -Cmd "docker compose up -d --build --wait" +# The command runs in Git Bash (same syntax as the Makefile/hooks); the exit code is the last +# line of the log ("exit=N"). Nothing secret is printed by the commands used with it. +param([Parameter(Mandatory)][string]$Log, [Parameter(Mandatory)][string]$Cmd) +$bash = Join-Path $env:ProgramFiles "Git\bin\bash.exe" +$root = Split-Path -Parent $PSScriptRoot +$logPath = if ([IO.Path]::IsPathRooted($Log)) { $Log } else { Join-Path $root $Log } +New-Item -ItemType Directory -Force (Split-Path -Parent $logPath) | Out-Null +$inner = "cd '$($root -replace '\\','/')' && export PYTHONUTF8=1 && { $Cmd ; } > '$($logPath -replace '\\','/')' 2>&1; echo exit=`$? >> '$($logPath -replace '\\','/')'" +Start-Process -FilePath $bash -ArgumentList @('-lc', "`"$inner`"") -WindowStyle Hidden diff --git a/scripts/init_pki.py b/scripts/init_pki.py new file mode 100644 index 0000000..a9e5eab --- /dev/null +++ b/scripts/init_pki.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Local PKI of the lab 7 stand: two CAs and one leaf certificate per service, in ./secrets/pki. + + .venv/Scripts/python scripts/init_pki.py (also called by scripts/init_secrets.py) + +Needs the `cryptography` package (requirements-test.txt). Idempotent: existing files are kept, +so re-running never replaces a CA that already signed the running stand. Prints file names +only, never key material. ./secrets is git-ignored and docker-ignored; nothing here is committed +or baked into an image. Delete ./secrets/pki to start a new PKI (then recreate the containers). + +Two trust domains (contracts/trust-matrix.md): + public-ca signs ONLY what people connect to: the HTTPS ingress (HAProxy, :8443) and the + Grafana UI, SAN localhost / 127.0.0.1 / ::1. Its certificate is the CA_FILE of the + public tests; it may be given to anyone. It is trusted by NO service. + internal-ca signs the service identities. SAN = the compose service name (the DNS name the + peer dials), EKU serverAuth and/or clientAuth by role. Services trust only it. +The CA private keys (*-ca.key) are mounted into no container: only this script uses them. + +Test-only material (never trusted by the stand): `foreign-ca` and a client certificate signed by +it with the allowed SAN `lb` - proves that the right name from a wrong CA is refused. +""" +from __future__ import annotations + +import datetime as dt +import ipaddress +import os +import sys +from pathlib import Path + +try: + from cryptography import x509 + from cryptography.hazmat.primitives import hashes, serialization + from cryptography.hazmat.primitives.asymmetric import ec + from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID +except ImportError: # pragma: no cover - message for a missing venv + sys.exit("init_pki.py needs `cryptography`: python -m venv .venv && " + ".venv/Scripts/python -m pip install -r requirements-test.txt") + +ROOT = Path(__file__).resolve().parents[1] +PKI = ROOT / "secrets" / "pki" +CA_DAYS = 5 * 365 +LEAF_DAYS = 365 + +SERVER, CLIENT = ExtendedKeyUsageOID.SERVER_AUTH, ExtendedKeyUsageOID.CLIENT_AUTH +LOCAL = ["localhost", "127.0.0.1"] # only for services whose own healthcheck/CLI dials loopback over TLS +# name -> (CA, extra SANs besides the name itself, EKUs). The name is the identity: CN and SAN. +LEAVES = { + # Public trust domain: what the user's client verifies (hostname localhost, both loopbacks). + "ingress": ("public-ca", ["127.0.0.1", "::1"], [SERVER], "localhost"), + "grafana-ui": ("public-ca", ["127.0.0.1", "::1"], [SERVER], "localhost"), + # Internal trust domain. + "lb": ("internal-ca", [], [CLIENT], None), # client of every API replica + "api": ("internal-ca", [], [SERVER, CLIENT], None), # server for lb, client of collector + "relay": ("internal-ca", [], [CLIENT], None), + "worker": ("internal-ca", [], [CLIENT], None), + "postgres": ("internal-ca", LOCAL, [SERVER], None), + "valkey": ("internal-ca", LOCAL, [SERVER], None), + "s3": ("internal-ca", LOCAL, [SERVER], None), + "broker": ("internal-ca", LOCAL, [SERVER], None), + "otel-collector": ("internal-ca", [], [SERVER, CLIENT], None), # server for apps, client of backends + "prometheus": ("internal-ca", LOCAL, [SERVER, CLIENT], None), # client: scrapes loki/tempo + "loki": ("internal-ca", LOCAL, [SERVER], None), + "tempo": ("internal-ca", LOCAL, [SERVER], None), + "grafana": ("internal-ca", [], [CLIENT], None), # client of the three datasources + "openbao": ("internal-ca", LOCAL, [SERVER], None), + # Test only: right SAN, wrong CA. + "foreign-lb": ("foreign-ca", [], [CLIENT], "lb"), +} +CAS = {"public-ca": "MTUSI lab7 public CA", "internal-ca": "MTUSI lab7 internal CA", + "foreign-ca": "Foreign CA (test only, trusted by nobody)"} + + +def now() -> dt.datetime: + return dt.datetime.now(dt.timezone.utc) + + +def save(path: Path, data: bytes) -> None: + path.write_bytes(data) # bytes: PEM keeps LF on Windows too + # Readable by the unprivileged container users through the bind mount (postgres copies its + # key to a 0600 file at start). The folder ./secrets itself is 0700 for the host user. + os.chmod(path, 0o644) + print(f"created secrets/pki/{path.name}") + + +def pem_key(key) -> bytes: + return key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, + serialization.NoEncryption()) + + +def load(name: str): + cert = x509.load_pem_x509_certificate((PKI / f"{name}.crt").read_bytes()) + key = serialization.load_pem_private_key((PKI / f"{name}.key").read_bytes(), None) + return cert, key + + +def make_ca(name: str) -> None: + if (PKI / f"{name}.crt").exists(): + print(f"keep secrets/pki/{name}.crt") + return + key = ec.generate_private_key(ec.SECP256R1()) + subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, CAS[name])]) + cert = (x509.CertificateBuilder().subject_name(subject).issuer_name(subject) + .public_key(key.public_key()).serial_number(x509.random_serial_number()) + .not_valid_before(now() - dt.timedelta(minutes=5)).not_valid_after(now() + dt.timedelta(days=CA_DAYS)) + .add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True) + .add_extension(x509.KeyUsage(digital_signature=False, content_commitment=False, key_encipherment=False, + data_encipherment=False, key_agreement=False, key_cert_sign=True, + crl_sign=True, encipher_only=False, decipher_only=False), critical=True) + .add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False) + .sign(key, hashes.SHA256())) + save(PKI / f"{name}.key", pem_key(key)) + save(PKI / f"{name}.crt", cert.public_bytes(serialization.Encoding.PEM)) + + +def san_entry(value: str) -> x509.GeneralName: + try: + return x509.IPAddress(ipaddress.ip_address(value)) + except ValueError: + return x509.DNSName(value) + + +def make_leaf(name: str, ca_name: str, extra: list[str], ekus: list, dns_name: str | None) -> None: + if (PKI / f"{name}.crt").exists(): + print(f"keep secrets/pki/{name}.crt") + return + ca_cert, ca_key = load(ca_name) + identity = dns_name or name + key = ec.generate_private_key(ec.SECP256R1()) + sans = [san_entry(v) for v in dict.fromkeys([identity, *extra])] + cert = (x509.CertificateBuilder() + .subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, identity)])) + .issuer_name(ca_cert.subject).public_key(key.public_key()).serial_number(x509.random_serial_number()) + .not_valid_before(now() - dt.timedelta(minutes=5)).not_valid_after(now() + dt.timedelta(days=LEAF_DAYS)) + .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True) + .add_extension(x509.KeyUsage(digital_signature=True, content_commitment=False, key_encipherment=False, + data_encipherment=False, key_agreement=True, key_cert_sign=False, + crl_sign=False, encipher_only=False, decipher_only=False), critical=True) + .add_extension(x509.ExtendedKeyUsage(ekus), critical=False) + .add_extension(x509.SubjectAlternativeName(sans), critical=False) + .add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()), critical=False) + .sign(ca_key, hashes.SHA256())) + cert_pem = cert.public_bytes(serialization.Encoding.PEM) + save(PKI / f"{name}.key", pem_key(key)) + save(PKI / f"{name}.crt", cert_pem) + + +def bundle(name: str) -> None: + """HAProxy wants certificate + key in one PEM file.""" + target = PKI / f"{name}.pem" + if target.exists(): + print(f"keep secrets/pki/{target.name}") + return + save(target, (PKI / f"{name}.crt").read_bytes() + (PKI / f"{name}.key").read_bytes()) + + +def main() -> int: + PKI.mkdir(parents=True, exist_ok=True) + os.chmod(PKI.parent, 0o700) + for ca in CAS: + make_ca(ca) + for name, (ca, extra, ekus, dns_name) in LEAVES.items(): + make_leaf(name, ca, extra, ekus, dns_name) + bundle("ingress") # HAProxy :8443 server certificate + bundle("lb") # HAProxy client certificate towards the API replicas + print("CA_FILE for the public tests:", (PKI / "public-ca.crt").as_posix()) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/init_secrets.py b/scripts/init_secrets.py index eb7e13e..7605794 100644 --- a/scripts/init_secrets.py +++ b/scripts/init_secrets.py @@ -74,7 +74,10 @@ def main() -> int: write(f"broker_url_{who}", f"amqp://{who}:{read(f'rabbitmq_{who}_password')}@broker:5672/?heartbeat=10") # Lab 6: Grafana admin (UI on 127.0.0.1:3000 and the evidence scripts, via its datasource proxy). write("grafana_admin_password", secrets.token_urlsafe(18)) - return 0 + # Lab 7: local PKI (two CAs + service certificates) in ./secrets/pki. + sys.path.insert(0, str(Path(__file__).resolve().parent)) + import init_pki + return init_pki.main() if __name__ == "__main__":