feat: add local pki, https ingress and api mtls

This commit is contained in:
2026-11-30 16:36:13 +03:00
parent f736ff1da4
commit ea50b60f7f
7 changed files with 251 additions and 16 deletions
-3
View File
@@ -39,7 +39,4 @@ COPY contracts/openapi.json ./contracts/openapi.json
USER node USER node
EXPOSE 8080 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"] CMD ["node", "dist/main.js"]
+54 -6
View File
@@ -1,11 +1,33 @@
name: messenger-lab7 name: messenger-lab7
x-lockdown: &lockdown
security_opt: [no-new-privileges:true]
cap_drop: [ALL]
x-otel: &otel x-otel: &otel
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318} OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab} OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab}
services: 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: secrets-init:
image: alpine:3.20.3 image: alpine:3.20.3
volumes: volumes:
@@ -177,12 +199,15 @@ services:
OTEL_SERVICE_NAME: messenger-api OTEL_SERVICE_NAME: messenger-api
volumes: volumes:
- { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: api } } - { 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: deploy:
replicas: ${API_REPLICAS:-2} replicas: ${API_REPLICAS:-2}
resources: resources:
limits: { cpus: "0.5", memory: 256M } limits: { cpus: "0.5", memory: 256M }
stop_grace_period: 10s stop_grace_period: 10s
depends_on: depends_on:
bootstrap:
condition: service_completed_successfully
migrate: migrate:
condition: service_completed_successfully condition: service_completed_successfully
redis: redis:
@@ -308,18 +333,25 @@ services:
restart: unless-stopped restart: unless-stopped
lb: lb:
<<: *lockdown
image: haproxy:3.0.6-alpine image: haproxy:3.0.6-alpine
user: "1000:1000"
ports: ports:
- "127.0.0.1:${APP_PORT:-8080}:8080" - "127.0.0.1:${HTTPS_PORT:-8443}:8443"
volumes: volumes:
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro - ./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: deploy:
resources: resources:
limits: { cpus: "0.25", memory: 64M } limits: {cpus: "0.25", memory: 96M}
depends_on:
api:
condition: service_healthy
restart: unless-stopped
otel-collector: otel-collector:
image: otel/opentelemetry-collector-contrib:0.115.1@sha256:d2da12c4336a79758826700be9e21ecf4a9f7d945b7f8a58ba55ee3fa45427c8 image: otel/opentelemetry-collector-contrib:0.115.1@sha256:d2da12c4336a79758826700be9e21ecf4a9f7d945b7f8a58ba55ee3fa45427c8
@@ -416,6 +448,21 @@ services:
condition: service_started condition: service_started
restart: unless-stopped 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: volumes:
pgdata: pgdata:
s3data: s3data:
@@ -425,6 +472,7 @@ volumes:
tempodata: tempodata:
grafanadata: grafanadata:
secrets: secrets:
pki:
networks: networks:
telemetry: telemetry:
+106
View File
@@ -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()
+11 -3
View File
@@ -1,11 +1,13 @@
global global
log stdout format raw local0 info log stdout format raw local0 info
maxconn 2000 maxconn 2000
ssl-default-bind-options ssl-min-ver TLSv1.2
ssl-default-server-options ssl-min-ver TLSv1.2
defaults defaults
mode http mode http
log global log global
option httplog log-format "%ci:%cp %ft %b/%s %ST %Tt"
option dontlognull option dontlognull
timeout connect 1s timeout connect 1s
timeout client 30s timeout client 30s
@@ -31,13 +33,19 @@ resolvers docker
accepted_payload_size 8192 accepted_payload_size 8192
frontend public frontend public
bind :8080 bind :8443 ssl crt /run/tls/ingress.pem
default_backend api 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 backend api
balance roundrobin balance roundrobin
http-request set-timeout server 60s if { method POST } { path_reg ^/api/v1/chats/[^/]+/attachments$ } http-request set-timeout server 60s if { method POST } { path_reg ^/api/v1/chats/[^/]+/attachments$ }
option httpchk GET /health/core option httpchk GET /health/core
http-check expect status 200 http-check expect status 200
default-server check inter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none 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
+58
View File
@@ -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()
+1 -2
View File
@@ -1,11 +1,10 @@
import { randomUUID } from 'crypto'; import { randomUUID } from 'crypto';
import { FastifyInstance, FastifyRequest } from 'fastify'; import { FastifyInstance, FastifyRequest } from 'fastify';
import { hostname } from 'os';
const REQUEST_ID_HEADER = 'x-request-id'; const REQUEST_ID_HEADER = 'x-request-id';
const INSTANCE_ID_HEADER = 'x-instance-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' { declare module 'fastify' {
interface FastifyRequest { interface FastifyRequest {
+21 -2
View File
@@ -1,4 +1,6 @@
import './telemetry/register'; import './telemetry/register';
import { readFileSync } from 'fs';
import { TLSSocket } from 'tls';
import { Logger } from '@nestjs/common'; import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core'; import { NestFactory } from '@nestjs/core';
import { import {
@@ -15,13 +17,30 @@ import { JsonLogger } from './telemetry/json-logger';
async function bootstrap(): Promise<void> { async function bootstrap(): Promise<void> {
const app = await NestFactory.create<NestFastifyApplication>( const app = await NestFactory.create<NestFastifyApplication>(
AppModule, 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, bufferLogs: true,
logger: new JsonLogger(), 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); configureApp(app);
registerHttpTelemetry(app.getHttpAdapter().getInstance()); registerHttpTelemetry(app.getHttpAdapter().getInstance());
setupSwagger(app); setupSwagger(app);
@@ -30,7 +49,7 @@ async function bootstrap(): Promise<void> {
const host = process.env.APP_HOST ?? '0.0.0.0'; const host = process.env.APP_HOST ?? '0.0.0.0';
const port = Number(process.env.APP_PORT ?? 8080); const port = Number(process.env.APP_PORT ?? 8080);
await app.listen(port, host); await app.listen(port, host);
Logger.log(`Listening on http://${host}:${port}`, 'Bootstrap'); Logger.log(`Listening on https://${host}:${port}`, 'Bootstrap');
} }
bootstrap().catch((error) => { bootstrap().catch((error) => {