feat(deploy): add edge proxy HTTPS and AmneziaWG tunnel templates
This commit is contained in:
1 parent
bdc5855001
commit
b8c3c83ed8
21 files changed
+954
-3
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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 прикладных зависимостей сохраняются отдельно.
|
||||
|
||||
Reference in new issue
Block a user