feat(deploy): add edge proxy HTTPS and AmneziaWG tunnel templates

This commit is contained in:
shira committed 2026-10-06 15:58:28 +03:00
1 parent bdc5855001
commit b8c3c83ed8
21 files changed
+954 -3

No files matched your search

+4
View File
@@ -2,6 +2,10 @@
APP_PROJECT=app
APP_NETWORK=app_default
APP_HTTP_PORT=8080
# Address the frontend port is published on. Keep the loopback default for a
# local stack. On a host that sits behind the edge proxy, set the address of
# its tunnel interface (for example 10.79.0.2); never 0.0.0.0.
APP_HTTP_BIND=127.0.0.1
POSTGRES_DB=lincodex
POSTGRES_USER=lincodex
+13
View File
@@ -91,6 +91,19 @@ ml-logs: ## Follow ML service logs
@test -f "$(ENV_FILE)" || { printf 'Missing %s.\n' "$(ENV_FILE)" >&2; exit 2; }
APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" logs -f
# Edge proxy (TLS and tunnel templates under deploy/edge). edge.env is local;
# the checked-in example is used when it does not exist.
.PHONY: edge-render edge-config
EDGE_DIR := $(ROOT)/deploy/edge
EDGE_ENV ?= $(if $(wildcard $(EDGE_DIR)/edge.env),$(EDGE_DIR)/edge.env,$(EDGE_DIR)/edge.env.example)
EDGE_NGINX_IMAGE ?= nginx:stable-alpine
edge-render: ## Render the edge nginx config from deploy/edge/edge.env into deploy/edge/rendered
@bash "$(EDGE_DIR)/scripts/render.sh" --env "$(EDGE_ENV)" --out "$(EDGE_DIR)/rendered" nginx
edge-config: ## Render the edge templates and check the nginx config with nginx -t in a container
@DOCKER="$(DOCKER)" EDGE_NGINX_IMAGE="$(EDGE_NGINX_IMAGE)" bash "$(EDGE_DIR)/scripts/check.sh" "$(EDGE_ENV)"
check: config check-workflows check-release ## Validate Compose files, CI workflow aggregates, and release tooling without starting services
check-workflows: ## Check that each workflow aggregate job requires every other job
+1
View File
@@ -10,6 +10,7 @@ Configuration for running the application with Docker Compose and Nginx.
- `docker/docker-compose.e2e.yml` is an overlay used only by the browser suite: it removes the frontend host port and adds the Playwright runner.
- `docker/docker-compose.release.yml` and `docker/docker-compose.ml.release.yml` are overlays that name the release images `lincodex.invalid/<service>:<tag>` and never pull them from a registry.
- `scripts/` contains the isolated stack smoke check, the browser E2E runner, and `release_manifest.py`, which builds, describes, and checks release images.
- `edge/` holds the public edge proxy: nginx and tunnel templates, certbot renewal hook, systemd drop-ins, and the scripts that render and check them. `make -C deploy edge-config` renders the nginx configuration and runs `nginx -t` in a container; see the [edge proxy runbook](../docs/en/DEPLOY.md#edge-proxy-https-and-tunnel).
Dockerfiles live in service directories and `.env.example` at the repository root. From the root, `make -C deploy config` checks Compose and `make -C deploy up` starts the core stack after `.env` is prepared. Start monitoring separately with `make -C deploy monitoring-up`. `make -C deploy test-e2e` runs the Playwright suite against a throwaway stack under a unique project name and removes it afterwards; see [TESTING.md](../docs/en/TESTING.md#browser-e2e-suite).
+1
View File
@@ -10,6 +10,7 @@
- `docker/docker-compose.e2e.yml` - overlay только для браузерного набора: убирает host-порт frontend и добавляет запуск Playwright.
- `docker/docker-compose.release.yml` и `docker/docker-compose.ml.release.yml` - overlay с именами образов выпуска `lincodex.invalid/<service>:<tag>` без скачивания из registry.
- `scripts/` содержит smoke-проверку изолированного стека, запуск браузерных E2E и `release_manifest.py` для сборки, описания и сверки образов выпуска.
- `edge/` содержит публичный edge proxy: шаблоны nginx и туннеля, hook продления certbot, drop-in systemd и скрипты, которые их отрисовывают и проверяют. `make -C deploy edge-config` отрисовывает конфигурацию nginx и выполняет `nginx -t` в контейнере; см. [runbook edge proxy](../docs/ru/DEPLOY.md#edge-proxy-https-и-туннель).
Dockerfile лежат в каталогах сервисов, `.env.example` - в корне репозитория. Из корня: `make -C deploy config` проверяет Compose, `make -C deploy up` запускает основной стек после подготовки `.env`. Мониторинг включается отдельно через `make -C deploy monitoring-up`. `make -C deploy test-e2e` запускает набор Playwright на одноразовом стеке с уникальным именем проекта и удаляет его после прогона; см. [TESTING.md](../docs/ru/TESTING.md#браузерный-e2e-набор).
+4 -1
View File
@@ -272,7 +272,10 @@ services:
backend:
condition: service_started
ports:
- "127.0.0.1:${APP_HTTP_PORT:-8080}:8080"
# Loopback by default. On the app host behind the edge proxy,
# APP_HTTP_BIND is the tunnel address (see docs/en/DEPLOY.md); never
# set it to 0.0.0.0, because Docker publishing bypasses ufw.
- "${APP_HTTP_BIND:-127.0.0.1}:${APP_HTTP_PORT:-8080}:8080"
healthcheck:
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/healthz"]
interval: 10s
+3
View File
@@ -0,0 +1,3 @@
# Local edge settings and rendered output; neither is committed.
/edge.env
/rendered/
@@ -0,0 +1,30 @@
# AmneziaWG, app host (client role): /etc/amnezia/amneziawg/{{AWG_IFACE}}.conf
# Rendered by deploy/edge/scripts/render.sh from the root-only parameters
# file on the host. The rendered file holds the private key: mode 600,
# never commit or print it.
[Interface]
Address = {{AWG_APP_IP}}/{{AWG_PREFIX}}
MTU = {{AWG_MTU}}
PrivateKey = {{AWG_PRIVATE_KEY}}
# Obfuscation parameters. Both ends must carry identical values.
Jc = {{AWG_JC}}
Jmin = {{AWG_JMIN}}
Jmax = {{AWG_JMAX}}
S1 = {{AWG_S1}}
S2 = {{AWG_S2}}
H1 = {{AWG_H1}}
H2 = {{AWG_H2}}
H3 = {{AWG_H3}}
H4 = {{AWG_H4}}
[Peer]
# The edge proxy.
PublicKey = {{AWG_PEER_PUBLIC_KEY}}
Endpoint = {{AWG_EDGE_ENDPOINT_IP}}:{{AWG_PORT}}
# Only the edge tunnel address. Never 0.0.0.0/0: the host keeps its own
# default route and its LAN access.
AllowedIPs = {{AWG_EDGE_IP}}/32
# This side sits behind NAT; the keepalive holds the mapping open so the
# edge can reach the app host at any time.
PersistentKeepalive = {{AWG_KEEPALIVE}}
@@ -0,0 +1,27 @@
# AmneziaWG, edge side (server role): /etc/amnezia/amneziawg/{{AWG_IFACE}}.conf
# Rendered by deploy/edge/scripts/render.sh from the root-only parameters
# file on the host. The rendered file holds the private key: mode 600,
# never commit or print it.
[Interface]
Address = {{AWG_EDGE_IP}}/{{AWG_PREFIX}}
ListenPort = {{AWG_PORT}}
MTU = {{AWG_MTU}}
PrivateKey = {{AWG_PRIVATE_KEY}}
# Obfuscation parameters. Both ends must carry identical values.
Jc = {{AWG_JC}}
Jmin = {{AWG_JMIN}}
Jmax = {{AWG_JMAX}}
S1 = {{AWG_S1}}
S2 = {{AWG_S2}}
H1 = {{AWG_H1}}
H2 = {{AWG_H2}}
H3 = {{AWG_H3}}
H4 = {{AWG_H4}}
[Peer]
# The app host. It initiates from behind NAT, so no Endpoint is set here.
PublicKey = {{AWG_PEER_PUBLIC_KEY}}
# Only the peer's tunnel address: the tunnel never carries other traffic and
# installs no default route.
AllowedIPs = {{AWG_APP_IP}}/32
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
# Certbot deploy hook, installed as
# /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh (mode 755).
# Certbot runs it only after a certificate was actually renewed. The reload
# is skipped when the new configuration does not pass the syntax test, so a
# bad file cannot take the running nginx down.
set -eu
nginx -t
systemctl reload nginx
+41
View File
@@ -0,0 +1,41 @@
# Edge proxy configuration. Copy to edge.env and adjust; the file holds no
# secrets, only names and addresses. Keys and obfuscation parameters of the
# tunnel live in a separate root-only file on each server (see awg/).
#
# Rendered with: make -C deploy edge-render
# Checked with: make -C deploy edge-config
# Public name served by the edge nginx. It must resolve to EDGE_LISTEN_IP.
EDGE_DOMAIN=lincodex.safelysvn.space
# Certbot lineage name; the certificate is read from
# /etc/letsencrypt/live/<EDGE_CERT_NAME>/. Use the domain unless certbot
# was run with --cert-name.
EDGE_CERT_NAME=lincodex.safelysvn.space
# The only address nginx binds to on ports 80 and 443. Never 0.0.0.0: the
# shared edge host has other listeners (for example UDP 443).
EDGE_LISTEN_IP=89.185.85.208
# Directory served for ACME http-01 challenges (certbot --webroot-path).
EDGE_ACME_WEBROOT=/var/www/certbot
# Strict-Transport-Security max-age in seconds (180 days). Raise it to
# 31536000 and consider preload only after the site has run on HTTPS for a while.
EDGE_HSTS_MAX_AGE=15552000
# Request body limit. Keep it at or above the inner nginx limit (10m) and the
# largest upload policy (resume: 5 MB plus multipart overhead).
EDGE_MAX_BODY=10m
# Tunnel: one dedicated point-to-point AmneziaWG link between the edge (server
# role) and the app host (client role, behind NAT, initiates the handshake).
# The /30 must not overlap any route or Docker range on either host.
AWG_IFACE=awg-lincodex
AWG_EDGE_IP=10.79.0.1
AWG_APP_IP=10.79.0.2
AWG_PREFIX=30
# Public address and UDP port the edge listens on for the tunnel (not 443).
AWG_EDGE_ENDPOINT_IP=213.165.42.19
AWG_PORT=51871
AWG_MTU=1380
AWG_KEEPALIVE=25
# Port the app host publishes for the frontend container (APP_HTTP_PORT in the
# app .env). The edge proxies to AWG_APP_IP:APP_HTTP_PORT.
APP_HTTP_PORT=8080
@@ -0,0 +1,27 @@
# Catch-all for requests whose Host is not a served name, on the one address
# this edge uses. It keeps unknown names away from the application and
# stops the TLS handshake without presenting a certificate.
#
# Rendered from deploy/edge/nginx/00-default.conf.template. Do not edit the
# installed copy; change the template and render again.
# Access log without the query string: $uri never contains it, so values
# such as email addresses or tokens in a query are not written to the log.
log_format lincodex '$remote_addr [$time_local] "$request_method $uri" '
'$status $body_bytes_sent rt=$request_time '
'urt=$upstream_response_time id=$request_id';
server {
listen {{EDGE_LISTEN_IP}}:80 default_server;
server_name _;
server_tokens off;
# 444 closes the connection without a response.
return 444;
}
server {
listen {{EDGE_LISTEN_IP}}:443 ssl default_server;
server_name _;
server_tokens off;
ssl_reject_handshake on;
}
@@ -0,0 +1,25 @@
# Port 80 for {{EDGE_DOMAIN}}: ACME http-01 challenges and the redirect to
# HTTPS. This is the only file needed to obtain the first certificate.
#
# Rendered from deploy/edge/nginx/lincodex-http.conf.template.
server {
listen {{EDGE_LISTEN_IP}}:80;
server_name {{EDGE_DOMAIN}};
server_tokens off;
access_log /var/log/nginx/lincodex.access.log lincodex;
# Certbot writes challenge files here (webroot method). Nothing else is
# served from this directory.
location ^~ /.well-known/acme-challenge/ {
root {{EDGE_ACME_WEBROOT}};
default_type text/plain;
try_files $uri =404;
}
# The target uses the configured name, not $host, so a forged Host header
# cannot turn the redirect into an open redirect.
location / {
return 301 https://{{EDGE_DOMAIN}}$request_uri;
}
}
@@ -0,0 +1,88 @@
# Port 443 for {{EDGE_DOMAIN}}: TLS termination and a reverse proxy to the
# frontend container of the app host, reached through the AmneziaWG tunnel.
# The frontend container serves the SPA (including the index.html fallback
# for deep links) and proxies /api to the Go backend, so this proxy forwards
# every path unchanged and both live on one origin.
#
# Rendered from deploy/edge/nginx/lincodex-https.conf.template. Needs the
# certificate from certbot; install it only after the first issuance.
upstream lincodex_app {
server {{EDGE_UPSTREAM}};
# Reused connections to the app host; the tunnel round trip is the
# expensive part of a request.
keepalive 16;
}
server {
listen {{EDGE_LISTEN_IP}}:443 ssl;
# No HTTP/3: QUIC would need UDP 443, which another service on this host
# already owns.
http2 on;
server_name {{EDGE_DOMAIN}};
server_tokens off;
access_log /var/log/nginx/lincodex.access.log lincodex;
ssl_certificate /etc/letsencrypt/live/{{EDGE_CERT_NAME}}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/{{EDGE_CERT_NAME}}/privkey.pem;
# Mozilla "intermediate" profile: TLS 1.2 and 1.3, AEAD suites with
# forward secrecy. The client picks the suite (prefer_server_ciphers off).
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305;
ssl_prefer_server_ciphers off;
ssl_session_timeout 1d;
ssl_session_cache shared:lincodex_tls:10m;
# Tickets would keep one long-lived key that undoes forward secrecy.
ssl_session_tickets off;
# OCSP stapling is deliberately absent: Let's Encrypt certificates no
# longer carry an OCSP responder URL, so there is nothing to staple.
# HSTS without preload. The header is set at server level only; a nested
# add_header in a location would drop it.
add_header Strict-Transport-Security "max-age={{EDGE_HSTS_MAX_AGE}}; includeSubDomains" always;
# Largest accepted request body. The resume upload limit is 5 MB; the
# frontend container allows 10 MB, and this value must not be lower.
client_max_body_size {{EDGE_MAX_BODY}};
client_header_timeout 15s;
client_body_timeout 60s;
send_timeout 60s;
# Compression for the static shell only. gzip over responses that mix
# secrets with attacker-influenced content enables BREACH, so JSON is not
# in gzip_types and the API location turns compression off outright.
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_types text/css text/javascript application/javascript image/svg+xml;
proxy_http_version 1.1;
# Clear Connection so the upstream keepalive pool is used.
proxy_set_header Connection "";
# Host is preserved: the backend and the frontend container see the public
# name, which is what origin and link checks compare against.
proxy_set_header Host $host;
# The edge is the first trusted hop, so it replaces client-supplied
# forwarding headers instead of appending to them.
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_redirect off;
proxy_connect_timeout 5s;
proxy_send_timeout 60s;
# The frontend container gives the backend 30 s; leave room for it.
proxy_read_timeout 60s;
location ^~ /api/ {
gzip off;
proxy_pass http://lincodex_app;
}
location / {
proxy_pass http://lincodex_app;
}
}
+121
View File
@@ -0,0 +1,121 @@
#!/usr/bin/env bash
# Generate and exchange AmneziaWG keys and obfuscation parameters.
#
# awg-keys.sh init PARAMS [--shared EXPORTED] create PARAMS on this host
# awg-keys.sh export PARAMS print the shareable part
# awg-keys.sh peer PARAMS EXPORTED store the other end's key
# awg-keys.sh public PARAMS print this host's public key
#
# PARAMS is a root-only KEY=VALUE file (mode 600), for example
# /etc/amnezia/amneziawg/awg-lincodex.params. It holds the private key and is
# read by render.sh. Run this script as root on the host that owns the key;
# the private key is never printed and never leaves PARAMS.
#
# Flow:
# edge: awg-keys.sh init PARAMS (keys + parameters)
# edge: awg-keys.sh export PARAMS > shared.env (public data only)
# app: awg-keys.sh init PARAMS --shared shared.env (own key, same parameters)
# app: awg-keys.sh export PARAMS > app-shared.env
# edge: awg-keys.sh peer PARAMS app-shared.env
# EXPORTED files carry a public key and obfuscation parameters. They are not
# public data: the parameters are shared secrets of the tunnel, so move them
# over SSH and delete the copies afterwards.
set -euo pipefail
umask 077
die() { printf 'awg-keys.sh: %s\n' "$*" >&2; exit 2; }
command -v awg >/dev/null || die "awg (amneziawg-tools) is not installed"
b64key='^[A-Za-z0-9+/]{43}=$'
shared_names="AWG_JC AWG_JMIN AWG_JMAX AWG_S1 AWG_S2 AWG_H1 AWG_H2 AWG_H3 AWG_H4"
# Print one value from a KEY=VALUE file.
get() { sed -n "s/^$2=//p" "$1" | head -n 1; }
# Uniform-enough integer in [lo, hi] from the kernel random source.
rand_range() {
local lo="$1" hi="$2" n
n="$(od -An -N4 -tu4 /dev/urandom | tr -d ' ')"
printf '%s' $((lo + n % (hi - lo + 1)))
}
cmd="${1:-}"; [ $# -ge 1 ] && shift
case "$cmd" in
init)
[ $# -ge 1 ] || die "usage: init PARAMS [--shared EXPORTED]"
params="$1"; shift
shared=""
if [ "${1:-}" = "--shared" ]; then [ $# -eq 2 ] || die "--shared needs a file"; shared="$2"; fi
[ ! -e "$params" ] || die "$params exists; refusing to overwrite keys"
[ "$(id -u)" -eq 0 ] || die "run as root"
priv="$(awg genkey)"
pub="$(printf '%s' "$priv" | awg pubkey)"
tmp="$(mktemp "$params.XXXXXX")"
trap 'rm -f "$tmp"' EXIT
{
printf 'AWG_PRIVATE_KEY=%s\n' "$priv"
printf 'AWG_PUBLIC_KEY=%s\n' "$pub"
if [ -n "$shared" ]; then
[ -f "$shared" ] || die "missing $shared"
peer="$(get "$shared" AWG_PEER_PUBLIC_KEY)"
printf '%s' "$peer" | grep -Eq "$b64key" || die "$shared has no valid AWG_PEER_PUBLIC_KEY"
printf 'AWG_PEER_PUBLIC_KEY=%s\n' "$peer"
for name in $shared_names; do
value="$(get "$shared" "$name")"
printf '%s' "$value" | grep -Eq '^[0-9]+$' || die "$shared has no valid $name"
printf '%s=%s\n' "$name" "$value"
done
else
jmin="$(rand_range 40 80)"
jmax="$(rand_range 700 1000)"
s1="$(rand_range 15 150)"
s2="$(rand_range 15 150)"
while [ $((s1 + 56)) -eq "$s2" ]; do s2="$(rand_range 15 150)"; done
printf 'AWG_JC=%s\nAWG_JMIN=%s\nAWG_JMAX=%s\nAWG_S1=%s\nAWG_S2=%s\n' "$(rand_range 4 8)" "$jmin" "$jmax" "$s1" "$s2"
seen=" "
for i in 1 2 3 4; do
h="$(rand_range 5 4294967295)"
while case "$seen" in *" $h "*) true ;; *) false ;; esac; do h="$(rand_range 5 4294967295)"; done
seen="$seen$h "
printf 'AWG_H%s=%s\n' "$i" "$h"
done
fi
} > "$tmp"
chmod 600 "$tmp"
mv "$tmp" "$params"
trap - EXIT
printf 'created %s; this host public key: %s\n' "$params" "$pub"
;;
export)
[ $# -eq 1 ] || die "usage: export PARAMS"
[ -f "$1" ] || die "missing $1"
printf 'AWG_PEER_PUBLIC_KEY=%s\n' "$(get "$1" AWG_PUBLIC_KEY)"
for name in $shared_names; do printf '%s=%s\n' "$name" "$(get "$1" "$name")"; done
;;
peer)
[ $# -eq 2 ] || die "usage: peer PARAMS EXPORTED"
params="$1"; exported="$2"
[ -f "$params" ] || die "missing $params"
[ -f "$exported" ] || die "missing $exported"
peer="$(get "$exported" AWG_PEER_PUBLIC_KEY)"
printf '%s' "$peer" | grep -Eq "$b64key" || die "$exported has no valid AWG_PEER_PUBLIC_KEY"
[ "$peer" != "$(get "$params" AWG_PUBLIC_KEY)" ] || die "that is this host's own public key"
for name in $shared_names; do
[ "$(get "$exported" "$name")" = "$(get "$params" "$name")" ] || die "$name differs between the hosts"
done
tmp="$(mktemp "$params.XXXXXX")"
trap 'rm -f "$tmp"' EXIT
grep -v '^AWG_PEER_PUBLIC_KEY=' "$params" > "$tmp" || true
printf 'AWG_PEER_PUBLIC_KEY=%s\n' "$peer" >> "$tmp"
chmod 600 "$tmp"
mv "$tmp" "$params"
trap - EXIT
printf 'stored peer public key in %s\n' "$params"
;;
public)
[ $# -eq 1 ] || die "usage: public PARAMS"
[ -f "$1" ] || die "missing $1"
get "$1" AWG_PUBLIC_KEY
;;
*) die "usage: awg-keys.sh init|export|peer|public ..." ;;
esac
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env bash
# Render the edge templates with the given variables and check the result:
# - nginx -t inside a throwaway nginx container, with a self-signed
# certificate at the path the config expects;
# - every nginx listen directive uses the configured address, never a
# wildcard;
# - both AmneziaWG templates render with well-formed throwaway keys.
#
# check.sh [ENV_FILE]
#
# DOCKER and EDGE_NGINX_IMAGE can be set in the environment. The image should
# follow the nginx version on the edge host (the Ubuntu package is 1.28).
set -euo pipefail
here="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
env_file="${1:-$here/edge.env.example}"
docker_bin="${DOCKER:-docker}"
image="${EDGE_NGINX_IMAGE:-nginx:stable-alpine}"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
"$here/scripts/render.sh" --env "$env_file" --out "$work/out" nginx
"$here/scripts/render.sh" --env "$env_file" --out "$work/out-edge" awg-edge --check-secrets
"$here/scripts/render.sh" --env "$env_file" --out "$work/out-app" awg-app --check-secrets
listen_ip="$(sed -n 's/^EDGE_LISTEN_IP=//p' "$env_file")"
cert_name="$(sed -n 's/^EDGE_CERT_NAME=//p' "$env_file")"
bad="$(grep -hE '^[[:space:]]*listen[[:space:]]' "$work"/out/nginx/*.conf | grep -vF "listen ${listen_ip}:" || true)"
if [ -n "$bad" ]; then
printf 'edge-config: listen directives that are not bound to %s:\n%s\n' "$listen_ip" "$bad" >&2
exit 1
fi
mkdir -p "$work/cert"
openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj "/CN=edge-config-check" \
-keyout "$work/cert/privkey.pem" -out "$work/cert/fullchain.pem" >/dev/null 2>&1
# nginx -t binds the listen sockets, so the container gets the edge address
# on its loopback (NET_ADMIN is needed only for that).
"$docker_bin" run --rm --entrypoint sh --cap-add NET_ADMIN \
-v "$work/out/nginx:/rendered:ro" -v "$work/cert:/cert:ro" \
-e "CERT_NAME=$cert_name" -e "LISTEN_IP=$listen_ip" "$image" -ec '
ip addr add "$LISTEN_IP/32" dev lo
rm -f /etc/nginx/conf.d/default.conf
cp /rendered/*.conf /etc/nginx/conf.d/
mkdir -p "/etc/letsencrypt/live/$CERT_NAME" /var/log/nginx /var/www/certbot
cp /cert/*.pem "/etc/letsencrypt/live/$CERT_NAME/"
nginx -v
nginx -t
'
printf 'edge-config: nginx -t passed; templates render with %s\n' "$env_file"
+153
View File
@@ -0,0 +1,153 @@
#!/usr/bin/env bash
# Render the edge templates from configuration.
#
# render.sh [--env FILE] [--out DIR] [--params FILE | --check-secrets] TARGET...
#
# TARGET is one or more of: nginx, awg-edge, awg-app.
#
# --env FILE variables (default: deploy/edge/edge.env)
# --out DIR output directory (default: deploy/edge/rendered)
# --params FILE tunnel keys and obfuscation parameters, written by
# awg-keys.sh (needed for awg-edge and awg-app)
# --check-secrets use well-formed throwaway key values instead of a
# params file; only for template checks, never for hosts
#
# Placeholders are written {{NAME}} so they cannot collide with nginx
# variables ($host) or with shell syntax. Every value is validated before it
# is substituted, and the script fails when a placeholder is left over.
set -euo pipefail
umask 077
here="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
env_file="$here/edge.env"
out_dir="$here/rendered"
params_file=""
fake_secrets=0
targets=()
die() { printf 'render.sh: %s\n' "$*" >&2; exit 2; }
while [ $# -gt 0 ]; do
case "$1" in
--env) [ $# -ge 2 ] || die "--env needs a value"; env_file="$2"; shift 2 ;;
--out) [ $# -ge 2 ] || die "--out needs a value"; out_dir="$2"; shift 2 ;;
--params) [ $# -ge 2 ] || die "--params needs a value"; params_file="$2"; shift 2 ;;
--check-secrets) fake_secrets=1; shift ;;
nginx|awg-edge|awg-app) targets+=("$1"); shift ;;
*) die "unknown argument: $1" ;;
esac
done
[ ${#targets[@]} -gt 0 ] || die "no target given (nginx, awg-edge, awg-app)"
[ -f "$env_file" ] || die "missing $env_file (copy deploy/edge/edge.env.example)"
# Read KEY=VALUE lines without executing the file.
load_vars() {
local file="$1" line key value
while IFS= read -r line || [ -n "$line" ]; do
case "$line" in ''|'#'*) continue ;; esac
case "$line" in *=*) ;; *) die "$file: not a KEY=VALUE line: $line" ;; esac
key="${line%%=*}"
value="${line#*=}"
# Only the project's own names, so a file cannot override PATH or IFS.
case "$key" in EDGE_*|AWG_*|APP_HTTP_PORT) ;; *) die "$file: unexpected variable name: $key" ;; esac
case "$key" in *[!A-Za-z0-9_]*) die "$file: bad variable name: $key" ;; esac
printf -v "$key" '%s' "$value"
done < "$file"
}
need() {
local name="$1" pattern="$2"
[ -n "${!name:-}" ] || die "$name is not set"
printf '%s' "${!name}" | grep -Eq "$pattern" || die "$name has an invalid value"
}
ipv4='^((25[0-5]|2[0-4][0-9]|1?[0-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1?[0-9]?[0-9])$'
uint='^[0-9]{1,10}$'
b64key='^[A-Za-z0-9+/]{43}=$'
load_vars "$env_file"
need EDGE_DOMAIN '^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$'
need EDGE_CERT_NAME '^[A-Za-z0-9._-]+$'
need EDGE_LISTEN_IP "$ipv4"
[ "$EDGE_LISTEN_IP" != "0.0.0.0" ] || die "EDGE_LISTEN_IP must be one address, not 0.0.0.0"
need EDGE_ACME_WEBROOT '^/[A-Za-z0-9._/-]+$'
need EDGE_HSTS_MAX_AGE "$uint"
need EDGE_MAX_BODY '^[0-9]+[kKmM]$'
need AWG_IFACE '^[A-Za-z0-9_.+=-]{1,15}$'
need AWG_EDGE_IP "$ipv4"
need AWG_APP_IP "$ipv4"
need AWG_PREFIX '^(2[89]|3[01])$'
need AWG_EDGE_ENDPOINT_IP "$ipv4"
need AWG_PORT '^[0-9]{4,5}$'
[ "$AWG_PORT" -ge 1024 ] && [ "$AWG_PORT" -le 65535 ] || die "AWG_PORT is out of range"
[ "$AWG_PORT" != "443" ] || die "AWG_PORT must not be 443"
need AWG_MTU '^[0-9]{3,4}$'
need AWG_KEEPALIVE '^[0-9]{1,3}$'
need APP_HTTP_PORT '^[0-9]{2,5}$'
[ "$AWG_EDGE_IP" != "$AWG_APP_IP" ] || die "AWG_EDGE_IP and AWG_APP_IP must differ"
EDGE_UPSTREAM="${AWG_APP_IP}:${APP_HTTP_PORT}"
# Fill every {{NAME}} for the listed variables; fail on leftovers.
render() {
local src="$1" dst="$2"; shift 2
local script="" name value
for name in "$@"; do
value="${!name}"
script="${script}s|{{${name}}}|${value}|g;"
done
sed -e "$script" "$src" > "$dst"
if grep -q '{{[A-Z0-9_]*}}' "$dst"; then
rm -f "$dst"
die "$src has placeholders without a value: $(sed -e "$script" "$src" | grep -o '{{[A-Z0-9_]*}}' | sort -u | tr '\n' ' ')"
fi
}
load_awg_params() {
if [ "$fake_secrets" -eq 1 ]; then
AWG_PRIVATE_KEY="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
AWG_PEER_PUBLIC_KEY="BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB="
AWG_JC=4 AWG_JMIN=50 AWG_JMAX=1000 AWG_S1=30 AWG_S2=60
AWG_H1=1000000001 AWG_H2=1000000002 AWG_H3=1000000003 AWG_H4=1000000004
else
[ -n "$params_file" ] || die "awg targets need --params FILE (or --check-secrets for a template check)"
[ -f "$params_file" ] || die "missing $params_file (run awg-keys.sh)"
load_vars "$params_file"
fi
need AWG_PRIVATE_KEY "$b64key"
need AWG_PEER_PUBLIC_KEY "$b64key"
need AWG_JC '^[0-9]{1,3}$'
need AWG_JMIN '^[0-9]{1,4}$'
need AWG_JMAX '^[0-9]{1,4}$'
need AWG_S1 '^[0-9]{1,4}$'
need AWG_S2 '^[0-9]{1,4}$'
local n
for n in AWG_H1 AWG_H2 AWG_H3 AWG_H4; do need "$n" "$uint"; [ "${!n}" -ge 5 ] && [ "${!n}" -le 4294967295 ] || die "$n is out of range"; done
[ "$AWG_JC" -ge 1 ] && [ "$AWG_JC" -le 128 ] || die "AWG_JC is out of range"
[ "$AWG_JMIN" -lt "$AWG_JMAX" ] && [ "$AWG_JMAX" -le 1280 ] || die "need AWG_JMIN < AWG_JMAX <= 1280"
[ "$AWG_S1" -le 1132 ] && [ "$AWG_S2" -le 1188 ] && [ $((AWG_S1 + 56)) -ne "$AWG_S2" ] || die "AWG_S1 and AWG_S2 are not valid together"
[ "$(printf '%s\n' "$AWG_H1" "$AWG_H2" "$AWG_H3" "$AWG_H4" | sort -u | wc -l | tr -d ' ')" -eq 4 ] || die "AWG_H1..H4 must be distinct"
}
mkdir -p "$out_dir"
for target in "${targets[@]}"; do
case "$target" in
nginx)
mkdir -p "$out_dir/nginx"
for name in 00-default lincodex-http lincodex-https; do
render "$here/nginx/$name.conf.template" "$out_dir/nginx/$name.conf" \
EDGE_DOMAIN EDGE_CERT_NAME EDGE_LISTEN_IP EDGE_ACME_WEBROOT EDGE_HSTS_MAX_AGE EDGE_MAX_BODY EDGE_UPSTREAM
done
printf 'rendered nginx -> %s/nginx\n' "$out_dir"
;;
awg-edge|awg-app)
load_awg_params
mkdir -p "$out_dir/awg"
render "$here/awg/awg-lincodex.${target#awg-}.conf.template" "$out_dir/awg/$AWG_IFACE.conf" \
AWG_IFACE AWG_EDGE_IP AWG_APP_IP AWG_PREFIX AWG_EDGE_ENDPOINT_IP AWG_PORT AWG_MTU AWG_KEEPALIVE \
AWG_PRIVATE_KEY AWG_PEER_PUBLIC_KEY AWG_JC AWG_JMIN AWG_JMAX AWG_S1 AWG_S2 AWG_H1 AWG_H2 AWG_H3 AWG_H4
chmod 600 "$out_dir/awg/$AWG_IFACE.conf"
printf 'rendered %s -> %s/awg/%s.conf\n' "$target" "$out_dir" "$AWG_IFACE"
;;
esac
done
@@ -0,0 +1,9 @@
# Drop-in for awg-quick@awg-lincodex.service on both hosts, installed as
# /etc/systemd/system/awg-quick@awg-lincodex.service.d/userspace.conf.
#
# The kernel module is not used: awg-quick falls back to the userspace
# daemon, which is installed from a pinned build (see docs/en/DEPLOY.md).
# The daemon is one process per interface and is not restarted by systemd
# on its own; check the handshake with `awg show` after incidents.
[Service]
Environment=WG_QUICK_USERSPACE_IMPLEMENTATION=/usr/local/bin/amneziawg-go
+12
View File
@@ -0,0 +1,12 @@
# Drop-in for docker.service on the app host, installed as
# /etc/systemd/system/docker.service.d/10-lincodex-awg.conf.
#
# The frontend container publishes its port on the tunnel address
# (APP_HTTP_BIND). Docker cannot publish a port on an address that does not
# exist yet, so the tunnel interface must be up before the daemon starts the
# restart-policy containers. Wants (not Requires) keeps Docker running when
# the tunnel unit fails; the frontend container then fails to start and is
# visible as such.
[Unit]
After=awg-quick@awg-lincodex.service
Wants=awg-quick@awg-lincodex.service
+12 -2
View File
@@ -1,3 +1,13 @@
# Behind the TLS edge proxy the client's scheme arrives in X-Forwarded-Proto
# (deploy/edge). Keep it when it is https so the backend sees the original
# scheme; every other value falls back to the scheme of this server. The
# header is trustworthy only because the frontend port is published on
# loopback or on the tunnel address, never on a public one.
map $http_x_forwarded_proto $forwarded_proto {
default $scheme;
https https;
}
server {
listen 8080;
server_name _;
@@ -25,7 +35,7 @@ server {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Proto $forwarded_proto;
proxy_set_header X-Request-ID $request_id;
proxy_connect_timeout 3s;
proxy_send_timeout 30s;
@@ -41,7 +51,7 @@ server {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Proto $forwarded_proto;
proxy_connect_timeout 2s;
proxy_send_timeout 5s;
proxy_read_timeout 5s;
+161
View File
@@ -309,6 +309,167 @@ PostgreSQL creates a separate exporter role only while initializing an empty vol
For remote ML scraping, set ML_METRICS_TARGET to hostname:port or IPv4:port and verify private routing and firewall rules. The standalone ML host does not yet have a separate Alloy config for forwarding its container logs to Loki.
## Edge proxy, HTTPS and tunnel
The Compose stack serves plain HTTP on the host. A public site puts a separate edge host in front of it: the edge terminates TLS and forwards every request through a dedicated tunnel to the app host. The files are in `deploy/edge/`; this section is the runbook. It describes the configuration in the repository. A rollout is an external action, and the test steps below show what a rollout has to prove.
browser --HTTPS--> edge nginx (EDGE_LISTEN_IP:80,443)
--AmneziaWG tunnel (10.79.0.0/30)--> app host (10.79.0.2:8080)
= frontend container (Nginx) --> backend
| Role | What runs there | Address in the reference rollout |
| --- | --- | --- |
| Edge host | nginx, certbot, the AmneziaWG server end | public `213.165.42.19` and `89.185.85.208`; tunnel `10.79.0.1` |
| App host | Docker Compose core stack, the AmneziaWG client end | LAN `192.168.10.111` behind NAT; tunnel `10.79.0.2` |
The edge host is shared with other services. Everything here only adds: nginx binds the one address in `EDGE_LISTEN_IP` and never a wildcard, the tunnel uses its own interface and subnet, and no existing interface, listener, container, or firewall rule is changed.
### Configuration
All names and addresses come from `deploy/edge/edge.env` (copy `deploy/edge/edge.env.example`; the file holds no secrets and Git ignores it). The main values are `EDGE_DOMAIN`, `EDGE_CERT_NAME`, `EDGE_LISTEN_IP`, `EDGE_ACME_WEBROOT`, `EDGE_HSTS_MAX_AGE`, `EDGE_MAX_BODY`, and the tunnel values `AWG_IFACE`, `AWG_EDGE_IP`, `AWG_APP_IP`, `AWG_PREFIX`, `AWG_EDGE_ENDPOINT_IP`, `AWG_PORT`, `AWG_MTU`, and `AWG_KEEPALIVE`. The edge proxies to `AWG_APP_IP:APP_HTTP_PORT`. The tunnel subnet must not overlap any route or Docker range on either host; `ip route` on both hosts is the check.
make -C deploy edge-config # render the templates and run nginx -t in a container
make -C deploy edge-render # write deploy/edge/rendered/nginx
`edge-config` renders the nginx templates and both tunnel templates (with throwaway keys), fails when a placeholder has no value or a `listen` directive is not bound to `EDGE_LISTEN_IP`, and runs `nginx -t` in `nginx:stable-alpine` (`EDGE_NGINX_IMAGE` changes it) with a self-signed certificate at the path the configuration expects. It needs Docker and proves syntax only, not that a certificate exists or the host is reachable. The Ubuntu edge package is nginx 1.28; keep the image close to it.
`deploy/edge/scripts/render.sh` validates every value before it substitutes it. Keys and obfuscation parameters are not part of `edge.env`: `deploy/edge/scripts/awg-keys.sh` writes them to a root-only parameters file on each host (`/etc/amnezia/amneziawg/awg-lincodex.params`), and `render.sh --params` reads that file to produce the tunnel configuration.
### One origin and the Secure cookie
The browser sees only `https://<EDGE_DOMAIN>`. The SPA and `/api` come from the same origin: the edge forwards every path unchanged, and the frontend container serves the SPA with its `try_files ... /index.html` fallback, so a deep link such as `/some/deep/link` returns the SPA, and proxies `/api/` to Go. The planned session cookie is `__Host-lincodex_session` with `Secure`, `HttpOnly`, and `SameSite=Strict`. Browsers accept it only from an HTTPS page, with `Path=/` and no `Domain`, which the single HTTPS origin gives. The edge keeps `Host` as the public name and sets `X-Forwarded-Proto: https`; the frontend container's Nginx keeps that value for the backend (`$forwarded_proto` in `deploy/nginx/conf.d/app.conf`) and otherwise reports its own scheme. `APP_PUBLIC_URL` in the app host `.env` must be `https://<EDGE_DOMAIN>`, which is the only origin value the backend reads.
Registration and login are not implemented yet (the operations answer 501), and the backend does not read `X-Forwarded-Proto`. Sign-in through the edge is therefore not verified end to end; what is verified is the transport the cookie needs (HTTPS, one origin, the original host and scheme forwarded).
### Request handling at the edge
- Port 80 serves only `/.well-known/acme-challenge/` from `EDGE_ACME_WEBROOT` and answers everything else with a 301 to `https://<EDGE_DOMAIN>` plus the original path and query. The target is the configured name, not the request `Host`. A request for any other name is dropped (nginx 444) on port 80 and refused at the TLS handshake on port 443.
- Port 443 allows TLS 1.2 and 1.3 with the Mozilla intermediate cipher list, HTTP/2, no session tickets, and `Strict-Transport-Security: max-age=<EDGE_HSTS_MAX_AGE>; includeSubDomains` without `preload`. The default max-age is 180 days; raise it to a year and consider preload only after the site has stayed on HTTPS. The upstream security headers (`X-Content-Type-Options`, `Referrer-Policy`, `X-Frame-Options`, `Permissions-Policy`) pass through from the frontend container.
- OCSP stapling is off on purpose: Let's Encrypt certificates no longer carry an OCSP responder URL, so there is nothing to staple. HTTP/3 is off because it would need UDP 443, which another service on the edge host owns.
- Compression is off for `/api/` and limited to CSS, JavaScript, SVG, and the HTML shell elsewhere (no JSON). Compressing responses that mix secrets with attacker-influenced content enables BREACH; a CSRF token delivered in an API response must never be compressed. Revisit this if a secret is ever rendered into HTML.
- `X-Forwarded-For` and `X-Real-IP` are replaced with the connecting address, not appended to client values, because the edge is the first trusted hop. The frontend container then appends the tunnel peer, so the backend reads the client address as the first `X-Forwarded-For` entry. The container's own `X-Real-IP` and the `/telemetry` rate limit see the tunnel peer or the Docker gateway address, so all clients share that bucket until the container trusts the edge for real client addresses.
- `client_max_body_size` is `EDGE_MAX_BODY` (10 MB, equal to the container limit). The 5 MB resume limit is a per-feature policy checked by the backend. Timeouts: 5 s to connect, 60 s to send and read (the container gives Go 30 s), 60 s for a request body.
- The access log (`/var/log/nginx/lincodex.access.log`, rotated by the package logrotate rule) records the path without the query string, so values such as addresses in a query do not reach the log.
### Rollout on the edge host
Ubuntu packages only; no system upgrade. Install nginx and certbot without starting nginx on its default wildcard site:
printf '#!/bin/sh\nexit 101\n' | sudo tee /usr/sbin/policy-rc.d >/dev/null && sudo chmod 755 /usr/sbin/policy-rc.d
sudo apt-get install -y --no-install-recommends nginx certbot
sudo rm -f /usr/sbin/policy-rc.d /etc/nginx/sites-enabled/default
1. Check that the domain resolves to `EDGE_LISTEN_IP` (`dig +short <domain> @1.1.1.1`) and that nothing listens on TCP 80 and 443 (`ss -tlnp`).
2. Copy `deploy/edge` to the host, create `edge.env`, and render: `deploy/edge/scripts/render.sh --env deploy/edge/edge.env --out deploy/edge/rendered nginx`.
3. Install the ACME directory and the first two files, then the firewall rules (ufw only gains rules; keep a second SSH session open while changing it):
sudo install -d -m 755 /var/www/certbot
sudo install -m 644 deploy/edge/rendered/nginx/00-default.conf deploy/edge/rendered/nginx/lincodex-http.conf /etc/nginx/conf.d/
sudo nginx -t
sudo ufw allow in to <EDGE_LISTEN_IP> port 80 proto tcp comment 'lincodex ACME and redirect'
sudo ufw allow in to <EDGE_LISTEN_IP> port 443 proto tcp comment 'lincodex HTTPS'
sudo systemctl enable --now nginx
4. Install the renewal hook and issue the certificate. Run the staging dry run first; the production CA limits repeated failures. The account has no email address (`--register-unsafely-without-email`), so Let's Encrypt cannot send expiry notices; add an address later with `certbot update_account --email <address>`. `--agree-tos` accepts the Let's Encrypt subscriber agreement.
sudo install -d -m 755 /etc/letsencrypt/renewal-hooks/deploy
sudo install -m 755 deploy/edge/certbot/reload-nginx.sh /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh
sudo certbot certonly --webroot -w /var/www/certbot -d <domain> --cert-name <domain> \
--register-unsafely-without-email --agree-tos --non-interactive --dry-run
sudo certbot certonly --webroot -w /var/www/certbot -d <domain> --cert-name <domain> \
--register-unsafely-without-email --agree-tos --non-interactive
5. Install the HTTPS file and reload: `sudo install -m 644 deploy/edge/rendered/nginx/lincodex-https.conf /etc/nginx/conf.d/ && sudo nginx -t && sudo systemctl reload nginx`. The site answers 502 or 504 until the tunnel and the app host are up.
6. Install the tunnel end (below), then `sudo ufw allow in to <AWG_EDGE_ENDPOINT_IP> port <AWG_PORT> proto udp comment 'lincodex tunnel'`.
### Tunnel
AmneziaWG runs in userspace (`amneziawg-go`) so that nothing depends on a kernel module for the host kernel. Both hosts use the same two pieces:
- `amneziawg-tools` (`awg`, `awg-quick`, and the `awg-quick@.service` unit) from the Amnezia PPA package for the release, downloaded and checked against the SHA-256 in the PPA package index, then installed with `dpkg -i`. The PPA is not added to apt, so the package does not update itself.
- `amneziawg-go`, built from the upstream tag `v3.1.20260828` (commit `b5928efb6ca1`) with `CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "-s -w"` and installed as `/usr/local/bin/amneziawg-go`. The reference build has SHA-256 `5e8877b58afdc4667be196aebb994839d167a4f189c5507e0155cc72ea1b14fa`. It is built off the hosts so they need no Go toolchain.
Keys and parameters are generated on the hosts and never leave them except as public data:
# edge, as root
deploy/edge/scripts/awg-keys.sh init /etc/amnezia/amneziawg/awg-lincodex.params
deploy/edge/scripts/awg-keys.sh export /etc/amnezia/amneziawg/awg-lincodex.params > shared.env
# app host, as root, after shared.env is copied over SSH
deploy/edge/scripts/awg-keys.sh init /etc/amnezia/amneziawg/awg-lincodex.params --shared shared.env
deploy/edge/scripts/awg-keys.sh export /etc/amnezia/amneziawg/awg-lincodex.params > app-shared.env
# edge, after app-shared.env is copied back
deploy/edge/scripts/awg-keys.sh peer /etc/amnezia/amneziawg/awg-lincodex.params app-shared.env
The exchanged files contain a public key and the obfuscation parameters. The parameters are shared secrets of the tunnel; delete the copies after use. Then, on each host (`awg-edge` on the edge, `awg-app` on the app host):
deploy/edge/scripts/render.sh --env deploy/edge/edge.env --out /tmp/awg --params /etc/amnezia/amneziawg/awg-lincodex.params awg-edge
sudo install -m 600 /tmp/awg/awg/awg-lincodex.conf /etc/amnezia/amneziawg/awg-lincodex.conf && rm -r /tmp/awg
sudo install -D -m 644 deploy/edge/systemd/awg-quick-userspace.conf /etc/systemd/system/awg-quick@awg-lincodex.service.d/userspace.conf
sudo systemctl daemon-reload && sudo systemctl enable --now awg-quick@awg-lincodex
The app host initiates the handshake from behind NAT and sends a keepalive every `AWG_KEEPALIVE` seconds; the edge has no peer endpoint. `AllowedIPs` lists only the other end's tunnel address, so the tunnel installs no default route and carries nothing else. Check it with `sudo awg show` (a recent `latest handshake`) and `ping <peer tunnel IP>`. The units start at boot. The userspace daemon is one process per interface; systemd does not restart it by itself, so check the handshake after an incident (`systemctl restart awg-quick@awg-lincodex` rebuilds the interface).
### Rollout on the app host
1. Install Docker Engine and the Compose plugin from the official Docker apt repository (`docker-ce`, `docker-compose-plugin`). The tunnel setup above comes first, because the next steps use its address.
2. Make Docker wait for the tunnel: `sudo install -D -m 644 deploy/edge/systemd/docker-after-awg.conf /etc/systemd/system/docker.service.d/10-lincodex-awg.conf && sudo systemctl daemon-reload`. Docker cannot publish a port on an address that does not exist yet, and containers with a restart policy start with the daemon, so the tunnel interface has to exist first.
3. Copy the committed tree of the repository to the host (`git archive HEAD`), copy `.env.example` to `.env` with mode 600, and generate the secrets on the host (passwords, S3 keys, and a `KAFKA_CLUSTER_ID` as described in `.env.example`). Set these values:
APP_HTTP_BIND=10.79.0.2
APP_PUBLIC_URL=https://<EDGE_DOMAIN>
EMAIL_PROVIDER=disabled
`APP_HTTP_BIND` is the address the frontend port is published on; the default `127.0.0.1` keeps a local stack private. `EMAIL_PROVIDER=disabled` sends no mail. To enable mail later, set `EMAIL_PROVIDER=resend`, `RESEND_API_KEY`, and `EMAIL_FROM` in the server `.env` and run `make -C deploy up` again; the key stays only in that file.
4. Start the stack with `make -C deploy up` and check `curl -s http://10.79.0.2:8080/healthz` on the app host.
### Firewall
On the edge host, ufw gains three rules: 80/tcp and 443/tcp to `EDGE_LISTEN_IP`, and the tunnel port over UDP to `AWG_EDGE_ENDPOINT_IP`. The host's other rules, WireGuard interface, and UDP 443 listener are untouched.
On the app host, ufw denies incoming traffic by default and allows SSH only from the LAN (`192.168.10.0/24`); the tunnel port needs no inbound rule because the app host initiates and replies are tracked connections. Apply the SSH rule and check a second session before enabling ufw so a mistake cannot lock the host out:
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow from 192.168.10.0/24 to any port 22 proto tcp
sudo ufw allow in on awg-lincodex from 10.79.0.1 to 10.79.0.2 port 8080 proto tcp
sudo ufw enable
Docker bypasses ufw for published ports: it adds its own NAT and FORWARD rules, so a ufw rule does not stop traffic to a published container port, and the last rule above does not govern it. The control that holds is the publish address. With `APP_HTTP_BIND=10.79.0.2`, the port answers only for packets addressed to the tunnel address, not on the LAN address or on loopback. A host on the same LAN can still send a packet addressed to `10.79.0.2` to the app host's MAC address if it adds a route for that address, so the port is protected from the network only by the tunnel being private and the LAN being trusted. Never publish the frontend port on `0.0.0.0`. Keep every other Compose port unpublished, as the stack already does.
### Renewal and reload
Ubuntu's `certbot.timer` runs `certbot renew` twice a day and renews a certificate that expires within 30 days. The renewal uses the webroot of the first issuance, so port 80 must keep serving `/.well-known/acme-challenge/`. After a renewal, the deploy hook `/etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh` runs `nginx -t && systemctl reload nginx`; it does not run when nothing was renewed. Check the pieces:
sudo certbot renew --dry-run --no-random-sleep-on-renew
systemctl list-timers certbot.timer
sudo certbot certificates
A reload starts new workers with the new certificate and configuration and lets the old workers finish their open connections, so in-flight requests and keep-alive connections are not dropped. Sessions are not held by nginx at all: the planned design keeps them in PostgreSQL behind an opaque cookie, so reloading or restarting nginx or the tunnel does not sign anyone out. Because sign-in is not implemented yet, the available proof is a request in flight and a kept connection across `systemctl reload nginx`: both complete without a 5xx, and the next request on the same connection succeeds.
### Verification
curl -sI http://<domain>/ # 301 to https://<domain>/
curl -sv https://<domain>/ -o /dev/null # valid chain, HTTP/2, Strict-Transport-Security
curl -s https://<domain>/some/deep/link # the SPA index.html
curl -s https://<domain>/api/v1/healthz # 200 from Go through both Nginx instances
openssl s_client -connect <EDGE_LISTEN_IP>:443 -servername <domain> -tls1_1 # handshake fails
openssl s_client -connect <EDGE_LISTEN_IP>:443 -servername <domain> -tls1_2 # works
When the local resolver does not return the public address, add `--resolve <domain>:443:<EDGE_LISTEN_IP>` to the curl commands.
### Rollback
- Take the site off the air without touching the edge host's other services: `sudo rm /etc/nginx/conf.d/lincodex-https.conf && sudo nginx -t && sudo systemctl reload nginx`. Port 80 then redirects to an HTTPS address that no longer answers, so remove `lincodex-http.conf` too if the redirect is unwanted. `sudo systemctl disable --now nginx` stops nginx entirely.
- Remove the certificate: `sudo certbot delete --cert-name <domain>`, and the hook file if nothing else uses it. Disable `certbot.timer` only if no other certificate depends on it.
- Remove the firewall rules by number after `sudo ufw status numbered`, checking the rule text, never the existing ones: the 80/tcp, 443/tcp, and tunnel UDP rules carry a `lincodex` comment.
- Tunnel: `sudo systemctl disable --now awg-quick@awg-lincodex` on both hosts, then remove `/etc/systemd/system/awg-quick@awg-lincodex.service.d`, `/etc/systemd/system/docker.service.d/10-lincodex-awg.conf` (app host), `/etc/amnezia/amneziawg/awg-lincodex.*`, and `/usr/local/bin/amneziawg-go`; `sudo dpkg -r amneziawg-tools` removes the tools.
- App host: set `APP_HTTP_BIND=127.0.0.1` in `.env` and run `make -C deploy up` to publish the frontend on loopback again, or `make -C deploy down` to stop the stack (volumes are kept).
- Packages: `sudo apt-get remove nginx certbot` leaves `/etc/letsencrypt` in place; deleting it also deletes the private key.
### Limits
This is one edge host and one app host. There is no failover, no external uptime check, and no rate limiting at the edge (the backend rate limits are separate and not implemented yet). The certificate covers only the one name, the site is IPv4 only, and the ACME account has no contact address. The tunnel carries no authentication beyond the AmneziaWG keys, and the obfuscation parameters raise the cost of blocking but are not a security control.
## Services and images
Container images use moving `latest` or `alpine` tags where the upstream publishes them. Check the current Compose references when updating the stack. These tags can move; the [release manifest](#release-manifest) records the actual image digests of a release. An SBOM is not produced yet. Application dependency lockfiles remain checked in separately.
+161
View File
@@ -311,6 +311,167 @@ Frontend телеметрия пока не подключена в React-при
Для удаленного ML scrape задайте ML_METRICS_TARGET в формате hostname:port или IPv4:port и проверьте private routing/firewall. Standalone ML host пока не имеет отдельного Alloy config для доставки своих контейнерных логов в Loki.
## Edge proxy, HTTPS и туннель
Compose-стенд отдает обычный HTTP на хосте. Публичный сайт ставит перед ним отдельный edge-хост: он завершает TLS и пересылает каждый запрос через выделенный туннель на app-хост. Файлы лежат в `deploy/edge/`; этот раздел - runbook. Он описывает конфигурацию в репозитории. Раскатка - внешнее действие, а шаги проверки ниже показывают, что раскатка должна доказать.
браузер --HTTPS--> edge nginx (EDGE_LISTEN_IP:80,443)
--туннель AmneziaWG (10.79.0.0/30)--> app-хост (10.79.0.2:8080)
= frontend контейнер (Nginx) --> backend
| Роль | Что работает | Адрес в эталонной раскатке |
| --- | --- | --- |
| Edge-хост | nginx, certbot, серверный конец AmneziaWG | публичные `213.165.42.19` и `89.185.85.208`; туннель `10.79.0.1` |
| App-хост | основной стек Docker Compose, клиентский конец AmneziaWG | LAN `192.168.10.111` за NAT; туннель `10.79.0.2` |
Edge-хост общий с другими сервисами. Здесь все только добавляется: nginx слушает один адрес из `EDGE_LISTEN_IP` и никогда wildcard, туннель использует собственный интерфейс и подсеть, существующие интерфейсы, listeners, контейнеры и правила firewall не меняются.
### Конфигурация
Все имена и адреса берутся из `deploy/edge/edge.env` (скопируйте `deploy/edge/edge.env.example`; в файле нет секретов, Git его игнорирует). Основные значения: `EDGE_DOMAIN`, `EDGE_CERT_NAME`, `EDGE_LISTEN_IP`, `EDGE_ACME_WEBROOT`, `EDGE_HSTS_MAX_AGE`, `EDGE_MAX_BODY` и значения туннеля `AWG_IFACE`, `AWG_EDGE_IP`, `AWG_APP_IP`, `AWG_PREFIX`, `AWG_EDGE_ENDPOINT_IP`, `AWG_PORT`, `AWG_MTU`, `AWG_KEEPALIVE`. Edge проксирует на `AWG_APP_IP:APP_HTTP_PORT`. Подсеть туннеля не должна пересекаться ни с одним маршрутом или диапазоном Docker на обоих хостах; проверка - `ip route` на каждом.
make -C deploy edge-config # отрисовать шаблоны и выполнить nginx -t в контейнере
make -C deploy edge-render # записать deploy/edge/rendered/nginx
`edge-config` отрисовывает шаблоны nginx и оба шаблона туннеля (с одноразовыми ключами), падает, если у placeholder нет значения или директива `listen` не привязана к `EDGE_LISTEN_IP`, и выполняет `nginx -t` в `nginx:stable-alpine` (образ меняет `EDGE_NGINX_IMAGE`) с самоподписанным сертификатом по пути, который ждет конфигурация. Нужен Docker; проверка доказывает только синтаксис, но не наличие сертификата и не доступность хоста. Пакет Ubuntu на edge - nginx 1.28; держите образ близко к нему.
`deploy/edge/scripts/render.sh` проверяет каждое значение до подстановки. Ключи и параметры обфускации не входят в `edge.env`: `deploy/edge/scripts/awg-keys.sh` записывает их в файл параметров, доступный только root, на каждом хосте (`/etc/amnezia/amneziawg/awg-lincodex.params`), а `render.sh --params` читает этот файл и создает конфигурацию туннеля.
### Один origin и Secure cookie
Браузер видит только `https://<EDGE_DOMAIN>`. SPA и `/api` приходят с одного origin: edge пересылает каждый путь без изменений, а frontend контейнер отдает SPA с запасным вариантом `try_files ... /index.html`, поэтому глубокая ссылка вроде `/some/deep/link` возвращает SPA, и проксирует `/api/` в Go. Планируемая cookie сессии - `__Host-lincodex_session` с `Secure`, `HttpOnly` и `SameSite=Strict`. Браузер принимает ее только со страницы HTTPS, с `Path=/` и без `Domain`; один HTTPS origin это обеспечивает. Edge сохраняет `Host` как публичное имя и ставит `X-Forwarded-Proto: https`; Nginx frontend контейнера сохраняет это значение для backend (`$forwarded_proto` в `deploy/nginx/conf.d/app.conf`), а иначе сообщает собственную схему. `APP_PUBLIC_URL` в `.env` app-хоста должен быть `https://<EDGE_DOMAIN>`: это единственное значение origin, которое читает backend.
Регистрация и вход еще не реализованы (операции отвечают 501), и backend не читает `X-Forwarded-Proto`. Поэтому вход через edge целиком не проверен; проверен транспорт, который нужен cookie (HTTPS, один origin, переданные исходные хост и схема).
### Обработка запросов на edge
- Порт 80 отдает только `/.well-known/acme-challenge/` из `EDGE_ACME_WEBROOT`, а остальное перенаправляет кодом 301 на `https://<EDGE_DOMAIN>` с исходным путем и query. Цель - настроенное имя, а не `Host` запроса. Запрос с любым другим именем обрывается (nginx 444) на порту 80 и отклоняется на TLS handshake на порту 443.
- Порт 443 разрешает TLS 1.2 и 1.3 с набором шифров Mozilla intermediate, HTTP/2, без session tickets и отдает `Strict-Transport-Security: max-age=<EDGE_HSTS_MAX_AGE>; includeSubDomains` без `preload`. По умолчанию max-age - 180 дней; поднимите до года и рассматривайте preload только после того, как сайт какое-то время проработает на HTTPS. Заголовки безопасности от frontend контейнера (`X-Content-Type-Options`, `Referrer-Policy`, `X-Frame-Options`, `Permissions-Policy`) проходят насквозь.
- OCSP stapling выключен намеренно: сертификаты Let's Encrypt больше не содержат URL OCSP-ответчика, прикреплять нечего. HTTP/3 выключен, потому что ему нужен UDP 443, который занят другим сервисом на edge-хосте.
- Сжатие выключено для `/api/` и в остальных местах ограничено CSS, JavaScript, SVG и HTML-оболочкой (JSON не сжимается). Сжатие ответов, где секрет смешан с управляемым атакующим содержимым, открывает BREACH; CSRF-токен в ответе API нельзя сжимать никогда. Пересмотрите это, если секрет когда-либо окажется в HTML.
- `X-Forwarded-For` и `X-Real-IP` заменяются адресом подключения, а не дополняют значения клиента, потому что edge - первый доверенный узел. Frontend контейнер затем добавляет адрес туннеля, поэтому backend читает адрес клиента как первую запись `X-Forwarded-For`. Собственный `X-Real-IP` контейнера и лимит `/telemetry` видят адрес пира туннеля или шлюза Docker, поэтому все клиенты делят одну корзину, пока контейнер не станет доверять edge для реальных адресов клиентов.
- `client_max_body_size` равен `EDGE_MAX_BODY` (10 МБ, как лимит контейнера). Лимит резюме 5 МБ - политика конкретной функции, ее проверяет backend. Тайм-ауты: 5 с на соединение, 60 с на отправку и чтение (контейнер дает Go 30 с), 60 с на тело запроса.
- Журнал доступа (`/var/log/nginx/lincodex.access.log`, ротируется правилом logrotate из пакета) пишет путь без query string, поэтому значения вроде адресов в query в журнал не попадают.
### Раскатка на edge-хосте
Только пакеты Ubuntu; без обновления системы. Установите nginx и certbot, не запуская nginx на его стандартном wildcard-сайте:
printf '#!/bin/sh\nexit 101\n' | sudo tee /usr/sbin/policy-rc.d >/dev/null && sudo chmod 755 /usr/sbin/policy-rc.d
sudo apt-get install -y --no-install-recommends nginx certbot
sudo rm -f /usr/sbin/policy-rc.d /etc/nginx/sites-enabled/default
1. Проверьте, что домен указывает на `EDGE_LISTEN_IP` (`dig +short <domain> @1.1.1.1`) и что на TCP 80 и 443 никто не слушает (`ss -tlnp`).
2. Скопируйте `deploy/edge` на хост, создайте `edge.env` и отрисуйте: `deploy/edge/scripts/render.sh --env deploy/edge/edge.env --out deploy/edge/rendered nginx`.
3. Установите каталог ACME и первые два файла, затем правила firewall (ufw только получает правила; держите вторую SSH-сессию открытой на время изменений):
sudo install -d -m 755 /var/www/certbot
sudo install -m 644 deploy/edge/rendered/nginx/00-default.conf deploy/edge/rendered/nginx/lincodex-http.conf /etc/nginx/conf.d/
sudo nginx -t
sudo ufw allow in to <EDGE_LISTEN_IP> port 80 proto tcp comment 'lincodex ACME and redirect'
sudo ufw allow in to <EDGE_LISTEN_IP> port 443 proto tcp comment 'lincodex HTTPS'
sudo systemctl enable --now nginx
4. Установите hook продления и выпустите сертификат. Сначала выполните dry run на staging: боевой CA ограничивает повторные ошибки. У аккаунта нет email (`--register-unsafely-without-email`), поэтому Let's Encrypt не пришлет уведомления об истечении; адрес можно добавить позже через `certbot update_account --email <address>`. `--agree-tos` принимает соглашение подписчика Let's Encrypt.
sudo install -d -m 755 /etc/letsencrypt/renewal-hooks/deploy
sudo install -m 755 deploy/edge/certbot/reload-nginx.sh /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh
sudo certbot certonly --webroot -w /var/www/certbot -d <domain> --cert-name <domain> \
--register-unsafely-without-email --agree-tos --non-interactive --dry-run
sudo certbot certonly --webroot -w /var/www/certbot -d <domain> --cert-name <domain> \
--register-unsafely-without-email --agree-tos --non-interactive
5. Установите файл HTTPS и перезагрузите конфигурацию: `sudo install -m 644 deploy/edge/rendered/nginx/lincodex-https.conf /etc/nginx/conf.d/ && sudo nginx -t && sudo systemctl reload nginx`. Пока туннель и app-хост не подняты, сайт отвечает 502 или 504.
6. Установите конец туннеля (ниже), затем `sudo ufw allow in to <AWG_EDGE_ENDPOINT_IP> port <AWG_PORT> proto udp comment 'lincodex tunnel'`.
### Туннель
AmneziaWG работает в userspace (`amneziawg-go`), чтобы ничто не зависело от модуля ядра под ядро хоста. Оба хоста используют одни и те же две части:
- `amneziawg-tools` (`awg`, `awg-quick` и unit `awg-quick@.service`) из пакета Amnezia PPA для релиза: пакет скачивается, сверяется с SHA-256 из индекса PPA и ставится через `dpkg -i`. PPA в apt не добавляется, поэтому пакет сам не обновляется.
- `amneziawg-go`, собранный из тега upstream `v3.1.20260828` (коммит `b5928efb6ca1`) командой `CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "-s -w"` и установленный как `/usr/local/bin/amneziawg-go`. У эталонной сборки SHA-256 `5e8877b58afdc4667be196aebb994839d167a4f189c5507e0155cc72ea1b14fa`. Ее собирают вне хостов, чтобы им не нужен toolchain Go.
Ключи и параметры создаются на хостах и покидают их только как публичные данные:
# edge, от root
deploy/edge/scripts/awg-keys.sh init /etc/amnezia/amneziawg/awg-lincodex.params
deploy/edge/scripts/awg-keys.sh export /etc/amnezia/amneziawg/awg-lincodex.params > shared.env
# app-хост, от root, после копирования shared.env по SSH
deploy/edge/scripts/awg-keys.sh init /etc/amnezia/amneziawg/awg-lincodex.params --shared shared.env
deploy/edge/scripts/awg-keys.sh export /etc/amnezia/amneziawg/awg-lincodex.params > app-shared.env
# edge, после копирования app-shared.env обратно
deploy/edge/scripts/awg-keys.sh peer /etc/amnezia/amneziawg/awg-lincodex.params app-shared.env
Передаваемые файлы содержат публичный ключ и параметры обфускации. Параметры - общие секреты туннеля; удалите копии после использования. Затем на каждом хосте (`awg-edge` на edge, `awg-app` на app-хосте):
deploy/edge/scripts/render.sh --env deploy/edge/edge.env --out /tmp/awg --params /etc/amnezia/amneziawg/awg-lincodex.params awg-edge
sudo install -m 600 /tmp/awg/awg/awg-lincodex.conf /etc/amnezia/amneziawg/awg-lincodex.conf && rm -r /tmp/awg
sudo install -D -m 644 deploy/edge/systemd/awg-quick-userspace.conf /etc/systemd/system/awg-quick@awg-lincodex.service.d/userspace.conf
sudo systemctl daemon-reload && sudo systemctl enable --now awg-quick@awg-lincodex
App-хост инициирует handshake из-за NAT и шлет keepalive каждые `AWG_KEEPALIVE` секунд; у edge адреса пира нет. `AllowedIPs` содержит только туннельный адрес другого конца, поэтому туннель не ставит маршрут по умолчанию и не несет другого трафика. Проверка: `sudo awg show` (свежий `latest handshake`) и `ping <туннельный адрес пира>`. Юниты стартуют при загрузке. Демон userspace - один процесс на интерфейс; systemd сам его не перезапускает, поэтому после инцидента проверяйте handshake (`systemctl restart awg-quick@awg-lincodex` пересоздает интерфейс).
### Раскатка на app-хосте
1. Установите Docker Engine и плагин Compose из официального apt-репозитория Docker (`docker-ce`, `docker-compose-plugin`). Туннель из раздела выше настраивается раньше, потому что следующие шаги используют его адрес.
2. Заставьте Docker ждать туннель: `sudo install -D -m 644 deploy/edge/systemd/docker-after-awg.conf /etc/systemd/system/docker.service.d/10-lincodex-awg.conf && sudo systemctl daemon-reload`. Docker не может опубликовать порт на адресе, которого еще нет, а контейнеры с политикой перезапуска стартуют вместе с демоном, поэтому интерфейс туннеля должен существовать раньше.
3. Скопируйте на хост зафиксированное дерево репозитория (`git archive HEAD`), скопируйте `.env.example` в `.env` с правами 600 и создайте секреты на хосте (пароли, ключи S3 и `KAFKA_CLUSTER_ID`, как описано в `.env.example`). Задайте значения:
APP_HTTP_BIND=10.79.0.2
APP_PUBLIC_URL=https://<EDGE_DOMAIN>
EMAIL_PROVIDER=disabled
`APP_HTTP_BIND` - адрес, на котором публикуется порт frontend; значение по умолчанию `127.0.0.1` оставляет локальный стенд закрытым. `EMAIL_PROVIDER=disabled` почту не отправляет. Чтобы включить почту позже, задайте в `.env` на сервере `EMAIL_PROVIDER=resend`, `RESEND_API_KEY` и `EMAIL_FROM` и снова выполните `make -C deploy up`; ключ хранится только в этом файле.
4. Запустите стек командой `make -C deploy up` и проверьте `curl -s http://10.79.0.2:8080/healthz` на app-хосте.
### Firewall
На edge-хосте ufw получает три правила: 80/tcp и 443/tcp на `EDGE_LISTEN_IP` и порт туннеля по UDP на `AWG_EDGE_ENDPOINT_IP`. Остальные правила хоста, интерфейс WireGuard и listener UDP 443 не затрагиваются.
На app-хосте ufw по умолчанию запрещает входящий трафик и разрешает SSH только из LAN (`192.168.10.0/24`); порту туннеля входящее правило не нужно, потому что app-хост инициирует соединение, а ответы - отслеживаемые соединения. Задайте правило SSH и проверьте вторую сессию до включения ufw, чтобы ошибка не заблокировала доступ:
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow from 192.168.10.0/24 to any port 22 proto tcp
sudo ufw allow in on awg-lincodex from 10.79.0.1 to 10.79.0.2 port 8080 proto tcp
sudo ufw enable
Docker обходит ufw для опубликованных портов: он добавляет собственные правила NAT и FORWARD, поэтому правило ufw не останавливает трафик на опубликованный порт контейнера, и последнее правило выше его не регулирует. Работает адрес публикации. При `APP_HTTP_BIND=10.79.0.2` порт отвечает только на пакеты, адресованные туннельному адресу, а не на адрес LAN или loopback. Хост в той же LAN все же может отправить пакет с адресом `10.79.0.2` на MAC app-хоста, если добавит маршрут, поэтому от сети порт защищают только приватность туннеля и доверие к LAN. Никогда не публикуйте порт frontend на `0.0.0.0`. Остальные порты Compose оставляйте неопубликованными, как стек и делает.
### Продление и reload
`certbot.timer` из Ubuntu запускает `certbot renew` дважды в сутки и продлевает сертификат, которому осталось меньше 30 дней. Продление использует webroot первого выпуска, поэтому порт 80 должен и дальше отдавать `/.well-known/acme-challenge/`. После продления deploy hook `/etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh` выполняет `nginx -t && systemctl reload nginx`; если продления не было, он не запускается. Проверка частей:
sudo certbot renew --dry-run --no-random-sleep-on-renew
systemctl list-timers certbot.timer
sudo certbot certificates
Reload запускает новые workers с новым сертификатом и конфигурацией и дает старым workers дойти до конца открытых соединений, поэтому запросы в полете и keep-alive соединения не обрываются. Сессии nginx вообще не хранит: планируемая схема держит их в PostgreSQL за непрозрачной cookie, поэтому reload или перезапуск nginx или туннеля никого не разлогинивает. Пока вход не реализован, доступное доказательство - запрос в полете и удерживаемое соединение через `systemctl reload nginx`: оба завершаются без 5xx, а следующий запрос по тому же соединению проходит.
### Проверка
curl -sI http://<domain>/ # 301 на https://<domain>/
curl -sv https://<domain>/ -o /dev/null # валидная цепочка, HTTP/2, Strict-Transport-Security
curl -s https://<domain>/some/deep/link # index.html SPA
curl -s https://<domain>/api/v1/healthz # 200 от Go через оба Nginx
openssl s_client -connect <EDGE_LISTEN_IP>:443 -servername <domain> -tls1_1 # handshake не проходит
openssl s_client -connect <EDGE_LISTEN_IP>:443 -servername <domain> -tls1_2 # работает
Если локальный resolver не возвращает публичный адрес, добавьте к командам curl `--resolve <domain>:443:<EDGE_LISTEN_IP>`.
### Откат
- Снять сайт, не трогая другие сервисы edge-хоста: `sudo rm /etc/nginx/conf.d/lincodex-https.conf && sudo nginx -t && sudo systemctl reload nginx`. Порт 80 после этого перенаправляет на адрес HTTPS, который больше не отвечает, поэтому удалите и `lincodex-http.conf`, если редирект не нужен. `sudo systemctl disable --now nginx` останавливает nginx полностью.
- Удалить сертификат: `sudo certbot delete --cert-name <domain>`, и файл hook, если им больше никто не пользуется. Отключайте `certbot.timer` только если от него не зависит другой сертификат.
- Удалить правила firewall по номеру после `sudo ufw status numbered`, сверяя текст правила и не трогая существующие: правила 80/tcp, 443/tcp и UDP туннеля имеют комментарий `lincodex`.
- Туннель: `sudo systemctl disable --now awg-quick@awg-lincodex` на обоих хостах, затем удалить `/etc/systemd/system/awg-quick@awg-lincodex.service.d`, `/etc/systemd/system/docker.service.d/10-lincodex-awg.conf` (app-хост), `/etc/amnezia/amneziawg/awg-lincodex.*` и `/usr/local/bin/amneziawg-go`; `sudo dpkg -r amneziawg-tools` удаляет инструменты.
- App-хост: задайте `APP_HTTP_BIND=127.0.0.1` в `.env` и выполните `make -C deploy up`, чтобы снова опубликовать frontend на loopback, либо `make -C deploy down`, чтобы остановить стек (тома сохраняются).
- Пакеты: `sudo apt-get remove nginx certbot` оставляет `/etc/letsencrypt` на месте; удаление каталога удаляет и закрытый ключ.
### Ограничения
Это один edge-хост и один app-хост. Нет failover, внешней проверки доступности и ограничения частоты запросов на edge (лимиты backend отдельные и еще не реализованы). Сертификат покрывает только одно имя, сайт работает только по IPv4, у аккаунта ACME нет контактного адреса. Туннель не имеет аутентификации кроме ключей AmneziaWG, а параметры обфускации повышают цену блокировки, но не являются мерой безопасности.
## Сервисы и образы
Для контейнерных образов выбраны moving tags `latest` или `alpine`, если upstream публикует такой вариант. При обновлении Compose сверяйте актуальные ссылки на образы. Теги `latest` и `alpine` могут перемещаться; фактические image digests выпуска фиксирует [манифест выпуска](#манифест-выпуска). SBOM пока не формируется. Lockfiles прикладных зависимостей сохраняются отдельно.