UI delivery: plan, summary and docs (CSP origins, --csp-connect-extra, nginx-unprivileged)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3347fffe8e
commit
b61989bd22
13 files changed
+203
-9
No files matched your search
@@ -0,0 +1,77 @@
|
||||
# Доставка UI: сборка, CSP и nginx без root (сводка, 2026-10-07)
|
||||
|
||||
План: [2026-10-07_UI_Delivery_Hardening_PLAN.md](2026-10-07_UI_Delivery_Hardening_PLAN.md). Выполнены этапы A-D, по коммиту на этап, последний коммит - документация. Код `APP_UI/src`, бэкенд (`APP_CORE`, `APP_PROFILER`), B4 (`disable-2fa`) и разбиение `BackupRestore.vue` не менялись.
|
||||
|
||||
Решения владельца: для этапа D взят `nginxinc/nginx-unprivileged:alpine` (порт 8080); переменная называется `OVPMON_CSP_CONNECT_EXTRA` (внутри контейнеров `OVP_CSP_CONNECT_EXTRA`), значение - origin через пробел.
|
||||
|
||||
## 1. Что сделано
|
||||
|
||||
### Этап A. `deploy/ui-dist` (коммит `d38acd7`)
|
||||
|
||||
`check-ui.sh` до пересборки: `stale` (сборка `7960728...`, исходники `d778aa1...`). `build-ui.sh --publish` (режим Docker, `node:20-alpine`) опубликовал сборку с `SOURCE_HASH d778aa16...`; `check-ui.sh` после: `fresh`. В коммит вошёл только `deploy/ui-dist` (новые файлы `Clients-*.js`, `useFormatters-*.js`, `useTrafficChart-*.js`, удалены `vite.svg` и старые хеши). Временных файлов в дереве нет.
|
||||
|
||||
### Этап B. CSP и дополнительные origin для `connect-src` (коммит `d5e83ea`)
|
||||
|
||||
| Шаг | Результат |
|
||||
|---|---|
|
||||
| B1 | `APP_UI/Dockerfile`: `ENV OVP_CSP_CONNECT_EXTRA=""`; шаблон: `connect-src 'self' ${OVP_CSP_CONNECT_EXTRA}`; `docker-compose.yml`: `OVP_CSP_CONNECT_EXTRA: ${OVPMON_CSP_CONNECT_EXTRA:-}` |
|
||||
| B2 | All-in-one: переменная добавлена в явный список `envsubst` в `entrypoint.sh`; `docker-compose.allinone.yml` передаёт `OVPMON_CSP_CONNECT_EXTRA` |
|
||||
| B3 | Единый CSP: `set $csp "..."` на уровне `server`, `add_header Content-Security-Policy $csp always;` в `server` и в `location /assets/` |
|
||||
| B4 | Проверка значения (только `https://host[:port]` и `http://host[:port]`, разделитель - пробелы, пустое допустимо; без `;`, кавычек, запятых, путей, пробела в начале и в конце): `deploy/docker/lib.sh` (`csp_extra_problem`, вызывается из `check_env_file`, то есть в `install.sh` и `update.sh`), `deploy/native/lib.sh` (та же функция), `APP_UI/check-csp-connect-extra.sh` - один скрипт для образа `app-ui` (`/docker-entrypoint.d/15-check-csp-connect-extra.sh`, выполняется до `20-envsubst-on-templates.sh`) и для all-in-one (копируется в образ, вызывается из `entrypoint.sh`). Три копии правила содержат комментарий «держать в согласии» |
|
||||
| B5 | Системный nginx: в `ovpmon.conf.template` добавлен CSP с `@CSP_CONNECT_EXTRA@` (на уровне `server`, `Cache-Control: no-store` остался). `render_nginx SRC PORT OUT [ORIGINS]` проверяет значение и подставляет его с ведущим пробелом, при пустом значении ничего не остаётся. `install.sh` и `update.sh` принимают `--csp-connect-extra ORIGINS`, значение хранится в состоянии `OVPMON_CSP_CONNECT_EXTRA`; `update.sh` без флага берёт его из состояния, `--csp-connect-extra ""` убирает; справка обновлена |
|
||||
| B6 | Документация: `DOCS/UI/Architecture.md`, `DOCS/Deployment/Containers/Reference.md`, `Troubleshooting.md`, `DOCS/Deployment/System_Services/Nginx_Configuration.md` (раздел 4), `README.md`, `Operations.md`, `Reference.md` (состояние), `APP_UI/README.md` |
|
||||
|
||||
### Этап C. `npm ci` в all-in-one (коммит `71ea4c5`)
|
||||
|
||||
`deploy/allinone/Dockerfile`: `npm install` -> `npm ci`.
|
||||
|
||||
### Этап D. nginx без root в `app-ui` (коммит `3347fff`)
|
||||
|
||||
| Шаг | Результат |
|
||||
|---|---|
|
||||
| D1 | `APP_UI/Dockerfile`: база `nginxinc/nginx-unprivileged:alpine`, `EXPOSE 8080`, комментарий о root заменён описанием |
|
||||
| D2 | Шаблон: `listen ${OVP_UI_PORT};`; `ENV OVP_UI_PORT=8080` в образе; в all-in-one `entrypoint.sh` задаёт `OVP_UI_PORT=80` и передаёт в `envsubst` |
|
||||
| D3 | `docker-compose.yml`: `"${OVPMON_HTTP_PORT:-80}:8080"`, healthcheck на `http://127.0.0.1:8080/`. `docker-compose.allinone.yml` не менялся (порт 80) |
|
||||
| D4 | В `deploy/docker/*.sh` внутренний порт 80 контейнера `app-ui` не упоминается (скрипты работают только с портом хоста). В документации обновлены `Containers/Reference.md` и `README.md`; прочие «порт 80» относятся к хосту, системному nginx или вариантам, которых изменение не касается |
|
||||
|
||||
## 2. Проверки (команды и результаты)
|
||||
|
||||
Все проверки в одноразовых контейнерах и образах с именами `ovpchk-*`; рабочие контейнеры `ovp-*` не запускались, не останавливались и не перезапускались.
|
||||
|
||||
| Что | Как | Результат |
|
||||
|---|---|---|
|
||||
| A | `deploy/native/check-ui.sh` до и после `build-ui.sh --publish` | `stale` (код 1) -> `fresh` (код 0) |
|
||||
| B4, правило | 23 значения (допустимые: пусто, один origin, два через пробел, с портом, IP; недопустимые: `;`, запятая, кавычки, путь, `*`, `ftp://`, пустой хост и порт, порт 99999, лишний `:`, пробел в начале и в конце, табуляция, `#`, `&`) через `sh` (dash) и `bash` | `deploy/native/lib.sh` и `deploy/docker/lib.sh` дают одинаковый вывод; скрипт `check-csp-connect-extra.sh` в busybox `ash` (контейнер `alpine:3`) принимает и отклоняет те же значения |
|
||||
| B4, `.env` | `check_env_file` с временным `.env` | пустое и допустимое значения проходят, `https://a.com; x` отклонено с сообщением |
|
||||
| B, `app-ui` | образ из `APP_UI` (на тот момент `nginx:alpine`), `curl -I` на `/`, `/assets/*.css`, `/config.json`, `/clients/some/route`, `/index.html`; пустое и непустое значение | заголовок CSP есть везде, origin в `connect-src`; недопустимое значение: контейнер завершается с кодом 1 и сообщением из `15-check-csp-connect-extra.sh` |
|
||||
| B, all-in-one | сборка образа, одноразовый контейнер (без `NET_ADMIN`, без томов), значения допустимое/пустое/недопустимое | допустимое: `200`, CSP с origin, `nginx -T` содержит `$csp` и `listen 80`, `nginx -t` проходит, запуск дошёл до `supervisord`; пустое: `200`, CSP без лишних origin; недопустимое: `FATAL` и остановка до миграций |
|
||||
| B5, системный nginx | `render_nginx` с пустым и непустым значением (в т.ч. с двойным пробелом между origin), `nginx -t` в контейнере `nginx:alpine` с временным сертификатом | оба конфига проходят; в файле нет остатков `@...@`; при пустом значении `connect-src 'self';`; значение с `;` отклонено до записи файла (код 1); `curl -kI` к одноразовому контейнеру: `Cache-Control: no-store` и CSP на `/` и на маршруте SPA |
|
||||
| B5, маркер | `install_managed` для файла без маркера | код 2, файл не изменён |
|
||||
| B5, справка | `install.sh --help`, `update.sh --help` | флаг описан |
|
||||
| C | `docker build --no-cache --target ui-build -f deploy/allinone/Dockerfile .` (чтобы не взять слой из кэша), затем полная сборка | `npm ci`: 201 пакет, `vite build` проходит |
|
||||
| D | образ `app-ui` на `nginx-unprivileged`: `id`, `ps`, `nginx -T`, `curl`, `wget` (команда healthcheck) | uid 101 (`nginx`), все процессы nginx от `nginx`; `listen 8080`; шаблон отрисован; `/`, `/config.json`, маршрут SPA - `200`, заголовки те же; `/api/x` без бэкенда - `502` (допустимо); `wget -q -O /dev/null http://127.0.0.1:8080/` успешен; порядок скриптов `10-listen`, `15-check-csp...`, `15-local-resolvers.envsh`, `20-envsubst`: проверочный скрипт выполняется и останавливает контейнер до отрисовки |
|
||||
| D, all-in-one | пересборка и запуск после D | `listen 80`, `200`, CSP с origin |
|
||||
| compose | `docker compose config` с временным `JWT_SECRET` | `app-ui`: `target: 8080`, `published: "80"`, `OVP_CSP_CONNECT_EXTRA` передан, healthcheck на 8080; all-in-one: конфигурация корректна |
|
||||
| Синтаксис | `sh -n` для изменённых скриптов | без ошибок |
|
||||
| Уборка | `docker image rm` временных образов (`ovpchk-*`, `nginx:alpine`, `nginxinc/nginx-unprivileged:alpine`), временные каталоги и файлы в `/tmp` | остатков нет |
|
||||
|
||||
## 3. Отклонения от плана
|
||||
|
||||
- Значение с пробелом в начале или в конце отклоняется (план: пробел в начале недопустим; конец добавлен для симметрии).
|
||||
- Проверка для `app-ui` и all-in-one вынесена в один скрипт `APP_UI/check-csp-connect-extra.sh` (план предлагал отдельные реализации); правило при этом продублировано ещё в двух библиотеках `lib.sh`.
|
||||
- В контейнере `app-ui` при пустом значении CSP содержит `connect-src 'self' ;` (пробел перед `;`): `envsubst` подставляет пустую строку. Для политики безвредно. В all-in-one и в системном nginx пробелы нормализуются.
|
||||
- Для системного nginx в шаблоне плейсхолдер стоит без пробела перед ним (`'self'@CSP_CONNECT_EXTRA@;`): `render_nginx` добавляет пробел вместе со значением.
|
||||
|
||||
## 4. Что не проверено
|
||||
|
||||
- Живые `install.sh` / `update.sh` на хосте (native и docker) и `docker compose up` стенда: нужно разрешение владельца. Проверены только отдельные функции (`csp_extra_problem`, `render_nginx`, `check_env_file`, `install_managed`), `sh -n`, справка и `docker compose config`.
|
||||
- Обновление существующей установки контейнеров: при `update.sh` пересоздание `ovp-ui` с портом 8080 внутри не запускалось.
|
||||
- Браузерная проверка CSP (шрифты Font Awesome, inline-стили Bootstrap и Chart.js): браузера в среде нет.
|
||||
- Вызов API другого origin с непустым `OVPMON_CSP_CONNECT_EXTRA` (CORS и `config.json`) проверен только по заголовку.
|
||||
- `update.sh` системных служб на установке с уже записанным состоянием (чтение `OVPMON_CSP_CONNECT_EXTRA` из `deploy.state`) не запускался.
|
||||
|
||||
## 5. Риски и примечания
|
||||
|
||||
- Пользовательские compose-файлы или внешний прокси, которые публикуют порт 80 контейнера `ovp-ui`, нужно перевести на 8080 (внешний порт хоста не меняется).
|
||||
- Образ `nginx-unprivileged` не входит в закреплённые версии (тег `alpine`); при необходимости зафиксировать версию.
|
||||
- Значение CSP попадает в заголовок ответа: проверка обязательна, при изменении правила менять все три копии (`deploy/native/lib.sh`, `deploy/docker/lib.sh`, `APP_UI/check-csp-connect-extra.sh`).
|
||||
@@ -0,0 +1,70 @@
|
||||
# Доставка UI: сборка, CSP и nginx без root (план, 2026-10-07)
|
||||
|
||||
Основание: открытые пункты после `2026-10-07_UI_Review_Fixes.md`. Код `APP_UI/src` не меняется. B4 (`disable-2fa`) и разбиение `BackupRestore.vue` остаются вне плана.
|
||||
|
||||
## 1. Что найдено при подготовке
|
||||
|
||||
| Факт | Следствие |
|
||||
|---|---|
|
||||
| `SOURCE_HASH` считается по `APP_UI/src`, `public`, `index.html`, `package*.json`, `vite.config.js`, `jsconfig.json`. Шаблон nginx и `Dockerfile` в хеш не входят | `deploy/ui-dist` устарел из-за этапов 1-4 прошлого изменения; пересборка нужна один раз и не зависит от остальных этапов этого плана |
|
||||
| Шаблон `APP_UI/default.conf.template` общий для образа `app-ui` и all-in-one. Образ `app-ui` подставляет переменные окружения сам, all-in-one вызывает `envsubst` с явным списком `OVP_*` (`deploy/allinone/entrypoint.sh:78`) | Новая переменная должна быть добавлена в оба места, иначе в конфиге останется буквальный `${...}` |
|
||||
| CSP в шаблоне записан дважды (в `server` и в `location /assets/`) | Единый источник: `set $csp "..."` на уровне `server`, `add_header Content-Security-Policy $csp always` в обоих местах |
|
||||
| Системный nginx (`deploy/native/nginx/ovpmon.conf.template`) отдаёт `Cache-Control: no-store` на всё и не имеет CSP; параметры (`HTTPS_PORT`) хранятся через `state_set` и подставляются `render_nginx` | Новый параметр хранится так же; существующие установки получают CSP при `update.sh`, пока в файле есть маркер управления |
|
||||
| Healthcheck `app-ui` и публикация порта в `docker-compose.yml` привязаны к порту 80 | Для nginx без root порт меняется на 8080: правки compose и healthcheck |
|
||||
|
||||
## 2. Этапы
|
||||
|
||||
### Этап A. Пересборка `deploy/ui-dist` (пункт 2)
|
||||
|
||||
1. `deploy/native/check-ui.sh`: зафиксировать `stale` до пересборки.
|
||||
2. `deploy/native/build-ui.sh --publish` (на хосте Node 18, поэтому режим Docker, образ `node:20-alpine`).
|
||||
3. `check-ui.sh`: результат `ok`.
|
||||
4. Коммит `deploy/ui-dist` отдельно от остальных этапов.
|
||||
|
||||
### Этап B. CSP для другого origin API (пункт 3)
|
||||
|
||||
| Шаг | Что делаем |
|
||||
|---|---|
|
||||
| B1 | Контейнеры: переменная `OVP_CSP_CONNECT_EXTRA` (пусто по умолчанию, значение: origin через пробел, например `https://api.example.com`). `ENV OVP_CSP_CONNECT_EXTRA=""` в `APP_UI/Dockerfile`; в шаблоне `connect-src 'self' ${OVP_CSP_CONNECT_EXTRA}`; в `docker-compose.yml` `OVP_CSP_CONNECT_EXTRA: ${OVPMON_CSP_CONNECT_EXTRA:-}` |
|
||||
| B2 | All-in-one: добавить переменную в список `envsubst` и значение по умолчанию в `entrypoint.sh`; `docker-compose.allinone.yml` передаёт `OVPMON_CSP_CONNECT_EXTRA` |
|
||||
| B3 | Единый CSP через `set $csp` (см. выше) |
|
||||
| B4 | Проверка значения: допускаются только `https://host[:port]` и `http://host[:port]` без пробелов, `;` и кавычек (иначе можно внедрить директиву CSP). Для контейнеров проверка в `entrypoint.sh` (all-in-one) и в `deploy/docker/lib.sh` (скрипты установки); для `app-ui` без entrypoint проверка там же, где читается `.env` |
|
||||
| B5 | Системный nginx: CSP добавляется в `ovpmon.conf.template` с плейсхолдером `@CSP_CONNECT_EXTRA@`; `render_nginx` подставляет значение из `state_get OVPMON_CSP_CONNECT_EXTRA` (по умолчанию пусто); `install.sh` и `update.sh` принимают `--csp-connect-extra ORIGINS` и сохраняют его через `state_set`. `Cache-Control: no-store` остаётся |
|
||||
| B6 | Документация: `DOCS/UI/Architecture.md`, `DOCS/Deployment/Containers/Reference.md`, `DOCS/Deployment/System_Services/Nginx_Configuration.md` и `Reference.md` |
|
||||
|
||||
### Этап C. `npm ci` в all-in-one (пункт 4, часть 1)
|
||||
|
||||
`deploy/allinone/Dockerfile`: `npm install` заменить на `npm ci`; сборка образа и `docker-compose.allinone.yml` не меняются. Проверка: `docker build -f deploy/allinone/Dockerfile .` во временный образ (после проверки удалить).
|
||||
|
||||
### Этап D. nginx без root в образе `app-ui` (пункт 5)
|
||||
|
||||
Решение: `nginxinc/nginx-unprivileged:alpine` (шаблоны из `/etc/nginx/templates` рендерятся как и раньше, процесс от пользователя `nginx`, порт 8080).
|
||||
|
||||
| Шаг | Что делаем |
|
||||
|---|---|
|
||||
| D1 | `APP_UI/Dockerfile`: базовый образ `nginxinc/nginx-unprivileged:alpine`, `EXPOSE 8080`; убрать комментарий о root |
|
||||
| D2 | Шаблон: `listen ${OVP_UI_PORT}`. `ENV OVP_UI_PORT=8080` в Dockerfile; в all-in-one значение 80 задаёт `entrypoint.sh` (все процессы там под supervisord от root для OpenVPN, образ не меняется) |
|
||||
| D3 | `docker-compose.yml`: `"${OVPMON_HTTP_PORT:-80}:8080"`, healthcheck на `http://127.0.0.1:8080/`. Внешний порт не меняется |
|
||||
| D4 | Проверка `deploy/docker/*.sh` и документации на упоминания внутреннего порта 80 `app-ui` |
|
||||
| D5 | Проверка в одноразовом контейнере: `nginx -t`, `id` (не root), `curl -I` (заголовки, 200 на `/`, прокси `/api/` отвечает 502 без бэкенда, что допустимо) |
|
||||
|
||||
Если образ без root не подходит (например, политика на образы), этап D откладывается, остальное не затрагивается.
|
||||
|
||||
## 3. Порядок и коммиты
|
||||
|
||||
A, B, C, D: по одному коммиту, этапы независимы. Код пишет субагент (Sonnet 5.5, Medium) после утверждения плана.
|
||||
|
||||
## 4. Проверки
|
||||
|
||||
- **A:** `check-ui.sh` до и после.
|
||||
- **B:** `nginx -t` на шаблоне с пустым и непустым `OVP_CSP_CONNECT_EXTRA`; `curl -I` показывает origin в `connect-src`; недопустимое значение (`;`, пробел в начале, кавычка) отклоняется с понятным сообщением. Для системного nginx: `render_nginx` во временный файл и `nginx -t` в одноразовом контейнере; `update.sh` не затирает файл без маркера.
|
||||
- **C, D:** сборка образов, `nginx -t`, `curl -I`, `docker image rm` временных образов.
|
||||
- Рабочие контейнеры и службы не трогаем; живая проверка `install.sh`/`update.sh` и compose на стенде делается только с разрешения владельца.
|
||||
- Автотесты не добавляем (оболочка и конфигурация).
|
||||
|
||||
## 5. Риски
|
||||
|
||||
- Значение CSP попадает в заголовок: без проверки B4 можно внедрить лишнюю директиву, поэтому проверка обязательна.
|
||||
- Этап D меняет внутренний порт образа: при пользовательских compose-файлах, ссылающихся на порт 80 контейнера `ovp-ui`, нужно обновить публикацию порта. Указать в сводке.
|
||||
- Браузерная проверка (шрифты Font Awesome, inline-стили под CSP) остаётся ручной: в среде нет браузера.
|
||||
- По завершении: сводка `2026-10-07_UI_Delivery_Hardening.md`, строка в `DOCS/Changes/README.md`, обновление `README.md` проекта и профильных документов.
|
||||
@@ -26,3 +26,4 @@ Every change has a plan (`*_PLAN.md`) before it and a summary of what was done a
|
||||
| 2026-10-07 | Резервное копирование: замечания и дополнения: имя сервера и точное время UTC в имени пакета, назначения SFTP (закрепление отпечатка ключа хоста) и FTP/FTPS, миграции монитора в образе профилировщика (вариант B), ограничение частоты сообщений сборщика, раздел Backups в Security_Architecture | [plan](2026-10-07_Backup_Restore_Fixes_PLAN.md) · [change](2026-10-07_Backup_Restore_Fixes.md) · [guide](../Profiler_Management/Backup_Restore.md) |
|
||||
| 2026-10-07 | Проверка скриптов установки и миграции на новом коде: проверка версии compose для варианта B (Docker Compose 2.17+), `ovpmon_backup.db` в резервной копии и восстановлении системных служб | [plan](2026-10-07_Deploy_Scripts_Check_PLAN.md) · [change](2026-10-07_Deploy_Scripts_Check.md) |
|
||||
| 2026-10-07 | Ревью фронта: 401 на `/auth/*` не разлогинивает, панель Expiring, `vpn_netmask` при сохранении (раньше сбрасывалась в /24), заголовки безопасности и кэш в nginx, `npm ci`, общий код графиков, `ConfirmModal` и тосты вместо `confirm()`/SweetAlert2, отдельный клиент `/api/auth`, доступность, ESLint и Vitest | [plan](2026-10-07_UI_Review_Fixes_PLAN.md) · [change](2026-10-07_UI_Review_Fixes.md) |
|
||||
| 2026-10-07 | Доставка UI: пересборка `deploy/ui-dist`, единый CSP с `OVPMON_CSP_CONNECT_EXTRA` (контейнеры и системный nginx, флаг `--csp-connect-extra`), `npm ci` в all-in-one, `app-ui` на `nginx-unprivileged` (порт 8080 внутри) | [plan](2026-10-07_UI_Delivery_Hardening_PLAN.md) · [change](2026-10-07_UI_Delivery_Hardening.md) |
|
||||
@@ -64,7 +64,7 @@ deploy/docker/install.sh --variant b --project ovpmon --http-port 8080 --vpn-por
|
||||
What `install.sh` does:
|
||||
|
||||
1. **Preflight:** docker and compose, running daemon, the other variant is not running, no foreign container with the same names, ports free, free disk space.
|
||||
2. **`.env`** next to the compose files, only if it does not exist: mode 600, random `JWT_SECRET`, initial administrator with a generated 24-character password. An existing `.env` is never overwritten (`--http-port` / `--vpn-port` only set their own keys in it).
|
||||
2. **`.env`** next to the compose files, only if it does not exist: mode 600, random `JWT_SECRET`, initial administrator with a generated 24-character password. An existing `.env` is never overwritten (`--http-port` / `--vpn-port` only set their own keys in it). It also checks `OVPMON_CSP_CONNECT_EXTRA` when set (see [Reference](Reference.md)).
|
||||
3. **Build, start** (`docker compose up -d`), write the state file `.ovpmon-deploy` (variant and project; used by `update.sh`, `backup.sh`, `restore.sh`), wait up to 3 minutes for the health checks.
|
||||
4. **Initial administrator:** when the users table is not empty, `OVPMON_INITIAL_ADMIN_*` are removed from `.env` and the container that reads them is recreated (variant B: `app-api`, variant A: `ovpmon`). If the table cannot be read or is empty, the lines stay in `.env` and a warning says so.
|
||||
5. **Result:** URL, ports, and the administrator login and password. **The password is shown once** and stored nowhere else. `JWT_SECRET` is never printed.
|
||||
|
||||
@@ -9,7 +9,8 @@ Configuration (`.env`), ports and volumes of the container installation. Install
|
||||
| `JWT_SECRET` | yes | none (compose refuses to start) | Signing key of both APIs (`OVPMON_API_SECRET_KEY`). At least 32 characters, no `change-me`/`changeme`: `install.sh`, `update.sh` and the all-in-one container refuse a weak value. Changing it logs every user out. Keep the same value across updates |
|
||||
| `OVPMON_INITIAL_ADMIN_USER`, `OVPMON_INITIAL_ADMIN_PASSWORD` | first start only | empty | Seed for the first user, used only while the users table is empty. Removed by `install.sh` afterwards |
|
||||
| `OVPMON_CORS_ORIGINS` | no | empty (off) | Comma-separated extra origins; the UI is same-origin behind nginx |
|
||||
| `OVPMON_HTTP_PORT` | no | `80` | Host port of the UI |
|
||||
| `OVPMON_HTTP_PORT` | no | `80` | Host port of the UI (variant B: mapped to port 8080 of `ovp-ui`, variant A: to port 80 of `ovp-allinone`) |
|
||||
| `OVPMON_CSP_CONNECT_EXTRA` | no | empty | Extra origins in the `connect-src` of the Content-Security-Policy, for a UI whose `config.json` points to an API on another host: `https://host[:port]` or `http://host[:port]`, separated by spaces (quote the value when there are several). Anything else is refused with a message by `install.sh` / `update.sh` and by the containers at start (the value goes into a response header). Passed to the containers as `OVP_CSP_CONNECT_EXTRA`; apply with `docker compose up -d` (the container is recreated) |
|
||||
| `OVPMON_VPN_PORT` | no | `1194` | Host UDP port of OpenVPN (the container side is always 1194) |
|
||||
|
||||
Variables of the scripts (environment of the shell, not `.env`): `OVPMON_BACKUP_DIR` (backup root, default `./backups`), `OVPMON_BACKUP_IMAGE` (helper image, default `alpine:3`), `OVPMON_HEALTH_TIMEOUT` (seconds, default 180), `OVPMON_MIN_FREE_MB` (docker data, default 2048), `OVPMON_MIN_FREE_BACKUP_MB` (backups, default 1024).
|
||||
@@ -20,7 +21,7 @@ Variables of the scripts (environment of the shell, not `.env`): `OVPMON_BACKUP_
|
||||
|
||||
| Port | Published | Purpose |
|
||||
|---|---|---|
|
||||
| `${OVPMON_HTTP_PORT:-80}/tcp` | yes | UI and reverse proxy to both APIs (plain HTTP) |
|
||||
| `${OVPMON_HTTP_PORT:-80}/tcp` | yes | UI and reverse proxy to both APIs (plain HTTP). Inside the container: `8080` in variant B (`ovp-ui` runs nginx as the unprivileged user `nginx`), `80` in variant A. Custom compose files or a proxy that target port 80 of `ovp-ui` must be changed to 8080 |
|
||||
| `${OVPMON_VPN_PORT:-1194}/udp` | yes | OpenVPN |
|
||||
| `5001` (monitoring API), `8000` (profiler API) | no | variant B: `expose`d on `ovp-net` only; variant A: listen on `127.0.0.1` inside the container |
|
||||
|
||||
@@ -51,4 +52,4 @@ The profiler resolves `easy-rsa/` and `client-config/` relative to its working d
|
||||
|
||||
Processes in `ovp-allinone` (`deploy/allinone/supervisord.conf`, started in this order, all with `autorestart`, logs to stdout/stderr): `gatherer`, `api` (`gunicorn -w 2 -b 127.0.0.1:5001 openvpn_api_v3:app`), `profiler` (`uvicorn` on `127.0.0.1:8000`, no reload), `nginx`. OpenVPN is started by the profiler API on request (direct start inside containers), as in variant B.
|
||||
|
||||
`deploy/allinone/entrypoint.sh` runs before `supervisord`: secret mapping (`JWT_SECRET` → `OVPMON_API_SECRET_KEY` when only the first is set), `/dev/net/tun`, easy-rsa workspace (copied only when the volume does not have it yet), NAT and MSS rules without duplicates, the nginx configuration rendered from `APP_UI/default.conf.template` for `127.0.0.1`, then the **database migration as an explicit step**: the container does not start if it fails. The services then run with `OVPMON_AUTO_MIGRATE=0` (they only verify the schema).
|
||||
`deploy/allinone/entrypoint.sh` runs before `supervisord`: secret mapping (`JWT_SECRET` → `OVPMON_API_SECRET_KEY` when only the first is set), `/dev/net/tun`, easy-rsa workspace (copied only when the volume does not have it yet), NAT and MSS rules without duplicates, the nginx configuration rendered from `APP_UI/default.conf.template` for `127.0.0.1` (port 80, CSP origins from `OVP_CSP_CONNECT_EXTRA`, checked first: an invalid value stops the container), then the **database migration as an explicit step**: the container does not start if it fails. The services then run with `OVPMON_AUTO_MIGRATE=0` (they only verify the schema).
|
||||
@@ -8,6 +8,7 @@ Install: [Containers](README.md). Update and backup: [Operations](Operations.md)
|
||||
|---|---|
|
||||
| `port 80/tcp is already in use` | Another service uses the port. Install with `--http-port 8080` or set `OVPMON_HTTP_PORT` in `.env` (same for `OVPMON_VPN_PORT`) |
|
||||
| `container 'ovp-...' of the OTHER variant is running` | Variants A and B cannot run together. Stop the other stack first |
|
||||
| `OVPMON_CSP_CONNECT_EXTRA ... is invalid` (script) or `check-csp-connect-extra` in the log of a container that stops at start | The value is not a list of origins. Use `https://host[:port]` or `http://host[:port]` separated by spaces (no `;`, quotes, commas, paths, leading space) or leave it empty |
|
||||
| `container 'ovp-ui' ... belongs to compose project 'x'` | A stack of another project uses the fixed names. Use `--project x` or remove that stack |
|
||||
| Health check does not turn healthy | `docker compose ps`, then `docker compose logs --tail 100 <service>` (A: `docker logs ovp-allinone`). The scripts print the last log lines of failing services. The profiler allows 40 s and the all-in-one container 60 s before failures count |
|
||||
| `FATAL: ... newer than this version` / migration "too new" | The database was migrated by a newer release. Do not start the old version on it: update to the newer sources, or restore a matching backup (`update.sh --rollback` or `restore.sh`) |
|
||||
|
||||
@@ -122,3 +122,25 @@ sudo apt install nginx
|
||||
```bash
|
||||
setsebool -P httpd_can_network_connect 1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Security headers and CSP (site written by `install.sh`)
|
||||
|
||||
The site that `install.sh` / `update.sh` write (`deploy/native/nginx/ovpmon.conf.template`, first line has the marker "managed by ovpmon") sends `Strict-Transport-Security`, `X-Content-Type-Options`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, `Cache-Control: no-store` and a Content-Security-Policy:
|
||||
|
||||
```
|
||||
default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:;
|
||||
connect-src 'self' <extra origins>; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'
|
||||
```
|
||||
|
||||
The headers are declared on the `server` level only: an `add_header` inside a `location` would drop all of them. `style-src 'unsafe-inline'` is needed by Bootstrap and Chart.js.
|
||||
|
||||
The default `connect-src` allows the page origin only. If `config.json` points the UI to an API on another host, add its origin:
|
||||
|
||||
```bash
|
||||
deploy/native/update.sh --csp-connect-extra "https://api.example.com http://10.0.0.5:5001" # several origins: separated by spaces
|
||||
deploy/native/update.sh --csp-connect-extra "" # remove them
|
||||
```
|
||||
|
||||
`install.sh` accepts the same option. The value is kept in `/etc/ovpmon/deploy.state` (`OVPMON_CSP_CONNECT_EXTRA`) and applied again by every update. Only `https://host[:port]` and `http://host[:port]` are accepted (the value ends up in a response header). An existing site without the marker line is not changed by `update.sh`: add the CSP there by hand. The API on the other origin must also allow this UI origin (`OVPMON_CORS_ORIGINS`).
|
||||
@@ -13,7 +13,7 @@ deploy/native/update.sh --no-pull # sources already in p
|
||||
deploy/native/update.sh --rollback # manual rollback to the newest backup
|
||||
```
|
||||
|
||||
Run it from the checkout that holds the new version (the script uses the templates of that checkout). `--prefix` and the HTTPS port come from `/etc/ovpmon/deploy.state`. The update needs access to PyPI for the new virtualenvs.
|
||||
Run it from the checkout that holds the new version (the script uses the templates of that checkout). `--prefix`, the HTTPS port and the extra CSP origins (`OVPMON_CSP_CONNECT_EXTRA`) come from `/etc/ovpmon/deploy.state`; `--csp-connect-extra "https://api.example.com"` changes the origins (`""` removes them) and re-renders the nginx site. A site that is not managed by the scripts (marker line removed) is left untouched. The update needs access to PyPI for the new virtualenvs.
|
||||
|
||||
Each phase is logged separately:
|
||||
|
||||
|
||||
@@ -100,6 +100,7 @@ Options:
|
||||
| `--node-download` | with `--build-ui`: use a temporary official Node 20 (checksum verified, glibc only) |
|
||||
| `--no-ui` | install a placeholder page on purpose; without any UI source and without this option the install stops |
|
||||
| `--https-port N` | HTTPS port of the web UI (default `8088`) |
|
||||
| `--csp-connect-extra ORIGINS` | extra origins the UI may call (CSP `connect-src`), for an API on another host: `https://host[:port]` or `http://host[:port]` separated by spaces, in quotes; default none (same origin only). Stored in `/etc/ovpmon/deploy.state` as `OVPMON_CSP_CONNECT_EXTRA`; anything else is refused |
|
||||
| `--host-name NAME` | DNS name or IP for the certificate and the CORS origin (default: the detected address of the default route) |
|
||||
| `--admin-user NAME` | login of the first administrator (default `admin`) |
|
||||
| `--force` | continue on an untested OS version |
|
||||
|
||||
@@ -64,6 +64,18 @@ With the unprivileged profiler the API only stages `server.conf`; **the helper c
|
||||
|
||||
OpenRC runs `/sbin/rc-service <unit> <action>`, systemd runs `systemctl <action> <unit>` (fixed argument list, fixed `PATH`). Unknown keys or invalid values make the helper refuse.
|
||||
|
||||
## Deployment state (`/etc/ovpmon/deploy.state`)
|
||||
|
||||
`KEY=VALUE` lines written by `install.sh` and `update.sh`; `update.sh` reads them back.
|
||||
|
||||
| Key | Meaning |
|
||||
|---|---|
|
||||
| `OVPMON_PREFIX` | install directory |
|
||||
| `OVPMON_HTTPS_PORT` | HTTPS port of the nginx site |
|
||||
| `OVPMON_CSP_CONNECT_EXTRA` | extra origins of the CSP `connect-src` in the nginx site (`install.sh` / `update.sh --csp-connect-extra`); empty = same origin only. Validated: `https://host[:port]` or `http://host[:port]` separated by spaces |
|
||||
| `OVPMON_OS`, `OVPMON_VERSION`, `OVPMON_INSTALLED_AT`, `OVPMON_LAST_UPDATE` | information |
|
||||
| `FIREWALL_*` | settings of `firewall.sh`, see [Firewall](Firewall.md) |
|
||||
|
||||
## Security notes
|
||||
|
||||
- Services run as `ovpmon` (no login shell); code and virtualenvs are root-owned and read-only for them. systemd units add `PrivateTmp`, `ProtectHome`, `ProtectSystem=full`, kernel and cgroup protection; `ovpmon-api` and `ovpmon-gatherer` also set `NoNewPrivileges`. `ovpmon-profiler` must **not** (it calls the setuid `doas`), must not use seccomp-based options either (`ProtectKernelTunables`, `ProtectKernelModules`, `RestrictRealtime`, `LockPersonality`, `SystemCallFilter`, ...): for an unprivileged unit systemd then sets NoNewPrivileges implicitly and `doas` fails with "not installed setuid" (check: `grep NoNewPrivs /proc/<main pid>/status` must show 0). It keeps `/etc/openvpn` writable, because the helper runs inside the profiler's mount namespace.
|
||||
|
||||
@@ -49,4 +49,12 @@ The UI is served by Nginx in production and proxies API requests to:
|
||||
See [Deployment Guide](../Deployment/README.md) for Nginx configuration details.
|
||||
|
||||
## Web server headers (container image)
|
||||
`APP_UI/default.conf.template` (also used by the all-in-one image) sends `X-Content-Type-Options`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer` and a CSP (`default-src 'self'`, inline styles allowed, `img-src`/`font-src` with `data:`, `connect-src 'self'`), compresses text files, serves `/assets/` with `immutable` caching and `index.html`/`config.json` with `no-cache`. If `config.json` points to another origin, add it to `connect-src`. The system-service nginx (`deploy/native/nginx`) has its own headers.
|
||||
`APP_UI/default.conf.template` (also used by the all-in-one image) sends `X-Content-Type-Options`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer` and a CSP (`default-src 'self'`, inline styles allowed, `img-src`/`font-src` with `data:`, `connect-src 'self'` plus optional extra origins), compresses text files, serves `/assets/` with `immutable` caching and `index.html`/`config.json` with `no-cache`.
|
||||
|
||||
The CSP is written once (`set $csp "..."` in the `server` block) and sent with `add_header Content-Security-Policy $csp always` in the `server` block and in `location /assets/` (a location with its own `add_header` does not inherit the server ones).
|
||||
|
||||
**API on another origin.** If `config.json` points the UI to another origin, list it in `OVPMON_CSP_CONNECT_EXTRA` (inside the containers `OVP_CSP_CONNECT_EXTRA`): origins `https://host[:port]` or `http://host[:port]` separated by spaces, empty by default (same origin only). The value goes into a response header, so anything but origins is refused (`;`, quotes, commas, paths, a leading space): by the deploy scripts, by the all-in-one entrypoint and by `/docker-entrypoint.d/15-check-csp-connect-extra.sh` of the `app-ui` image (the container stops with a message). The API on the other origin must also allow this UI origin in `OVPMON_CORS_ORIGINS`.
|
||||
|
||||
The `app-ui` image is based on `nginxinc/nginx-unprivileged:alpine`: nginx runs as the user `nginx` (uid 101) and listens on `OVP_UI_PORT` (8080 in the image); docker-compose publishes it as the host port `OVPMON_HTTP_PORT` (default 80). In the all-in-one image the same template listens on 80 (the supervisor runs everything as root, OpenVPN needs it).
|
||||
|
||||
The system-service nginx (`deploy/native/nginx/ovpmon.conf.template`) sends the same CSP (headers are declared on the `server` level only); extra origins are set with `install.sh` / `update.sh --csp-connect-extra`, see [System services](../Deployment/System_Services/README.md).
|
||||
Reference in new issue
Block a user