Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ec65249bf1 | ||
|
|
6329a4df27 | ||
|
|
880d77810a | ||
|
|
8ebce28e34 | ||
|
|
dd7d43c2c2 | ||
|
|
a8c5e9701f | ||
|
|
be3d73f374 | ||
|
|
5fca165c69 | ||
|
|
293115e0e1 | ||
|
|
6d2051f813 |
@@ -32,6 +32,6 @@ powershell -NoProfile -File scripts/commit/staged-context.ps1
|
||||
- Новая пользовательская возможность → `feat` (minor)
|
||||
- Починка ожидаемого поведения / баг → `fix` (patch)
|
||||
- Follow-up баги после недавнего `feat` в том же scope → **`fix`**, не `feat`
|
||||
- Только перестройка без нового поведения → `refactor` (none)
|
||||
- Только перестройка без нового поведения → `refactor` (patch, без новых функций)
|
||||
|
||||
Заголовок — EN, императив, ≤72 символов. Тело — RU.
|
||||
|
||||
@@ -50,7 +50,7 @@ powershell -NoProfile -File scripts/commit/staged-context.ps1
|
||||
| `feat` | **новая** пользовательская возможность (раньше нельзя было) | minor |
|
||||
| `fix` | восстановление **ожидаемого** поведения; баг, регрессия, падение UI | patch |
|
||||
| `perf` | ускорение без смены API | patch |
|
||||
| `refactor` | реструктуризация **без** новой возможности и **без** исправления бага | — |
|
||||
| `refactor` | реструктуризация **без** новой возможности и **без** исправления бага | patch |
|
||||
| `docs` | только документация | — |
|
||||
| `test` | тесты | — |
|
||||
| `ci` | CI/CD (`.gitea/`, workflows); правки, из‑за которых нужны новые образы | patch |
|
||||
@@ -62,7 +62,7 @@ powershell -NoProfile -File scripts/commit/staged-context.ps1
|
||||
|
||||
1. Появилось **новое** действие / экран / API / настройка, которых не было → `feat`
|
||||
2. То, что **должно было работать**, не работало (кнопки, диалоги, сохранение, 500) → `fix`
|
||||
3. Только перестройка кода или UI на другой паттерн, поведение для пользователя то же → `refactor`
|
||||
3. Только перестройка кода или UI на другой паттерн, поведение для пользователя то же → `refactor` (patch, без новых функций)
|
||||
4. Ускорение без изменения контракта → `perf`
|
||||
|
||||
**Не путать с формулировкой diff:**
|
||||
@@ -105,7 +105,7 @@ feat(web): migrate modules list to AppDataTable
|
||||
# Хорошо — если не было нового user-facing
|
||||
refactor(web): migrate modules list to AppDataTable
|
||||
|
||||
Единый паттерн таблиц; поведение списка модулей без изменений.
|
||||
Единый паттерн таблиц; поведение списка модулей без изменений. Semver: patch.
|
||||
```
|
||||
|
||||
```
|
||||
|
||||
@@ -101,7 +101,7 @@ git commit -m "$( @'
|
||||
| Пользователь получает **новую** возможность? | `feat` (minor) |
|
||||
| Восстанавливается **ожидаемое** поведение / устранён баг? | `fix` (patch) |
|
||||
| Только скорость, контракт тот же? | `perf` (patch) |
|
||||
| Только структура кода/UI, поведение то же? | `refactor` (none) |
|
||||
| Только структура кода/UI, поведение то же? | `refactor` (patch) |
|
||||
|
||||
**Follow-up:** правки сразу после `feat` в том же scope без новой возможности → **`fix`**, не `feat` (слова *enhance/improve/refactor* в задаче не делают commit `feat`).
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
{ "type": "fix", "release": "patch" },
|
||||
{ "type": "perf", "release": "patch" },
|
||||
{ "type": "ci", "release": "patch" },
|
||||
{ "type": "refactor", "release": "patch" },
|
||||
{ "breaking": true, "release": "major" }
|
||||
]
|
||||
}
|
||||
|
||||
@@ -55,8 +55,12 @@ func main() {
|
||||
startBirdMetricsPoller(ctx)
|
||||
|
||||
httpSrv := &http.Server{
|
||||
Addr: cfg.HTTPAddr,
|
||||
Handler: srv.Handler(),
|
||||
Addr: cfg.HTTPAddr,
|
||||
Handler: srv.Handler(),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 120 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
go func() {
|
||||
svc := platform.ServiceName("evobgp-all")
|
||||
@@ -91,6 +95,7 @@ func startBirdMetricsPoller(ctx context.Context) {
|
||||
return birdfmt.ShowProtocols(ctx, socket, birdcBin)
|
||||
},
|
||||
birdfmt.CountEstablishedBGPSessions,
|
||||
birdfmt.ParseBGPProtocolStates,
|
||||
)
|
||||
log.Printf("birdc protocols poller enabled (socket=%s interval=%s)", sock, interval)
|
||||
}
|
||||
|
||||
@@ -42,8 +42,12 @@ func main() {
|
||||
startBirdMetricsPoller(ctx)
|
||||
|
||||
httpSrv := &http.Server{
|
||||
Addr: cfg.HTTPAddr,
|
||||
Handler: srv.Handler(),
|
||||
Addr: cfg.HTTPAddr,
|
||||
Handler: srv.Handler(),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 120 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
go func() {
|
||||
svc := platform.ServiceName("evobgp-api")
|
||||
@@ -53,7 +57,7 @@ func main() {
|
||||
tid, mCDN, mIP, rev, sp := srv.Store().DemoIDs()
|
||||
log.Printf("demo tenant=%s module_cdn=%s module_ip_ranges=%s revision=%s speaker=%s", tid, mCDN, mIP, rev, sp)
|
||||
log.Printf("example: EVOBGP_API_KEYS=op|%s|operator,node|%s|node", tid, tid)
|
||||
log.Printf("with EVOBGP_DEV_INSECURE=1 use Authorization: Bearer dev (operator, demo tenant only)")
|
||||
log.Printf("demo auth: Authorization: Bearer dev (operator, demo tenant only)")
|
||||
}
|
||||
if err := httpSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatal(err)
|
||||
@@ -84,6 +88,7 @@ func startBirdMetricsPoller(ctx context.Context) {
|
||||
return birdfmt.ShowProtocols(ctx, socket, birdcBin)
|
||||
},
|
||||
birdfmt.CountEstablishedBGPSessions,
|
||||
birdfmt.ParseBGPProtocolStates,
|
||||
)
|
||||
log.Printf("birdc protocols poller enabled (socket=%s interval=%s)", sock, interval)
|
||||
}
|
||||
|
||||
@@ -5,8 +5,14 @@ server {
|
||||
gzip on;
|
||||
gzip_types text/css application/javascript application/json image/svg+xml;
|
||||
|
||||
# Docker embedded DNS: без resolver nginx кэширует IP upstream при старте —
|
||||
# после recreate evobgp-all остаётся 502 (connection refused на старый IP).
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
set $evobgp_upstream evobgp-api;
|
||||
|
||||
location /v1/ {
|
||||
proxy_pass http://evobgp-api:8080/v1/;
|
||||
# С переменной в proxy_pass нельзя полагаться на замену URI — передаём $request_uri целиком.
|
||||
proxy_pass http://$evobgp_upstream:8080$request_uri;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
@@ -15,7 +21,7 @@ server {
|
||||
}
|
||||
|
||||
location = /metrics {
|
||||
proxy_pass http://evobgp-api:8080/metrics;
|
||||
proxy_pass http://$evobgp_upstream:8080/metrics;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
+17
-3
@@ -22,6 +22,19 @@ opkey|01ARZ3NDEKTSV4RRFFQ69G5FAV|operator,nodekey|01ARZ3NDEKTSV4RRFFQ69G5FAV|nod
|
||||
|
||||
При включённом демо-сиде сервер при старте может вывести в лог готовую подсказку с реальным `tenant_id` из БД — см. лог `evobgp-api` / `evobgp-all`.
|
||||
|
||||
Ключи из `EVOBGP_API_KEYS` загружаются при старте и **дополняют** ключи из таблицы `api_key` в БД (break-glass / bootstrap). После первого operator-ключа можно создавать остальные через API или веб-настройки.
|
||||
|
||||
### Управление через API и UI
|
||||
|
||||
При подключённой БД operator может:
|
||||
|
||||
- `GET|POST /v1/api-keys`, `GET|PATCH|DELETE /v1/api-keys/{id}`, `POST /v1/api-keys/{id}/rotate` — см. OpenAPI, тег **API keys**.
|
||||
- В веб-панели: **Права доступа** (`/access`) → блок «API-ключи» (только для роли `operator`). Токен для браузера — в **Настройки** (`/settings`).
|
||||
|
||||
Полный токен возвращается **один раз** в ответе `201` (создание) и `200` (ротация). В списках — только `prefix` (первые 8 символов). В БД хранится SHA-256 токена, не plaintext.
|
||||
|
||||
`GET /v1/auth/session` — текущие `tenant_id` и `role` (для UI).
|
||||
|
||||
### Роли
|
||||
|
||||
| Роль | Уровень | Назначение |
|
||||
@@ -33,11 +46,11 @@ opkey|01ARZ3NDEKTSV4RRFFQ69G5FAV|operator,nodekey|01ARZ3NDEKTSV4RRFFQ69G5FAV|nod
|
||||
|
||||
Обратное ограничение: для эндпоинтов ноды требуется именно роль **`node`**; остальные роли получают отказ.
|
||||
|
||||
### Режим разработки `EVOBGP_DEV_INSECURE`
|
||||
### Токен `dev` (локальная разработка)
|
||||
|
||||
Если установлено `EVOBGP_DEV_INSECURE=1` и в store доступен демо-tenant (`DemoIDs`), то запрос с заголовком **`Authorization: Bearer dev`** получает контекст **`operator`** для этого tenant.
|
||||
Если в store доступен демо-tenant (`DemoIDs`, обычно `EVOBGP_SEED_DEMO` не равен `0`), заголовок **`Authorization: Bearer dev`** даёт роль **`operator`** для этого tenant. **Не зависит** от `EVOBGP_DEV_INSECURE`.
|
||||
|
||||
**Запрещено** в продакшене: любой, кто знает заголовок, получает полные права оператора на демо-данные. В reference Compose (`deploy/compose/docker-compose.yaml`) флаг включён только для локальной разработки.
|
||||
**Запрещено** в продакшене: не оставляйте demo-seed с известным токеном `dev` на боевых данных. Переменная `EVOBGP_DEV_INSECURE` в текущей версии **не влияет** на аутентификацию (оставлена в compose для совместимости; не включайте в production — см. SEC-02 в инженерных правилах).
|
||||
|
||||
### Синхронные «тяжёлые» GET (control plane)
|
||||
|
||||
@@ -93,6 +106,7 @@ http://localhost:5173,http://127.0.0.1:5173,https://ui.example.com
|
||||
| GET модули, ревизии, peers, speakers | да | да | да | нет |
|
||||
| POST/PATCH/DELETE CRUD сущностей | нет | да | да | нет |
|
||||
| apply, rollback, PATCH settings | нет | нет | да | нет |
|
||||
| Управление API-ключами (`/v1/api-keys`) | нет | нет | да | нет |
|
||||
| bundle, latest revision, enroll | нет | нет | нет | да |
|
||||
|
||||
Точные проверки по каждому маршруту — в коде `internal/httpapi` и в схеме безопасности операций в OpenAPI.
|
||||
|
||||
@@ -44,6 +44,12 @@
|
||||
- `GET|POST /v1/communities`
|
||||
- `GET|PATCH|DELETE /v1/communities/{id}`
|
||||
|
||||
### API keys
|
||||
|
||||
- `GET /v1/auth/session` — tenant и роль текущего ключа
|
||||
- `GET|POST /v1/api-keys` — список и создание (operator)
|
||||
- `GET|PATCH|DELETE /v1/api-keys/{id}`, `POST /v1/api-keys/{id}/rotate`
|
||||
|
||||
### Peers
|
||||
|
||||
- `GET /v1/peers`, `POST /v1/peers`
|
||||
|
||||
@@ -45,6 +45,10 @@ tags:
|
||||
description: "API для evobgp-node (бандлы ревизий и enrollment). Отдельный ключ или mTLS, роль node."
|
||||
- name: Settings
|
||||
description: Глобальные настройки и feature flags; изменение - только operator.
|
||||
- name: API keys
|
||||
description: Управление API-ключами tenant (operator). Секрет возвращается только при создании и ротации.
|
||||
- name: Auth
|
||||
description: Сессия текущего API-ключа (tenant и роль).
|
||||
|
||||
security:
|
||||
- bearerAuth: []
|
||||
@@ -135,6 +139,12 @@ components:
|
||||
required: true
|
||||
schema:
|
||||
$ref: "#/components/schemas/ResourceId"
|
||||
ApiKeyId:
|
||||
name: id
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
$ref: "#/components/schemas/ResourceId"
|
||||
SourceId:
|
||||
name: source_id
|
||||
in: path
|
||||
@@ -639,6 +649,82 @@ components:
|
||||
vault_secret_ref:
|
||||
type: ["string", "null"]
|
||||
|
||||
AuthSession:
|
||||
type: object
|
||||
required: [tenant_id, role]
|
||||
properties:
|
||||
tenant_id:
|
||||
$ref: "#/components/schemas/ResourceId"
|
||||
role:
|
||||
type: string
|
||||
enum: [viewer, editor, operator, node]
|
||||
|
||||
ApiKey:
|
||||
type: object
|
||||
required: [id, name, role, prefix, created_at, updated_at]
|
||||
properties:
|
||||
id:
|
||||
$ref: "#/components/schemas/ResourceId"
|
||||
name:
|
||||
type: string
|
||||
role:
|
||||
type: string
|
||||
enum: [viewer, editor, operator, node]
|
||||
prefix:
|
||||
type: string
|
||||
description: Первые 8 символов токена для идентификации в UI.
|
||||
created_at:
|
||||
type: string
|
||||
format: date-time
|
||||
updated_at:
|
||||
type: string
|
||||
format: date-time
|
||||
expires_at:
|
||||
type: ["string", "null"]
|
||||
format: date-time
|
||||
revoked_at:
|
||||
type: ["string", "null"]
|
||||
format: date-time
|
||||
last_used_at:
|
||||
type: ["string", "null"]
|
||||
format: date-time
|
||||
additionalProperties: true
|
||||
|
||||
ApiKeyCreate:
|
||||
type: object
|
||||
required: [name, role]
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
role:
|
||||
type: string
|
||||
enum: [viewer, editor, operator, node]
|
||||
expires_at:
|
||||
type: ["string", "null"]
|
||||
format: date-time
|
||||
|
||||
ApiKeyPatch:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
role:
|
||||
type: string
|
||||
enum: [viewer, editor, operator, node]
|
||||
expires_at:
|
||||
type: ["string", "null"]
|
||||
format: date-time
|
||||
|
||||
ApiKeyCreated:
|
||||
allOf:
|
||||
- $ref: "#/components/schemas/ApiKey"
|
||||
- type: object
|
||||
required: [token]
|
||||
properties:
|
||||
token:
|
||||
type: string
|
||||
description: Полный Bearer-токен; показывается один раз.
|
||||
|
||||
BgpCommunity:
|
||||
type: object
|
||||
required:
|
||||
@@ -2643,6 +2729,170 @@ paths:
|
||||
default:
|
||||
$ref: "#/components/responses/DefaultProblem"
|
||||
|
||||
/v1/auth/session:
|
||||
get:
|
||||
tags: [Auth]
|
||||
summary: Текущая сессия API-ключа
|
||||
operationId: getAuthSession
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/TenantId"
|
||||
responses:
|
||||
"200":
|
||||
description: Успешно.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/AuthSession"
|
||||
"401":
|
||||
$ref: "#/components/responses/Unauthorized"
|
||||
default:
|
||||
$ref: "#/components/responses/DefaultProblem"
|
||||
|
||||
/v1/api-keys:
|
||||
get:
|
||||
tags: [API keys]
|
||||
summary: Список API-ключей tenant
|
||||
description: Только роль **operator**. Секреты не возвращаются.
|
||||
operationId: listApiKeys
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/TenantId"
|
||||
- $ref: "#/components/parameters/Cursor"
|
||||
- $ref: "#/components/parameters/Limit"
|
||||
responses:
|
||||
"200":
|
||||
description: Успешно.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [items, has_more]
|
||||
properties:
|
||||
items:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/ApiKey"
|
||||
next_cursor:
|
||||
type: ["string", "null"]
|
||||
has_more:
|
||||
type: boolean
|
||||
"403":
|
||||
$ref: "#/components/responses/Forbidden"
|
||||
default:
|
||||
$ref: "#/components/responses/DefaultProblem"
|
||||
post:
|
||||
tags: [API keys]
|
||||
summary: Создать API-ключ
|
||||
operationId: createApiKey
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/TenantId"
|
||||
- $ref: "#/components/parameters/IdempotencyKey"
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ApiKeyCreate"
|
||||
responses:
|
||||
"201":
|
||||
description: Ключ создан; token в ответе один раз.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ApiKeyCreated"
|
||||
"403":
|
||||
$ref: "#/components/responses/Forbidden"
|
||||
"422":
|
||||
$ref: "#/components/responses/UnprocessableEntity"
|
||||
default:
|
||||
$ref: "#/components/responses/DefaultProblem"
|
||||
|
||||
/v1/api-keys/{id}:
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/TenantId"
|
||||
- $ref: "#/components/parameters/ApiKeyId"
|
||||
get:
|
||||
tags: [API keys]
|
||||
summary: Получить метаданные API-ключа
|
||||
operationId: getApiKey
|
||||
responses:
|
||||
"200":
|
||||
description: Успешно.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ApiKey"
|
||||
"403":
|
||||
$ref: "#/components/responses/Forbidden"
|
||||
"404":
|
||||
$ref: "#/components/responses/NotFound"
|
||||
default:
|
||||
$ref: "#/components/responses/DefaultProblem"
|
||||
patch:
|
||||
tags: [API keys]
|
||||
summary: Обновить API-ключ
|
||||
operationId: patchApiKey
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/IdempotencyKey"
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ApiKeyPatch"
|
||||
responses:
|
||||
"200":
|
||||
description: Успешно.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ApiKey"
|
||||
"403":
|
||||
$ref: "#/components/responses/Forbidden"
|
||||
"404":
|
||||
$ref: "#/components/responses/NotFound"
|
||||
default:
|
||||
$ref: "#/components/responses/DefaultProblem"
|
||||
delete:
|
||||
tags: [API keys]
|
||||
summary: Отозвать API-ключ
|
||||
operationId: revokeApiKey
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/IdempotencyKey"
|
||||
responses:
|
||||
"204":
|
||||
description: Отозван.
|
||||
"403":
|
||||
$ref: "#/components/responses/Forbidden"
|
||||
"404":
|
||||
$ref: "#/components/responses/NotFound"
|
||||
default:
|
||||
$ref: "#/components/responses/DefaultProblem"
|
||||
|
||||
/v1/api-keys/{id}/rotate:
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/TenantId"
|
||||
- $ref: "#/components/parameters/ApiKeyId"
|
||||
post:
|
||||
tags: [API keys]
|
||||
summary: Ротировать секрет API-ключа
|
||||
description: Выдаёт новый token; старый перестаёт работать сразу.
|
||||
operationId: rotateApiKey
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/IdempotencyKey"
|
||||
responses:
|
||||
"200":
|
||||
description: Успешно.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ApiKeyCreated"
|
||||
"403":
|
||||
$ref: "#/components/responses/Forbidden"
|
||||
"404":
|
||||
$ref: "#/components/responses/NotFound"
|
||||
default:
|
||||
$ref: "#/components/responses/DefaultProblem"
|
||||
|
||||
/v1/settings:
|
||||
get:
|
||||
tags: [Settings]
|
||||
|
||||
+4
-2
@@ -7,9 +7,11 @@ EvoBGP использует [Conventional Commits](https://www.conventionalcommi
|
||||
| Тип коммита | Bump |
|
||||
|-------------|------|
|
||||
| `feat` | minor (1.0.0 → 1.1.0) |
|
||||
| `fix`, `perf`, `ci` | patch (1.5.1 → 1.5.2) |
|
||||
| `fix`, `perf`, `ci`, `refactor` | patch (1.5.1 → 1.5.2) |
|
||||
| `feat!`, `fix!` или `BREAKING CHANGE:` в теле | major (1.0.0 → 2.0.0) |
|
||||
| `docs`, `chore`, `test`, `refactor` | без релиза |
|
||||
| `docs`, `chore`, `test` | без релиза |
|
||||
|
||||
`refactor` — patch без новых функций: перестройка кода/UI при том же поведении для пользователя. По semver на одном уровне с `fix`, но семантически «мельче» `feat` (не minor).
|
||||
|
||||
Отдельного суффикса `1.x.y.fix` в semver нет: «fix» в Conventional Commits означает **patch** (третья цифра). Для починки пайплайна без смены продукта — `fix(ci):` или `ci:` (оба дают patch после настройки `.releaserc.json`).
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
// Package authkey generates API tokens and derives lookup hashes (no persistence).
|
||||
package authkey
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
const tokenPrefix = "evobgp_"
|
||||
|
||||
// GenerateToken returns a new bearer token (evobgp_ + 32 random bytes, base64url).
|
||||
func GenerateToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("authkey: generate token: %w", err)
|
||||
}
|
||||
return tokenPrefix + base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// HashToken returns SHA-256 of the full token (32 bytes).
|
||||
func HashToken(token string) []byte {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
// Prefix returns the first 8 characters of the token for display.
|
||||
func Prefix(token string) string {
|
||||
if len(token) <= 8 {
|
||||
return token
|
||||
}
|
||||
return token[:8]
|
||||
}
|
||||
@@ -9,6 +9,21 @@ import (
|
||||
|
||||
const maxBGPASN = 4294967295
|
||||
|
||||
const filterPrefixChunkSize = 500
|
||||
|
||||
func writePrefixSetAcceptBlocks(b *strings.Builder, keys []string) {
|
||||
for i := 0; i < len(keys); i += filterPrefixChunkSize {
|
||||
end := i + filterPrefixChunkSize
|
||||
if end > len(keys) {
|
||||
end = len(keys)
|
||||
}
|
||||
chunk := keys[i:end]
|
||||
b.WriteString(" if net ~ [ ")
|
||||
b.WriteString(strings.Join(chunk, ", "))
|
||||
b.WriteString(" ] then accept;\n")
|
||||
}
|
||||
}
|
||||
|
||||
func filterUniqueASNs(pathASNs []int64) []int64 {
|
||||
seen := make(map[int64]struct{})
|
||||
for _, a := range pathASNs {
|
||||
@@ -52,9 +67,7 @@ func RenderExportFilterIPv4(filterName string, prefixes []netip.Prefix, pathASNs
|
||||
b.WriteString(strings.TrimSpace(filterName))
|
||||
b.WriteString(" {\n")
|
||||
if len(keys) > 0 {
|
||||
b.WriteString(" if net ~ [ ")
|
||||
b.WriteString(strings.Join(keys, ", "))
|
||||
b.WriteString(" ] then accept;\n")
|
||||
writePrefixSetAcceptBlocks(&b, keys)
|
||||
}
|
||||
for _, asn := range asns {
|
||||
fmt.Fprintf(&b, " if bgp_path ~ [= * %d =] then accept;\n", asn)
|
||||
@@ -95,9 +108,7 @@ func RenderExportFilterIPv6(filterName string, prefixes []netip.Prefix, pathASNs
|
||||
b.WriteString(strings.TrimSpace(filterName))
|
||||
b.WriteString(" {\n")
|
||||
if len(keys) > 0 {
|
||||
b.WriteString(" if net ~ [ ")
|
||||
b.WriteString(strings.Join(keys, ", "))
|
||||
b.WriteString(" ] then accept;\n")
|
||||
writePrefixSetAcceptBlocks(&b, keys)
|
||||
}
|
||||
for _, asn := range asns {
|
||||
fmt.Fprintf(&b, " if bgp_path ~ [= * %d =] then accept;\n", asn)
|
||||
|
||||
@@ -50,3 +50,48 @@ func CountEstablishedBGPSessions(showProtocolsOutput string) int {
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// ParseBGPProtocolStates parses `birdc show protocols all` summary rows into protocol_name -> state.
|
||||
func ParseBGPProtocolStates(output string) map[string]string {
|
||||
out := make(map[string]string)
|
||||
for _, raw := range strings.Split(output, "\n") {
|
||||
line := strings.TrimSpace(raw)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
low := strings.ToLower(line)
|
||||
if strings.HasPrefix(low, "bird ") || strings.HasPrefix(low, "name ") || strings.HasPrefix(low, "table ") {
|
||||
continue
|
||||
}
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) < 4 {
|
||||
continue
|
||||
}
|
||||
if !strings.EqualFold(fields[1], "BGP") {
|
||||
continue
|
||||
}
|
||||
state := extractBGPSessionStateLine(line)
|
||||
if state == "" {
|
||||
state = fields[3]
|
||||
}
|
||||
out[fields[0]] = state
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func extractBGPSessionStateLine(line string) string {
|
||||
known := []string{
|
||||
"Established",
|
||||
"Idle",
|
||||
"Connect",
|
||||
"Active",
|
||||
"OpenSent",
|
||||
"OpenConfirm",
|
||||
}
|
||||
for _, st := range known {
|
||||
if strings.Contains(line, st) {
|
||||
return st
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -6,9 +6,12 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"evobgp/migrations"
|
||||
|
||||
@@ -22,6 +25,17 @@ func OpenPostgresPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if max := os.Getenv("EVOBGP_DB_MAX_CONNS"); max != "" {
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(max)); err == nil && n > 0 {
|
||||
cfg.MaxConns = int32(n)
|
||||
}
|
||||
}
|
||||
if min := os.Getenv("EVOBGP_DB_MIN_CONNS"); min != "" {
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(min)); err == nil && n >= 0 {
|
||||
cfg.MinConns = int32(n)
|
||||
}
|
||||
}
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"sync"
|
||||
|
||||
"evobgp/internal/store"
|
||||
)
|
||||
|
||||
type apiKeyResolver struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
envByToken map[string]apiKeyRecord
|
||||
byHash map[string]apiKeyRecord
|
||||
}
|
||||
|
||||
func newAPIKeyResolver(envSpec string, st store.Backend) (*apiKeyResolver, error) {
|
||||
r := &apiKeyResolver{
|
||||
envByToken: make(map[string]apiKeyRecord),
|
||||
byHash: make(map[string]apiKeyRecord),
|
||||
}
|
||||
for _, rec := range parseAPIKeysSpec(envSpec) {
|
||||
r.envByToken[rec.token] = rec
|
||||
}
|
||||
return r, r.reloadFromStore(st)
|
||||
}
|
||||
|
||||
func (r *apiKeyResolver) reloadFromStore(st store.Backend) error {
|
||||
rows, err := st.ListActiveAPIKeyHashes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
byHash := make(map[string]apiKeyRecord, len(rows))
|
||||
for _, row := range rows {
|
||||
if len(row.TokenHash) != 32 {
|
||||
continue
|
||||
}
|
||||
byHash[hex.EncodeToString(row.TokenHash)] = apiKeyRecord{
|
||||
token: "",
|
||||
tenantID: row.TenantID,
|
||||
role: row.Role,
|
||||
keyID: row.ID,
|
||||
}
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.byHash = byHash
|
||||
r.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *apiKeyResolver) Reload(st store.Backend) error {
|
||||
return r.reloadFromStore(st)
|
||||
}
|
||||
|
||||
func (r *apiKeyResolver) Lookup(raw string) (apiKeyRecord, bool) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
if rec, ok := r.envByToken[raw]; ok {
|
||||
return rec, true
|
||||
}
|
||||
sum := sha256.Sum256([]byte(raw))
|
||||
key := hex.EncodeToString(sum[:])
|
||||
rec, ok := r.byHash[key]
|
||||
return rec, ok
|
||||
}
|
||||
+13
-21
@@ -15,6 +15,7 @@ type Auth struct {
|
||||
TenantID string
|
||||
Role string // viewer, editor, operator, node
|
||||
Token string
|
||||
APIKeyID string // non-empty for DB-managed keys
|
||||
}
|
||||
|
||||
func authFromContext(ctx context.Context) (Auth, bool) {
|
||||
@@ -26,6 +27,7 @@ type apiKeyRecord struct {
|
||||
token string
|
||||
tenantID string
|
||||
role string
|
||||
keyID string // set for DB-managed keys (last_used_at)
|
||||
}
|
||||
|
||||
func parseAPIKeysSpec(spec string) []apiKeyRecord {
|
||||
@@ -54,20 +56,6 @@ func parseAPIKeysSpec(spec string) []apiKeyRecord {
|
||||
|
||||
func (s *Server) authMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if s.insecureDev {
|
||||
h := r.Header.Get("Authorization")
|
||||
const p = "Bearer "
|
||||
if strings.HasPrefix(h, p) {
|
||||
tok := strings.TrimSpace(strings.TrimPrefix(h, p))
|
||||
if tok == "dev" {
|
||||
if a, ok := s.devAuth(); ok {
|
||||
r = r.WithContext(context.WithValue(r.Context(), authCtxKey, a))
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
h := r.Header.Get("Authorization")
|
||||
const p = "Bearer "
|
||||
if !strings.HasPrefix(h, p) {
|
||||
@@ -75,18 +63,22 @@ func (s *Server) authMiddleware(next http.Handler) http.Handler {
|
||||
return
|
||||
}
|
||||
raw := strings.TrimSpace(strings.TrimPrefix(h, p))
|
||||
var matched *apiKeyRecord
|
||||
for i := range s.apiKeys {
|
||||
if s.apiKeys[i].token == raw {
|
||||
matched = &s.apiKeys[i]
|
||||
break
|
||||
if raw == "dev" {
|
||||
if a, ok := s.devAuth(); ok {
|
||||
r = r.WithContext(context.WithValue(r.Context(), authCtxKey, a))
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
if matched == nil {
|
||||
matched, ok := s.keyResolver.Lookup(raw)
|
||||
if !ok {
|
||||
writeProblem(w, http.StatusUnauthorized, "Unauthorized", "unknown api key")
|
||||
return
|
||||
}
|
||||
a := Auth{TenantID: matched.tenantID, Role: matched.role, Token: raw}
|
||||
a := Auth{TenantID: matched.tenantID, Role: matched.role, Token: raw, APIKeyID: matched.keyID}
|
||||
if matched.keyID != "" {
|
||||
go func(id string) { _ = s.store.TouchAPIKeyLastUsed(id) }(matched.keyID)
|
||||
}
|
||||
r = r.WithContext(context.WithValue(r.Context(), authCtxKey, a))
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
|
||||
@@ -53,6 +53,21 @@ func BootstrapWorkers(ctx context.Context, opts Options) (store.Backend, *jobs.R
|
||||
wk := &jobs.Worker{Store: backend, HTTPClient: cdnHTTP}
|
||||
reg := jobs.NewRegistry(wk.Process)
|
||||
wk.Registry = reg
|
||||
if pool != nil {
|
||||
audit := repository.NewJobAuditWriter(pool)
|
||||
reg.SetTerminalHook(func(j *jobs.Job) {
|
||||
if j == nil {
|
||||
return
|
||||
}
|
||||
st := j.Snapshot()
|
||||
status, _ := st["status"].(string)
|
||||
var errMsg *string
|
||||
if e, ok := st["error"].(string); ok && e != "" {
|
||||
errMsg = &e
|
||||
}
|
||||
audit.MarkTerminal(context.Background(), j.TenantID, j.ID, status, errMsg, time.Now().UTC())
|
||||
})
|
||||
}
|
||||
observability.RegisterStoreBackend(backend)
|
||||
return backend, reg, pool, nil
|
||||
}
|
||||
|
||||
@@ -69,6 +69,7 @@ func (s *Server) registerV1(m *http.ServeMux) {
|
||||
m.HandleFunc("GET /bird/status", s.handleBirdStatus)
|
||||
m.HandleFunc("GET /jobs", s.handleListJobs)
|
||||
m.HandleFunc("GET /jobs/{job_id}", s.handleGetJob)
|
||||
m.HandleFunc("GET /jobs/{job_id}/report", s.handleGetJobReport)
|
||||
m.HandleFunc("POST /jobs/{job_id}/cancel", s.handleCancelJob)
|
||||
m.HandleFunc("GET /speakers/{speaker_id}/revisions/latest", s.handleNodeLatestRevision)
|
||||
m.HandleFunc("GET /speakers/{speaker_id}/bundle/{revision_id}", s.handleNodeBundle)
|
||||
@@ -201,6 +202,22 @@ func (s *Server) handleListModules(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
filtered := make([]*store.Module, 0)
|
||||
limit := parseListLimit(r)
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
if typeFilter == "" && enabledFilter == nil {
|
||||
page, next, more := s.store.ListModulesPage(a.TenantID, cursor, limit)
|
||||
for _, mod := range page {
|
||||
filtered = append(filtered, mod)
|
||||
}
|
||||
items := make([]map[string]any, 0, len(filtered))
|
||||
for _, mod := range filtered {
|
||||
items = append(items, moduleJSON(mod))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"items": items, "next_cursor": strPtrOrNull(next), "has_more": more,
|
||||
})
|
||||
return
|
||||
}
|
||||
for _, mod := range s.store.ListModules(a.TenantID) {
|
||||
if typeFilter != "" && mod.Type != typeFilter {
|
||||
continue
|
||||
@@ -275,7 +292,7 @@ func (s *Server) handleListPeers(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
allPeers := s.store.ListPeers(a.TenantID)
|
||||
page, next, more := store.PaginateOffset(allPeers, r.URL.Query().Get("cursor"), parseListLimit(r))
|
||||
liveStates := s.liveBGPProtocolStates(r.Context())
|
||||
liveStates := s.liveBGPProtocolStates(r)
|
||||
items := make([]map[string]any, 0, len(page))
|
||||
for _, p := range page {
|
||||
row := peerJSON(p)
|
||||
@@ -289,7 +306,17 @@ func (s *Server) handleListPeers(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) liveBGPProtocolStates(ctx context.Context) map[string]string {
|
||||
func (s *Server) liveBGPProtocolStates(r *http.Request) map[string]string {
|
||||
if r != nil && strings.EqualFold(strings.TrimSpace(r.URL.Query().Get("live")), "1") {
|
||||
return s.liveBGPProtocolStatesFresh(r.Context())
|
||||
}
|
||||
if cached, ok := observability.CachedBirdProtocolStates(90 * time.Second); ok {
|
||||
return cached
|
||||
}
|
||||
return s.liveBGPProtocolStatesFresh(r.Context())
|
||||
}
|
||||
|
||||
func (s *Server) liveBGPProtocolStatesFresh(ctx context.Context) map[string]string {
|
||||
sock := strings.TrimSpace(os.Getenv("EVOBGP_BIRDC_SOCKET"))
|
||||
if sock == "" {
|
||||
return map[string]string{}
|
||||
@@ -298,7 +325,9 @@ func (s *Server) liveBGPProtocolStates(ctx context.Context) map[string]string {
|
||||
if err != nil {
|
||||
return map[string]string{}
|
||||
}
|
||||
return parseBGPProtocolStates(out)
|
||||
states := birdfmt.ParseBGPProtocolStates(out)
|
||||
observability.SetBirdProtocolStates(states)
|
||||
return states
|
||||
}
|
||||
|
||||
// parseBGPProtocolStates parses `birdc show protocols all` summary rows into protocol_name -> state.
|
||||
@@ -522,7 +551,8 @@ func (s *Server) enqueueModuleRefreshIfEnabled(tenantID, moduleID, trigger strin
|
||||
return
|
||||
}
|
||||
mid := moduleID
|
||||
_, _, _ = s.jobs.Enqueue(tenantID, jobs.KindModuleRefresh, nil, &mid, map[string]any{
|
||||
key := "module_refresh:" + moduleID
|
||||
_, _, _ = s.jobs.Enqueue(tenantID, jobs.KindModuleRefresh, &key, &mid, map[string]any{
|
||||
"module_id": moduleID,
|
||||
"trigger": trigger,
|
||||
})
|
||||
@@ -589,6 +619,9 @@ func (s *Server) handleRevisionPreview(w http.ResponseWriter, r *http.Request) {
|
||||
for k, v := range rev.PreviewFragments {
|
||||
obj[k] = v
|
||||
}
|
||||
if expanded := pipeline.BuildExpandedBirdPreview(rev.PreviewFragments); expanded != "" {
|
||||
obj[pipeline.AuxBirdFullExpandedKey()] = expanded
|
||||
}
|
||||
writeJSON(w, http.StatusOK, obj)
|
||||
}
|
||||
|
||||
@@ -843,6 +876,44 @@ func (s *Server) handleGetJob(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, j.Snapshot())
|
||||
}
|
||||
|
||||
func (s *Server) handleGetJobReport(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok {
|
||||
writeProblem(w, http.StatusUnauthorized, "Unauthorized", "missing auth")
|
||||
return
|
||||
}
|
||||
if !s.requireAtLeast(w, a, "viewer") {
|
||||
return
|
||||
}
|
||||
j, err := s.jobs.Get(a.TenantID, r.PathValue("job_id"))
|
||||
if err != nil {
|
||||
writeProblem(w, http.StatusNotFound, "Not Found", "job not found")
|
||||
return
|
||||
}
|
||||
snap := j.Snapshot()
|
||||
meta, _ := snap["meta"].(map[string]any)
|
||||
out := map[string]any{
|
||||
"job_id": snap["job_id"],
|
||||
"kind": snap["kind"],
|
||||
"status": snap["status"],
|
||||
"meta": meta,
|
||||
"error": snap["error"],
|
||||
"created_at": snap["created_at"],
|
||||
}
|
||||
if meta != nil {
|
||||
if v, ok := meta["log_entries"]; ok {
|
||||
out["log_entries"] = v
|
||||
}
|
||||
if v, ok := meta["log_total"]; ok {
|
||||
out["log_total"] = v
|
||||
}
|
||||
if v, ok := meta["revision_id"]; ok {
|
||||
out["revision_id"] = v
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (s *Server) handleCancelJob(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok {
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"evobgp/internal/store"
|
||||
)
|
||||
|
||||
func (s *Server) registerAPIKeyRoutes(m *http.ServeMux) {
|
||||
m.HandleFunc("GET /auth/session", s.handleAuthSession)
|
||||
m.HandleFunc("GET /api-keys", s.handleListAPIKeys)
|
||||
m.HandleFunc("POST /api-keys", s.handlePostAPIKey)
|
||||
m.HandleFunc("GET /api-keys/{id}", s.handleGetAPIKey)
|
||||
m.HandleFunc("PATCH /api-keys/{id}", s.handlePatchAPIKey)
|
||||
m.HandleFunc("DELETE /api-keys/{id}", s.handleDeleteAPIKey)
|
||||
m.HandleFunc("POST /api-keys/{id}/rotate", s.handleRotateAPIKey)
|
||||
}
|
||||
|
||||
func (s *Server) handleAuthSession(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "viewer") {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"tenant_id": a.TenantID,
|
||||
"role": a.Role,
|
||||
})
|
||||
}
|
||||
|
||||
func apiKeyJSON(k *store.APIKey) map[string]any {
|
||||
m := map[string]any{
|
||||
"id": k.ID,
|
||||
"name": k.Name,
|
||||
"role": k.Role,
|
||||
"prefix": k.Prefix,
|
||||
"created_at": k.CreatedAt.UTC().Format(time.RFC3339),
|
||||
"updated_at": k.UpdatedAt.UTC().Format(time.RFC3339),
|
||||
}
|
||||
if k.ExpiresAt != nil {
|
||||
m["expires_at"] = k.ExpiresAt.UTC().Format(time.RFC3339)
|
||||
} else {
|
||||
m["expires_at"] = nil
|
||||
}
|
||||
if k.RevokedAt != nil {
|
||||
m["revoked_at"] = k.RevokedAt.UTC().Format(time.RFC3339)
|
||||
} else {
|
||||
m["revoked_at"] = nil
|
||||
}
|
||||
if k.LastUsedAt != nil {
|
||||
m["last_used_at"] = k.LastUsedAt.UTC().Format(time.RFC3339)
|
||||
} else {
|
||||
m["last_used_at"] = nil
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (s *Server) handleListAPIKeys(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "operator") {
|
||||
return
|
||||
}
|
||||
list, err := s.store.ListAPIKeys(a.TenantID)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
writePaginatedListJSON(w, r, list, func(k *store.APIKey) map[string]any {
|
||||
return apiKeyJSON(k)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleGetAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "operator") {
|
||||
return
|
||||
}
|
||||
k, err := s.store.GetAPIKey(a.TenantID, r.PathValue("id"))
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, apiKeyJSON(k))
|
||||
}
|
||||
|
||||
func (s *Server) handlePostAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "operator") {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Name string `json:"name"`
|
||||
Role string `json:"role"`
|
||||
ExpiresAt *string `json:"expires_at"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid json")
|
||||
return
|
||||
}
|
||||
in := &store.APIKeyCreate{
|
||||
Name: strings.TrimSpace(body.Name),
|
||||
Role: strings.TrimSpace(body.Role),
|
||||
}
|
||||
if body.ExpiresAt != nil && strings.TrimSpace(*body.ExpiresAt) != "" {
|
||||
t, err := time.Parse(time.RFC3339, strings.TrimSpace(*body.ExpiresAt))
|
||||
if err != nil {
|
||||
writeProblem(w, http.StatusUnprocessableEntity, "Unprocessable Entity", "invalid expires_at")
|
||||
return
|
||||
}
|
||||
in.ExpiresAt = &t
|
||||
}
|
||||
created, err := s.store.CreateAPIKey(a.TenantID, in)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
if err := s.keyResolver.Reload(s.store); err != nil {
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Server Error", "failed to reload api keys")
|
||||
return
|
||||
}
|
||||
out := apiKeyJSON(&created.APIKey)
|
||||
out["token"] = created.Token
|
||||
writeJSON(w, http.StatusCreated, out)
|
||||
}
|
||||
|
||||
func (s *Server) handlePatchAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "operator") {
|
||||
return
|
||||
}
|
||||
var raw map[string]json.RawMessage
|
||||
if err := json.NewDecoder(r.Body).Decode(&raw); err != nil {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid json")
|
||||
return
|
||||
}
|
||||
patch := &store.APIKeyPatch{}
|
||||
if v, ok := raw["name"]; ok {
|
||||
var name string
|
||||
if err := json.Unmarshal(v, &name); err != nil {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid name")
|
||||
return
|
||||
}
|
||||
patch.Name = &name
|
||||
}
|
||||
if v, ok := raw["role"]; ok {
|
||||
var role string
|
||||
if err := json.Unmarshal(v, &role); err != nil {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid role")
|
||||
return
|
||||
}
|
||||
patch.Role = &role
|
||||
}
|
||||
if v, ok := raw["expires_at"]; ok {
|
||||
if string(v) == "null" {
|
||||
patch.ClearExpiresAt = true
|
||||
} else {
|
||||
var s string
|
||||
if err := json.Unmarshal(v, &s); err != nil {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid expires_at")
|
||||
return
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339, strings.TrimSpace(s))
|
||||
if err != nil {
|
||||
writeProblem(w, http.StatusUnprocessableEntity, "Unprocessable Entity", "invalid expires_at")
|
||||
return
|
||||
}
|
||||
patch.ExpiresAt = &t
|
||||
}
|
||||
}
|
||||
k, err := s.store.UpdateAPIKey(a.TenantID, r.PathValue("id"), patch)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
if err := s.keyResolver.Reload(s.store); err != nil {
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Server Error", "failed to reload api keys")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, apiKeyJSON(k))
|
||||
}
|
||||
|
||||
func (s *Server) handleDeleteAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "operator") {
|
||||
return
|
||||
}
|
||||
if err := s.store.RevokeAPIKey(a.TenantID, r.PathValue("id")); err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
if err := s.keyResolver.Reload(s.store); err != nil {
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Server Error", "failed to reload api keys")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) handleRotateAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "operator") {
|
||||
return
|
||||
}
|
||||
rotated, err := s.store.RotateAPIKey(a.TenantID, r.PathValue("id"))
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
if err := s.keyResolver.Reload(s.store); err != nil {
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Server Error", "failed to reload api keys")
|
||||
return
|
||||
}
|
||||
out := apiKeyJSON(&rotated.APIKey)
|
||||
out["token"] = rotated.Token
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBearerDevWithoutInsecureDev(t *testing.T) {
|
||||
srv, err := New(Options{SeedDemo: true, BundleSeedHex: testBundleSeed})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer srv.Close()
|
||||
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
defer ts.Close()
|
||||
|
||||
req, _ := http.NewRequest(http.MethodGet, ts.URL+"/v1/modules?limit=1", nil)
|
||||
req.Header.Set("Authorization", "Bearer dev")
|
||||
resp, err := ts.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("status=%d body=%s", resp.StatusCode, b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIKeysCRUDAndAuth(t *testing.T) {
|
||||
srv, err := New(Options{SeedDemo: true, BundleSeedHex: testBundleSeed})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer srv.Close()
|
||||
tenant, _, _, _, _ := srv.Store().DemoIDs()
|
||||
mustSetTestAPIKeys(t, srv, "opkey|"+tenant+"|operator")
|
||||
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
defer ts.Close()
|
||||
client := ts.Client()
|
||||
base := ts.URL
|
||||
|
||||
reqCreate, _ := http.NewRequest(http.MethodPost, base+"/v1/api-keys", strings.NewReader(`{"name":"ci","role":"editor"}`))
|
||||
reqCreate.Header.Set("Authorization", "Bearer opkey")
|
||||
reqCreate.Header.Set("Content-Type", "application/json")
|
||||
respCreate, err := client.Do(reqCreate)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = respCreate.Body.Close() }()
|
||||
if respCreate.StatusCode != http.StatusCreated {
|
||||
b, _ := io.ReadAll(respCreate.Body)
|
||||
t.Fatalf("create status=%d body=%s", respCreate.StatusCode, b)
|
||||
}
|
||||
var created map[string]any
|
||||
if err := json.NewDecoder(respCreate.Body).Decode(&created); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, _ := created["token"].(string)
|
||||
if token == "" {
|
||||
t.Fatal("missing token in create response")
|
||||
}
|
||||
id, _ := created["id"].(string)
|
||||
if id == "" {
|
||||
t.Fatal("missing id")
|
||||
}
|
||||
|
||||
reqMod, _ := http.NewRequest(http.MethodGet, base+"/v1/modules?limit=1", nil)
|
||||
reqMod.Header.Set("Authorization", "Bearer "+token)
|
||||
respMod, err := client.Do(reqMod)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = respMod.Body.Close() }()
|
||||
if respMod.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(respMod.Body)
|
||||
t.Fatalf("modules status=%d body=%s", respMod.StatusCode, b)
|
||||
}
|
||||
|
||||
reqDel, _ := http.NewRequest(http.MethodDelete, base+"/v1/api-keys/"+id, nil)
|
||||
reqDel.Header.Set("Authorization", "Bearer opkey")
|
||||
respDel, err := client.Do(reqDel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = respDel.Body.Close() }()
|
||||
if respDel.StatusCode != http.StatusNoContent {
|
||||
t.Fatalf("delete status=%d", respDel.StatusCode)
|
||||
}
|
||||
|
||||
reqAfter, _ := http.NewRequest(http.MethodGet, base+"/v1/modules?limit=1", nil)
|
||||
reqAfter.Header.Set("Authorization", "Bearer "+token)
|
||||
respAfter, err := client.Do(reqAfter)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = respAfter.Body.Close() }()
|
||||
if respAfter.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401 after revoke, got %d", respAfter.StatusCode)
|
||||
}
|
||||
|
||||
mustSetTestAPIKeys(t, srv, "nodekey|"+tenant+"|node,opkey|"+tenant+"|operator")
|
||||
reqNode2, _ := http.NewRequest(http.MethodGet, base+"/v1/api-keys", nil)
|
||||
reqNode2.Header.Set("Authorization", "Bearer nodekey")
|
||||
respNode, err := client.Do(reqNode2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = respNode.Body.Close() }()
|
||||
if respNode.StatusCode != http.StatusForbidden {
|
||||
t.Fatalf("node list api-keys status=%d want 403", respNode.StatusCode)
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,8 @@ func (s *Server) registerCRUDRoutes(m *http.ServeMux) {
|
||||
|
||||
m.HandleFunc("GET /settings", s.handleGetSettings)
|
||||
m.HandleFunc("PATCH /settings", s.handlePatchSettings)
|
||||
|
||||
s.registerAPIKeyRoutes(m)
|
||||
}
|
||||
|
||||
func (s *Server) handlePostModule(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -21,7 +21,7 @@ func TestModuleEntriesCSVImportExportIPRanges(t *testing.T) {
|
||||
defer srv.Close()
|
||||
|
||||
tenant, _, modIP, _, _ := srv.Store().DemoIDs()
|
||||
srv.apiKeys = parseAPIKeysSpec("opkey|" + tenant + "|operator")
|
||||
mustSetTestAPIKeys(t, srv, "opkey|"+tenant+"|operator")
|
||||
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
defer ts.Close()
|
||||
|
||||
@@ -17,7 +17,7 @@ func TestNestedModuleListPagination(t *testing.T) {
|
||||
}
|
||||
defer srv.Close()
|
||||
tenant, _, modIP, _, _ := srv.Store().DemoIDs()
|
||||
srv.apiKeys = parseAPIKeysSpec("edkey|" + tenant + "|editor")
|
||||
mustSetTestAPIKeys(t, srv, "edkey|"+tenant+"|editor")
|
||||
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
defer ts.Close()
|
||||
|
||||
@@ -21,8 +21,7 @@ type Server struct {
|
||||
pgPool *pgxpool.Pool
|
||||
jobs *jobs.Registry
|
||||
bundlePriv ed25519.PrivateKey
|
||||
apiKeys []apiKeyRecord
|
||||
insecureDev bool
|
||||
keyResolver *apiKeyResolver
|
||||
corsOrigins []string
|
||||
cdnHTTP *http.Client
|
||||
mux *http.ServeMux
|
||||
@@ -60,13 +59,16 @@ func New(opts Options) (*Server, error) {
|
||||
_, priv, _ = ed25519.GenerateKey(rand.Reader)
|
||||
}
|
||||
|
||||
resolver, err := newAPIKeyResolver(opts.APIKeys, backend)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s := &Server{
|
||||
store: backend,
|
||||
pgPool: pool,
|
||||
jobs: reg,
|
||||
bundlePriv: priv,
|
||||
apiKeys: parseAPIKeysSpec(opts.APIKeys),
|
||||
insecureDev: opts.InsecureDev && opts.SeedDemo,
|
||||
keyResolver: resolver,
|
||||
corsOrigins: parseCORSOrigins(opts.CORSAllowedOrigins),
|
||||
cdnHTTP: NewCDNHTTPClient(),
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ func TestAPIRefreshApplyJobsBundle(t *testing.T) {
|
||||
}
|
||||
defer srv.Close()
|
||||
tenant, modCDN, modIP, rev, speaker := srv.Store().DemoIDs()
|
||||
srv.apiKeys = parseAPIKeysSpec("nodekey|" + tenant + "|node,opkey|" + tenant + "|operator,edkey|" + tenant + "|editor")
|
||||
mustSetTestAPIKeys(t, srv, "nodekey|"+tenant+"|node,opkey|"+tenant+"|operator,edkey|"+tenant+"|editor")
|
||||
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
defer ts.Close()
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package httpapi
|
||||
|
||||
import "testing"
|
||||
|
||||
func mustSetTestAPIKeys(t *testing.T, srv *Server, spec string) {
|
||||
t.Helper()
|
||||
resolver, err := newAPIKeyResolver(spec, srv.store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv.keyResolver = resolver
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package jobs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultJobTimeoutModuleRefresh = 10 * time.Minute
|
||||
defaultJobTimeoutTenantRefresh = 15 * time.Minute
|
||||
defaultJobTimeoutDeployApply = 5 * time.Minute
|
||||
defaultJobTimeoutPeerReconcile = 10 * time.Minute
|
||||
defaultJobTimeoutRollback = 5 * time.Minute
|
||||
defaultJobTimeoutBirdReload = 2 * time.Minute
|
||||
)
|
||||
|
||||
func jobTimeout(kind string) time.Duration {
|
||||
envKey := map[string]string{
|
||||
KindModuleRefresh: "EVOBGP_JOB_TIMEOUT_MODULE_REFRESH",
|
||||
KindTenantRefresh: "EVOBGP_JOB_TIMEOUT_TENANT_REFRESH",
|
||||
KindDeployApply: "EVOBGP_JOB_TIMEOUT_DEPLOY_APPLY",
|
||||
KindPeerReconcile: "EVOBGP_JOB_TIMEOUT_PEER_RECONCILE",
|
||||
KindRevisionRollback: "EVOBGP_JOB_TIMEOUT_ROLLBACK",
|
||||
KindBirdReload: "EVOBGP_JOB_TIMEOUT_BIRD_RELOAD",
|
||||
}[kind]
|
||||
if envKey != "" {
|
||||
if d, err := time.ParseDuration(os.Getenv(envKey)); err == nil && d > 0 {
|
||||
return d
|
||||
}
|
||||
}
|
||||
switch kind {
|
||||
case KindModuleRefresh:
|
||||
return defaultJobTimeoutModuleRefresh
|
||||
case KindTenantRefresh:
|
||||
return defaultJobTimeoutTenantRefresh
|
||||
case KindDeployApply:
|
||||
return defaultJobTimeoutDeployApply
|
||||
case KindPeerReconcile:
|
||||
return defaultJobTimeoutPeerReconcile
|
||||
case KindRevisionRollback:
|
||||
return defaultJobTimeoutRollback
|
||||
case KindBirdReload:
|
||||
return defaultJobTimeoutBirdReload
|
||||
default:
|
||||
if n, err := strconv.Atoi(os.Getenv("EVOBGP_JOB_TIMEOUT_SEC")); err == nil && n > 0 {
|
||||
return time.Duration(n) * time.Second
|
||||
}
|
||||
return defaultJobTimeoutModuleRefresh
|
||||
}
|
||||
}
|
||||
|
||||
// workContext returns a timeout context that also cancels when the job is cancelled.
|
||||
func (j *Job) workContext() (context.Context, context.CancelFunc) {
|
||||
if j == nil {
|
||||
return context.Background(), func() {}
|
||||
}
|
||||
timeout := jobTimeout(j.Kind)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
go func() {
|
||||
ticker := time.NewTicker(500 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if j.IsCancelRequested() {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return ctx, cancel
|
||||
}
|
||||
+51
-2
@@ -9,6 +9,8 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"evobgp/internal/observability"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
@@ -178,6 +180,8 @@ type Registry struct {
|
||||
byID map[string]*Job
|
||||
byIdempo map[idempoKey]*Job
|
||||
workerStart func(j *Job)
|
||||
workerSem chan struct{}
|
||||
onTerminal func(j *Job)
|
||||
}
|
||||
|
||||
type idempoKey struct {
|
||||
@@ -186,13 +190,44 @@ type idempoKey struct {
|
||||
}
|
||||
|
||||
func NewRegistry(workerStart func(j *Job)) *Registry {
|
||||
maxWorkers := registryMaxConcurrentJobs()
|
||||
return &Registry{
|
||||
byID: make(map[string]*Job),
|
||||
byIdempo: make(map[idempoKey]*Job),
|
||||
workerStart: workerStart,
|
||||
workerSem: make(chan struct{}, maxWorkers),
|
||||
}
|
||||
}
|
||||
|
||||
// SetTerminalHook registers a best-effort callback when jobs reach a terminal state.
|
||||
func (r *Registry) SetTerminalHook(fn func(j *Job)) {
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.onTerminal = fn
|
||||
}
|
||||
|
||||
func (r *Registry) fireTerminal(j *Job) {
|
||||
if r == nil || j == nil {
|
||||
return
|
||||
}
|
||||
r.mu.RLock()
|
||||
fn := r.onTerminal
|
||||
r.mu.RUnlock()
|
||||
if fn != nil {
|
||||
fn(j)
|
||||
}
|
||||
}
|
||||
|
||||
func registryMaxConcurrentJobs() int {
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(os.Getenv("EVOBGP_JOB_MAX_CONCURRENT"))); err == nil && n > 0 {
|
||||
return n
|
||||
}
|
||||
return 8
|
||||
}
|
||||
|
||||
// pruneTerminalIfOver удаляет самые старые завершённые джобы (succeeded/failed/cancelled), пока len(byID) > maxJobs.
|
||||
func (r *Registry) pruneTerminalIfOver(maxJobs int) {
|
||||
if r == nil || maxJobs <= 0 || len(r.byID) <= maxJobs {
|
||||
@@ -244,7 +279,11 @@ func (r *Registry) Enqueue(tenantID, kind string, idempotencyKey *string, module
|
||||
if idempotencyKey != nil && *idempotencyKey != "" {
|
||||
k := idempoKey{tenant: tenantID, key: *idempotencyKey}
|
||||
if existing, ok := r.byIdempo[k]; ok {
|
||||
return existing, false, nil
|
||||
st := existing.statusLocked()
|
||||
if st == StatusQueued || st == StatusRunning {
|
||||
return existing, false, nil
|
||||
}
|
||||
delete(r.byIdempo, k)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,7 +304,17 @@ func (r *Registry) Enqueue(tenantID, kind string, idempotencyKey *string, module
|
||||
r.pruneTerminalIfOver(maxJobs)
|
||||
|
||||
if r.workerStart != nil {
|
||||
go r.workerStart(j)
|
||||
go func() {
|
||||
r.workerSem <- struct{}{}
|
||||
active := len(r.workerSem)
|
||||
capacity := cap(r.workerSem)
|
||||
observability.RecordJobQueueDepth(active, capacity)
|
||||
defer func() {
|
||||
<-r.workerSem
|
||||
observability.RecordJobQueueDepth(len(r.workerSem), capacity)
|
||||
}()
|
||||
r.workerStart(j)
|
||||
}()
|
||||
}
|
||||
return j, true, nil
|
||||
}
|
||||
|
||||
+56
-8
@@ -82,6 +82,9 @@ func (w *Worker) httpClient() *http.Client {
|
||||
func (w *Worker) Process(j *Job) {
|
||||
defer func() {
|
||||
observability.RecordJobTerminal(j.Kind, j.statusLocked())
|
||||
if w != nil && w.Registry != nil {
|
||||
w.Registry.fireTerminal(j)
|
||||
}
|
||||
}()
|
||||
|
||||
if w == nil || w.Store == nil {
|
||||
@@ -102,7 +105,17 @@ func (w *Worker) Process(j *Job) {
|
||||
j.Fail("missing module_id in job meta")
|
||||
return
|
||||
}
|
||||
if err := pipeline.RefreshModuleIngest(context.Background(), w.Store, w.httpClient(), j.TenantID, mid); err != nil {
|
||||
ctx, cancel := j.workContext()
|
||||
defer cancel()
|
||||
if ctx.Err() != nil {
|
||||
j.MarkCancelled()
|
||||
return
|
||||
}
|
||||
if err := pipeline.RefreshModuleIngest(ctx, w.Store, w.httpClient(), j.TenantID, mid); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
j.MarkCancelled()
|
||||
return
|
||||
}
|
||||
j.Fail(err.Error())
|
||||
return
|
||||
}
|
||||
@@ -121,11 +134,17 @@ func (w *Worker) Process(j *Job) {
|
||||
j.Succeed()
|
||||
return
|
||||
}
|
||||
ctx, cancel := j.workContext()
|
||||
defer cancel()
|
||||
ctl := &birdfmt.BirdCtl{
|
||||
Socket: sock,
|
||||
Birdc: strings.TrimSpace(os.Getenv("EVOBGP_BIRDC_BIN")),
|
||||
}
|
||||
if err := ctl.Configure(context.Background()); err != nil {
|
||||
if err := ctl.Configure(ctx); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
j.MarkCancelled()
|
||||
return
|
||||
}
|
||||
j.Fail(err.Error())
|
||||
return
|
||||
}
|
||||
@@ -152,9 +171,14 @@ func (w *Worker) runPeerReconcile(j *Job) {
|
||||
return
|
||||
}
|
||||
if len(latest) == 0 {
|
||||
// First run fallback: render full tenant state once if no baseline revision exists yet.
|
||||
rid, err := pipeline.RenderTenantRevision(context.Background(), w.Store, w.httpClient(), j.TenantID, triggerModuleID)
|
||||
ctx, cancel := j.workContext()
|
||||
defer cancel()
|
||||
rid, err := pipeline.RenderTenantRevision(ctx, w.Store, w.httpClient(), j.TenantID, triggerModuleID)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
j.MarkCancelled()
|
||||
return
|
||||
}
|
||||
j.Fail(err.Error())
|
||||
return
|
||||
}
|
||||
@@ -171,8 +195,14 @@ func (w *Worker) runPeerReconcile(j *Job) {
|
||||
}
|
||||
cursor = next
|
||||
}
|
||||
rid, err := pipeline.RenderTenantRevisionFromPrefixes(context.Background(), w.Store, w.httpClient(), j.TenantID, triggerModuleID, rows)
|
||||
ctx, cancel := j.workContext()
|
||||
defer cancel()
|
||||
rid, err := pipeline.RenderTenantRevisionFromPrefixes(ctx, w.Store, w.httpClient(), j.TenantID, triggerModuleID, rows)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
j.MarkCancelled()
|
||||
return
|
||||
}
|
||||
j.Fail(err.Error())
|
||||
return
|
||||
}
|
||||
@@ -230,7 +260,13 @@ func (w *Worker) runTenantRefresh(j *Job) {
|
||||
j.Fail("missing module_ids in job meta")
|
||||
return
|
||||
}
|
||||
if err := pipeline.RefreshTenantModules(context.Background(), w.Store, w.httpClient(), j.TenantID, moduleIDs); err != nil {
|
||||
ctx, cancel := j.workContext()
|
||||
defer cancel()
|
||||
if err := pipeline.RefreshTenantModules(ctx, w.Store, w.httpClient(), j.TenantID, moduleIDs); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
j.MarkCancelled()
|
||||
return
|
||||
}
|
||||
j.Fail(err.Error())
|
||||
return
|
||||
}
|
||||
@@ -275,6 +311,8 @@ func (w *Worker) finishModuleRefreshSuccess(j *Job, triggerModuleID string) {
|
||||
mu := w.tenantRefreshMu(j.TenantID)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
ctx, cancel := j.workContext()
|
||||
defer cancel()
|
||||
deferDeploy := false
|
||||
if w.Registry != nil {
|
||||
deferDeploy = w.Registry.CountOtherActiveRefresh(j.TenantID, j.ID) > 0
|
||||
@@ -288,8 +326,12 @@ func (w *Worker) finishModuleRefreshSuccess(j *Job, triggerModuleID string) {
|
||||
return
|
||||
}
|
||||
|
||||
rev, err := pipeline.RenderTenantRevision(context.Background(), w.Store, w.httpClient(), j.TenantID, triggerModuleID)
|
||||
rev, err := pipeline.RenderTenantRevision(ctx, w.Store, w.httpClient(), j.TenantID, triggerModuleID)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
j.MarkCancelled()
|
||||
return
|
||||
}
|
||||
j.Fail(err.Error())
|
||||
return
|
||||
}
|
||||
@@ -335,6 +377,8 @@ func (w *Worker) runDeployApply(j *Job) {
|
||||
j.Fail("missing revision_id in job meta")
|
||||
return
|
||||
}
|
||||
ctx, cancel := j.workContext()
|
||||
defer cancel()
|
||||
activeDir := strings.TrimSpace(os.Getenv("EVOBGP_BIRD_ACTIVE_DIR"))
|
||||
if activeDir != "" {
|
||||
revObj, err := w.Store.GetRevision(j.TenantID, revID)
|
||||
@@ -354,7 +398,11 @@ func (w *Worker) runDeployApply(j *Job) {
|
||||
Socket: strings.TrimSpace(os.Getenv("EVOBGP_BIRDC_SOCKET")),
|
||||
}
|
||||
ctl := &birdfmt.BirdCtl{Bird: cfg.BirdBin, Birdc: cfg.BirdcBin, Socket: cfg.Socket}
|
||||
if err := birddeploy.ApplyRevision(context.Background(), ctl, revObj, cfg); err != nil {
|
||||
if err := birddeploy.ApplyRevision(ctx, ctl, revObj, cfg); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
j.MarkCancelled()
|
||||
return
|
||||
}
|
||||
j.Fail(err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
@@ -80,6 +80,38 @@ var (
|
||||
Help: "Prefix row count after CIDR aggregation on tenant render.",
|
||||
Buckets: prometheus.ExponentialBuckets(1, 2, 16),
|
||||
})
|
||||
|
||||
pipelineRefreshDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Namespace: namespace,
|
||||
Name: "pipeline_refresh_duration_seconds",
|
||||
Help: "Module refresh ingest duration by module type.",
|
||||
Buckets: prometheus.ExponentialBuckets(0.05, 2, 14),
|
||||
}, []string{"module_type"})
|
||||
|
||||
renderPrefixCount = promauto.NewHistogram(prometheus.HistogramOpts{
|
||||
Namespace: namespace,
|
||||
Name: "render_prefix_count",
|
||||
Help: "Materialized prefix count per tenant render.",
|
||||
Buckets: prometheus.ExponentialBuckets(10, 2, 16),
|
||||
})
|
||||
|
||||
jobQueueActive = promauto.NewGauge(prometheus.GaugeOpts{
|
||||
Namespace: namespace,
|
||||
Name: "job_queue_active",
|
||||
Help: "Currently running in-process async jobs.",
|
||||
})
|
||||
|
||||
jobQueueCapacity = promauto.NewGauge(prometheus.GaugeOpts{
|
||||
Namespace: namespace,
|
||||
Name: "job_queue_capacity",
|
||||
Help: "Maximum concurrent in-process async jobs.",
|
||||
})
|
||||
)
|
||||
|
||||
var (
|
||||
birdProtocolStatesMu sync.RWMutex
|
||||
birdProtocolStates map[string]string
|
||||
birdProtocolStatesAt time.Time
|
||||
)
|
||||
|
||||
// RecordPrefixAggregation records tenant render CIDR aggregation stats.
|
||||
@@ -93,6 +125,27 @@ func RecordPrefixAggregation(rawCount, aggregatedCount int, duration time.Durati
|
||||
prefixAggregationDuration.Observe(duration.Seconds())
|
||||
prefixAggregationRawCount.Observe(float64(rawCount))
|
||||
prefixAggregationAggregatedCount.Observe(float64(aggregatedCount))
|
||||
renderPrefixCount.Observe(float64(aggregatedCount))
|
||||
}
|
||||
|
||||
// RecordPipelineRefresh records module ingest duration.
|
||||
func RecordPipelineRefresh(moduleType string, duration time.Duration) {
|
||||
if moduleType == "" {
|
||||
moduleType = "unknown"
|
||||
}
|
||||
pipelineRefreshDuration.WithLabelValues(moduleType).Observe(duration.Seconds())
|
||||
}
|
||||
|
||||
// RecordJobQueueDepth updates in-process job worker utilization gauges.
|
||||
func RecordJobQueueDepth(active, capacity int) {
|
||||
if active < 0 {
|
||||
active = 0
|
||||
}
|
||||
if capacity < 0 {
|
||||
capacity = 0
|
||||
}
|
||||
jobQueueActive.Set(float64(active))
|
||||
jobQueueCapacity.Set(float64(capacity))
|
||||
}
|
||||
|
||||
// RecordJobTerminal increments jobs_finished_total for terminal statuses.
|
||||
@@ -205,6 +258,35 @@ func SetBirdSessionMetrics(established int, scrapeOK bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// SetBirdProtocolStates caches parsed BGP protocol states from the last birdc scrape.
|
||||
func SetBirdProtocolStates(states map[string]string) {
|
||||
birdProtocolStatesMu.Lock()
|
||||
defer birdProtocolStatesMu.Unlock()
|
||||
if states == nil {
|
||||
birdProtocolStates = map[string]string{}
|
||||
} else {
|
||||
birdProtocolStates = states
|
||||
}
|
||||
birdProtocolStatesAt = time.Now()
|
||||
}
|
||||
|
||||
// CachedBirdProtocolStates returns cached protocol states if younger than maxAge.
|
||||
func CachedBirdProtocolStates(maxAge time.Duration) (map[string]string, bool) {
|
||||
if maxAge <= 0 {
|
||||
maxAge = 60 * time.Second
|
||||
}
|
||||
birdProtocolStatesMu.RLock()
|
||||
defer birdProtocolStatesMu.RUnlock()
|
||||
if birdProtocolStates == nil || time.Since(birdProtocolStatesAt) > maxAge {
|
||||
return nil, false
|
||||
}
|
||||
out := make(map[string]string, len(birdProtocolStates))
|
||||
for k, v := range birdProtocolStates {
|
||||
out[k] = v
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
// MetricsHandler returns the Prometheus scrape handler.
|
||||
func MetricsHandler() http.Handler {
|
||||
return promhttp.HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{})
|
||||
@@ -231,7 +313,7 @@ func (s *statusRecorder) WriteHeader(code int) {
|
||||
|
||||
// StartBirdProtocolsPoller runs birdc "show protocols" on interval when socket is non-empty.
|
||||
// Горутина завершается при отмене ctx (корректное завершение вместе с процессом API).
|
||||
func StartBirdProtocolsPoller(ctx context.Context, socket string, birdcPath string, interval time.Duration, showFn func(ctx context.Context, socket, birdcBin string) (string, error), countFn func(output string) int) {
|
||||
func StartBirdProtocolsPoller(ctx context.Context, socket string, birdcPath string, interval time.Duration, showFn func(ctx context.Context, socket, birdcBin string) (string, error), countFn func(output string) int, parseFn func(output string) map[string]string) {
|
||||
socket = trimSpace(socket)
|
||||
if ctx == nil || socket == "" || interval <= 0 || showFn == nil || countFn == nil {
|
||||
return
|
||||
@@ -245,6 +327,9 @@ func StartBirdProtocolsPoller(ctx context.Context, socket string, birdcPath stri
|
||||
return
|
||||
}
|
||||
SetBirdSessionMetrics(countFn(out), true)
|
||||
if parseFn != nil {
|
||||
SetBirdProtocolStates(parseFn(out))
|
||||
}
|
||||
}
|
||||
go func() {
|
||||
scrape()
|
||||
|
||||
@@ -44,6 +44,7 @@ func resolveASNForEntry(ctx context.Context, st store.Backend, hc *http.Client,
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
asnresolve.PolitePause()
|
||||
holder, _ := asnresolve.ASHolderName(ctx, hc, asn)
|
||||
if st != nil {
|
||||
strs := make([]string, len(pfxs))
|
||||
|
||||
@@ -25,9 +25,6 @@ func cachedCDNPrefixRows(st store.Backend, tenantID, moduleID string, priorSnaps
|
||||
return cached
|
||||
}
|
||||
}
|
||||
if cached := latestCDNRowsBySource(st, tenantID)[sourceKey]; len(cached) > 0 {
|
||||
return cached
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -45,6 +42,35 @@ func mergeSnapshotDropSource(rows []store.PrefixRow, sourceKey string) []store.P
|
||||
return out
|
||||
}
|
||||
|
||||
// mergeSnapshotDropCDNSources removes all cdn:* rows (used before batch CDN merge).
|
||||
func mergeSnapshotDropCDNSources(rows []store.PrefixRow) []store.PrefixRow {
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make([]store.PrefixRow, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
if !strings.HasPrefix(strings.TrimSpace(row.Source), "cdn:") {
|
||||
out = append(out, row)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// mergeAllCDNSourcesIntoModuleSnapshot replaces all CDN rows in one write (avoids parallel read-modify-write races).
|
||||
func mergeAllCDNSourcesIntoModuleSnapshot(st store.Backend, tenantID string, mod *store.Module, priorSnapshot []store.PrefixRow, cdnRows []store.PrefixRow) error {
|
||||
if st == nil || mod == nil {
|
||||
return nil
|
||||
}
|
||||
var base []store.PrefixRow
|
||||
if len(priorSnapshot) > 0 {
|
||||
base = mergeSnapshotDropCDNSources(priorSnapshot)
|
||||
} else if snap, ok, _ := st.GetModulePrefixSnapshot(tenantID, mod.ID); ok && snap != nil {
|
||||
base = mergeSnapshotDropCDNSources(snap.Prefixes)
|
||||
}
|
||||
merged := append(base, cdnRows...)
|
||||
return persistModuleSnapshot(st, tenantID, mod, merged)
|
||||
}
|
||||
|
||||
func cdnRowsFromParsed(mod *store.Module, src *store.CDNSource, pfxStrings []string) []store.PrefixRow {
|
||||
var rows []store.PrefixRow
|
||||
for _, p := range pfxStrings {
|
||||
@@ -156,3 +182,68 @@ func applyCDNSourceHTTPResult(ctx context.Context, st store.Backend, hc *http.Cl
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// fetchCDNSourceRows loads CDN prefixes without persisting the module snapshot (caller merges once).
|
||||
func fetchCDNSourceRows(ctx context.Context, st store.Backend, hc *http.Client, tenantID, moduleID string, mod *store.Module, src *store.CDNSource, priorSnapshot []store.PrefixRow, now time.Time) ([]store.PrefixRow, error) {
|
||||
u := strings.TrimSpace(src.URL)
|
||||
if u == "" {
|
||||
return nil, nil
|
||||
}
|
||||
sourceKey := cdnSourceKey(src.ID)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if etag := strings.TrimSpace(src.Etag); etag != "" {
|
||||
req.Header.Set("If-None-Match", etag)
|
||||
}
|
||||
resp, err := hc.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cdn fetch %s: %w", u, err)
|
||||
}
|
||||
|
||||
if resp.StatusCode == http.StatusNotModified {
|
||||
if cached := cachedCDNPrefixRows(st, tenantID, moduleID, priorSnapshot, sourceKey); len(cached) > 0 {
|
||||
_ = resp.Body.Close()
|
||||
return cached, nil
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
req2, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err = hc.Do(req2)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cdn fetch %s: %w", u, err)
|
||||
}
|
||||
if resp.StatusCode == http.StatusNotModified {
|
||||
_ = resp.Body.Close()
|
||||
return nil, fmt.Errorf("cdn url %s: 304 without cached prefixes", u)
|
||||
}
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
return nil, fmt.Errorf("cdn url %s: %s", u, resp.Status)
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
prefixStrs, err := parseCDNBody(string(body), src)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cdn parse %s: %w", u, err)
|
||||
}
|
||||
etag := strings.TrimSpace(resp.Header.Get("ETag"))
|
||||
patch := &store.CDNSourcePatch{}
|
||||
if etag != "" && etag != strings.TrimSpace(src.Etag) {
|
||||
e := etag
|
||||
patch.Etag = &e
|
||||
}
|
||||
refreshedAt := now
|
||||
patch.LastRefreshedAt = &refreshedAt
|
||||
_, _ = st.UpdateCDNSource(tenantID, moduleID, src.ID, patch)
|
||||
|
||||
return cdnRowsFromParsed(mod, src, prefixStrs), nil
|
||||
}
|
||||
|
||||
@@ -97,15 +97,18 @@ func collectASPrefixRows(ctx context.Context, st store.Backend, hc *http.Client,
|
||||
|
||||
seenPfx := make(map[string]struct{})
|
||||
var out []store.PrefixRow
|
||||
var metaUpdates []store.ASEntryResolveMetaUpdate
|
||||
now := time.Now().UTC()
|
||||
for _, r := range results {
|
||||
if r.err != nil {
|
||||
return nil, r.err
|
||||
}
|
||||
if r.metaID != "" {
|
||||
if err := st.UpdateASEntryResolveMeta(tenantID, moduleID, r.metaID, r.holder, r.count, now); err != nil {
|
||||
return nil, fmt.Errorf("as entry meta AS%d: %w", r.asn, err)
|
||||
}
|
||||
metaUpdates = append(metaUpdates, store.ASEntryResolveMetaUpdate{
|
||||
EntryID: r.metaID,
|
||||
ASNName: r.holder,
|
||||
PrefixCount: r.count,
|
||||
})
|
||||
}
|
||||
for _, row := range r.rows {
|
||||
k := row.Prefix
|
||||
@@ -116,6 +119,11 @@ func collectASPrefixRows(ctx context.Context, st store.Backend, hc *http.Client,
|
||||
out = append(out, row)
|
||||
}
|
||||
}
|
||||
if len(metaUpdates) > 0 {
|
||||
if err := st.UpdateASEntryResolveMetaBatch(tenantID, moduleID, metaUpdates, now); err != nil {
|
||||
return nil, fmt.Errorf("as entry meta batch: %w", err)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -150,12 +158,14 @@ func collectCDNPrefixRows(ctx context.Context, st store.Backend, hc *http.Client
|
||||
results[idx] = srcResult{rows: cached}
|
||||
return
|
||||
}
|
||||
if cached := latestCDNRowsBySource(st, tenantID)[sourceKey]; len(cached) > 0 {
|
||||
results[idx] = srcResult{rows: cached}
|
||||
return
|
||||
if snap, ok, _ := st.GetModulePrefixSnapshot(tenantID, moduleID); ok && snap != nil {
|
||||
if cached := prefixRowsForSource(snap.Prefixes, sourceKey); len(cached) > 0 {
|
||||
results[idx] = srcResult{rows: cached}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
rows, err := applyCDNSourceHTTPResult(ctx, st, hc, tenantID, moduleID, mod, src, priorSnapshot, now)
|
||||
rows, err := fetchCDNSourceRows(ctx, st, hc, tenantID, moduleID, mod, src, priorSnapshot, now)
|
||||
if err != nil {
|
||||
results[idx] = srcResult{err: err}
|
||||
return
|
||||
@@ -172,6 +182,11 @@ func collectCDNPrefixRows(ctx context.Context, st store.Backend, hc *http.Client
|
||||
}
|
||||
out = append(out, r.rows...)
|
||||
}
|
||||
if len(valid) > 0 {
|
||||
if err := mergeAllCDNSourcesIntoModuleSnapshot(st, tenantID, mod, priorSnapshot, out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,11 @@ const (
|
||||
revisionDefaultTTL = 30 * 24 * time.Hour
|
||||
)
|
||||
|
||||
// AuxBirdFullExpandedKey returns the preview map key for the expanded BIRD config (generated on demand).
|
||||
func AuxBirdFullExpandedKey() string {
|
||||
return auxBirdFullExpanded
|
||||
}
|
||||
|
||||
// MaterializedASPrefixKey returns the revision snapshot key for an AS-only entry (not a CIDR).
|
||||
func MaterializedASPrefixKey(asn int64) string {
|
||||
return fmt.Sprintf("as:%d", asn)
|
||||
@@ -47,10 +52,14 @@ func RefreshModuleIngest(ctx context.Context, st store.Backend, hc *http.Client,
|
||||
if hc == nil {
|
||||
hc = http.DefaultClient
|
||||
}
|
||||
start := time.Now()
|
||||
mod, err := st.GetModule(tenantID, moduleID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
observability.RecordPipelineRefresh(mod.Type, time.Since(start))
|
||||
}()
|
||||
if !mod.Enabled {
|
||||
return fmt.Errorf("pipeline: module disabled")
|
||||
}
|
||||
@@ -197,33 +206,6 @@ func shouldSkipCDNSourceFetch(src *store.CDNSource, now time.Time) bool {
|
||||
return now.UTC().Before(nextRefreshAt)
|
||||
}
|
||||
|
||||
func latestCDNRowsBySource(st store.Backend, tenantID string) map[string][]store.PrefixRow {
|
||||
out := make(map[string][]store.PrefixRow)
|
||||
if st == nil {
|
||||
return out
|
||||
}
|
||||
revs, _, _ := st.ListRevisions(tenantID, "", "", 1)
|
||||
if len(revs) == 0 || strings.TrimSpace(revs[0].ID) == "" {
|
||||
return out
|
||||
}
|
||||
revID := strings.TrimSpace(revs[0].ID)
|
||||
cursor := ""
|
||||
for {
|
||||
page, next, more := st.ListRevisionPrefixes(tenantID, revID, cursor, 2000)
|
||||
for _, row := range page {
|
||||
if !strings.HasPrefix(strings.TrimSpace(row.Source), "cdn:") {
|
||||
continue
|
||||
}
|
||||
out[row.Source] = append(out[row.Source], row)
|
||||
}
|
||||
if !more || strings.TrimSpace(next) == "" {
|
||||
break
|
||||
}
|
||||
cursor = next
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type dohJSONAnswer struct {
|
||||
Type int `json:"type"`
|
||||
Data string `json:"data"`
|
||||
@@ -836,10 +818,18 @@ func buildPreviewFragments(st store.Backend, tenantID, moduleID, revisionID stri
|
||||
px6: birdfmt.JoinFragments(birdfmt.ManagedBanner(revisionID), staticV6),
|
||||
pPeers: peersBody,
|
||||
}
|
||||
out[auxBirdFullExpanded] = buildExpandedBirdText(main, out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// BuildExpandedBirdPreview concatenates bird.conf and deployable includes for UI preview (not persisted in revision).
|
||||
func BuildExpandedBirdPreview(frags map[string]string) string {
|
||||
if frags == nil {
|
||||
return ""
|
||||
}
|
||||
main := frags["bird.conf"]
|
||||
return buildExpandedBirdText(main, frags)
|
||||
}
|
||||
|
||||
func renderStaticProtocolsByCommunity(groups []staticCommunityRoutes) (string, string) {
|
||||
var b4 strings.Builder
|
||||
var b6 strings.Builder
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// JobAuditWriter persists async job lifecycle rows to job_audit (optional cross-process queue foundation).
|
||||
type JobAuditWriter struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewJobAuditWriter(pool *pgxpool.Pool) *JobAuditWriter {
|
||||
if pool == nil {
|
||||
return nil
|
||||
}
|
||||
return &JobAuditWriter{pool: pool}
|
||||
}
|
||||
|
||||
// UpsertRunning inserts or updates a running job row (best-effort).
|
||||
func (w *JobAuditWriter) UpsertRunning(ctx context.Context, tenantID, jobID, kind string, idempotencyKey *string, meta map[string]any) {
|
||||
if w == nil || w.pool == nil {
|
||||
return
|
||||
}
|
||||
metaJSON, _ := json.Marshal(meta)
|
||||
var idem any
|
||||
if idempotencyKey != nil && *idempotencyKey != "" {
|
||||
idem = *idempotencyKey
|
||||
}
|
||||
_, _ = w.pool.Exec(ctx, `
|
||||
INSERT INTO job_audit (id, tenant_id, kind, status, idempotency_key, meta_json, created_at, started_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3, 'running', $4, $5::jsonb, now(), now())
|
||||
ON CONFLICT (tenant_id, idempotency_key) WHERE idempotency_key IS NOT NULL
|
||||
DO UPDATE SET status='running', started_at=now(), meta_json=EXCLUDED.meta_json`,
|
||||
jobID, tenantID, kind, idem, metaJSON)
|
||||
}
|
||||
|
||||
// MarkTerminal updates job_audit terminal state (best-effort).
|
||||
func (w *JobAuditWriter) MarkTerminal(ctx context.Context, tenantID, jobID, status string, errMsg *string, finishedAt time.Time) {
|
||||
if w == nil || w.pool == nil {
|
||||
return
|
||||
}
|
||||
_, _ = w.pool.Exec(ctx, `
|
||||
UPDATE job_audit SET status=$3, error_message=$4, finished_at=$5
|
||||
WHERE id=$1::uuid AND tenant_id=$2::uuid`,
|
||||
jobID, tenantID, status, errMsg, finishedAt.UTC())
|
||||
}
|
||||
+127
-27
@@ -126,6 +126,7 @@ func (p *Postgres) ListModules(tenantID string) []*store.Module {
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []*store.Module
|
||||
moduleByID := make(map[string]*store.Module)
|
||||
for rows.Next() {
|
||||
var m store.Module
|
||||
m.TenantID = tenantID
|
||||
@@ -152,14 +153,84 @@ func (p *Postgres) ListModules(tenantID string) []*store.Module {
|
||||
t := last.UTC()
|
||||
m.LastRefreshedAt = &t
|
||||
}
|
||||
if err := p.fillModuleDohFields(ctx, &m); err != nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, &m)
|
||||
moduleByID[m.ID] = &m
|
||||
}
|
||||
if err := p.batchFillModuleDohFields(ctx, moduleByID); err != nil {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (p *Postgres) ListModulesPage(tenantID, cursor string, limit int) ([]*store.Module, string, bool) {
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
off := 0
|
||||
if cursor != "" {
|
||||
if n, err := strconv.Atoi(cursor); err == nil && n >= 0 {
|
||||
off = n
|
||||
}
|
||||
}
|
||||
ctx := context.Background()
|
||||
rows, err := p.pool.Query(ctx, `
|
||||
SELECT id, type, name, enabled, priority, doh_profile_id::text, doh_resolver_policy,
|
||||
refresh_interval_sec, cron_expr, default_community_id::text, last_refreshed_at
|
||||
FROM module WHERE tenant_id = $1 AND deleted_at IS NULL
|
||||
ORDER BY priority, name
|
||||
LIMIT $2 OFFSET $3`, tenantID, limit+1, off)
|
||||
if err != nil {
|
||||
return nil, "", false
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []*store.Module
|
||||
moduleByID := make(map[string]*store.Module)
|
||||
for rows.Next() {
|
||||
var m store.Module
|
||||
m.TenantID = tenantID
|
||||
var doh, dc, cron *string
|
||||
var refresh *int32
|
||||
var last *time.Time
|
||||
if err := rows.Scan(&m.ID, &m.Type, &m.Name, &m.Enabled, &m.Priority, &doh, &m.DohResolverPolicy, &refresh, &cron, &dc, &last); err != nil {
|
||||
continue
|
||||
}
|
||||
m.DohResolverPolicy = store.NormalizeDohResolverPolicy(m.DohResolverPolicy)
|
||||
if refresh != nil {
|
||||
m.RefreshIntervalSec = int(*refresh)
|
||||
}
|
||||
if cron != nil {
|
||||
m.CronExpr = *cron
|
||||
}
|
||||
if doh != nil && *doh != "" {
|
||||
m.DohProfileID = doh
|
||||
}
|
||||
if dc != nil && *dc != "" {
|
||||
m.DefaultCommunityID = dc
|
||||
}
|
||||
if last != nil {
|
||||
t := last.UTC()
|
||||
m.LastRefreshedAt = &t
|
||||
}
|
||||
out = append(out, &m)
|
||||
moduleByID[m.ID] = &m
|
||||
}
|
||||
if err := p.batchFillModuleDohFields(ctx, moduleByID); err != nil {
|
||||
return nil, "", false
|
||||
}
|
||||
more := len(out) > limit
|
||||
if more {
|
||||
out = out[:limit]
|
||||
}
|
||||
next := ""
|
||||
if more {
|
||||
next = fmt.Sprintf("%d", off+limit)
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil, "", false
|
||||
}
|
||||
return out, next, more
|
||||
}
|
||||
|
||||
func (p *Postgres) GetModule(tenantID, moduleID string) (*store.Module, error) {
|
||||
ctx := context.Background()
|
||||
var m store.Module
|
||||
@@ -685,7 +756,13 @@ func (p *Postgres) ListRevisionPrefixes(tenantID, revisionID string, cursor stri
|
||||
}
|
||||
}
|
||||
ctx := context.Background()
|
||||
if _, err := p.GetRevision(tenantID, revisionID); err != nil {
|
||||
var one int
|
||||
if err := p.pool.QueryRow(ctx, `
|
||||
SELECT 1 FROM config_revision WHERE id = $1::uuid AND tenant_id = $2::uuid`,
|
||||
revisionID, tenantID).Scan(&one); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, "", false
|
||||
}
|
||||
return nil, "", false
|
||||
}
|
||||
rows, err := p.pool.Query(ctx, `
|
||||
@@ -754,6 +831,8 @@ func (p *Postgres) CreateRollbackRevision(tenantID, sourceRevisionID string) (st
|
||||
return newID, nil
|
||||
}
|
||||
|
||||
const maxRevisionDiffRows = 5000
|
||||
|
||||
func (p *Postgres) RevisionDiff(tenantID, aID, bID string) (map[string]any, error) {
|
||||
if _, err := p.GetRevision(tenantID, aID); err != nil {
|
||||
return nil, err
|
||||
@@ -778,7 +857,7 @@ func (p *Postgres) RevisionDiff(tenantID, aID, bID string) (map[string]any, erro
|
||||
SELECT prefix FROM revision_materialized_prefix WHERE revision_id=$1::uuid
|
||||
EXCEPT
|
||||
SELECT prefix FROM revision_materialized_prefix WHERE revision_id=$2::uuid
|
||||
) s ORDER BY 1`, bID, aID)
|
||||
) s ORDER BY 1 LIMIT $3`, bID, aID, maxRevisionDiffRows+1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -790,13 +869,18 @@ func (p *Postgres) RevisionDiff(tenantID, aID, bID string) (map[string]any, erro
|
||||
continue
|
||||
}
|
||||
added = append(added, s)
|
||||
if len(added) > maxRevisionDiffRows {
|
||||
added = added[:maxRevisionDiffRows]
|
||||
break
|
||||
}
|
||||
}
|
||||
addedTruncated := len(added) >= maxRevisionDiffRows
|
||||
rowsRem, err := p.pool.Query(ctx, `
|
||||
SELECT prefix::text FROM (
|
||||
SELECT prefix FROM revision_materialized_prefix WHERE revision_id=$1::uuid
|
||||
EXCEPT
|
||||
SELECT prefix FROM revision_materialized_prefix WHERE revision_id=$2::uuid
|
||||
) s ORDER BY 1`, aID, bID)
|
||||
) s ORDER BY 1 LIMIT $3`, aID, bID, maxRevisionDiffRows+1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -808,40 +892,56 @@ func (p *Postgres) RevisionDiff(tenantID, aID, bID string) (map[string]any, erro
|
||||
continue
|
||||
}
|
||||
removed = append(removed, s)
|
||||
if len(removed) > maxRevisionDiffRows {
|
||||
removed = removed[:maxRevisionDiffRows]
|
||||
break
|
||||
}
|
||||
}
|
||||
return map[string]any{
|
||||
"revision_a": aID,
|
||||
"revision_b": bID,
|
||||
"prefixes": map[string]any{
|
||||
"added": added, "removed": removed, "unchanged_count": unchanged,
|
||||
"truncated": addedTruncated || len(removed) >= maxRevisionDiffRows,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *Postgres) PruneRevisionsBefore(tenantID string, cutoff time.Time) (int, error) {
|
||||
ctx := context.Background()
|
||||
cmd, err := p.pool.Exec(ctx, `
|
||||
DELETE FROM config_revision AS cr
|
||||
WHERE cr.tenant_id = $1
|
||||
AND cr.created_at < $2
|
||||
AND cr.id <> (
|
||||
SELECT id
|
||||
FROM config_revision
|
||||
WHERE tenant_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM bgp_speaker AS sp
|
||||
WHERE sp.tenant_id = $1
|
||||
AND (sp.last_applied_revision_id = cr.id OR sp.published_revision_id = cr.id)
|
||||
)`,
|
||||
tenantID, cutoff.UTC())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
total := 0
|
||||
const batchSize = 50
|
||||
for {
|
||||
cmd, err := p.pool.Exec(ctx, `
|
||||
DELETE FROM config_revision AS cr
|
||||
WHERE cr.id IN (
|
||||
SELECT id FROM config_revision
|
||||
WHERE tenant_id = $1
|
||||
AND created_at < $2
|
||||
AND id <> (
|
||||
SELECT id FROM config_revision
|
||||
WHERE tenant_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM bgp_speaker AS sp
|
||||
WHERE sp.tenant_id = $1
|
||||
AND (sp.last_applied_revision_id = config_revision.id OR sp.published_revision_id = config_revision.id)
|
||||
)
|
||||
ORDER BY created_at ASC
|
||||
LIMIT $3
|
||||
)`, tenantID, cutoff.UTC(), batchSize)
|
||||
if err != nil {
|
||||
return total, err
|
||||
}
|
||||
n := int(cmd.RowsAffected())
|
||||
total += n
|
||||
if n < batchSize {
|
||||
break
|
||||
}
|
||||
}
|
||||
return int(cmd.RowsAffected()), nil
|
||||
return total, nil
|
||||
}
|
||||
|
||||
func (p *Postgres) SetLastAppliedRevision(tenantID, speakerID, revisionID string) error {
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"evobgp/internal/authkey"
|
||||
"evobgp/internal/store"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (p *Postgres) ListAPIKeys(tenantID string) ([]*store.APIKey, error) {
|
||||
ctx := context.Background()
|
||||
rows, err := p.pool.Query(ctx, `
|
||||
SELECT id::text, name, role, token_prefix, created_at, updated_at, expires_at, revoked_at, last_used_at
|
||||
FROM api_key WHERE tenant_id=$1 ORDER BY created_at DESC`, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []*store.APIKey
|
||||
for rows.Next() {
|
||||
k, err := scanAPIKeyRow(rows.Scan, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, k)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (p *Postgres) GetAPIKey(tenantID, id string) (*store.APIKey, error) {
|
||||
ctx := context.Background()
|
||||
row := p.pool.QueryRow(ctx, `
|
||||
SELECT id::text, name, role, token_prefix, created_at, updated_at, expires_at, revoked_at, last_used_at
|
||||
FROM api_key WHERE id=$1 AND tenant_id=$2`, id, tenantID)
|
||||
k, err := scanAPIKeyRow(row.Scan, tenantID)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, store.ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return k, nil
|
||||
}
|
||||
|
||||
func (p *Postgres) CreateAPIKey(tenantID string, in *store.APIKeyCreate) (*store.APIKeyWithSecret, error) {
|
||||
if in == nil || strings.TrimSpace(in.Name) == "" || !store.ValidAPIKeyRole(in.Role) {
|
||||
return nil, store.ErrInvalidInput
|
||||
}
|
||||
tok, err := authkey.GenerateToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id := uuid.NewString()
|
||||
hash := authkey.HashToken(tok)
|
||||
prefix := authkey.Prefix(tok)
|
||||
role := strings.ToLower(strings.TrimSpace(in.Role))
|
||||
ctx := context.Background()
|
||||
_, err = p.pool.Exec(ctx, `
|
||||
INSERT INTO api_key (id, tenant_id, name, role, token_prefix, token_hash, expires_at)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7)`,
|
||||
id, tenantID, strings.TrimSpace(in.Name), role, prefix, hash, in.ExpiresAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
k, err := p.GetAPIKey(tenantID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &store.APIKeyWithSecret{APIKey: *k, Token: tok}, nil
|
||||
}
|
||||
|
||||
func (p *Postgres) UpdateAPIKey(tenantID, id string, patch *store.APIKeyPatch) (*store.APIKey, error) {
|
||||
cur, err := p.GetAPIKey(tenantID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cur.RevokedAt != nil {
|
||||
return nil, store.ErrInvalidInput
|
||||
}
|
||||
if patch == nil {
|
||||
return nil, store.ErrInvalidInput
|
||||
}
|
||||
if patch.Name != nil {
|
||||
n := strings.TrimSpace(*patch.Name)
|
||||
if n == "" {
|
||||
return nil, store.ErrInvalidInput
|
||||
}
|
||||
cur.Name = n
|
||||
}
|
||||
if patch.Role != nil {
|
||||
if !store.ValidAPIKeyRole(*patch.Role) {
|
||||
return nil, store.ErrInvalidInput
|
||||
}
|
||||
cur.Role = strings.ToLower(strings.TrimSpace(*patch.Role))
|
||||
}
|
||||
if patch.ClearExpiresAt {
|
||||
cur.ExpiresAt = nil
|
||||
} else if patch.ExpiresAt != nil {
|
||||
cur.ExpiresAt = patch.ExpiresAt
|
||||
}
|
||||
ctx := context.Background()
|
||||
_, err = p.pool.Exec(ctx, `
|
||||
UPDATE api_key SET name=$3, role=$4, expires_at=$5, updated_at=now()
|
||||
WHERE id=$1 AND tenant_id=$2 AND revoked_at IS NULL`,
|
||||
id, tenantID, cur.Name, cur.Role, cur.ExpiresAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p.GetAPIKey(tenantID, id)
|
||||
}
|
||||
|
||||
func (p *Postgres) RevokeAPIKey(tenantID, id string) error {
|
||||
ctx := context.Background()
|
||||
tag, err := p.pool.Exec(ctx, `
|
||||
UPDATE api_key SET revoked_at=now(), updated_at=now()
|
||||
WHERE id=$1 AND tenant_id=$2 AND revoked_at IS NULL`, id, tenantID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return store.ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Postgres) RotateAPIKey(tenantID, id string) (*store.APIKeyWithSecret, error) {
|
||||
cur, err := p.GetAPIKey(tenantID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cur.RevokedAt != nil {
|
||||
return nil, store.ErrInvalidInput
|
||||
}
|
||||
tok, err := authkey.GenerateToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hash := authkey.HashToken(tok)
|
||||
prefix := authkey.Prefix(tok)
|
||||
ctx := context.Background()
|
||||
_, err = p.pool.Exec(ctx, `
|
||||
UPDATE api_key SET token_hash=$3, token_prefix=$4, updated_at=now()
|
||||
WHERE id=$1 AND tenant_id=$2 AND revoked_at IS NULL`,
|
||||
id, tenantID, hash, prefix)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
k, err := p.GetAPIKey(tenantID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &store.APIKeyWithSecret{APIKey: *k, Token: tok}, nil
|
||||
}
|
||||
|
||||
func (p *Postgres) ListActiveAPIKeyHashes() ([]store.APIKeyAuthRow, error) {
|
||||
ctx := context.Background()
|
||||
rows, err := p.pool.Query(ctx, `
|
||||
SELECT id::text, tenant_id::text, role, token_hash
|
||||
FROM api_key
|
||||
WHERE revoked_at IS NULL AND (expires_at IS NULL OR expires_at > now())`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []store.APIKeyAuthRow
|
||||
for rows.Next() {
|
||||
var row store.APIKeyAuthRow
|
||||
var hash []byte
|
||||
if err := rows.Scan(&row.ID, &row.TenantID, &row.Role, &hash); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
row.TokenHash = append([]byte(nil), hash...)
|
||||
out = append(out, row)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (p *Postgres) TouchAPIKeyLastUsed(id string) error {
|
||||
ctx := context.Background()
|
||||
_, err := p.pool.Exec(ctx, `UPDATE api_key SET last_used_at=now() WHERE id=$1`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
type scanFn func(dest ...any) error
|
||||
|
||||
func scanAPIKeyRow(scan scanFn, tenantID string) (*store.APIKey, error) {
|
||||
var k store.APIKey
|
||||
k.TenantID = tenantID
|
||||
var expires, revoked, lastUsed *time.Time
|
||||
if err := scan(&k.ID, &k.Name, &k.Role, &k.Prefix, &k.CreatedAt, &k.UpdatedAt, &expires, &revoked, &lastUsed); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
k.ExpiresAt = expires
|
||||
k.RevokedAt = revoked
|
||||
k.LastUsedAt = lastUsed
|
||||
return &k, nil
|
||||
}
|
||||
@@ -325,6 +325,38 @@ func (p *Postgres) UpdateASEntryResolveMeta(tenantID, moduleID, entryID string,
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Postgres) UpdateASEntryResolveMetaBatch(tenantID, moduleID string, updates []store.ASEntryResolveMetaUpdate, resolvedAt time.Time) error {
|
||||
if len(updates) == 0 {
|
||||
return nil
|
||||
}
|
||||
if _, err := p.GetModule(tenantID, moduleID); err != nil {
|
||||
return err
|
||||
}
|
||||
ctx := context.Background()
|
||||
batch := &pgx.Batch{}
|
||||
for _, u := range updates {
|
||||
var nameArg any
|
||||
sn := strings.TrimSpace(u.ASNName)
|
||||
if sn == "" {
|
||||
nameArg = nil
|
||||
} else {
|
||||
nameArg = sn
|
||||
}
|
||||
batch.Queue(`
|
||||
UPDATE module_as_entry SET asn_name=$3, prefix_count=$4, asn_resolved_at=$5, updated_at=now()
|
||||
WHERE id=$1 AND module_id=$2`,
|
||||
u.EntryID, moduleID, nameArg, u.PrefixCount, resolvedAt.UTC())
|
||||
}
|
||||
br := p.pool.SendBatch(ctx, batch)
|
||||
defer func() { _ = br.Close() }()
|
||||
for range updates {
|
||||
if _, err := br.Exec(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Postgres) DeleteASEntry(tenantID, moduleID, entryID string) error {
|
||||
if _, err := p.GetModule(tenantID, moduleID); err != nil {
|
||||
return err
|
||||
|
||||
@@ -10,28 +10,41 @@ func (p *Postgres) fillModuleDohFields(ctx context.Context, m *store.Module) err
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
return p.batchFillModuleDohFields(ctx, map[string]*store.Module{m.ID: m})
|
||||
}
|
||||
|
||||
func (p *Postgres) batchFillModuleDohFields(ctx context.Context, modules map[string]*store.Module) error {
|
||||
if len(modules) == 0 {
|
||||
return nil
|
||||
}
|
||||
ids := make([]string, 0, len(modules))
|
||||
for id := range modules {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
rows, err := p.pool.Query(ctx, `
|
||||
SELECT doh_profile_id::text
|
||||
SELECT module_id::text, doh_profile_id::text
|
||||
FROM module_doh_profile
|
||||
WHERE module_id = $1
|
||||
ORDER BY sort_order, doh_profile_id`, m.ID)
|
||||
WHERE module_id = ANY($1::uuid[])
|
||||
ORDER BY module_id, sort_order, doh_profile_id`, ids)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
var ids []string
|
||||
byModule := make(map[string][]string, len(modules))
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
var moduleID, profileID string
|
||||
if err := rows.Scan(&moduleID, &profileID); err != nil {
|
||||
return err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
byModule[moduleID] = append(byModule[moduleID], profileID)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
m.DohProfileIDs = store.NormalizeDohProfileIDList(ids)
|
||||
m.SyncLegacyDohProfileID()
|
||||
for id, m := range modules {
|
||||
m.DohProfileIDs = store.NormalizeDohProfileIDList(byModule[id])
|
||||
m.SyncLegacyDohProfileID()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package store
|
||||
|
||||
// ASEntryResolveMetaUpdate is one row for batch AS resolve metadata writes.
|
||||
type ASEntryResolveMetaUpdate struct {
|
||||
EntryID string
|
||||
ASNName string
|
||||
PrefixCount int64
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -18,6 +19,8 @@ type Backend interface {
|
||||
|
||||
// ListModules returns all modules for a tenant (control plane may paginate in httpapi).
|
||||
ListModules(tenantID string) []*Module
|
||||
// ListModulesPage returns one page of modules (limit capped by caller).
|
||||
ListModulesPage(tenantID, cursor string, limit int) ([]*Module, string, bool)
|
||||
GetModule(tenantID, moduleID string) (*Module, error)
|
||||
CreateModule(tenantID string, in *Module) (*Module, error)
|
||||
UpdateModule(tenantID, moduleID string, patch *ModulePatch) (*Module, error)
|
||||
@@ -34,6 +37,7 @@ type Backend interface {
|
||||
DeleteASEntry(tenantID, moduleID, entryID string) error
|
||||
// UpdateASEntryResolveMeta записывает имя AS, число объявленных префиксов и время успешного резолва (pipeline).
|
||||
UpdateASEntryResolveMeta(tenantID, moduleID, entryID string, asnName string, prefixCount int64, resolvedAt time.Time) error
|
||||
UpdateASEntryResolveMetaBatch(tenantID, moduleID string, updates []ASEntryResolveMetaUpdate, resolvedAt time.Time) error
|
||||
|
||||
ListDomainEntries(tenantID, moduleID string) ([]*DomainEntry, error)
|
||||
CreateDomainEntry(tenantID, moduleID string, in *DomainEntry) (*DomainEntry, error)
|
||||
@@ -85,6 +89,15 @@ type Backend interface {
|
||||
ListGlobalSettings(tenantID string) (map[string]any, error)
|
||||
PatchGlobalSettings(tenantID string, patch map[string]any) error
|
||||
|
||||
ListAPIKeys(tenantID string) ([]*APIKey, error)
|
||||
GetAPIKey(tenantID, id string) (*APIKey, error)
|
||||
CreateAPIKey(tenantID string, in *APIKeyCreate) (*APIKeyWithSecret, error)
|
||||
UpdateAPIKey(tenantID, id string, patch *APIKeyPatch) (*APIKey, error)
|
||||
RevokeAPIKey(tenantID, id string) error
|
||||
RotateAPIKey(tenantID, id string) (*APIKeyWithSecret, error)
|
||||
ListActiveAPIKeyHashes() ([]APIKeyAuthRow, error)
|
||||
TouchAPIKeyLastUsed(id string) error
|
||||
|
||||
// Module prefix snapshots cache last successful collect per module (pipeline ingest/render).
|
||||
GetModulePrefixSnapshot(tenantID, moduleID string) (*ModulePrefixSnapshot, bool, error)
|
||||
SetModulePrefixSnapshot(tenantID, moduleID, inputHash string, prefixes []PrefixRow) error
|
||||
@@ -224,6 +237,59 @@ type CommunityPatch struct {
|
||||
ValueJSON *string `json:"value_json,omitempty"`
|
||||
}
|
||||
|
||||
// APIKey is tenant-scoped API key metadata (secret never stored in plaintext).
|
||||
type APIKey struct {
|
||||
ID string `json:"id"`
|
||||
TenantID string `json:"tenant_id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Role string `json:"role"`
|
||||
Prefix string `json:"prefix"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||
RevokedAt *time.Time `json:"revoked_at,omitempty"`
|
||||
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
||||
}
|
||||
|
||||
// APIKeyCreate is input for issuing a new key.
|
||||
type APIKeyCreate struct {
|
||||
Name string `json:"name"`
|
||||
Role string `json:"role"`
|
||||
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||
}
|
||||
|
||||
// APIKeyPatch is a partial update (role change affects auth after resolver reload).
|
||||
type APIKeyPatch struct {
|
||||
Name *string `json:"name,omitempty"`
|
||||
Role *string `json:"role,omitempty"`
|
||||
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||
ClearExpiresAt bool `json:"-"`
|
||||
}
|
||||
|
||||
// APIKeyWithSecret is returned only on create/rotate.
|
||||
type APIKeyWithSecret struct {
|
||||
APIKey
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// APIKeyAuthRow is used to build the in-process auth index.
|
||||
type APIKeyAuthRow struct {
|
||||
ID string
|
||||
TenantID string
|
||||
Role string
|
||||
TokenHash []byte
|
||||
}
|
||||
|
||||
// ValidAPIKeyRole reports whether role is allowed for API keys.
|
||||
func ValidAPIKeyRole(role string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(role)) {
|
||||
case "viewer", "editor", "operator", "node":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
type PeerPatch struct {
|
||||
Neighbor *string `json:"neighbor,omitempty"`
|
||||
RemoteASN *int64 `json:"remote_asn,omitempty"`
|
||||
|
||||
@@ -43,6 +43,7 @@ type Memory struct {
|
||||
revPrefixes map[string][]PrefixRow
|
||||
moduleSnapshots map[string]*moduleSnapshotRec
|
||||
asnPrefixCache map[int64]*ASNPrefixCacheEntry
|
||||
apiKeys map[string]*apiKeyRec
|
||||
|
||||
// DemoIDs valid after SeedDemo()
|
||||
demoTenantID string
|
||||
@@ -57,6 +58,11 @@ type publishedInfo struct {
|
||||
PublishedAt time.Time
|
||||
}
|
||||
|
||||
type apiKeyRec struct {
|
||||
APIKey
|
||||
TokenHash []byte
|
||||
}
|
||||
|
||||
type Tenant struct {
|
||||
ID string
|
||||
Name string
|
||||
@@ -133,6 +139,7 @@ func NewMemory() *Memory {
|
||||
revPrefixes: make(map[string][]PrefixRow),
|
||||
moduleSnapshots: make(map[string]*moduleSnapshotRec),
|
||||
asnPrefixCache: make(map[int64]*ASNPrefixCacheEntry),
|
||||
apiKeys: make(map[string]*apiKeyRec),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -382,6 +389,11 @@ func (m *Memory) ListModules(tenantID string) []*Module {
|
||||
return out
|
||||
}
|
||||
|
||||
func (m *Memory) ListModulesPage(tenantID, cursor string, limit int) ([]*Module, string, bool) {
|
||||
all := m.ListModules(tenantID)
|
||||
return PaginateOffset(all, cursor, limit)
|
||||
}
|
||||
|
||||
// ListPeers returns BGP peers for a tenant (sorted by name).
|
||||
func (m *Memory) ListPeers(tenantID string) []*BGPPeer {
|
||||
m.mu.RLock()
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"evobgp/internal/authkey"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func (m *Memory) ListAPIKeys(tenantID string) ([]*APIKey, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
var out []*APIKey
|
||||
for _, rec := range m.apiKeys {
|
||||
if rec.TenantID == tenantID {
|
||||
out = append(out, apiKeyCopy(&rec.APIKey))
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m *Memory) GetAPIKey(tenantID, id string) (*APIKey, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
rec, ok := m.apiKeys[id]
|
||||
if !ok || rec.TenantID != tenantID {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return apiKeyCopy(&rec.APIKey), nil
|
||||
}
|
||||
|
||||
func (m *Memory) CreateAPIKey(tenantID string, in *APIKeyCreate) (*APIKeyWithSecret, error) {
|
||||
if in == nil || strings.TrimSpace(in.Name) == "" || !ValidAPIKeyRole(in.Role) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
tok, err := authkey.GenerateToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if _, ok := m.tenants[tenantID]; !ok {
|
||||
return nil, ErrTenantScope
|
||||
}
|
||||
id := uuid.NewString()
|
||||
k := &apiKeyRec{
|
||||
APIKey: APIKey{
|
||||
ID: id,
|
||||
TenantID: tenantID,
|
||||
Name: strings.TrimSpace(in.Name),
|
||||
Role: strings.ToLower(strings.TrimSpace(in.Role)),
|
||||
Prefix: authkey.Prefix(tok),
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
ExpiresAt: in.ExpiresAt,
|
||||
},
|
||||
TokenHash: authkey.HashToken(tok),
|
||||
}
|
||||
m.apiKeys[id] = k
|
||||
return &APIKeyWithSecret{APIKey: *apiKeyCopy(&k.APIKey), Token: tok}, nil
|
||||
}
|
||||
|
||||
func (m *Memory) UpdateAPIKey(tenantID, id string, patch *APIKeyPatch) (*APIKey, error) {
|
||||
if patch == nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
rec, ok := m.apiKeys[id]
|
||||
if !ok || rec.TenantID != tenantID {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if rec.RevokedAt != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if patch.Name != nil {
|
||||
n := strings.TrimSpace(*patch.Name)
|
||||
if n == "" {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
rec.Name = n
|
||||
}
|
||||
if patch.Role != nil {
|
||||
if !ValidAPIKeyRole(*patch.Role) {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
rec.Role = strings.ToLower(strings.TrimSpace(*patch.Role))
|
||||
}
|
||||
if patch.ClearExpiresAt {
|
||||
rec.ExpiresAt = nil
|
||||
} else if patch.ExpiresAt != nil {
|
||||
rec.ExpiresAt = patch.ExpiresAt
|
||||
}
|
||||
rec.UpdatedAt = time.Now().UTC()
|
||||
return apiKeyCopy(&rec.APIKey), nil
|
||||
}
|
||||
|
||||
func (m *Memory) RevokeAPIKey(tenantID, id string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
rec, ok := m.apiKeys[id]
|
||||
if !ok || rec.TenantID != tenantID {
|
||||
return ErrNotFound
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
rec.RevokedAt = &now
|
||||
rec.UpdatedAt = now
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) RotateAPIKey(tenantID, id string) (*APIKeyWithSecret, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
rec, ok := m.apiKeys[id]
|
||||
if !ok || rec.TenantID != tenantID {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if rec.RevokedAt != nil {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
tok, err := authkey.GenerateToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
rec.TokenHash = authkey.HashToken(tok)
|
||||
rec.Prefix = authkey.Prefix(tok)
|
||||
rec.UpdatedAt = now
|
||||
return &APIKeyWithSecret{APIKey: *apiKeyCopy(&rec.APIKey), Token: tok}, nil
|
||||
}
|
||||
|
||||
func (m *Memory) ListActiveAPIKeyHashes() ([]APIKeyAuthRow, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
now := time.Now().UTC()
|
||||
var out []APIKeyAuthRow
|
||||
for _, rec := range m.apiKeys {
|
||||
if rec.RevokedAt != nil {
|
||||
continue
|
||||
}
|
||||
if rec.ExpiresAt != nil && !rec.ExpiresAt.After(now) {
|
||||
continue
|
||||
}
|
||||
out = append(out, APIKeyAuthRow{
|
||||
ID: rec.ID,
|
||||
TenantID: rec.TenantID,
|
||||
Role: rec.Role,
|
||||
TokenHash: append([]byte(nil), rec.TokenHash...),
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m *Memory) TouchAPIKeyLastUsed(id string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
rec, ok := m.apiKeys[id]
|
||||
if !ok {
|
||||
return ErrNotFound
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
rec.LastUsedAt = &now
|
||||
return nil
|
||||
}
|
||||
|
||||
func apiKeyCopy(k *APIKey) *APIKey {
|
||||
cp := *k
|
||||
if k.ExpiresAt != nil {
|
||||
t := *k.ExpiresAt
|
||||
cp.ExpiresAt = &t
|
||||
}
|
||||
if k.RevokedAt != nil {
|
||||
t := *k.RevokedAt
|
||||
cp.RevokedAt = &t
|
||||
}
|
||||
if k.LastUsedAt != nil {
|
||||
t := *k.LastUsedAt
|
||||
cp.LastUsedAt = &t
|
||||
}
|
||||
return &cp
|
||||
}
|
||||
@@ -301,6 +301,15 @@ func (m *Memory) UpdateASEntryResolveMeta(tenantID, moduleID, entryID string, as
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) UpdateASEntryResolveMetaBatch(tenantID, moduleID string, updates []ASEntryResolveMetaUpdate, resolvedAt time.Time) error {
|
||||
for _, u := range updates {
|
||||
if err := m.UpdateASEntryResolveMeta(tenantID, moduleID, u.EntryID, u.ASNName, u.PrefixCount, resolvedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) DeleteASEntry(tenantID, moduleID, entryID string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
DROP INDEX IF EXISTS idx_rev_mat_prefix_rev_id;
|
||||
DROP INDEX IF EXISTS idx_config_revision_tenant_module_created;
|
||||
DROP INDEX IF EXISTS idx_bgp_speaker_published;
|
||||
DROP INDEX IF EXISTS idx_bgp_speaker_last_applied;
|
||||
DROP INDEX IF EXISTS idx_module_default_community;
|
||||
DROP INDEX IF EXISTS idx_module_doh_profile_id;
|
||||
@@ -0,0 +1,17 @@
|
||||
CREATE INDEX IF NOT EXISTS idx_module_doh_profile_id
|
||||
ON module (doh_profile_id) WHERE deleted_at IS NULL AND doh_profile_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_module_default_community
|
||||
ON module (default_community_id) WHERE deleted_at IS NULL AND default_community_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_bgp_speaker_last_applied
|
||||
ON bgp_speaker (last_applied_revision_id) WHERE last_applied_revision_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_bgp_speaker_published
|
||||
ON bgp_speaker (published_revision_id) WHERE published_revision_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_config_revision_tenant_module_created
|
||||
ON config_revision (tenant_id, module_id, created_at DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_rev_mat_prefix_rev_id
|
||||
ON revision_materialized_prefix (revision_id, id);
|
||||
@@ -0,0 +1,3 @@
|
||||
DROP INDEX IF EXISTS idx_api_key_tenant_active;
|
||||
DROP INDEX IF EXISTS idx_api_key_token_hash;
|
||||
DROP TABLE IF EXISTS api_key;
|
||||
@@ -0,0 +1,19 @@
|
||||
CREATE TABLE api_key (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id UUID NOT NULL REFERENCES tenant (id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
role TEXT NOT NULL,
|
||||
token_prefix TEXT NOT NULL,
|
||||
token_hash BYTEA NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
expires_at TIMESTAMPTZ,
|
||||
revoked_at TIMESTAMPTZ,
|
||||
last_used_at TIMESTAMPTZ,
|
||||
CONSTRAINT api_key_role_chk CHECK (role IN ('viewer', 'editor', 'operator', 'node')),
|
||||
CONSTRAINT api_key_name_chk CHECK (length(trim(name)) > 0),
|
||||
CONSTRAINT api_key_token_hash_len_chk CHECK (octet_length(token_hash) = 32)
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX idx_api_key_token_hash ON api_key (token_hash);
|
||||
CREATE INDEX idx_api_key_tenant_active ON api_key (tenant_id) WHERE revoked_at IS NULL;
|
||||
@@ -0,0 +1,6 @@
|
||||
DROP INDEX IF EXISTS idx_rev_mat_prefix_rev_id;
|
||||
DROP INDEX IF EXISTS idx_config_revision_tenant_module_created;
|
||||
DROP INDEX IF EXISTS idx_bgp_speaker_published;
|
||||
DROP INDEX IF EXISTS idx_bgp_speaker_last_applied;
|
||||
DROP INDEX IF EXISTS idx_module_default_community;
|
||||
DROP INDEX IF EXISTS idx_module_doh_profile_id;
|
||||
@@ -0,0 +1,17 @@
|
||||
CREATE INDEX IF NOT EXISTS idx_module_doh_profile_id
|
||||
ON module (doh_profile_id) WHERE deleted_at IS NULL AND doh_profile_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_module_default_community
|
||||
ON module (default_community_id) WHERE deleted_at IS NULL AND default_community_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_bgp_speaker_last_applied
|
||||
ON bgp_speaker (last_applied_revision_id) WHERE last_applied_revision_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_bgp_speaker_published
|
||||
ON bgp_speaker (published_revision_id) WHERE published_revision_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_config_revision_tenant_module_created
|
||||
ON config_revision (tenant_id, module_id, created_at DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_rev_mat_prefix_rev_id
|
||||
ON revision_materialized_prefix (revision_id, id);
|
||||
@@ -0,0 +1,3 @@
|
||||
DROP INDEX IF EXISTS idx_api_key_tenant_active;
|
||||
DROP INDEX IF EXISTS idx_api_key_token_hash;
|
||||
DROP TABLE IF EXISTS api_key;
|
||||
@@ -0,0 +1,19 @@
|
||||
CREATE TABLE api_key (
|
||||
id TEXT PRIMARY KEY,
|
||||
tenant_id TEXT NOT NULL REFERENCES tenant (id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
role TEXT NOT NULL,
|
||||
token_prefix TEXT NOT NULL,
|
||||
token_hash BLOB NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
||||
expires_at TEXT,
|
||||
revoked_at TEXT,
|
||||
last_used_at TEXT,
|
||||
CHECK (role IN ('viewer', 'editor', 'operator', 'node')),
|
||||
CHECK (length(trim(name)) > 0),
|
||||
CHECK (length(token_hash) = 32)
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX idx_api_key_token_hash ON api_key (token_hash);
|
||||
CREATE INDEX idx_api_key_tenant_active ON api_key (tenant_id) WHERE revoked_at IS NULL;
|
||||
@@ -253,3 +253,33 @@ export type JobsResponse = Page<JobRow>;
|
||||
|
||||
// ---- Settings ----
|
||||
export type AppSettings = Record<string, unknown>;
|
||||
|
||||
// ---- Auth / API keys ----
|
||||
export type AuthSession = {
|
||||
tenant_id: string;
|
||||
role: 'viewer' | 'editor' | 'operator' | 'node';
|
||||
};
|
||||
|
||||
export type ApiKeyRole = AuthSession['role'];
|
||||
|
||||
export type ApiKey = {
|
||||
id: string;
|
||||
name: string;
|
||||
role: ApiKeyRole;
|
||||
prefix: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
expires_at: string | null;
|
||||
revoked_at: string | null;
|
||||
last_used_at: string | null;
|
||||
};
|
||||
|
||||
export type ApiKeysResponse = Page<ApiKey>;
|
||||
|
||||
export type ApiKeyCreate = {
|
||||
name: string;
|
||||
role: ApiKeyRole;
|
||||
expires_at?: string | null;
|
||||
};
|
||||
|
||||
export type ApiKeyCreated = ApiKey & { token: string };
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
<script lang="ts">
|
||||
import { apiMutate } from '$lib/api/client.js';
|
||||
import type { ApiKey, ApiKeyCreate, ApiKeyCreated, ApiKeyRole } from '$lib/api/types.js';
|
||||
import { Button } from '$lib/ui/core/button/index.js';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle
|
||||
} from '$lib/ui/core/card/index.js';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '$lib/ui/core/dialog/index.js';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger } from '$lib/ui/core/select/index.js';
|
||||
import FormField from '$lib/ui/patterns/form/form-field.svelte';
|
||||
import AppInput from '$lib/ui/patterns/form/app-input.svelte';
|
||||
import AppDataTable from '$lib/ui/patterns/data-table/app-data-table.svelte';
|
||||
import { confirm } from '$lib/ui/patterns/confirm/confirm-state.svelte.js';
|
||||
import { notify, notifyApiError } from '$lib/ui/app/toast.js';
|
||||
import Plus from '@lucide/svelte/icons/plus';
|
||||
import Trash2 from '@lucide/svelte/icons/trash-2';
|
||||
import RefreshCw from '@lucide/svelte/icons/refresh-cw';
|
||||
import Copy from '@lucide/svelte/icons/copy';
|
||||
|
||||
type Props = {
|
||||
items: ApiKey[];
|
||||
loading?: boolean;
|
||||
initialLoading?: boolean;
|
||||
error?: string | null;
|
||||
onRefresh: () => void | Promise<void>;
|
||||
};
|
||||
|
||||
let { items, loading = false, initialLoading = false, error = null, onRefresh }: Props = $props();
|
||||
|
||||
const roleOptions: Array<{ value: ApiKeyRole; label: string }> = [
|
||||
{ value: 'viewer', label: 'viewer — только чтение' },
|
||||
{ value: 'editor', label: 'editor — CRUD без apply' },
|
||||
{ value: 'operator', label: 'operator — полный доступ' },
|
||||
{ value: 'node', label: 'node — только API ноды' }
|
||||
];
|
||||
|
||||
let dialogOpen = $state(false);
|
||||
let tokenDialogOpen = $state(false);
|
||||
let revealedToken = $state('');
|
||||
let form = $state<ApiKeyCreate>({ name: '', role: 'editor' });
|
||||
let expiresLocal = $state('');
|
||||
let saving = $state(false);
|
||||
|
||||
const columns = [
|
||||
{ id: 'name', label: 'Имя', sortable: true, sortValue: (k: ApiKey) => k.name },
|
||||
{ id: 'role', label: 'Роль', sortable: true, sortValue: (k: ApiKey) => k.role },
|
||||
{ id: 'prefix', label: 'Префикс', sortable: true, sortValue: (k: ApiKey) => k.prefix },
|
||||
{
|
||||
id: 'revoked',
|
||||
label: 'Статус',
|
||||
sortable: true,
|
||||
sortValue: (k: ApiKey) => (k.revoked_at ? 1 : 0)
|
||||
},
|
||||
{ id: 'actions', label: '', class: 'w-24' }
|
||||
] as const;
|
||||
|
||||
function openCreate() {
|
||||
form = { name: '', role: 'editor' };
|
||||
expiresLocal = '';
|
||||
dialogOpen = true;
|
||||
}
|
||||
|
||||
function showToken(created: ApiKeyCreated) {
|
||||
revealedToken = created.token;
|
||||
tokenDialogOpen = true;
|
||||
}
|
||||
|
||||
async function copyToken() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(revealedToken);
|
||||
notify.success('Скопировано');
|
||||
} catch {
|
||||
notify.error('Не удалось скопировать');
|
||||
}
|
||||
}
|
||||
|
||||
function requestRevoke(k: ApiKey) {
|
||||
if (k.revoked_at) return;
|
||||
void confirm({
|
||||
title: 'Отозвать API-ключ?',
|
||||
description: `${k.name} (${k.prefix}…)`,
|
||||
confirmLabel: 'Отозвать',
|
||||
destructive: true,
|
||||
onConfirm: async () => {
|
||||
await apiMutate(`/v1/api-keys/${k.id}`, 'DELETE', undefined, { idempotent: false });
|
||||
notify.success('Ключ отозван');
|
||||
await onRefresh();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function requestRotate(k: ApiKey) {
|
||||
if (k.revoked_at) return;
|
||||
void confirm({
|
||||
title: 'Ротировать ключ?',
|
||||
description: 'Старый токен перестанет работать сразу.',
|
||||
confirmLabel: 'Ротировать',
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
const out = await apiMutate<ApiKeyCreated>(
|
||||
`/v1/api-keys/${k.id}/rotate`,
|
||||
'POST',
|
||||
undefined,
|
||||
{ idempotent: false }
|
||||
);
|
||||
notify.success('Ключ обновлён');
|
||||
showToken(out);
|
||||
await onRefresh();
|
||||
} catch (e) {
|
||||
notifyApiError(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!form.name.trim()) {
|
||||
notify.error('Укажите имя');
|
||||
return;
|
||||
}
|
||||
saving = true;
|
||||
try {
|
||||
const body: ApiKeyCreate = {
|
||||
name: form.name.trim(),
|
||||
role: form.role
|
||||
};
|
||||
if (expiresLocal.trim()) {
|
||||
const d = new Date(expiresLocal);
|
||||
if (Number.isNaN(d.getTime())) {
|
||||
notify.error('Некорректная дата истечения');
|
||||
return;
|
||||
}
|
||||
body.expires_at = d.toISOString();
|
||||
}
|
||||
const created = await apiMutate<ApiKeyCreated>('/v1/api-keys', 'POST', body);
|
||||
notify.success('Ключ создан');
|
||||
dialogOpen = false;
|
||||
showToken(created);
|
||||
await onRefresh();
|
||||
} catch (e) {
|
||||
notifyApiError(e);
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<Card>
|
||||
<CardHeader
|
||||
class="flex flex-col gap-3 border-b py-3 sm:flex-row sm:items-center sm:justify-between"
|
||||
>
|
||||
<div class="min-w-0 flex-1">
|
||||
<CardTitle class="text-base">API-ключи</CardTitle>
|
||||
<CardDescription>
|
||||
Управление ключами tenant. Полный токен показывается только при создании и ротации.
|
||||
</CardDescription>
|
||||
</div>
|
||||
<div class="flex shrink-0 flex-wrap items-center justify-end gap-2">
|
||||
<Button size="sm" variant="outline" onclick={() => onRefresh()} disabled={loading}>
|
||||
<RefreshCw class={loading ? 'animate-spin' : ''} />
|
||||
Обновить
|
||||
</Button>
|
||||
<Button size="sm" onclick={openCreate}><Plus />Создать</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent class="p-4 pt-0">
|
||||
<AppDataTable
|
||||
columns={[...columns]}
|
||||
rows={items}
|
||||
rowKey={(k) => k.id}
|
||||
loading={initialLoading || loading}
|
||||
{error}
|
||||
emptyTitle="Нет ключей"
|
||||
emptyDescription="Создайте API-ключ для автоматизации или отдельного доступа."
|
||||
>
|
||||
{#snippet cell({ row: k, column })}
|
||||
{#if column.id === 'name'}
|
||||
<span class="font-medium">{k.name}</span>
|
||||
{:else if column.id === 'role'}
|
||||
<span class="font-mono text-sm">{k.role}</span>
|
||||
{:else if column.id === 'prefix'}
|
||||
<span class="font-mono text-xs text-muted-foreground">{k.prefix}…</span>
|
||||
{:else if column.id === 'revoked'}
|
||||
{#if k.revoked_at}
|
||||
<span class="text-sm text-destructive">отозван</span>
|
||||
{:else}
|
||||
<span class="text-sm text-muted-foreground">активен</span>
|
||||
{/if}
|
||||
{:else if column.id === 'actions'}
|
||||
<div class="flex gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="Ротировать"
|
||||
disabled={!!k.revoked_at}
|
||||
onclick={() => requestRotate(k)}
|
||||
>
|
||||
<RefreshCw class="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="text-destructive"
|
||||
disabled={!!k.revoked_at}
|
||||
onclick={() => requestRevoke(k)}
|
||||
>
|
||||
<Trash2 class="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
{/snippet}
|
||||
</AppDataTable>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog bind:open={dialogOpen}>
|
||||
<DialogContent class="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Новый API-ключ</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div class="flex flex-col gap-4 py-2">
|
||||
<FormField label="Имя" id="key-name" required>
|
||||
<AppInput id="key-name" bind:value={form.name} placeholder="CI / оператор UI" />
|
||||
</FormField>
|
||||
<FormField label="Роль" id="key-role" required>
|
||||
<Select
|
||||
type="single"
|
||||
value={form.role}
|
||||
onValueChange={(v) => (form.role = v as ApiKeyRole)}
|
||||
>
|
||||
<SelectTrigger id="key-role" class="w-full">
|
||||
{roleOptions.find((o) => o.value === form.role)?.label ?? form.role}
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{#each roleOptions as opt (opt.value)}
|
||||
<SelectItem value={opt.value} label={opt.label}>{opt.label}</SelectItem>
|
||||
{/each}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormField>
|
||||
<FormField label="Истекает (опционально)" id="key-expires">
|
||||
<AppInput id="key-expires" type="datetime-local" bind:value={expiresLocal} />
|
||||
</FormField>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onclick={() => (dialogOpen = false)}>Отмена</Button>
|
||||
<Button onclick={save} disabled={saving}>
|
||||
{saving ? 'Создание…' : 'Создать'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog bind:open={tokenDialogOpen}>
|
||||
<DialogContent class="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Сохраните токен</DialogTitle>
|
||||
<DialogDescription
|
||||
>Он больше не будет показан. Скопируйте в безопасное хранилище.</DialogDescription
|
||||
>
|
||||
</DialogHeader>
|
||||
<div class="rounded-md border bg-muted/40 p-3 font-mono text-xs break-all">{revealedToken}</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onclick={copyToken}><Copy />Копировать</Button>
|
||||
<Button onclick={() => (tokenDialogOpen = false)}>Готово</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
@@ -0,0 +1,212 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { defaults, superForm } from 'sveltekit-superforms';
|
||||
import { zod4 } from 'sveltekit-superforms/adapters';
|
||||
import {
|
||||
birdSettingsSchema,
|
||||
emptyBirdSettingsForm,
|
||||
type BirdSettingsForm
|
||||
} from '$lib/settings/bird-settings.schema.js';
|
||||
import {
|
||||
buildPayloadFromFormFields,
|
||||
loadSettings,
|
||||
partitionSettings,
|
||||
patchSettings
|
||||
} from '$lib/settings/settings-api.js';
|
||||
import { BIRD_SETTING_KEYS } from '$lib/settings/settings-known-keys.js';
|
||||
import { Button } from '$lib/ui/core/button/index.js';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle
|
||||
} from '$lib/ui/core/card/index.js';
|
||||
import { Input } from '$lib/ui/core/input/index.js';
|
||||
import { Alert, AlertDescription, AlertTitle } from '$lib/ui/core/alert/index.js';
|
||||
import FormField from '$lib/ui/patterns/form/form-field.svelte';
|
||||
import { notify, notifyApiError } from '$lib/ui/app/toast.js';
|
||||
import Save from '@lucide/svelte/icons/save';
|
||||
import Info from '@lucide/svelte/icons/info';
|
||||
|
||||
let loading = $state(false);
|
||||
let saving = $state(false);
|
||||
let loaded = $state(false);
|
||||
|
||||
const { form, errors, reset, validateForm } = superForm(
|
||||
defaults(emptyBirdSettingsForm(), zod4(birdSettingsSchema)),
|
||||
{
|
||||
validators: zod4(birdSettingsSchema),
|
||||
SPA: true,
|
||||
dataType: 'json'
|
||||
}
|
||||
);
|
||||
|
||||
let hasValidationErrors = $derived(
|
||||
BIRD_SETTING_KEYS.some((key) => Boolean($errors[key as keyof BirdSettingsForm]?.length))
|
||||
);
|
||||
|
||||
let canSave = $derived.by(() => {
|
||||
if (loading || saving || hasValidationErrors || !loaded) return false;
|
||||
return BIRD_SETTING_KEYS.some((key) => {
|
||||
const value = String($form[key as keyof BirdSettingsForm] ?? '').trim();
|
||||
return value !== '' && !$errors[key as keyof BirdSettingsForm]?.length;
|
||||
});
|
||||
});
|
||||
|
||||
async function load() {
|
||||
loading = true;
|
||||
try {
|
||||
const settings = await loadSettings();
|
||||
const { partitioned } = partitionSettings(settings);
|
||||
reset({ data: partitioned.bird });
|
||||
loaded = true;
|
||||
} catch (e) {
|
||||
notifyApiError(e);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
const validation = await validateForm({ update: true });
|
||||
if (!validation.valid) {
|
||||
notify.error('Исправьте ошибки в полях настроек');
|
||||
return;
|
||||
}
|
||||
if (!canSave) {
|
||||
notify.error('Нечего сохранять или есть ошибки в полях');
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = buildPayloadFromFormFields(
|
||||
BIRD_SETTING_KEYS,
|
||||
$form as Record<string, string>,
|
||||
$errors as Partial<Record<string, string[]>>
|
||||
);
|
||||
|
||||
saving = true;
|
||||
try {
|
||||
await patchSettings(payload);
|
||||
notify.success('Параметры BIRD сохранены');
|
||||
await load();
|
||||
} catch (e) {
|
||||
notifyApiError(e);
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
void load();
|
||||
});
|
||||
</script>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Control plane</CardTitle>
|
||||
<CardDescription>
|
||||
Глобальные параметры BIRD для pipeline refresh/apply. Сохранение через
|
||||
<code class="text-xs">PATCH /v1/settings</code> (роль operator).
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="space-y-5">
|
||||
<Alert class="border-info/30 bg-info/5">
|
||||
<Info class="text-info" />
|
||||
<AlertTitle>Подстановка в конфиг</AlertTitle>
|
||||
<AlertDescription>
|
||||
Значения используются при генерации BIRD-конфигурации в pipeline (router id, local AS,
|
||||
адреса). Пиры и спикеры настраиваются на соседних вкладках.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
{#if loading && !loaded}
|
||||
<p class="text-sm text-muted-foreground">Загрузка…</p>
|
||||
{:else if !loaded}
|
||||
<Button variant="outline" onclick={load}>Загрузить параметры</Button>
|
||||
{:else}
|
||||
<div class="space-y-3">
|
||||
<FormField
|
||||
id="bird-router-id"
|
||||
label="Router ID (bird_router_id)"
|
||||
error={$errors.bird_router_id?.[0]}
|
||||
>
|
||||
<Input id="bird-router-id" bind:value={$form.bird_router_id} placeholder="203.0.113.1" />
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
id="bird-local-ipv4"
|
||||
label="Локальный IPv4 (bird_local_ipv4)"
|
||||
error={$errors.bird_local_ipv4?.[0]}
|
||||
>
|
||||
<Input
|
||||
id="bird-local-ipv4"
|
||||
bind:value={$form.bird_local_ipv4}
|
||||
placeholder="198.51.100.10"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
id="bird-local-ipv6"
|
||||
label="Локальный IPv6 (bird_local_ipv6)"
|
||||
error={$errors.bird_local_ipv6?.[0]}
|
||||
>
|
||||
<Input
|
||||
id="bird-local-ipv6"
|
||||
bind:value={$form.bird_local_ipv6}
|
||||
placeholder="2001:db8::10"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
id="bird-local-asn"
|
||||
label="Локальный ASN (bird_local_asn)"
|
||||
error={$errors.bird_local_asn?.[0]}
|
||||
>
|
||||
<Input
|
||||
id="bird-local-asn"
|
||||
type="number"
|
||||
min="1"
|
||||
bind:value={$form.bird_local_asn}
|
||||
placeholder="65001"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
id="bird-bgp-source-ipv4"
|
||||
label="BGP source IPv4 (bird_bgp_source_ipv4)"
|
||||
error={$errors.bird_bgp_source_ipv4?.[0]}
|
||||
>
|
||||
<Input
|
||||
id="bird-bgp-source-ipv4"
|
||||
bind:value={$form.bird_bgp_source_ipv4}
|
||||
placeholder="198.51.100.11"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
id="bird-bgp-source-ipv6"
|
||||
label="BGP source IPv6 (bird_bgp_source_ipv6)"
|
||||
error={$errors.bird_bgp_source_ipv6?.[0]}
|
||||
>
|
||||
<Input
|
||||
id="bird-bgp-source-ipv6"
|
||||
bind:value={$form.bird_bgp_source_ipv6}
|
||||
placeholder="2001:db8::11"
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
{#if hasValidationErrors}
|
||||
<p class="text-sm text-destructive">
|
||||
Есть ошибки в полях. Исправьте их, чтобы сохранить изменения.
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
<Button onclick={save} disabled={!canSave}>
|
||||
<Save />
|
||||
{saving ? 'Сохранение…' : 'Применить параметры'}
|
||||
</Button>
|
||||
{/if}
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -0,0 +1,223 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { defaults, superForm } from 'sveltekit-superforms';
|
||||
import { zod4 } from 'sveltekit-superforms/adapters';
|
||||
import {
|
||||
emptyRevisionSettingsForm,
|
||||
revisionSettingsSchema
|
||||
} from '$lib/settings/revision-settings.schema.js';
|
||||
import {
|
||||
buildPayloadFromFormFields,
|
||||
loadSettings,
|
||||
partitionSettings,
|
||||
patchSettings,
|
||||
type AdditionalSettingEntry
|
||||
} from '$lib/settings/settings-api.js';
|
||||
import { REVISION_SETTING_KEYS } from '$lib/settings/settings-known-keys.js';
|
||||
import { Button } from '$lib/ui/core/button/index.js';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle
|
||||
} from '$lib/ui/core/card/index.js';
|
||||
import { Input } from '$lib/ui/core/input/index.js';
|
||||
import { Alert, AlertDescription, AlertTitle } from '$lib/ui/core/alert/index.js';
|
||||
import FormField from '$lib/ui/patterns/form/form-field.svelte';
|
||||
import EmptyState from '$lib/ui/patterns/empty-state/empty-state.svelte';
|
||||
import { notify, notifyApiError } from '$lib/ui/app/toast.js';
|
||||
import Save from '@lucide/svelte/icons/save';
|
||||
import Plus from '@lucide/svelte/icons/plus';
|
||||
import Trash2 from '@lucide/svelte/icons/trash-2';
|
||||
import Info from '@lucide/svelte/icons/info';
|
||||
|
||||
let loading = $state(false);
|
||||
let saving = $state(false);
|
||||
let loaded = $state(false);
|
||||
let additionalSettings = $state<AdditionalSettingEntry[]>([]);
|
||||
let additionalIdCounter = $state(1);
|
||||
|
||||
const { form, errors, reset, validateForm } = superForm(
|
||||
defaults(emptyRevisionSettingsForm(), zod4(revisionSettingsSchema)),
|
||||
{
|
||||
validators: zod4(revisionSettingsSchema),
|
||||
SPA: true,
|
||||
dataType: 'json'
|
||||
}
|
||||
);
|
||||
|
||||
let hasValidationErrors = $derived(Boolean($errors.revision_retention_minutes?.length));
|
||||
|
||||
function addAdditionalSetting() {
|
||||
additionalSettings.push({ id: additionalIdCounter++, key: '', value: '' });
|
||||
}
|
||||
|
||||
function removeAdditionalSetting(id: number) {
|
||||
additionalSettings = additionalSettings.filter((entry) => entry.id !== id);
|
||||
}
|
||||
|
||||
let canSave = $derived.by(() => {
|
||||
if (loading || saving || hasValidationErrors || !loaded) return false;
|
||||
|
||||
const hasRetention = String($form.revision_retention_minutes ?? '').trim() !== '';
|
||||
const hasAdditional = additionalSettings.some((entry) => entry.key.trim() !== '');
|
||||
|
||||
return hasRetention || hasAdditional;
|
||||
});
|
||||
|
||||
async function load() {
|
||||
loading = true;
|
||||
try {
|
||||
const settings = await loadSettings();
|
||||
const { partitioned, nextId } = partitionSettings(settings, additionalIdCounter);
|
||||
reset({ data: partitioned.revision });
|
||||
additionalSettings = partitioned.additional;
|
||||
additionalIdCounter = nextId;
|
||||
loaded = true;
|
||||
} catch (e) {
|
||||
notifyApiError(e);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
const validation = await validateForm({ update: true });
|
||||
if (!validation.valid) {
|
||||
notify.error('Исправьте ошибки в полях настроек');
|
||||
return;
|
||||
}
|
||||
if (!canSave) {
|
||||
notify.error('Нечего сохранять или есть ошибки в полях');
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = buildPayloadFromFormFields(
|
||||
REVISION_SETTING_KEYS,
|
||||
$form as Record<string, string>,
|
||||
$errors as Partial<Record<string, string[]>>
|
||||
);
|
||||
|
||||
for (const entry of additionalSettings) {
|
||||
const key = entry.key.trim();
|
||||
if (!key) continue;
|
||||
payload[key] = entry.value;
|
||||
}
|
||||
|
||||
saving = true;
|
||||
try {
|
||||
await patchSettings(payload);
|
||||
notify.success('Системные настройки сохранены');
|
||||
await load();
|
||||
} catch (e) {
|
||||
notifyApiError(e);
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
void load();
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-6">
|
||||
<Alert class="border-info/30 bg-info/5">
|
||||
<Info class="text-info" />
|
||||
<AlertTitle>Operator-only</AlertTitle>
|
||||
<AlertDescription>
|
||||
Изменение параметров через <code class="text-xs">PATCH /v1/settings</code> требует роли operator.
|
||||
При отсутствии прав API вернёт 403.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Хранение ревизий</CardTitle>
|
||||
<CardDescription>
|
||||
Автоматическая очистка старых ревизий. Последняя раскатанная ревизия не удаляется.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{#if loading && !loaded}
|
||||
<p class="text-sm text-muted-foreground">Загрузка…</p>
|
||||
{:else if !loaded}
|
||||
<Button variant="outline" onclick={load}>Загрузить настройки</Button>
|
||||
{:else}
|
||||
<FormField
|
||||
id="revision-retention-minutes"
|
||||
label="Время жизни ревизий, мин (revision_retention_minutes)"
|
||||
error={$errors.revision_retention_minutes?.[0]}
|
||||
description="Допустимый диапазон: 15–43200 минут."
|
||||
>
|
||||
<Input
|
||||
id="revision-retention-minutes"
|
||||
type="number"
|
||||
min="15"
|
||||
max="43200"
|
||||
bind:value={$form.revision_retention_minutes}
|
||||
placeholder="43200"
|
||||
/>
|
||||
</FormField>
|
||||
{/if}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div class="space-y-1">
|
||||
<CardTitle>Дополнительные параметры</CardTitle>
|
||||
<CardDescription>Произвольные KV-пары в global_settings.</CardDescription>
|
||||
</div>
|
||||
{#if loaded}
|
||||
<Button variant="outline" size="sm" onclick={addAdditionalSetting}>
|
||||
<Plus class="size-4" />
|
||||
Добавить строку
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{#if !loaded}
|
||||
<p class="text-sm text-muted-foreground">Загрузите настройки выше.</p>
|
||||
{:else if additionalSettings.length === 0}
|
||||
<EmptyState
|
||||
title="Нет дополнительных параметров"
|
||||
description="Добавьте KV-пару при необходимости."
|
||||
/>
|
||||
{:else}
|
||||
<div class="space-y-2">
|
||||
{#each additionalSettings as entry (entry.id)}
|
||||
<div class="grid grid-cols-1 gap-2 md:grid-cols-[1fr_1fr_auto]">
|
||||
<Input bind:value={entry.key} placeholder="Ключ (например, bird_log_level)" />
|
||||
<Input bind:value={entry.value} placeholder="Значение (строка)" />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label="Удалить строку"
|
||||
onclick={() => removeAdditionalSetting(entry.id)}
|
||||
>
|
||||
<Trash2 class="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{#if loaded}
|
||||
{#if hasValidationErrors}
|
||||
<p class="text-sm text-destructive">
|
||||
Есть ошибки в полях. Исправьте их, чтобы сохранить изменения.
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
<Button onclick={save} disabled={!canSave}>
|
||||
<Save />
|
||||
{saving ? 'Сохранение…' : 'Применить настройки'}
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,24 @@
|
||||
import { z } from 'zod';
|
||||
import { optionalIPv4, optionalIPv6 } from './ip-validation.js';
|
||||
|
||||
export const birdSettingsSchema = z.object({
|
||||
bird_router_id: optionalIPv4('router id'),
|
||||
bird_local_ipv4: optionalIPv4('local IPv4'),
|
||||
bird_local_ipv6: optionalIPv6('local IPv6'),
|
||||
bird_local_asn: z.string().refine((v) => v.trim() === '' || /^[1-9]\d*$/.test(v.trim()), {
|
||||
message: 'ASN должен быть целым числом больше 0'
|
||||
}),
|
||||
bird_bgp_source_ipv4: optionalIPv4('BGP source IPv4'),
|
||||
bird_bgp_source_ipv6: optionalIPv6('BGP source IPv6')
|
||||
});
|
||||
|
||||
export type BirdSettingsForm = z.infer<typeof birdSettingsSchema>;
|
||||
|
||||
export const emptyBirdSettingsForm = (): BirdSettingsForm => ({
|
||||
bird_router_id: '',
|
||||
bird_local_ipv4: '',
|
||||
bird_local_ipv6: '',
|
||||
bird_local_asn: '',
|
||||
bird_bgp_source_ipv4: '',
|
||||
bird_bgp_source_ipv6: ''
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
function isValidIPv4(value: string): boolean {
|
||||
const parts = value.split('.');
|
||||
if (parts.length !== 4) return false;
|
||||
for (const part of parts) {
|
||||
if (!/^\d{1,3}$/.test(part)) return false;
|
||||
if (part.length > 1 && part.startsWith('0')) return false;
|
||||
const n = Number(part);
|
||||
if (!Number.isInteger(n) || n < 0 || n > 255) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function isValidIPv6(value: string): boolean {
|
||||
if (!/^[0-9A-Fa-f:.]+$/.test(value)) return false;
|
||||
if ((value.match(/::/g) ?? []).length > 1) return false;
|
||||
const hasCompression = value.includes('::');
|
||||
const [leftRaw, rightRaw = ''] = value.split('::');
|
||||
const left = leftRaw === '' ? [] : leftRaw.split(':');
|
||||
const right = rightRaw === '' ? [] : rightRaw.split(':');
|
||||
if (left.some((part) => part === '') || right.some((part) => part === '')) return false;
|
||||
let segments = [...left, ...right];
|
||||
let ipv4TailSegments = 0;
|
||||
const lastSegment = segments.at(-1);
|
||||
if (lastSegment && lastSegment.includes('.')) {
|
||||
if (!isValidIPv4(lastSegment)) return false;
|
||||
segments = segments.slice(0, -1);
|
||||
ipv4TailSegments = 2;
|
||||
}
|
||||
for (const segment of segments) {
|
||||
if (!/^[0-9A-Fa-f]{1,4}$/.test(segment)) return false;
|
||||
}
|
||||
const totalSegments = segments.length + ipv4TailSegments;
|
||||
if (hasCompression) return totalSegments < 8;
|
||||
return totalSegments === 8;
|
||||
}
|
||||
|
||||
export const optionalIPv4 = (label: string) =>
|
||||
z.string().refine((v) => v.trim() === '' || isValidIPv4(v.trim()), {
|
||||
message: `Введите корректный IPv4 адрес (${label})`
|
||||
});
|
||||
|
||||
export const optionalIPv6 = (label: string) =>
|
||||
z.string().refine((v) => v.trim() === '' || isValidIPv6(v.trim()), {
|
||||
message: `Введите корректный IPv6 адрес (${label})`
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const revisionSettingsSchema = z.object({
|
||||
revision_retention_minutes: z.string().refine(
|
||||
(v) => {
|
||||
const s = v.trim();
|
||||
if (s === '') return true;
|
||||
const ttl = Number(s);
|
||||
return /^\d+$/.test(s) && Number.isInteger(ttl) && ttl >= 15 && ttl <= 43200;
|
||||
},
|
||||
{ message: 'TTL ревизий должен быть целым числом от 15 до 43200 минут' }
|
||||
)
|
||||
});
|
||||
|
||||
export type RevisionSettingsForm = z.infer<typeof revisionSettingsSchema>;
|
||||
|
||||
export const emptyRevisionSettingsForm = (): RevisionSettingsForm => ({
|
||||
revision_retention_minutes: ''
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { apiJSON, apiMutate } from '$lib/api/client.js';
|
||||
import type { AppSettings } from '$lib/api/types.js';
|
||||
import { emptyBirdSettingsForm, type BirdSettingsForm } from './bird-settings.schema.js';
|
||||
import {
|
||||
emptyRevisionSettingsForm,
|
||||
type RevisionSettingsForm
|
||||
} from './revision-settings.schema.js';
|
||||
import {
|
||||
BIRD_SETTING_KEYS,
|
||||
KNOWN_SETTING_KEYS,
|
||||
NUMERIC_SETTING_KEYS,
|
||||
type BirdSettingKey,
|
||||
type KnownSettingKey,
|
||||
type RevisionSettingKey
|
||||
} from './settings-known-keys.js';
|
||||
|
||||
export type AdditionalSettingEntry = { id: number; key: string; value: string };
|
||||
|
||||
export type PartitionedSettings = {
|
||||
bird: BirdSettingsForm;
|
||||
revision: RevisionSettingsForm;
|
||||
additional: AdditionalSettingEntry[];
|
||||
};
|
||||
|
||||
function parseKnownValue(key: KnownSettingKey, value: unknown): string {
|
||||
if (NUMERIC_SETTING_KEYS.has(key)) {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
|
||||
if (typeof value === 'string') return value;
|
||||
return '';
|
||||
}
|
||||
if (typeof value === 'string') return value;
|
||||
return '';
|
||||
}
|
||||
|
||||
export function partitionSettings(
|
||||
settings: AppSettings,
|
||||
nextId = 1
|
||||
): { partitioned: PartitionedSettings; nextId: number } {
|
||||
const bird = emptyBirdSettingsForm();
|
||||
const revision = emptyRevisionSettingsForm();
|
||||
const additional: AdditionalSettingEntry[] = [];
|
||||
let idCounter = nextId;
|
||||
|
||||
for (const [key, value] of Object.entries(settings as Record<string, unknown>)) {
|
||||
if ((BIRD_SETTING_KEYS as readonly string[]).includes(key)) {
|
||||
bird[key as BirdSettingKey] = parseKnownValue(key as KnownSettingKey, value);
|
||||
} else if (key === 'revision_retention_minutes') {
|
||||
revision.revision_retention_minutes = parseKnownValue(key as RevisionSettingKey, value);
|
||||
} else {
|
||||
additional.push({
|
||||
id: idCounter++,
|
||||
key,
|
||||
value: typeof value === 'string' ? value : String(value)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
partitioned: { bird, revision, additional },
|
||||
nextId: idCounter
|
||||
};
|
||||
}
|
||||
|
||||
export async function loadSettings(): Promise<AppSettings> {
|
||||
return apiJSON<AppSettings>('/v1/settings');
|
||||
}
|
||||
|
||||
export async function patchSettings(payload: Record<string, string | number>): Promise<void> {
|
||||
await apiMutate('/v1/settings', 'PATCH', payload);
|
||||
}
|
||||
|
||||
export function buildPayloadFromFormFields(
|
||||
keys: readonly KnownSettingKey[],
|
||||
form: Record<string, string>,
|
||||
errors: Partial<Record<string, string[]>>
|
||||
): Record<string, string | number> {
|
||||
const payload: Record<string, string | number> = {};
|
||||
for (const key of keys) {
|
||||
const value = String(form[key] ?? '').trim();
|
||||
if (!value || errors[key]?.length) continue;
|
||||
if (NUMERIC_SETTING_KEYS.has(key)) payload[key] = Number(value);
|
||||
else payload[key] = value;
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
export function isKnownSettingKey(key: string): key is KnownSettingKey {
|
||||
return (KNOWN_SETTING_KEYS as readonly string[]).includes(key);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
export const BIRD_SETTING_KEYS = [
|
||||
'bird_router_id',
|
||||
'bird_local_ipv4',
|
||||
'bird_local_ipv6',
|
||||
'bird_local_asn',
|
||||
'bird_bgp_source_ipv4',
|
||||
'bird_bgp_source_ipv6'
|
||||
] as const;
|
||||
|
||||
export const REVISION_SETTING_KEYS = ['revision_retention_minutes'] as const;
|
||||
|
||||
export const KNOWN_SETTING_KEYS = [...BIRD_SETTING_KEYS, ...REVISION_SETTING_KEYS] as const;
|
||||
|
||||
export type BirdSettingKey = (typeof BIRD_SETTING_KEYS)[number];
|
||||
export type RevisionSettingKey = (typeof REVISION_SETTING_KEYS)[number];
|
||||
export type KnownSettingKey = (typeof KNOWN_SETTING_KEYS)[number];
|
||||
|
||||
export const NUMERIC_SETTING_KEYS = new Set<KnownSettingKey>([
|
||||
'bird_local_asn',
|
||||
'revision_retention_minutes'
|
||||
]);
|
||||
@@ -1,79 +1,15 @@
|
||||
import { z } from 'zod';
|
||||
import { birdSettingsSchema, emptyBirdSettingsForm } from './bird-settings.schema.js';
|
||||
import { emptyRevisionSettingsForm, revisionSettingsSchema } from './revision-settings.schema.js';
|
||||
|
||||
function isValidIPv4(value: string): boolean {
|
||||
const parts = value.split('.');
|
||||
if (parts.length !== 4) return false;
|
||||
for (const part of parts) {
|
||||
if (!/^\d{1,3}$/.test(part)) return false;
|
||||
if (part.length > 1 && part.startsWith('0')) return false;
|
||||
const n = Number(part);
|
||||
if (!Number.isInteger(n) || n < 0 || n > 255) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function isValidIPv6(value: string): boolean {
|
||||
if (!/^[0-9A-Fa-f:.]+$/.test(value)) return false;
|
||||
if ((value.match(/::/g) ?? []).length > 1) return false;
|
||||
const hasCompression = value.includes('::');
|
||||
const [leftRaw, rightRaw = ''] = value.split('::');
|
||||
const left = leftRaw === '' ? [] : leftRaw.split(':');
|
||||
const right = rightRaw === '' ? [] : rightRaw.split(':');
|
||||
if (left.some((part) => part === '') || right.some((part) => part === '')) return false;
|
||||
let segments = [...left, ...right];
|
||||
let ipv4TailSegments = 0;
|
||||
const lastSegment = segments.at(-1);
|
||||
if (lastSegment && lastSegment.includes('.')) {
|
||||
if (!isValidIPv4(lastSegment)) return false;
|
||||
segments = segments.slice(0, -1);
|
||||
ipv4TailSegments = 2;
|
||||
}
|
||||
for (const segment of segments) {
|
||||
if (!/^[0-9A-Fa-f]{1,4}$/.test(segment)) return false;
|
||||
}
|
||||
const totalSegments = segments.length + ipv4TailSegments;
|
||||
if (hasCompression) return totalSegments < 8;
|
||||
return totalSegments === 8;
|
||||
}
|
||||
|
||||
const optionalIPv4 = (label: string) =>
|
||||
z.string().refine((v) => v.trim() === '' || isValidIPv4(v.trim()), {
|
||||
message: `Введите корректный IPv4 адрес (${label})`
|
||||
});
|
||||
|
||||
const optionalIPv6 = (label: string) =>
|
||||
z.string().refine((v) => v.trim() === '' || isValidIPv6(v.trim()), {
|
||||
message: `Введите корректный IPv6 адрес (${label})`
|
||||
});
|
||||
|
||||
export const settingsKnownSchema = z.object({
|
||||
bird_router_id: optionalIPv4('router id'),
|
||||
bird_local_ipv4: optionalIPv4('local IPv4'),
|
||||
bird_local_ipv6: optionalIPv6('local IPv6'),
|
||||
bird_local_asn: z.string().refine((v) => v.trim() === '' || /^[1-9]\d*$/.test(v.trim()), {
|
||||
message: 'ASN должен быть целым числом больше 0'
|
||||
}),
|
||||
bird_bgp_source_ipv4: optionalIPv4('BGP source IPv4'),
|
||||
bird_bgp_source_ipv6: optionalIPv6('BGP source IPv6'),
|
||||
revision_retention_minutes: z.string().refine(
|
||||
(v) => {
|
||||
const s = v.trim();
|
||||
if (s === '') return true;
|
||||
const ttl = Number(s);
|
||||
return /^\d+$/.test(s) && Number.isInteger(ttl) && ttl >= 15 && ttl <= 43200;
|
||||
},
|
||||
{ message: 'TTL ревизий должен быть целым числом от 15 до 43200 минут' }
|
||||
)
|
||||
});
|
||||
/** @deprecated Используйте birdSettingsSchema и revisionSettingsSchema отдельно. */
|
||||
export const settingsKnownSchema = birdSettingsSchema.merge(revisionSettingsSchema);
|
||||
|
||||
/** @deprecated Используйте BirdSettingsForm и RevisionSettingsForm. */
|
||||
export type SettingsKnownForm = z.infer<typeof settingsKnownSchema>;
|
||||
|
||||
/** @deprecated Используйте emptyBirdSettingsForm и emptyRevisionSettingsForm. */
|
||||
export const emptySettingsKnownForm = (): SettingsKnownForm => ({
|
||||
bird_router_id: '',
|
||||
bird_local_ipv4: '',
|
||||
bird_local_ipv6: '',
|
||||
bird_local_asn: '',
|
||||
bird_bgp_source_ipv4: '',
|
||||
bird_bgp_source_ipv6: '',
|
||||
revision_retention_minutes: ''
|
||||
...emptyBirdSettingsForm(),
|
||||
...emptyRevisionSettingsForm()
|
||||
});
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { browser } from '$app/environment';
|
||||
import { applyTheme, readTheme, THEME_STORAGE_KEY, type ThemePreference } from './theme.js';
|
||||
|
||||
class ThemePreferencesState {
|
||||
pref = $state<ThemePreference>('system');
|
||||
|
||||
init(): void {
|
||||
if (!browser) return;
|
||||
this.pref = readTheme();
|
||||
applyTheme(this.pref);
|
||||
}
|
||||
|
||||
set(next: ThemePreference): void {
|
||||
this.pref = next;
|
||||
}
|
||||
|
||||
persist(): void {
|
||||
if (!browser) return;
|
||||
applyTheme(this.pref);
|
||||
try {
|
||||
localStorage.setItem(THEME_STORAGE_KEY, this.pref);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const themeState = new ThemePreferencesState();
|
||||
@@ -7,6 +7,7 @@ import Gauge from '@lucide/svelte/icons/gauge';
|
||||
import LayoutDashboard from '@lucide/svelte/icons/layout-dashboard';
|
||||
import Network from '@lucide/svelte/icons/network';
|
||||
import Settings from '@lucide/svelte/icons/settings';
|
||||
import Shield from '@lucide/svelte/icons/shield';
|
||||
export type NavItem = {
|
||||
href: string;
|
||||
label: string;
|
||||
@@ -23,4 +24,7 @@ export const mainNav: NavItem[] = [
|
||||
{ href: '/monitoring', label: 'Мониторинг', icon: Gauge }
|
||||
];
|
||||
|
||||
export const bottomNav: NavItem[] = [{ href: '/settings', label: 'Настройки', icon: Settings }];
|
||||
export const bottomNav: NavItem[] = [
|
||||
{ href: '/access', label: 'Права доступа', icon: Shield },
|
||||
{ href: '/settings', label: 'Настройки', icon: Settings }
|
||||
];
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
<script lang="ts">
|
||||
type Props = {
|
||||
items: readonly string[];
|
||||
rowHeight?: number;
|
||||
viewportHeight?: number;
|
||||
class?: string;
|
||||
};
|
||||
|
||||
let { items, rowHeight = 20, viewportHeight = 320, class: className = '' }: Props = $props();
|
||||
|
||||
let scrollTop = $state(0);
|
||||
const totalHeight = $derived(items.length * rowHeight);
|
||||
const startIndex = $derived(Math.max(0, Math.floor(scrollTop / rowHeight) - 2));
|
||||
const visibleCount = $derived(Math.ceil(viewportHeight / rowHeight) + 4);
|
||||
const visibleItems = $derived(items.slice(startIndex, startIndex + visibleCount));
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="overflow-auto rounded-md border {className}"
|
||||
style="height: {viewportHeight}px"
|
||||
onscroll={(e) => {
|
||||
scrollTop = e.currentTarget.scrollTop;
|
||||
}}
|
||||
>
|
||||
<div style="height: {totalHeight}px; position: relative">
|
||||
{#each visibleItems as pfx, i (`${startIndex + i}-${pfx}`)}
|
||||
<p
|
||||
class="truncate px-2 font-mono text-xs leading-5"
|
||||
style="position: absolute; top: {(startIndex + i) *
|
||||
rowHeight}px; left: 0; right: 0; height: {rowHeight}px"
|
||||
>
|
||||
{pfx}
|
||||
</p>
|
||||
{:else}
|
||||
<p class="text-muted-foreground p-2 text-sm">Нет префиксов</p>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
@@ -5,19 +5,17 @@
|
||||
import favicon from '$lib/assets/favicon.svg';
|
||||
import AppLayout from '$lib/ui/app/layout/app-layout.svelte';
|
||||
import ConfirmDialog from '$lib/ui/patterns/confirm/confirm-dialog.svelte';
|
||||
import { applyTheme, readTheme, THEME_STORAGE_KEY, type ThemePreference } from '$lib/theme.js';
|
||||
import { applyTheme } from '$lib/theme.js';
|
||||
import { themeState } from '$lib/theme-preferences.svelte.js';
|
||||
import { Toaster } from 'svelte-sonner';
|
||||
|
||||
let { children } = $props();
|
||||
|
||||
let themePref = $state<ThemePreference>('system');
|
||||
|
||||
onMount(() => {
|
||||
themePref = readTheme();
|
||||
applyTheme(themePref);
|
||||
themeState.init();
|
||||
const mq = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
const onOs = () => {
|
||||
if (themePref === 'system') applyTheme('system');
|
||||
if (themeState.pref === 'system') applyTheme('system');
|
||||
};
|
||||
mq.addEventListener('change', onOs);
|
||||
return () => mq.removeEventListener('change', onOs);
|
||||
@@ -25,16 +23,11 @@
|
||||
|
||||
$effect(() => {
|
||||
if (!browser) return;
|
||||
applyTheme(themePref);
|
||||
try {
|
||||
localStorage.setItem(THEME_STORAGE_KEY, themePref);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
themeState.persist();
|
||||
});
|
||||
|
||||
const sonnerTheme = $derived(
|
||||
themePref === 'system' ? 'system' : themePref === 'dark' ? 'dark' : 'light'
|
||||
themeState.pref === 'system' ? 'system' : themeState.pref === 'dark' ? 'dark' : 'light'
|
||||
);
|
||||
</script>
|
||||
|
||||
@@ -44,4 +37,4 @@
|
||||
</svelte:head>
|
||||
<Toaster richColors theme={sonnerTheme} position="top-right" />
|
||||
<ConfirmDialog />
|
||||
<AppLayout bind:theme={themePref}>{@render children()}</AppLayout>
|
||||
<AppLayout bind:theme={themeState.pref}>{@render children()}</AppLayout>
|
||||
|
||||
+67
-24
@@ -159,37 +159,68 @@
|
||||
}
|
||||
]);
|
||||
|
||||
function toErrorMessage(e: unknown): string {
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
|
||||
async function load() {
|
||||
if (!initialLoading) refreshing = true;
|
||||
loadError = null;
|
||||
try {
|
||||
const [h, m, p, s, r, j] = await Promise.all([
|
||||
apiFetch('/v1/health'),
|
||||
try {
|
||||
const h = await apiFetch('/v1/health');
|
||||
healthy = h.ok;
|
||||
if (!h.ok) {
|
||||
loadError = `GET /v1/health: HTTP ${h.status}`;
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
healthy = false;
|
||||
loadError = toErrorMessage(e);
|
||||
notifyApiError(e);
|
||||
return;
|
||||
}
|
||||
|
||||
const [m, p, s, r, j] = await Promise.allSettled([
|
||||
apiJSON<ModulesResponse>('/v1/modules?limit=200'),
|
||||
apiJSON<PeersResponse>('/v1/peers?limit=200'),
|
||||
apiJSON<SpeakersResponse>('/v1/speakers?limit=200'),
|
||||
apiJSON<RevisionsResponse>('/v1/revisions?limit=200'),
|
||||
apiJSON<JobsResponse>('/v1/jobs?limit=20')
|
||||
apiJSON<RevisionsResponse>('/v1/revisions?limit=10'),
|
||||
apiJSON<JobsResponse>('/v1/jobs?limit=10')
|
||||
]);
|
||||
|
||||
healthy = h.ok;
|
||||
moduleItems = m.items ?? [];
|
||||
modulesHasMore = m.has_more;
|
||||
peerItems = p.items ?? [];
|
||||
peersHasMore = p.has_more;
|
||||
speakerItems = s.items ?? [];
|
||||
speakersHasMore = s.has_more;
|
||||
revisionItems = r.items ?? [];
|
||||
revisionsHasMore = r.has_more;
|
||||
jobItems = j.items ?? [];
|
||||
recentJobs = jobItems.slice(0, 10);
|
||||
recentRevisions = revisionItems.slice(0, 10);
|
||||
runningJobs = jobItems.filter((i) => i.status === 'running' || i.status === 'queued').length;
|
||||
lastUpdated = new Date();
|
||||
} catch (e) {
|
||||
healthy = false;
|
||||
loadError = e instanceof Error ? e.message : String(e);
|
||||
notifyApiError(e);
|
||||
const firstReject = [m, p, s, r, j].find((x) => x.status === 'rejected');
|
||||
if (firstReject?.status === 'rejected') {
|
||||
loadError = toErrorMessage(firstReject.reason);
|
||||
notifyApiError(firstReject.reason);
|
||||
}
|
||||
|
||||
if (m.status === 'fulfilled') {
|
||||
moduleItems = m.value.items ?? [];
|
||||
modulesHasMore = m.value.has_more;
|
||||
}
|
||||
if (p.status === 'fulfilled') {
|
||||
peerItems = p.value.items ?? [];
|
||||
peersHasMore = p.value.has_more;
|
||||
}
|
||||
if (s.status === 'fulfilled') {
|
||||
speakerItems = s.value.items ?? [];
|
||||
speakersHasMore = s.value.has_more;
|
||||
}
|
||||
if (r.status === 'fulfilled') {
|
||||
revisionItems = r.value.items ?? [];
|
||||
revisionsHasMore = r.value.has_more;
|
||||
}
|
||||
if (j.status === 'fulfilled') {
|
||||
jobItems = j.value.items ?? [];
|
||||
recentJobs = jobItems.slice(0, 10);
|
||||
recentRevisions = revisionItems.slice(0, 10);
|
||||
runningJobs = jobItems.filter(
|
||||
(i) => i.status === 'running' || i.status === 'queued'
|
||||
).length;
|
||||
}
|
||||
|
||||
if (!loadError) lastUpdated = new Date();
|
||||
} finally {
|
||||
initialLoading = false;
|
||||
refreshing = false;
|
||||
@@ -235,18 +266,30 @@
|
||||
<AlertTitle>Проверка API…</AlertTitle>
|
||||
<AlertDescription>Запрос к <code class="text-xs">/v1/health</code></AlertDescription>
|
||||
</Alert>
|
||||
{:else if healthy}
|
||||
{:else if healthy && !loadError}
|
||||
<Alert class="border-success/30 bg-success/5">
|
||||
<CheckCircle class="text-success" />
|
||||
<AlertTitle>API работает</AlertTitle>
|
||||
<AlertDescription>Сервер отвечает на запросы health-check.</AlertDescription>
|
||||
</Alert>
|
||||
{:else if healthy && loadError}
|
||||
<Alert class="border-warning/30 bg-warning/5">
|
||||
<Info class="text-warning" />
|
||||
<AlertTitle>API доступен, данные не загружены</AlertTitle>
|
||||
<AlertDescription>
|
||||
{loadError}. Для локального демо укажите Bearer-токен
|
||||
<code class="text-xs">dev</code> в
|
||||
<Button variant="link" class="h-auto p-0" href={resolve('/settings')}>Настройках</Button>
|
||||
(нужен <code class="text-xs">EVOBGP_DEV_INSECURE=1</code> на API).
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
{:else}
|
||||
<Alert variant="destructive" class="border-destructive/30 bg-destructive/5">
|
||||
<XCircle class="text-destructive" />
|
||||
<AlertTitle>API недоступен</AlertTitle>
|
||||
<AlertDescription>
|
||||
Не удалось получить ответ от сервера. Проверьте подключение и статус API.
|
||||
{loadError ??
|
||||
'Не удалось получить ответ от сервера. Проверьте, что API запущен (порт 8080), в dev — `npm run dev` с прокси Vite, в Docker — контейнер evobgp-api / evobgp-all и nginx в evobgp-web.'}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
{/if}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
<script lang="ts">
|
||||
import { resolve } from '$app/paths';
|
||||
import { onMount } from 'svelte';
|
||||
import { apiJSON } from '$lib/api/client.js';
|
||||
import type { ApiKey, ApiKeysResponse, AuthSession } from '$lib/api/types.js';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle
|
||||
} from '$lib/ui/core/card/index.js';
|
||||
import { notifyApiError } from '$lib/ui/app/toast.js';
|
||||
import AccessApiKeysCard from '$lib/components/access/AccessApiKeysCard.svelte';
|
||||
import Shield from '@lucide/svelte/icons/shield';
|
||||
import PageHeader from '$lib/ui/app/page-header/page-header.svelte';
|
||||
|
||||
let session = $state<AuthSession | null>(null);
|
||||
let apiKeys = $state<ApiKey[]>([]);
|
||||
let keysLoading = $state(false);
|
||||
let keysInitial = $state(true);
|
||||
let keysError = $state<string | null>(null);
|
||||
|
||||
const isOperator = $derived(session?.role === 'operator');
|
||||
|
||||
async function loadSession() {
|
||||
try {
|
||||
session = await apiJSON<AuthSession>('/v1/auth/session');
|
||||
} catch {
|
||||
session = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadApiKeys() {
|
||||
keysLoading = true;
|
||||
keysError = null;
|
||||
try {
|
||||
const page = await apiJSON<ApiKeysResponse>('/v1/api-keys?limit=500');
|
||||
apiKeys = page.items ?? [];
|
||||
} catch (e) {
|
||||
apiKeys = [];
|
||||
keysError = e instanceof Error ? e.message : 'Ошибка загрузки';
|
||||
notifyApiError(e);
|
||||
} finally {
|
||||
keysLoading = false;
|
||||
keysInitial = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
void (async () => {
|
||||
await loadSession();
|
||||
if (session?.role === 'operator') await loadApiKeys();
|
||||
else keysInitial = false;
|
||||
})();
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="mx-auto flex max-w-4xl flex-col gap-6">
|
||||
<PageHeader
|
||||
title="Права доступа"
|
||||
description="API-ключи control plane и текущая сессия Bearer-токена."
|
||||
icon={Shield}
|
||||
iconClass="bg-primary/10 text-primary"
|
||||
/>
|
||||
|
||||
{#if session}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="text-base">Текущая сессия</CardTitle>
|
||||
<CardDescription>Tenant и роль ключа, с которым открыта панель.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="grid gap-3 text-sm sm:grid-cols-2">
|
||||
<div>
|
||||
<p class="text-muted-foreground">Tenant</p>
|
||||
<p class="font-mono text-xs break-all">{session.tenant_id}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-muted-foreground">Роль</p>
|
||||
<p class="font-mono">{session.role}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/if}
|
||||
|
||||
{#if isOperator}
|
||||
<AccessApiKeysCard
|
||||
items={apiKeys}
|
||||
loading={keysLoading}
|
||||
initialLoading={keysInitial}
|
||||
error={keysError}
|
||||
onRefresh={loadApiKeys}
|
||||
/>
|
||||
{:else if session}
|
||||
<Card>
|
||||
<CardContent class="py-6 text-sm text-muted-foreground">
|
||||
Управление API-ключами доступно только роли <strong>operator</strong>. Текущая роль:
|
||||
<span class="font-mono">{session.role}</span>. Для выдачи ключей войдите с operator-ключом
|
||||
или создайте ключ через API / переменную <code class="text-xs">EVOBGP_API_KEYS</code>.
|
||||
</CardContent>
|
||||
</Card>
|
||||
{:else}
|
||||
<Card>
|
||||
<CardContent class="py-6 text-sm text-muted-foreground">
|
||||
Не удалось определить сессию. Укажите Bearer-токен в
|
||||
<a href={resolve('/settings')} class="text-primary underline-offset-4 hover:underline"
|
||||
>настройках</a
|
||||
>
|
||||
интерфейса.
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1,32 +1,33 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import { page } from '$app/state';
|
||||
import { resolve } from '$app/paths';
|
||||
import { apiJSON } from '$lib/api/client.js';
|
||||
import type { PeerRow, PeersResponse, SpeakerRow, SpeakersResponse } from '$lib/api/types.js';
|
||||
import { Badge } from '$lib/ui/core/badge/index.js';
|
||||
import { Button } from '$lib/ui/core/button/index.js';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
CardDescription
|
||||
} from '$lib/ui/core/card/index.js';
|
||||
import { Alert, AlertDescription, AlertTitle } from '$lib/ui/core/alert/index.js';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '$lib/ui/core/tabs/index.js';
|
||||
import CardSkeleton from '$lib/ui/patterns/feedback/card-skeleton.svelte';
|
||||
import KpiMetricsGrid from '$lib/ui/patterns/kpi/kpi-metrics-grid.svelte';
|
||||
import PageHeader from '$lib/ui/app/page-header/page-header.svelte';
|
||||
import { notifyApiError } from '$lib/ui/app/toast.js';
|
||||
import NetworkPeersCard from '$lib/components/network/NetworkPeersCard.svelte';
|
||||
import NetworkSpeakersCard from '$lib/components/network/NetworkSpeakersCard.svelte';
|
||||
import { cn } from '$lib/utils.js';
|
||||
import BirdSettingsForm from '$lib/components/network/BirdSettingsForm.svelte';
|
||||
import RefreshCw from '@lucide/svelte/icons/refresh-cw';
|
||||
import NetworkIcon from '@lucide/svelte/icons/network';
|
||||
import Info from '@lucide/svelte/icons/info';
|
||||
import Share2 from '@lucide/svelte/icons/share-2';
|
||||
import CheckCircle2 from '@lucide/svelte/icons/check-circle-2';
|
||||
import Server from '@lucide/svelte/icons/server';
|
||||
|
||||
type NetworkTab = 'peers' | 'speakers' | 'control-plane';
|
||||
|
||||
function parseNetworkTab(value: string | null): NetworkTab {
|
||||
if (value === 'speakers' || value === 'control-plane') return value;
|
||||
return 'peers';
|
||||
}
|
||||
|
||||
let peers = $state<PeerRow[]>([]);
|
||||
let speakers = $state<SpeakerRow[]>([]);
|
||||
let peersLoading = $state(false);
|
||||
@@ -34,6 +35,8 @@
|
||||
let initialLoading = $state(true);
|
||||
let loadError = $state<string | null>(null);
|
||||
let lastUpdated = $state<Date | null>(null);
|
||||
let activeTab = $state<NetworkTab>('peers');
|
||||
let tabSyncReady = $state(false);
|
||||
|
||||
const establishedCount = $derived(peers.filter((p) => p.session_state === 'Established').length);
|
||||
|
||||
@@ -150,7 +153,27 @@
|
||||
}
|
||||
}
|
||||
|
||||
onMount(load);
|
||||
onMount(() => {
|
||||
activeTab = parseNetworkTab(page.url.searchParams.get('tab'));
|
||||
tabSyncReady = true;
|
||||
void load();
|
||||
});
|
||||
|
||||
function syncTabToUrl(tab: NetworkTab) {
|
||||
if (!tabSyncReady) return;
|
||||
const url = new URL(page.url);
|
||||
if (tab === 'peers') url.searchParams.delete('tab');
|
||||
else url.searchParams.set('tab', tab);
|
||||
const next = `${url.pathname}${url.search}${url.hash}`;
|
||||
if (next !== `${page.url.pathname}${page.url.search}${page.url.hash}`) {
|
||||
void goto(next, { replaceState: true, keepFocus: true, noScroll: true });
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!tabSyncReady) return;
|
||||
syncTabToUrl(activeTab);
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-6">
|
||||
@@ -187,10 +210,11 @@
|
||||
class="sm:grid-cols-3"
|
||||
/>
|
||||
|
||||
<Tabs value="peers">
|
||||
<Tabs bind:value={activeTab}>
|
||||
<TabsList>
|
||||
<TabsTrigger value="peers">Пиры</TabsTrigger>
|
||||
<TabsTrigger value="speakers">Спикеры</TabsTrigger>
|
||||
<TabsTrigger value="control-plane">Control plane</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="peers" class="mt-4">
|
||||
@@ -213,5 +237,9 @@
|
||||
onRefresh={refreshSpeakers}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="control-plane" class="mt-4">
|
||||
<BirdSettingsForm />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
@@ -53,12 +53,14 @@
|
||||
import OperationsDiffTab from '$lib/components/operations/OperationsDiffTab.svelte';
|
||||
import OperationsJobsTab from '$lib/components/operations/OperationsJobsTab.svelte';
|
||||
import OperationsJobsFilters from '$lib/components/operations/OperationsJobsFilters.svelte';
|
||||
import OperationsSystemSettingsTab from '$lib/components/operations/OperationsSystemSettingsTab.svelte';
|
||||
import type {
|
||||
JobDetailedReport,
|
||||
JobLogEntry,
|
||||
ReportRow
|
||||
} from '$lib/components/operations/types.js';
|
||||
import ScrollPreBlock from '$lib/components/app/scroll-pre-block.svelte';
|
||||
import VirtualPrefixList from '$lib/ui/patterns/virtual-list/virtual-prefix-list.svelte';
|
||||
import CardSkeleton from '$lib/ui/patterns/feedback/card-skeleton.svelte';
|
||||
import KpiMetricsGrid from '$lib/ui/patterns/kpi/kpi-metrics-grid.svelte';
|
||||
import { confirm } from '$lib/ui/patterns/confirm/confirm-state.svelte.js';
|
||||
@@ -80,10 +82,10 @@
|
||||
import Info from '@lucide/svelte/icons/info';
|
||||
import ArrowRight from '@lucide/svelte/icons/arrow-right';
|
||||
|
||||
type OpsTab = 'revisions' | 'diff' | 'jobs';
|
||||
type OpsTab = 'revisions' | 'diff' | 'jobs' | 'system';
|
||||
|
||||
function parseOpsTab(value: string | null): OpsTab {
|
||||
if (value === 'diff' || value === 'jobs') return value;
|
||||
if (value === 'diff' || value === 'jobs' || value === 'system') return value;
|
||||
return 'revisions';
|
||||
}
|
||||
|
||||
@@ -127,6 +129,7 @@
|
||||
let jobs = $state<JobRow[]>([]);
|
||||
let jobsLoading = $state(false);
|
||||
let jobSearchQ = $state('');
|
||||
let jobSearchDebounced = $state('');
|
||||
let jobFilterStatus = $state('');
|
||||
let jobFilterKind = $state('');
|
||||
let jobFilterModule = $state('');
|
||||
@@ -301,13 +304,23 @@
|
||||
return j.kind === 'module_refresh' && mid === jobFilterModule;
|
||||
});
|
||||
}
|
||||
const q = jobSearchQ.trim();
|
||||
const q = jobSearchDebounced.trim();
|
||||
if (q) {
|
||||
list = list.filter((j) => jobMatchesSearch(j, q));
|
||||
}
|
||||
return list;
|
||||
});
|
||||
|
||||
let jobSearchTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
$effect(() => {
|
||||
const q = jobSearchQ;
|
||||
clearTimeout(jobSearchTimer);
|
||||
jobSearchTimer = setTimeout(() => {
|
||||
jobSearchDebounced = q;
|
||||
}, 250);
|
||||
return () => clearTimeout(jobSearchTimer);
|
||||
});
|
||||
|
||||
const jobModuleOptions = $derived(
|
||||
[...moduleNameById.entries()]
|
||||
.map(([id, name]) => ({ id, name }))
|
||||
@@ -339,8 +352,18 @@
|
||||
|
||||
onMount(() => {
|
||||
activeTab = parseOpsTab(page.url.searchParams.get('tab'));
|
||||
lastLoadedTab = activeTab;
|
||||
tabSyncReady = true;
|
||||
void refreshAll(true);
|
||||
void refreshActiveTab(true);
|
||||
});
|
||||
|
||||
let lastLoadedTab = $state('');
|
||||
$effect(() => {
|
||||
if (!tabSyncReady) return;
|
||||
const tab = activeTab;
|
||||
if (tab === lastLoadedTab) return;
|
||||
lastLoadedTab = tab;
|
||||
void refreshActiveTab();
|
||||
});
|
||||
|
||||
const statAccents = [
|
||||
@@ -424,6 +447,29 @@
|
||||
syncTabToUrl(activeTab);
|
||||
});
|
||||
|
||||
async function refreshActiveTab(isInitial = false) {
|
||||
if (isInitial) initialLoading = true;
|
||||
else refreshing = true;
|
||||
switch (activeTab) {
|
||||
case 'revisions':
|
||||
await loadRevisions();
|
||||
break;
|
||||
case 'jobs':
|
||||
await Promise.all([loadJobs(), loadModules()]);
|
||||
break;
|
||||
case 'diff':
|
||||
break;
|
||||
case 'system':
|
||||
await loadBirdStatus();
|
||||
break;
|
||||
default:
|
||||
await loadRevisions();
|
||||
}
|
||||
lastUpdated = new Date();
|
||||
initialLoading = false;
|
||||
refreshing = false;
|
||||
}
|
||||
|
||||
async function refreshAll(isInitial = false) {
|
||||
if (isInitial) initialLoading = true;
|
||||
else refreshing = true;
|
||||
@@ -882,12 +928,12 @@
|
||||
|
||||
<Alert class="border-info/30 bg-info/5">
|
||||
<Info class="text-info" />
|
||||
<AlertTitle>Три раздела на одной странице</AlertTitle>
|
||||
<AlertTitle>Четыре раздела на одной странице</AlertTitle>
|
||||
<AlertDescription>
|
||||
<strong>Ревизии</strong> — история конфигов и откат; <strong>Сравнение</strong> — diff
|
||||
префиксов;
|
||||
<strong>Задачи</strong> — ingest, apply, rollback. Apply и Reload требуют operator. Сводный
|
||||
мониторинг BGP — на
|
||||
<strong>Задачи</strong> — ingest, apply, rollback; <strong>Система</strong> — TTL ревизий и
|
||||
дополнительные KV. Apply и Reload требуют operator. Сводный мониторинг BGP — на
|
||||
<Button variant="link" class="h-auto p-0" href={resolve('/monitoring')}>Мониторинг</Button>.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
@@ -918,6 +964,7 @@
|
||||
<TabsTrigger value="revisions">Ревизии ({revisions.length})</TabsTrigger>
|
||||
<TabsTrigger value="diff">Сравнение</TabsTrigger>
|
||||
<TabsTrigger value="jobs">Задачи ({jobs.length})</TabsTrigger>
|
||||
<TabsTrigger value="system">Система</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
|
||||
@@ -982,6 +1029,10 @@
|
||||
jobStatusVariant={jobStatusBadgeVariant}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="system" class="mt-4">
|
||||
<OperationsSystemSettingsTab />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
@@ -1055,15 +1106,7 @@
|
||||
<span class="font-medium">Префиксов:</span>
|
||||
{prefixesData.length}
|
||||
</p>
|
||||
<div
|
||||
class="flex min-h-[10rem] min-w-0 flex-1 flex-col overflow-auto overscroll-contain rounded-lg border border-border bg-muted/40 p-3 [scrollbar-gutter:stable]"
|
||||
>
|
||||
{#each prefixesData as pfx, idx (`${idx}-${pfx}`)}
|
||||
<p class="font-mono text-xs">{pfx}</p>
|
||||
{:else}
|
||||
<p class="text-muted-foreground text-xs">Нет префиксов</p>
|
||||
{/each}
|
||||
</div>
|
||||
<VirtualPrefixList items={prefixesData} viewportHeight={360} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
@@ -1,110 +1,34 @@
|
||||
<script lang="ts">
|
||||
import { browser } from '$app/environment';
|
||||
import { resolve } from '$app/paths';
|
||||
import { onMount } from 'svelte';
|
||||
import { defaults, superForm } from 'sveltekit-superforms';
|
||||
import { zod4 } from 'sveltekit-superforms/adapters';
|
||||
import { TOKEN_STORAGE_KEY } from '$lib/api/client.js';
|
||||
import { apiJSON, apiMutate } from '$lib/api/client.js';
|
||||
import type { AppSettings } from '$lib/api/types.js';
|
||||
import {
|
||||
emptySettingsKnownForm,
|
||||
settingsKnownSchema,
|
||||
type SettingsKnownForm
|
||||
} from '$lib/settings/settings-known.schema.js';
|
||||
import { themeState } from '$lib/theme-preferences.svelte.js';
|
||||
import type { ThemePreference } from '$lib/theme.js';
|
||||
import { Button } from '$lib/ui/core/button/index.js';
|
||||
import { Card, CardContent, CardHeader, CardDescription } from '$lib/ui/core/card/index.js';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle
|
||||
} from '$lib/ui/core/card/index.js';
|
||||
import { Input } from '$lib/ui/core/input/index.js';
|
||||
import { Label } from '$lib/ui/core/label/index.js';
|
||||
import FormField from '$lib/ui/patterns/form/form-field.svelte';
|
||||
import { notify, notifyApiError } from '$lib/ui/app/toast.js';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger } from '$lib/ui/core/select/index.js';
|
||||
import { notify } from '$lib/ui/app/toast.js';
|
||||
import Save from '@lucide/svelte/icons/save';
|
||||
import Plus from '@lucide/svelte/icons/plus';
|
||||
import SettingsIcon from '@lucide/svelte/icons/settings';
|
||||
import PageHeader from '$lib/ui/app/page-header/page-header.svelte';
|
||||
import Trash2 from '@lucide/svelte/icons/trash-2';
|
||||
|
||||
let token = $state('');
|
||||
let apiSettings = $state<AppSettings | null>(null);
|
||||
let loadingSettings = $state(false);
|
||||
let savingSettings = $state(false);
|
||||
let additionalSettings = $state<Array<{ id: number; key: string; value: string }>>([]);
|
||||
let additionalIdCounter = $state(1);
|
||||
|
||||
type KnownFieldKey = keyof SettingsKnownForm;
|
||||
|
||||
type SettingsSection = 'token' | 'bird' | 'revisions' | 'additional';
|
||||
|
||||
const knownFieldKeys: KnownFieldKey[] = [
|
||||
'bird_router_id',
|
||||
'bird_local_ipv4',
|
||||
'bird_local_ipv6',
|
||||
'bird_local_asn',
|
||||
'bird_bgp_source_ipv4',
|
||||
'bird_bgp_source_ipv6',
|
||||
'revision_retention_minutes'
|
||||
const themeOptions: Array<{ value: ThemePreference; label: string }> = [
|
||||
{ value: 'light', label: 'Светлая' },
|
||||
{ value: 'dark', label: 'Тёмная' },
|
||||
{ value: 'system', label: 'Как в системе' }
|
||||
];
|
||||
|
||||
const { form, errors, reset, validateForm } = superForm(
|
||||
defaults(emptySettingsKnownForm(), zod4(settingsKnownSchema)),
|
||||
{
|
||||
validators: zod4(settingsKnownSchema),
|
||||
SPA: true,
|
||||
dataType: 'json'
|
||||
}
|
||||
);
|
||||
|
||||
let activeSection = $state<SettingsSection>('token');
|
||||
|
||||
const sectionItems: Array<{ id: SettingsSection; label: string; description: string }> = [
|
||||
{ id: 'token', label: 'API-ключ', description: 'Авторизация в UI' },
|
||||
{ id: 'bird', label: 'BIRD', description: 'Сетевые параметры' },
|
||||
{ id: 'revisions', label: 'Ревизии', description: 'Хранение истории' },
|
||||
{ id: 'additional', label: 'Дополнительно', description: 'Ключ-значение' }
|
||||
];
|
||||
|
||||
let hasValidationErrors = $derived(knownFieldKeys.some((key) => Boolean($errors[key]?.length)));
|
||||
|
||||
function addAdditionalSetting() {
|
||||
additionalSettings.push({ id: additionalIdCounter++, key: '', value: '' });
|
||||
}
|
||||
|
||||
function removeAdditionalSetting(id: number) {
|
||||
additionalSettings = additionalSettings.filter((entry) => entry.id !== id);
|
||||
}
|
||||
|
||||
function resetFormFromApi(settings: AppSettings) {
|
||||
const parsedKnown: Record<KnownFieldKey, string> = {
|
||||
bird_router_id: '',
|
||||
bird_local_ipv4: '',
|
||||
bird_local_ipv6: '',
|
||||
bird_local_asn: '',
|
||||
bird_bgp_source_ipv4: '',
|
||||
bird_bgp_source_ipv6: '',
|
||||
revision_retention_minutes: ''
|
||||
};
|
||||
const parsedAdditional: Array<{ id: number; key: string; value: string }> = [];
|
||||
|
||||
for (const [key, value] of Object.entries(settings as Record<string, unknown>)) {
|
||||
if (knownFieldKeys.includes(key as KnownFieldKey)) {
|
||||
if (key === 'bird_local_asn' || key === 'revision_retention_minutes') {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) parsedKnown[key] = String(value);
|
||||
else if (typeof value === 'string') parsedKnown[key] = value;
|
||||
} else if (typeof value === 'string') {
|
||||
parsedKnown[key as KnownFieldKey] = value;
|
||||
}
|
||||
} else {
|
||||
parsedAdditional.push({
|
||||
id: additionalIdCounter++,
|
||||
key,
|
||||
value: typeof value === 'string' ? value : String(value)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
reset({ data: parsedKnown });
|
||||
additionalSettings = parsedAdditional;
|
||||
}
|
||||
|
||||
function saveToken() {
|
||||
if (!browser) return;
|
||||
const t = token.trim();
|
||||
@@ -113,295 +37,76 @@
|
||||
notify.success('Токен сохранён');
|
||||
}
|
||||
|
||||
async function loadApiSettings() {
|
||||
loadingSettings = true;
|
||||
try {
|
||||
const s = await apiJSON<AppSettings>('/v1/settings');
|
||||
apiSettings = s;
|
||||
resetFormFromApi(s);
|
||||
} catch (e) {
|
||||
notifyApiError(e);
|
||||
} finally {
|
||||
loadingSettings = false;
|
||||
}
|
||||
}
|
||||
|
||||
let canSaveSettings = $derived.by(() => {
|
||||
if (loadingSettings || savingSettings || hasValidationErrors) return false;
|
||||
|
||||
const hasKnownValues = knownFieldKeys.some((key) => {
|
||||
const value = String($form[key] ?? '').trim();
|
||||
return value !== '' && !$errors[key]?.length;
|
||||
});
|
||||
const hasAdditionalValues = additionalSettings.some((entry) => entry.key.trim() !== '');
|
||||
|
||||
return hasKnownValues || hasAdditionalValues;
|
||||
});
|
||||
|
||||
async function saveApiSettings() {
|
||||
const validation = await validateForm({ update: true });
|
||||
if (!validation.valid) {
|
||||
notify.error('Исправьте ошибки в полях настроек');
|
||||
return;
|
||||
}
|
||||
if (!canSaveSettings) {
|
||||
notify.error('Нечего сохранять или есть ошибки в полях');
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: Record<string, string | number> = {};
|
||||
for (const key of knownFieldKeys) {
|
||||
const value = String($form[key] ?? '').trim();
|
||||
if (!value || $errors[key]?.length) continue;
|
||||
if (key === 'bird_local_asn' || key === 'revision_retention_minutes')
|
||||
payload[key] = Number(value);
|
||||
else payload[key] = value;
|
||||
}
|
||||
for (const entry of additionalSettings) {
|
||||
const key = entry.key.trim();
|
||||
if (!key) continue;
|
||||
payload[key] = entry.value;
|
||||
}
|
||||
|
||||
savingSettings = true;
|
||||
try {
|
||||
await apiMutate('/v1/settings', 'PATCH', payload);
|
||||
notify.success('Настройки сохранены');
|
||||
await loadApiSettings();
|
||||
} catch (e) {
|
||||
notifyApiError(e);
|
||||
} finally {
|
||||
savingSettings = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
themeState.init();
|
||||
if (browser) {
|
||||
token = localStorage.getItem(TOKEN_STORAGE_KEY) ?? '';
|
||||
}
|
||||
void loadApiSettings();
|
||||
});
|
||||
|
||||
function onThemeChange(value: string) {
|
||||
if (value === 'light' || value === 'dark' || value === 'system') {
|
||||
themeState.set(value);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="mx-auto flex max-w-5xl flex-col gap-6">
|
||||
<div class="mx-auto flex max-w-3xl flex-col gap-6">
|
||||
<PageHeader
|
||||
title="Настройки"
|
||||
description="Управление токеном доступа и глобальными параметрами control plane."
|
||||
description="Параметры интерфейса и подключения браузера к API."
|
||||
icon={SettingsIcon}
|
||||
iconClass="bg-muted text-muted-foreground"
|
||||
/>
|
||||
|
||||
<Card>
|
||||
<CardContent class="p-4 md:p-6">
|
||||
<div class="grid gap-6 md:grid-cols-[220px_1fr]">
|
||||
<div class="space-y-1">
|
||||
{#each sectionItems as section (section.id)}
|
||||
<button
|
||||
type="button"
|
||||
class={[
|
||||
'w-full rounded-lg border px-3 py-2 text-left transition-colors',
|
||||
activeSection === section.id
|
||||
? 'border-primary bg-muted text-foreground'
|
||||
: 'border-transparent text-muted-foreground hover:border-border hover:bg-muted/70 hover:text-foreground'
|
||||
]}
|
||||
onclick={() => (activeSection = section.id)}
|
||||
>
|
||||
<div class="text-sm font-medium">{section.label}</div>
|
||||
<div class="text-xs opacity-80">{section.description}</div>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<div class="rounded-xl border border-border p-4 md:p-5">
|
||||
{#if activeSection === 'token'}
|
||||
<div class="space-y-4">
|
||||
<div class="space-y-1">
|
||||
<h2 class="text-base font-semibold">API-ключ</h2>
|
||||
<p class="text-sm text-muted-foreground">
|
||||
Bearer-токен хранится только в localStorage браузера. Для локального демо с
|
||||
<code class="rounded bg-muted px-1 py-0.5 text-xs">EVOBGP_DEV_INSECURE=1</code>
|
||||
используйте токен <code class="rounded bg-muted px-1 py-0.5 text-xs">dev</code>.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<Label for="token">Токен</Label>
|
||||
<Input
|
||||
id="token"
|
||||
type="password"
|
||||
autocomplete="off"
|
||||
bind:value={token}
|
||||
placeholder="Bearer …"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button onclick={saveToken}>
|
||||
<Save />
|
||||
Сохранить токен
|
||||
</Button>
|
||||
</div>
|
||||
{:else if loadingSettings}
|
||||
<p class="text-sm text-muted-foreground">Загрузка…</p>
|
||||
{:else if apiSettings === null}
|
||||
<Button variant="outline" onclick={loadApiSettings}>Загрузить настройки</Button>
|
||||
{:else}
|
||||
<div class="space-y-5">
|
||||
{#if activeSection === 'bird'}
|
||||
<div class="space-y-3">
|
||||
<h2 class="text-base font-semibold">Параметры BIRD</h2>
|
||||
|
||||
<FormField
|
||||
id="bird-router-id"
|
||||
label="Router ID (bird_router_id)"
|
||||
error={$errors.bird_router_id?.[0]}
|
||||
>
|
||||
<Input
|
||||
id="bird-router-id"
|
||||
bind:value={$form.bird_router_id}
|
||||
placeholder="203.0.113.1"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
id="bird-local-ipv4"
|
||||
label="Локальный IPv4 (bird_local_ipv4)"
|
||||
error={$errors.bird_local_ipv4?.[0]}
|
||||
>
|
||||
<Input
|
||||
id="bird-local-ipv4"
|
||||
bind:value={$form.bird_local_ipv4}
|
||||
placeholder="198.51.100.10"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
id="bird-local-ipv6"
|
||||
label="Локальный IPv6 (bird_local_ipv6)"
|
||||
error={$errors.bird_local_ipv6?.[0]}
|
||||
>
|
||||
<Input
|
||||
id="bird-local-ipv6"
|
||||
bind:value={$form.bird_local_ipv6}
|
||||
placeholder="2001:db8::10"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
id="bird-local-asn"
|
||||
label="Локальный ASN (bird_local_asn)"
|
||||
error={$errors.bird_local_asn?.[0]}
|
||||
>
|
||||
<Input
|
||||
id="bird-local-asn"
|
||||
type="number"
|
||||
min="1"
|
||||
bind:value={$form.bird_local_asn}
|
||||
placeholder="65001"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
id="bird-bgp-source-ipv4"
|
||||
label="BGP source IPv4 (bird_bgp_source_ipv4)"
|
||||
error={$errors.bird_bgp_source_ipv4?.[0]}
|
||||
>
|
||||
<Input
|
||||
id="bird-bgp-source-ipv4"
|
||||
bind:value={$form.bird_bgp_source_ipv4}
|
||||
placeholder="198.51.100.11"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
id="bird-bgp-source-ipv6"
|
||||
label="BGP source IPv6 (bird_bgp_source_ipv6)"
|
||||
error={$errors.bird_bgp_source_ipv6?.[0]}
|
||||
>
|
||||
<Input
|
||||
id="bird-bgp-source-ipv6"
|
||||
bind:value={$form.bird_bgp_source_ipv6}
|
||||
placeholder="2001:db8::11"
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
{:else if activeSection === 'revisions'}
|
||||
<div class="space-y-3">
|
||||
<h2 class="text-base font-semibold">Управление ревизиями</h2>
|
||||
|
||||
<FormField
|
||||
id="revision-retention-minutes"
|
||||
label="Время жизни ревизий, мин (revision_retention_minutes)"
|
||||
error={$errors.revision_retention_minutes?.[0]}
|
||||
description="Старые ревизии удаляются автоматически. Последняя раскатанная ревизия не удаляется."
|
||||
>
|
||||
<Input
|
||||
id="revision-retention-minutes"
|
||||
type="number"
|
||||
min="15"
|
||||
max="43200"
|
||||
bind:value={$form.revision_retention_minutes}
|
||||
placeholder="43200"
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
{:else if activeSection === 'additional'}
|
||||
<div class="space-y-3">
|
||||
<div class="flex items-center justify-between">
|
||||
<h2 class="text-base font-semibold">Дополнительные настройки (KV)</h2>
|
||||
<Button variant="outline" size="sm" onclick={addAdditionalSetting}>
|
||||
<Plus class="size-4" />
|
||||
Добавить строку
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{#if additionalSettings.length === 0}
|
||||
<p class="text-sm text-muted-foreground">Нет дополнительных параметров.</p>
|
||||
{/if}
|
||||
|
||||
<div class="space-y-2">
|
||||
{#each additionalSettings as entry (entry.id)}
|
||||
<div class="grid grid-cols-1 gap-2 md:grid-cols-[1fr_1fr_auto]">
|
||||
<Input
|
||||
bind:value={entry.key}
|
||||
placeholder="Ключ (например, bird_log_level)"
|
||||
/>
|
||||
<Input bind:value={entry.value} placeholder="Значение (строка)" />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label="Удалить строку"
|
||||
onclick={() => removeAdditionalSetting(entry.id)}
|
||||
>
|
||||
<Trash2 class="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if hasValidationErrors}
|
||||
<p class="text-sm text-red-600">
|
||||
Есть ошибки в полях. Исправьте их, чтобы сохранить изменения.
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
<div class="pt-2">
|
||||
<Button onclick={saveApiSettings} disabled={!canSaveSettings}>
|
||||
<Save />
|
||||
{savingSettings ? 'Сохранение…' : 'Применить настройки'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
<CardHeader class="pt-0">
|
||||
<CardHeader>
|
||||
<CardTitle>Подключение к API</CardTitle>
|
||||
<CardDescription>
|
||||
<code class="text-xs">GET/PATCH /v1/settings</code> — глобальные параметры control plane (хранятся
|
||||
в БД). Требуется роль operator.
|
||||
Bearer-токен хранится только в этом браузере (localStorage). Управление ключами tenant — в
|
||||
разделе <a href={resolve('/access')} class="text-primary underline-offset-4 hover:underline"
|
||||
>Права доступа</a
|
||||
>.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="space-y-4">
|
||||
<div class="space-y-2">
|
||||
<Label for="token">Токен для запросов</Label>
|
||||
<Input
|
||||
id="token"
|
||||
type="password"
|
||||
autocomplete="off"
|
||||
bind:value={token}
|
||||
placeholder="Bearer …"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button onclick={saveToken}>
|
||||
<Save />
|
||||
Сохранить токен
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Оформление</CardTitle>
|
||||
<CardDescription>
|
||||
Тема интерфейса. Быстрый переключатель также доступен в боковой панели.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="space-y-2">
|
||||
<Label for="theme-select">Тема</Label>
|
||||
<Select type="single" value={themeState.pref} onValueChange={onThemeChange}>
|
||||
<SelectTrigger id="theme-select" class="w-full max-w-xs">
|
||||
{themeOptions.find((o) => o.value === themeState.pref)?.label ?? 'Как в системе'}
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{#each themeOptions as option (option.value)}
|
||||
<SelectItem value={option.value} label={option.label}>{option.label}</SelectItem>
|
||||
{/each}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user