[GH-ISSUE #7069] Add a read-only "metrics" API-token scope backed by a dedicated aggregate endpoint #6608

Open
opened 2026-11-07 14:33:29 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @OlegEnot on GitHub (Nov 4, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/7069

Motivation

A metrics collector cannot authenticate with this panel today unless it is given a full-access admin
token:

  • 2FA is global and interactive. panel.UserService.CheckUser verifies twoFactorEnable /
    twoFactorToken with totp.VerifyWithSkew(...) on every login, so a non-interactive client has no
    way through. Tokens bypass CheckUser entirely (checkAPIAuth → c.Set("api_authed", true)),
    which is exactly the right mechanism — but the only usable scope is admin.
  • Session login is a poor fit anyway: CSRF round-trip, the 5-fail/15-min login limiter, fail2ban
    counters and a 59-minute re-auth cycle in the client.

So the ask is narrow: a token that can read numbers, not configuration.

Current state (v3.11.0)

Scopes: admin, monitor, node-sync, node-admin
(internal/database/model/model.go:167, NormalizeScope in internal/web/service/panel/api_token.go).

monitorScopeAllow (internal/web/controller/api.go:82) covers GET /server/status,
GET /server/history/*, GET /server/xrayMetrics*, GET /nodes/history/*, and
enforceTokenScope (api.go:142) only accepts it for GET/HEAD:

case model.ApiScopeMonitor:
    if _, allowed := monitorScopeAllow[rel]; allowed &&
        (c.Request.Method == http.MethodGet || c.Request.Method == http.MethodHead) {

What a metrics collector actually reads

Call Method Data
/panel/api/server/status GET xray version/state, panel version, threads, mem, uptime
inbounds list GET per-inbound id/remark/up/down, per-client id/email/up/down
/panel/api/clients/onlines POST []email — count of online users

monitor covers the first, misses the other two. admin covers all three and also lets the holder
rewrite inbounds, read the DB, and mint more tokens.

Why the existing endpoints cannot simply be reused

GET /panel/api/inbounds/list returns the model.Inbound row as-is, including:

  • StreamSettings — for VLESS Reality this contains realitySettings.privateKey;
  • Settings — top-level keys such as WireGuard secretKey are not removed by the slimming
    helper (slimSettingsClients, internal/web/service/inbound.go:257); it only rewrites
    settings.clients[];
  • per-client emails and traffic.

GET /panel/api/inbounds/list/slim (controller/inbound.go:113) strips only settings.clients[],
but still ships streamSettings and all other settings keys. Handing that to a container in a
monitoring stack is a credential leak, not a read-only metrics grant.

Allowing POST /clients/onlines in a "read-only" scope is also a smell: the scope's safety property
today is "GET/HEAD only", and it is worth keeping.

Proposal: one aggregate GET endpoint + a GET-only scope

Endpoint

GET /panel/api/server/metrics

{
  "success": true,
  "obj": {
    "panelVersion": "3.11.0",
    "xray": { "version": "25.9.11", "state": "running", "errorMsg": "" },
    "appStats": { "threads": 42, "mem": 73400320, "uptime": 86400 },
    "onlineClients": 12,
    "inbounds": [
      {
        "id": 1, "remark": "VLESS-443", "enable": true,
        "up": 1048576, "down": 8388608,
        "clients": [ { "id": 7, "email": "user@example", "up": 1024, "down": 2048 } ]
      }
    ]
  }
}
  • Only counters and labels a dashboard needs — no settings, no streamSettings, no UUIDs,
    passwords, sub-ids or node credentials.
  • onlineClients is a count, so the collector needs no POST at all, and the scope stays GET-only.
  • Implementation reuses existing services: GetOnlineClients() for the count and a new
    GetInboundsMetrics(userId) that selects id, remark, enable, up, down plus the preloaded
    ClientStats (same Preload as GetInbounds, no settings columns). No schema change, no
    migration.
  • It is one handler in ServerController (controller/server.go) plus one service method; the
    OpenAPI spec and docs regenerate from the existing tooling.

Scope

New scope name metrics:

  • internal/database/model/model.go: ApiScopeMetrics = "metrics", add to IsKnownApiScope;
  • NormalizeScope in panel/api_token.go: accept it;
  • enforceTokenScope: case model.ApiScopeMetrics: with a method-scoped allowlist, reusing the
    existing scopeAllows/nodeSyncScopeAllow pattern (api.go:131):
var metricsScopeAllow = map[string]map[string]struct{}{
    "/server/status":  {http.MethodGet: {}},
    "/server/metrics": {http.MethodGet: {}},
}

/server/status is included on purpose: it is already available to monitor tokens and lets a client
run a cheap preflight without touching the aggregate endpoint.

  • UI: add metrics to the scope selector + the four i18n locales;
  • docs: docs/content/docs/*/reference/api/api-tokens.mdx are generated — regenerate and note that
    metrics is read-only over counters and that monitor is unchanged.

Properties

  • The invariants that make monitor safe stay intact: no POST, no config, no secrets.
  • A leaked metrics token reveals traffic volumes and client emails — it is still a secret, so the
    docs should say "treat like any other credential, set an expiry".
  • Backwards compatible: admin, monitor, node-sync, node-admin untouched.

Non-goals

  • Do not widen the existing monitor scope — that would silently change the meaning of tokens
    already in the wild.
  • Do not add mutating methods to any read-only scope.
  • Do not add "2FA bypass for session login" flags; the token path already bypasses CheckUser
    correctly and is the safer primitive.

Tests

  • internal/web/service/panel/api_token_scope_test.go: metrics is known, normalized, and rejected
    for mutating routes.
  • Controller test: metrics token → 200 on /server/metrics and /server/status, 403 with the
    existing "this API token is not permitted to access this endpoint" on /inbounds/add,
    /setting/update, /clients/onlines.
  • Service test: GetInboundsMetrics never selects settings / stream_settings.

Acceptance criteria

  1. A metrics token can fetch everything a Prometheus exporter needs with GET-only calls.
  2. The same token cannot mutate anything and cannot read inbound/client credentials.
  3. monitor, admin, node-sync, node-admin behaviour is byte-for-byte unchanged.
  4. Docs list each scope with its exact endpoint/method allowlist.
Originally created by @OlegEnot on GitHub (Nov 4, 2026). Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/7069 ## Motivation A metrics collector cannot authenticate with this panel today unless it is given a **full-access `admin`** token: - **2FA is global and interactive.** `panel.UserService.CheckUser` verifies `twoFactorEnable` / `twoFactorToken` with `totp.VerifyWithSkew(...)` on every login, so a non-interactive client has no way through. Tokens bypass `CheckUser` entirely (`checkAPIAuth` → `c.Set("api_authed", true)`), which is exactly the right mechanism — but the only usable scope is `admin`. - **Session login is a poor fit anyway:** CSRF round-trip, the 5-fail/15-min login limiter, fail2ban counters and a 59-minute re-auth cycle in the client. So the ask is narrow: a token that can read *numbers*, not configuration. ## Current state (v3.11.0) Scopes: `admin`, `monitor`, `node-sync`, `node-admin` (`internal/database/model/model.go:167`, `NormalizeScope` in `internal/web/service/panel/api_token.go`). `monitorScopeAllow` (`internal/web/controller/api.go:82`) covers `GET /server/status`, `GET /server/history/*`, `GET /server/xrayMetrics*`, `GET /nodes/history/*`, and `enforceTokenScope` (`api.go:142`) only accepts it for `GET`/`HEAD`: ```go case model.ApiScopeMonitor: if _, allowed := monitorScopeAllow[rel]; allowed && (c.Request.Method == http.MethodGet || c.Request.Method == http.MethodHead) { ``` ## What a metrics collector actually reads | Call | Method | Data | | --- | --- | --- | | `/panel/api/server/status` | GET | xray version/state, panel version, threads, mem, uptime | | inbounds list | GET | per-inbound `id`/`remark`/`up`/`down`, per-client `id`/`email`/`up`/`down` | | `/panel/api/clients/onlines` | POST | `[]email` — count of online users | `monitor` covers the first, misses the other two. `admin` covers all three and also lets the holder rewrite inbounds, read the DB, and mint more tokens. ## Why the existing endpoints cannot simply be reused `GET /panel/api/inbounds/list` returns the `model.Inbound` row as-is, including: - `StreamSettings` — for VLESS Reality this contains `realitySettings.privateKey`; - `Settings` — top-level keys such as WireGuard `secretKey` are **not** removed by the slimming helper (`slimSettingsClients`, `internal/web/service/inbound.go:257`); it only rewrites `settings.clients[]`; - per-client emails and traffic. `GET /panel/api/inbounds/list/slim` (`controller/inbound.go:113`) strips only `settings.clients[]`, but still ships `streamSettings` and all other `settings` keys. Handing that to a container in a monitoring stack is a credential leak, not a read-only metrics grant. Allowing `POST /clients/onlines` in a "read-only" scope is also a smell: the scope's safety property today is "GET/HEAD only", and it is worth keeping. ## Proposal: one aggregate GET endpoint + a GET-only scope ### Endpoint `GET /panel/api/server/metrics` ```json { "success": true, "obj": { "panelVersion": "3.11.0", "xray": { "version": "25.9.11", "state": "running", "errorMsg": "" }, "appStats": { "threads": 42, "mem": 73400320, "uptime": 86400 }, "onlineClients": 12, "inbounds": [ { "id": 1, "remark": "VLESS-443", "enable": true, "up": 1048576, "down": 8388608, "clients": [ { "id": 7, "email": "user@example", "up": 1024, "down": 2048 } ] } ] } } ``` - Only counters and labels a dashboard needs — no `settings`, no `streamSettings`, no UUIDs, passwords, sub-ids or node credentials. - `onlineClients` is a count, so the collector needs **no POST at all**, and the scope stays GET-only. - Implementation reuses existing services: `GetOnlineClients()` for the count and a new `GetInboundsMetrics(userId)` that selects `id, remark, enable, up, down` plus the preloaded `ClientStats` (same `Preload` as `GetInbounds`, no settings columns). No schema change, no migration. - It is one handler in `ServerController` (`controller/server.go`) plus one service method; the OpenAPI spec and docs regenerate from the existing tooling. ### Scope New scope name `metrics`: - `internal/database/model/model.go`: `ApiScopeMetrics = "metrics"`, add to `IsKnownApiScope`; - `NormalizeScope` in `panel/api_token.go`: accept it; - `enforceTokenScope`: `case model.ApiScopeMetrics:` with a **method-scoped** allowlist, reusing the existing `scopeAllows`/`nodeSyncScopeAllow` pattern (`api.go:131`): ```go var metricsScopeAllow = map[string]map[string]struct{}{ "/server/status": {http.MethodGet: {}}, "/server/metrics": {http.MethodGet: {}}, } ``` `/server/status` is included on purpose: it is already available to `monitor` tokens and lets a client run a cheap preflight without touching the aggregate endpoint. - UI: add `metrics` to the scope selector + the four i18n locales; - docs: `docs/content/docs/*/reference/api/api-tokens.mdx` are generated — regenerate and note that `metrics` is read-only over counters and that `monitor` is unchanged. ### Properties - The invariants that make `monitor` safe stay intact: no POST, no config, no secrets. - A leaked metrics token reveals traffic volumes and client emails — it is still a secret, so the docs should say "treat like any other credential, set an expiry". - Backwards compatible: `admin`, `monitor`, `node-sync`, `node-admin` untouched. ## Non-goals - Do **not** widen the existing `monitor` scope — that would silently change the meaning of tokens already in the wild. - Do not add mutating methods to any read-only scope. - Do not add "2FA bypass for session login" flags; the token path already bypasses `CheckUser` correctly and is the safer primitive. ## Tests - `internal/web/service/panel/api_token_scope_test.go`: `metrics` is known, normalized, and rejected for mutating routes. - Controller test: `metrics` token → 200 on `/server/metrics` and `/server/status`, 403 with the existing `"this API token is not permitted to access this endpoint"` on `/inbounds/add`, `/setting/update`, `/clients/onlines`. - Service test: `GetInboundsMetrics` never selects `settings` / `stream_settings`. ## Acceptance criteria 1. A `metrics` token can fetch everything a Prometheus exporter needs with GET-only calls. 2. The same token cannot mutate anything and cannot read inbound/client credentials. 3. `monitor`, `admin`, `node-sync`, `node-admin` behaviour is byte-for-byte unchanged. 4. Docs list each scope with its exact endpoint/method allowlist.
Author
Owner

@OlegEnot commented on GitHub (Nov 4, 2026):

Client side: the metrics exporter that needs this is hteppl/3x-ui-exporter#19 (Bearer auth + preflight). With a metrics token it would call only GET /server/status and GET /server/metrics, and needs neither inbounds/list nor the POST /clients/onlines route.

<!-- gh-comment-id:6640008869 --> @OlegEnot commented on GitHub (Nov 4, 2026): Client side: the metrics exporter that needs this is hteppl/3x-ui-exporter#19 (Bearer auth + preflight). With a `metrics` token it would call only `GET /server/status` and `GET /server/metrics`, and needs neither `inbounds/list` nor the `POST /clients/onlines` route.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#6608
No description provided.