From ea50b60f7fcca84ce03aa77021bca3858dd4e4f1 Mon Sep 17 00:00:00 2001 From: aegor Date: Mon, 30 Nov 2026 16:36:13 +0300 Subject: [PATCH] feat: add local pki, https ingress and api mtls --- Dockerfile | 3 - compose.yaml | 60 +++++++++++++-- infra/bootstrap.py | 106 ++++++++++++++++++++++++++ infra/haproxy/haproxy.cfg | 14 +++- scripts/check_mtls.py | 58 ++++++++++++++ src/common/interceptors/request-id.ts | 3 +- src/main.ts | 23 +++++- 7 files changed, 251 insertions(+), 16 deletions(-) create mode 100644 infra/bootstrap.py create mode 100644 scripts/check_mtls.py diff --git a/Dockerfile b/Dockerfile index 13d717b..a689593 100644 --- a/Dockerfile +++ b/Dockerfile @@ -39,7 +39,4 @@ COPY contracts/openapi.json ./contracts/openapi.json USER node EXPOSE 8080 -HEALTHCHECK --interval=5s --timeout=2s --start-period=5s --retries=3 \ - CMD node -e "require('http').get('http://127.0.0.1:8080/health/core',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))" - CMD ["node", "dist/main.js"] diff --git a/compose.yaml b/compose.yaml index 7459504..7eb258f 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,11 +1,33 @@ name: messenger-lab7 +x-lockdown: &lockdown + security_opt: [no-new-privileges:true] + cap_drop: [ALL] + x-otel: &otel OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318} OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab} services: + bootstrap: + build: + dockerfile_inline: | + FROM python:3.12.7-alpine + RUN apk add --no-cache openssl + ENTRYPOINT ["python", "/work/bootstrap.py"] + image: mtusi-messenger-lab7-bootstrap:dev + network_mode: none + security_opt: [no-new-privileges:true] + cap_drop: [ALL] + cap_add: [CHOWN, DAC_OVERRIDE, FOWNER] + volumes: + - ./infra/bootstrap.py:/work/bootstrap.py:ro + - pki:/state + deploy: + resources: + limits: {cpus: "1.0", memory: 96M} + secrets-init: image: alpine:3.20.3 volumes: @@ -177,12 +199,15 @@ services: OTEL_SERVICE_NAME: messenger-api volumes: - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: api } } + - { type: volume, source: pki, target: /run/tls, read_only: true, volume: { subpath: api } } deploy: replicas: ${API_REPLICAS:-2} resources: limits: { cpus: "0.5", memory: 256M } stop_grace_period: 10s depends_on: + bootstrap: + condition: service_completed_successfully migrate: condition: service_completed_successfully redis: @@ -308,18 +333,25 @@ services: restart: unless-stopped lb: + <<: *lockdown image: haproxy:3.0.6-alpine + user: "1000:1000" ports: - - "127.0.0.1:${APP_PORT:-8080}:8080" + - "127.0.0.1:${HTTPS_PORT:-8443}:8443" volumes: - ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + - {type: volume, source: pki, target: /run/tls, read_only: true, volume: {subpath: lb}} + healthcheck: + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8404/"] + interval: 3s + timeout: 2s + retries: 20 + depends_on: + api: {condition: service_started} + restart: unless-stopped deploy: resources: - limits: { cpus: "0.25", memory: 64M } - depends_on: - api: - condition: service_healthy - restart: unless-stopped + limits: {cpus: "0.25", memory: 96M} otel-collector: image: otel/opentelemetry-collector-contrib:0.115.1@sha256:d2da12c4336a79758826700be9e21ecf4a9f7d945b7f8a58ba55ee3fa45427c8 @@ -416,6 +448,21 @@ services: condition: service_started restart: unless-stopped + checks: + <<: *lockdown + profiles: [tools] + image: mtusi-messenger-lab7-bootstrap:dev + entrypoint: [python] + working_dir: /work + volumes: + - .:/work:ro + - {type: volume, source: pki, target: /run/tls, read_only: true, volume: {subpath: checks}} + depends_on: + bootstrap: {condition: service_completed_successfully} + deploy: + resources: + limits: {cpus: "0.5", memory: 128M} + volumes: pgdata: s3data: @@ -425,6 +472,7 @@ volumes: tempodata: grafanadata: secrets: + pki: networks: telemetry: diff --git a/infra/bootstrap.py b/infra/bootstrap.py new file mode 100644 index 0000000..b0cb7c3 --- /dev/null +++ b/infra/bootstrap.py @@ -0,0 +1,106 @@ +"""Generate local stand identities and credentials, once per secrets volume.""" + +import os +import secrets +import shutil +import subprocess +from pathlib import Path + +ROOT = Path("/state") +ROLES = {"api": 10, "worker": 5, "relay": 3, "reconciler": 2} + + +def openssl(*args): + subprocess.run(["openssl", *args], check=True, stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE) + + +def write(path, value): + path.write_text(value, encoding="utf-8") + + +def own(directory, uid): + for path in directory.iterdir(): + path.chmod(0o400) + os.chown(path, uid, -1) + os.chown(directory, uid, -1) + + +def ca(directory, name): + key, crt = directory / f"{name}.key", directory / f"{name}.crt" + openssl("req", "-new", "-newkey", "rsa:3072", "-nodes", "-x509", "-sha256", + "-days", "365", "-subj", f"/CN={name}", "-addext", + "basicConstraints=critical,CA:TRUE", "-addext", "keyUsage=critical,keyCertSign,cRLSign", + "-keyout", key, "-out", crt) + return key, crt + + +def leaf(directory, name, issuer, purpose="server", extra_san=""): + key, crt = directory / f"{name}.key", directory / f"{name}.crt" + csr, ext = directory / "request.csr", directory / "extensions.cnf" + openssl("req", "-new", "-newkey", "rsa:2048", "-nodes", "-subj", f"/CN={name}", + "-keyout", key, "-out", csr) + write(ext, "basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\n" + "subjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid\n" + f"extendedKeyUsage={purpose}Auth\nsubjectAltName=DNS:{name}{extra_san}\n") + openssl("x509", "-req", "-in", csr, "-out", crt, "-CA", issuer[1], "-CAkey", + issuer[0], "-set_serial", f"0x{secrets.token_hex(16)}", "-sha256", + "-days", "90", "-extfile", ext) + csr.unlink() + ext.unlink() + return key, crt + + +def copy_ca(directory, issuer): + shutil.copyfile(issuer[1], directory / "ca.crt") + + +def bundle(directory, name, pair): + write(directory / name, pair[1].read_text() + pair[0].read_text()) + + +def main(): + if (ROOT / "initialized").is_file(): + print("Local identities already initialized") + return + os.umask(0o077) + names = ("operator", "lb", "checks", *ROLES) + directories = {name: ROOT / name for name in names} + for directory in directories.values(): + directory.mkdir(exist_ok=True) + operator = directories["operator"] + server_ca = ca(operator, "lab7-servers") + client_ca = ca(operator, "lab7-clients") + for directory in directories.values(): + copy_ca(directory, server_ca) + + api = directories["api"] + lb = directories["lb"] + checks = directories["checks"] + leaf(api, "api", server_ca) + shutil.copyfile(client_ca[1], api / "clients.crt") + lb_client = leaf(lb, "lb.lab7.internal", client_ca, "client") + bundle(lb, "client.pem", lb_client) + for path in lb_client: + shutil.copyfile(path, checks / path.name) + bundle(lb, "ingress.pem", leaf(lb, "localhost", server_ca, extra_san=",IP:127.0.0.1")) + leaf(checks, "unrelated.lab7.internal", client_ca, "client") + foreign_ca = ca(operator, "lab7-untrusted") + foreign_dir = checks / "foreign" + foreign_dir.mkdir(exist_ok=True) + foreign = leaf(foreign_dir, "lb.lab7.internal", foreign_ca, "client") + for path in foreign: + path.rename(checks / f"foreign-{path.name}") + foreign_dir.rmdir() + shutil.copyfile(foreign_ca[1], checks / "foreign-ca.crt") + + shutil.copyfile(api / "api.crt", checks / "api.crt") + owners = {"lb": 1000, **dict.fromkeys(ROLES, 1000)} + for name, uid in owners.items(): + own(directories[name], uid) + (ROOT / "initialized").touch() + print("Generated local TLS identities and stand credentials") + + +if __name__ == "__main__": + main() diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg index 22e7790..4683a9b 100644 --- a/infra/haproxy/haproxy.cfg +++ b/infra/haproxy/haproxy.cfg @@ -1,11 +1,13 @@ global log stdout format raw local0 info maxconn 2000 + ssl-default-bind-options ssl-min-ver TLSv1.2 + ssl-default-server-options ssl-min-ver TLSv1.2 defaults mode http log global - option httplog + log-format "%ci:%cp %ft %b/%s %ST %Tt" option dontlognull timeout connect 1s timeout client 30s @@ -31,13 +33,19 @@ resolvers docker accepted_payload_size 8192 frontend public - bind :8080 + bind :8443 ssl crt /run/tls/ingress.pem default_backend api +frontend local-health + bind 127.0.0.1:8404 + no log + http-request return status 200 if { nbsrv(api) gt 0 } + http-request return status 503 + backend api balance roundrobin http-request set-timeout server 60s if { method POST } { path_reg ^/api/v1/chats/[^/]+/attachments$ } option httpchk GET /health/core http-check expect status 200 default-server check inter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none - server-template api 1-4 api:8080 + server-template api 1-4 api:8080 ssl ca-file /run/tls/ca.crt verify required verifyhost api sni str(api) check-sni api crt /run/tls/client.pem diff --git a/scripts/check_mtls.py b/scripts/check_mtls.py new file mode 100644 index 0000000..7b62bc3 --- /dev/null +++ b/scripts/check_mtls.py @@ -0,0 +1,58 @@ +"""Verify the lab ingress and all API replicas using local fixture identities.""" + +import socket +import ssl +from http.client import HTTPResponse, RemoteDisconnected +from pathlib import Path + +TLS = Path("/run/tls") + + +def context(identity=None, ca="ca.crt"): + result = ssl.create_default_context(cafile=str(TLS / ca)) + if identity: + result.load_cert_chain(TLS / (identity + ".crt"), TLS / (identity + ".key")) + return result + + +def get(address, port, name, tls): + with socket.create_connection((address, port), timeout=5) as connection: + with tls.wrap_socket(connection, server_hostname=name) as encrypted: + encrypted.sendall( + f"GET /health/live HTTP/1.1\r\nHost: {name}\r\nConnection: close\r\n\r\n".encode() + ) + with HTTPResponse(encrypted) as response: + response.begin() + return response.status, response.getheader("X-Instance-Id") + + +def rejected(address, port, name, tls): + try: + get(address, port, name, tls) + except (ssl.SSLError, RemoteDisconnected, ConnectionResetError, BrokenPipeError): + return + raise AssertionError("An untrusted TLS connection returned an HTTP response") + + +def main(): + assert get("lb", 8443, "localhost", context())[0] == 200 + rejected("lb", 8443, "localhost", context(ca="foreign-ca.crt")) + rejected("lb", 8443, "wrong.lab7.internal", context()) + print("PASS: ingress verified CA and SAN; foreign CA and mismatched hostname rejected") + replicas = {info[4][0] for info in socket.getaddrinfo("api", 8080, type=socket.SOCK_STREAM)} + assert len(replicas) >= 2, "Expected at least two independent replicas" + instances = set() + for address in sorted(replicas): + status, instance = get(address, 8080, "api", context("lb.lab7.internal")) + assert status == 200 and instance + rejected(address, 8080, "api", context()) + rejected(address, 8080, "api", context("foreign-lb.lab7.internal")) + rejected(address, 8080, "api", context("unrelated.lab7.internal")) + assert get(address, 8080, "api", context("lb.lab7.internal")) == (200, instance) + instances.add(instance) + print(f"PASS: {instance}: accepted LB, rejected missing cert, foreign CA and wrong signed SAN") + assert len(instances) == len(replicas) + + +if __name__ == "__main__": + main() diff --git a/src/common/interceptors/request-id.ts b/src/common/interceptors/request-id.ts index fc49470..9c05494 100644 --- a/src/common/interceptors/request-id.ts +++ b/src/common/interceptors/request-id.ts @@ -1,11 +1,10 @@ import { randomUUID } from 'crypto'; import { FastifyInstance, FastifyRequest } from 'fastify'; -import { hostname } from 'os'; const REQUEST_ID_HEADER = 'x-request-id'; const INSTANCE_ID_HEADER = 'x-instance-id'; -export const INSTANCE_ID = process.env.INSTANCE_ID ?? hostname(); +export const INSTANCE_ID = process.env.INSTANCE_ID ?? randomUUID(); declare module 'fastify' { interface FastifyRequest { diff --git a/src/main.ts b/src/main.ts index 68982df..bed07cf 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,4 +1,6 @@ import './telemetry/register'; +import { readFileSync } from 'fs'; +import { TLSSocket } from 'tls'; import { Logger } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { @@ -15,13 +17,30 @@ import { JsonLogger } from './telemetry/json-logger'; async function bootstrap(): Promise { const app = await NestFactory.create( AppModule, - new FastifyAdapter(), + new FastifyAdapter({ + https: { + key: readFileSync('/run/tls/api.key'), + cert: readFileSync('/run/tls/api.crt'), + ca: readFileSync('/run/tls/clients.crt'), + requestCert: true, + rejectUnauthorized: true, + minVersion: 'TLSv1.2', + }, + }), { bufferLogs: true, logger: new JsonLogger(), }, ); + app.getHttpServer().on('secureConnection', (socket: TLSSocket) => { + const certificate = socket.getPeerX509Certificate(); + if (!socket.authorized || certificate?.checkHost('lb.lab7.internal', { + subject: 'never', wildcards: false, + }) === undefined) { + socket.destroy(); + } + }); configureApp(app); registerHttpTelemetry(app.getHttpAdapter().getInstance()); setupSwagger(app); @@ -30,7 +49,7 @@ async function bootstrap(): Promise { const host = process.env.APP_HOST ?? '0.0.0.0'; const port = Number(process.env.APP_PORT ?? 8080); await app.listen(port, host); - Logger.log(`Listening on http://${host}:${port}`, 'Bootstrap'); + Logger.log(`Listening on https://${host}:${port}`, 'Bootstrap'); } bootstrap().catch((error) => {