From 7f960f2d24c8919235751a96cd094f968845e28c Mon Sep 17 00:00:00 2001 From: Louis Huang Date: Mon, 2 Nov 2026 19:18:49 +0900 Subject: [PATCH 1/2] feat: add stats data scope for API keys Currently, runtime and token usage statistics require dashboard authentication because their endpoints use the system scope, which developer API keys cannot access. External collectors therefore need dashboard credentials. We hence add a read-only stats scope for the two existing statistics endpoints /api/v1/stats and /api/v1/stats/provider-tokens. The scope needs opt-in (requires explicit selection) so existing keys and default permissions remain unchanged. --- astrbot/dashboard/api/stats.py | 6 +- astrbot/dashboard/services/auth_service.py | 1 + .../src/api/generated/openapi-v1/types.gen.ts | 2 +- docs/en/dev/openapi-scopes.md | 9 +++ docs/public/openapi.json | 61 +++++++++++++++- docs/scripts/update_openapi_json.py | 1 + docs/zh/dev/openapi-scopes.md | 9 +++ openspec/openapi-v1.yaml | 13 ++-- tests/test_fastapi_v1_dashboard.py | 69 +++++++++++++++++++ tests/unit/test_openapi_scope_docs.py | 3 + 10 files changed, 164 insertions(+), 10 deletions(-) diff --git a/astrbot/dashboard/api/stats.py b/astrbot/dashboard/api/stats.py index 78b3943c2e7..97458144ace 100644 --- a/astrbot/dashboard/api/stats.py +++ b/astrbot/dashboard/api/stats.py @@ -11,7 +11,7 @@ ) from astrbot.dashboard.services.stat_service import StatService, StatServiceError -from .auth import AuthContext, require_dashboard_user, require_scope +from .auth import AuthContext, ScopeDependency, require_dashboard_user, require_scope router = APIRouter(tags=["System Stats"]) legacy_router = APIRouter( @@ -55,7 +55,7 @@ def _parse_int(value: object, default: int, name: str) -> int: @router.get("/stats") async def get_stats( offset_sec: int = Query(default=86400), - _auth: AuthContext = Depends(require_system_scope), + _auth: AuthContext = Depends(ScopeDependency("stats")), service: StatService = Depends(get_service), ): return await _run(service.get_stat(offset_sec)) @@ -64,7 +64,7 @@ async def get_stats( @router.get("/stats/provider-tokens") async def get_provider_token_stats( days: int = Query(default=1), - _auth: AuthContext = Depends(require_system_scope), + _auth: AuthContext = Depends(ScopeDependency("stats")), service: StatService = Depends(get_service), ): return await _run(service.get_provider_token_stats(days)) diff --git a/astrbot/dashboard/services/auth_service.py b/astrbot/dashboard/services/auth_service.py index 4ff021f06eb..8f824ba61ac 100644 --- a/astrbot/dashboard/services/auth_service.py +++ b/astrbot/dashboard/services/auth_service.py @@ -71,6 +71,7 @@ ALL_OPEN_API_SCOPES = ( *DEFAULT_OPEN_API_SCOPES, + "stats", CHAT_ADMIN_SCOPE, CONFIG_EDIT_ADMIN_SCOPE, ) diff --git a/dashboard/src/api/generated/openapi-v1/types.gen.ts b/dashboard/src/api/generated/openapi-v1/types.gen.ts index 21a6bc42371..0c957899bed 100644 --- a/dashboard/src/api/generated/openapi-v1/types.gen.ts +++ b/dashboard/src/api/generated/openapi-v1/types.gen.ts @@ -274,7 +274,7 @@ export type ConversationRef = { export type CreateApiKeyRequest = { name: string; - scopes?: Array<('bot' | 'provider' | 'persona' | 'im' | 'config' | 'config:edit_admin' | 'chat' | 'chat:admin' | 'data' | 'file' | 'plugin' | 'mcp' | 'skill')>; + scopes?: Array<('bot' | 'provider' | 'persona' | 'im' | 'config' | 'config:edit_admin' | 'chat' | 'chat:admin' | 'data' | 'file' | 'plugin' | 'mcp' | 'skill' | 'stats')>; expires_at?: string; expires_in_days?: number; }; diff --git a/docs/en/dev/openapi-scopes.md b/docs/en/dev/openapi-scopes.md index d7fe11a0d67..93c17a2c9ef 100644 --- a/docs/en/dev/openapi-scopes.md +++ b/docs/en/dev/openapi-scopes.md @@ -331,3 +331,12 @@ Manage Skills, archives, files, and Shipyard Neo Skill workflows. | `GET` | `/api/v1/skills/{skill_name}/files` | — | | `GET` | `/api/v1/skills/{skill_name}/files/{file_path}` | — | | `PUT` | `/api/v1/skills/{skill_name}/files/{file_path}` | — | + +## `stats` + +Read runtime and token usage statistics. + +| Method | Endpoint | Conditional sensitive sub-scope | +| --- | --- | --- | +| `GET` | `/api/v1/stats` | — | +| `GET` | `/api/v1/stats/provider-tokens` | — | diff --git a/docs/public/openapi.json b/docs/public/openapi.json index d9ce07ffc25..d8fe48ce60b 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -3,9 +3,13 @@ "info": { "title": "AstrBot OpenAPI v1", "version": "0.1.0", - "description": "Target REST contract for migrating AstrBot HTTP APIs to /api/v1. Dynamic AstrBot configuration payloads are intentionally modeled as open JSON objects because their schemas are provided at runtime by template endpoints. Developer API keys currently support these scopes only: bot, provider, persona, im, config, chat, data, file, plugin, mcp, skill, plus the sensitive config:edit_admin and chat:admin sub-scopes. The config scope also grants bot and provider access, but no parent scope grants a sensitive sub-scope.\n" + "description": "Target REST contract for migrating AstrBot HTTP APIs to /api/v1. Dynamic AstrBot configuration payloads are intentionally modeled as open JSON objects because their schemas are provided at runtime by template endpoints. Developer API keys currently support these scopes only: bot, provider, persona, im, config, chat, data, file, plugin, mcp, skill, stats, plus the sensitive config:edit_admin and chat:admin sub-scopes. The config scope also grants bot and provider access, but no parent scope grants a sensitive sub-scope.\n" }, "x-astrbot-scope-definitions": { + "stats": { + "description": "Read runtime and token usage statistics.", + "description_zh": "读取运行状态和 Token 使用统计。" + }, "bot": { "description": "Manage bot and platform configurations.", "description_zh": "管理机器人及平台配置。" @@ -133,6 +137,9 @@ { "name": "Conversations" }, + { + "name": "Stats" + }, { "name": "T2I" }, @@ -6741,6 +6748,58 @@ "description": "**Required scope:** `data`" } }, + "/api/v1/stats": { + "get": { + "tags": [ + "Stats" + ], + "summary": "Get runtime statistics", + "operationId": "getStats", + "x-astrbot-scope": "stats", + "parameters": [ + { + "name": "offset_sec", + "in": "query", + "schema": { + "type": "integer", + "default": 86400 + } + } + ], + "responses": { + "200": { + "$ref": "#/components/responses/Ok" + } + }, + "description": "**Required scope:** `stats`" + } + }, + "/api/v1/stats/provider-tokens": { + "get": { + "tags": [ + "Stats" + ], + "summary": "Get provider token usage statistics", + "operationId": "getProviderTokenStats", + "x-astrbot-scope": "stats", + "parameters": [ + { + "name": "days", + "in": "query", + "schema": { + "type": "integer", + "minimum": 1 + } + } + ], + "responses": { + "200": { + "$ref": "#/components/responses/Ok" + } + }, + "description": "**Required scope:** `stats`" + } + }, "/api/v1/t2i/templates": { "get": { "tags": [ diff --git a/docs/scripts/update_openapi_json.py b/docs/scripts/update_openapi_json.py index 04516cd28a5..3b565bab337 100644 --- a/docs/scripts/update_openapi_json.py +++ b/docs/scripts/update_openapi_json.py @@ -26,6 +26,7 @@ "plugin", "mcp", "skill", + "stats", ) PUBLIC_OPEN_API_EXCLUDED_PATHS = { "/api/v1/live-chat/ws", diff --git a/docs/zh/dev/openapi-scopes.md b/docs/zh/dev/openapi-scopes.md index 9bce064d2ef..a1dbba3f0bf 100644 --- a/docs/zh/dev/openapi-scopes.md +++ b/docs/zh/dev/openapi-scopes.md @@ -331,3 +331,12 @@ outline: deep | `GET` | `/api/v1/skills/{skill_name}/files` | — | | `GET` | `/api/v1/skills/{skill_name}/files/{file_path}` | — | | `PUT` | `/api/v1/skills/{skill_name}/files/{file_path}` | — | + +## `stats` + +读取运行状态和 Token 使用统计。 + +| 方法 | 接口 | 条件性敏感子权限 | +| --- | --- | --- | +| `GET` | `/api/v1/stats` | — | +| `GET` | `/api/v1/stats/provider-tokens` | — | diff --git a/openspec/openapi-v1.yaml b/openspec/openapi-v1.yaml index b6d5884bd6f..09d90831b68 100644 --- a/openspec/openapi-v1.yaml +++ b/openspec/openapi-v1.yaml @@ -8,10 +8,13 @@ info: JSON objects because their schemas are provided at runtime by template endpoints. Developer API keys currently support these scopes only: bot, provider, - persona, im, config, chat, data, file, plugin, mcp, skill, plus the sensitive + persona, im, config, chat, data, file, plugin, mcp, skill, stats, plus the sensitive config:edit_admin and chat:admin sub-scopes. The config scope also grants bot and provider access, but no parent scope grants a sensitive sub-scope. x-astrbot-scope-definitions: + stats: + description: Read runtime and token usage statistics. + description_zh: 读取运行状态和 Token 使用统计。 bot: description: Manage bot and platform configurations. description_zh: 管理机器人及平台配置。 @@ -4583,7 +4586,7 @@ paths: tags: [Stats] summary: Get runtime statistics operationId: getStats - x-astrbot-scope: system + x-astrbot-scope: stats parameters: - name: offset_sec in: query @@ -4599,7 +4602,7 @@ paths: tags: [Stats] summary: Get provider token usage statistics operationId: getProviderTokenStats - x-astrbot-scope: system + x-astrbot-scope: stats parameters: - name: days in: query @@ -5833,8 +5836,8 @@ components: type: array items: type: string - enum: [bot, provider, persona, im, config, "config:edit_admin", chat, "chat:admin", data, file, plugin, mcp, skill] - example: [bot, provider, persona, im, config, "config:edit_admin", chat, "chat:admin", data, file, plugin, mcp, skill] + enum: [bot, provider, persona, im, config, "config:edit_admin", chat, "chat:admin", data, file, plugin, mcp, skill, stats] + example: [bot, provider, persona, im, config, "config:edit_admin", chat, "chat:admin", data, file, plugin, mcp, skill, stats] expires_at: type: string format: date-time diff --git a/tests/test_fastapi_v1_dashboard.py b/tests/test_fastapi_v1_dashboard.py index 2fc86f71c18..946407ff503 100644 --- a/tests/test_fastapi_v1_dashboard.py +++ b/tests/test_fastapi_v1_dashboard.py @@ -5255,3 +5255,72 @@ async def test_bot_delete_cleanup_query_is_validated(asgi_app, asgi_client, rout invalid = await asgi_client.delete(route, params={"bot_id": "bot", "cleanup": "unknown"}, headers=_jwt_headers()) assert invalid.status_code == 422 assert delete_bot.await_count == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("path", "method"), + [ + ("/api/v1/stats", "get_stat"), + ("/api/v1/stats/provider-tokens", "get_provider_token_stats"), + ], +) +async def test_v1_stats_scope( + asgi_client: httpx.AsyncClient, + fake_db: FakeDb, + monkeypatch: pytest.MonkeyPatch, + path: str, + method: str, +): + from astrbot.dashboard.services.stat_service import StatService + + operation = AsyncMock(return_value={"sample": 42}) + monkeypatch.setattr(StatService, method, operation) + fake_db.add_api_key("abk_stats_only", scopes=["stats"]) + fake_db.add_api_key("abk_without_stats", scopes=["bot"]) + + for headers, expected in [ + ({}, 401), + ({"X-API-Key": "invalid"}, 401), + ({"X-API-Key": "abk_without_stats"}, 403), + ({"X-API-Key": "abk_stats_only"}, 200), + (_jwt_headers(), 200), + ]: + response = await asgi_client.get(path, headers=headers) + assert response.status_code == expected + if expected == 200: + assert response.json()["data"] == {"sample": 42} + assert operation.await_count == 2 + + +@pytest.mark.asyncio +async def test_v1_stats_scope_cannot_perform_admin_actions( + asgi_client: httpx.AsyncClient, + fake_db: FakeDb, + monkeypatch: pytest.MonkeyPatch, +): + from astrbot.dashboard.services.stat_service import StatService + + restart = AsyncMock() + cleanup = AsyncMock() + monkeypatch.setattr(StatService, "restart_core", restart) + monkeypatch.setattr(StatService, "cleanup_storage", cleanup) + fake_db.add_api_key("abk_stats_only", scopes=["stats"]) + for path, payload in [ + ("/api/v1/system/restart", {}), + ("/api/v1/stats/storage/cleanup", {"target": "traces"}), + ]: + response = await asgi_client.post( + path, json=payload, headers={"X-API-Key": "abk_stats_only"} + ) + assert response.status_code == 403 + restart.assert_not_awaited() + cleanup.assert_not_awaited() + + +def test_stats_scope_is_explicitly_opt_in(): + from astrbot.dashboard.services.auth_service import DEFAULT_OPEN_API_SCOPES + + assert ApiKeyService._normalize_scopes(["stats"]) == ["stats"] + assert "stats" not in ApiKeyService._normalize_scopes(None) + assert "stats" not in DEFAULT_OPEN_API_SCOPES diff --git a/tests/unit/test_openapi_scope_docs.py b/tests/unit/test_openapi_scope_docs.py index 902069cec64..ca894bb70c1 100644 --- a/tests/unit/test_openapi_scope_docs.py +++ b/tests/unit/test_openapi_scope_docs.py @@ -29,6 +29,9 @@ def test_public_openapi_is_filtered_by_supported_scope() -> None: assert "/api/v1/files/tokens/{file_token}" not in spec["paths"] assert "/api/v1/stats/versions" not in spec["paths"] + for path in ("/api/v1/stats", "/api/v1/stats/provider-tokens"): + assert spec["paths"][path]["get"]["x-astrbot-scope"] == "stats" + for methods in spec["paths"].values(): for operation in methods.values(): assert operation["x-astrbot-scope"] in PUBLIC_OPEN_API_SCOPES From 146391ba7fd7cd33a9b26fc8d6fcf9fc0852c4cc Mon Sep 17 00:00:00 2001 From: Louis Huang Date: Mon, 2 Nov 2026 19:19:20 +0900 Subject: [PATCH 2/2] feat: expose stats scope in API key settings Enable developers to select "stats" permission through the existing key creation interface. --- .../src/i18n/locales/en-US/features/settings.json | 1 + .../src/i18n/locales/ja-JP/features/settings.json | 1 + .../src/i18n/locales/ru-RU/features/settings.json | 1 + .../src/i18n/locales/zh-CN/features/settings.json | 1 + dashboard/src/views/Settings.vue | 1 + docs/en/dev/openapi.md | 11 ++++++++++- docs/zh/dev/openapi.md | 11 ++++++++++- 7 files changed, 25 insertions(+), 2 deletions(-) diff --git a/dashboard/src/i18n/locales/en-US/features/settings.json b/dashboard/src/i18n/locales/en-US/features/settings.json index 3a1c9990b4b..bf5c80d5c1f 100644 --- a/dashboard/src/i18n/locales/en-US/features/settings.json +++ b/dashboard/src/i18n/locales/en-US/features/settings.json @@ -282,6 +282,7 @@ "createConfirm": "Create an API key with the following scopes?\n\n{scopes}", "sensitiveCreateConfirm": "You are about to create an API key with these high-risk scopes:\n\n{scopes}\n\nThe holder may gain administrator capabilities. Continue?", "scopeDescriptions": { + "stats": "Read runtime and token usage statistics (includes plugin and session breakdowns).", "bot": "Read and manage bot and platform configurations.", "provider": "Read and manage model providers.", "persona": "Read and manage personas.", diff --git a/dashboard/src/i18n/locales/ja-JP/features/settings.json b/dashboard/src/i18n/locales/ja-JP/features/settings.json index e357ce5c9e5..ea18df0c0ef 100644 --- a/dashboard/src/i18n/locales/ja-JP/features/settings.json +++ b/dashboard/src/i18n/locales/ja-JP/features/settings.json @@ -282,6 +282,7 @@ "createConfirm": "次の権限を持つ API キーを作成しますか?\n\n{scopes}", "sensitiveCreateConfirm": "次の高リスク権限を持つ API キーを作成しようとしています:\n\n{scopes}\n\nこの API キーの所持者が管理者権限を取得する可能性があります。続行しますか?", "scopeDescriptions": { + "stats": "実行状態とトークン使用統計を読み取ります(プラグインとセッションの内訳を含む)。", "bot": "ボットとプラットフォームの設定を読み取り、管理します。", "provider": "モデルプロバイダーを読み取り、管理します。", "persona": "ペルソナを読み取り、管理します。", diff --git a/dashboard/src/i18n/locales/ru-RU/features/settings.json b/dashboard/src/i18n/locales/ru-RU/features/settings.json index d68bd493498..f152894e1db 100644 --- a/dashboard/src/i18n/locales/ru-RU/features/settings.json +++ b/dashboard/src/i18n/locales/ru-RU/features/settings.json @@ -282,6 +282,7 @@ "createConfirm": "Создать API-ключ со следующими областями доступа?\n\n{scopes}", "sensitiveCreateConfirm": "Будет создан API-ключ со следующими высокорисковыми правами:\n\n{scopes}\n\nВладелец может получить административные возможности. Продолжить?", "scopeDescriptions": { + "stats": "Чтение статистики работы и токенов, включая данные плагинов и сессий.", "bot": "Чтение и управление конфигурациями бота и платформ.", "provider": "Чтение и управление провайдерами моделей.", "persona": "Чтение и управление персонами.", diff --git a/dashboard/src/i18n/locales/zh-CN/features/settings.json b/dashboard/src/i18n/locales/zh-CN/features/settings.json index f0b96458d38..a5ad3a958eb 100644 --- a/dashboard/src/i18n/locales/zh-CN/features/settings.json +++ b/dashboard/src/i18n/locales/zh-CN/features/settings.json @@ -282,6 +282,7 @@ "createConfirm": "确认创建具有以下权限的 API Key 吗?\n\n{scopes}", "sensitiveCreateConfirm": "即将创建包含以下高风险权限的 API Key:\n\n{scopes}\n\n持有者可能获得管理员能力。确认继续吗?", "scopeDescriptions": { + "stats": "读取运行状态和 Token 使用统计(包括插件和会话明细)。", "bot": "读取和管理机器人及平台配置。", "provider": "读取和管理模型服务提供商。", "persona": "读取和管理人格设定。", diff --git a/dashboard/src/views/Settings.vue b/dashboard/src/views/Settings.vue index a76285ea6bd..37588fb9c69 100644 --- a/dashboard/src/views/Settings.vue +++ b/dashboard/src/views/Settings.vue @@ -601,6 +601,7 @@ const apiKeyExpiryOptions = computed(() => [ ]); const availableScopes = [ + { value: 'stats', label: 'stats', descriptionKey: 'apiKey.scopeDescriptions.stats' }, { value: 'bot', label: 'bot', descriptionKey: 'apiKey.scopeDescriptions.bot' }, { value: 'provider', label: 'provider', descriptionKey: 'apiKey.scopeDescriptions.provider' }, { value: 'persona', label: 'persona', descriptionKey: 'apiKey.scopeDescriptions.persona' }, diff --git a/docs/en/dev/openapi.md b/docs/en/dev/openapi.md index 51304942652..a04a5948d53 100644 --- a/docs/en/dev/openapi.md +++ b/docs/en/dev/openapi.md @@ -38,7 +38,7 @@ If the API Key does not include the required scope for the target endpoint, the - `config:edit_admin` and `chat:admin` must be granted explicitly and are never inherited from their parent scopes. - Deselecting `bot` or `provider` in the WebUI also removes the dependent `config` scope. -Developer API keys currently support 11 top-level scopes and two sensitive sub-scopes. `tool`, `skills`, `kb`, and `system` are not valid developer API key scopes. Use the singular `skill` scope for `/api/v1/skills/*` endpoints. +Developer API keys currently support 12 top-level scopes and two sensitive sub-scopes. `tool`, `skills`, `kb`, and `system` are not valid developer API key scopes. Use the singular `skill` scope for `/api/v1/skills/*` endpoints. Every operation in the interactive reference also displays `Required scope: ...`; operations involving administrator capabilities additionally display `Conditional sensitive scope: ...`. @@ -163,3 +163,12 @@ curl -N 'http://localhost:6185/api/v1/chat' \ Use the interactive docs: - https://docs.astrbot.app/scalar.html + +## Read statistics + +In Settings → OpenAPI, create a key with `stats` scope. + +```sh +curl -H "Authorization: Bearer abk_xxx" "http://localhost:6185/api/v1/stats" +curl -H "Authorization: Bearer abk_xxx" "http://localhost:6185/api/v1/stats/provider-tokens?days=1" +``` diff --git a/docs/zh/dev/openapi.md b/docs/zh/dev/openapi.md index 780a5669f98..f450a57123c 100644 --- a/docs/zh/dev/openapi.md +++ b/docs/zh/dev/openapi.md @@ -38,7 +38,7 @@ X-API-Key: abk_xxx - `config:edit_admin` 和 `chat:admin` 必须显式授予,不会随父 scope 隐式获得。 - WebUI 中取消 `bot` 或 `provider` 时,会同步取消依赖它们的 `config`。 -当前开发者 API Key 开放 11 个顶级 scope 和 2 个敏感子权限。`tool`、`skills`、`kb`、`system` 暂不支持作为开发者 API Key scope。`/api/v1/skills/*` 接口使用单数 `skill` scope,不使用复数 `skills`。 +当前开发者 API Key 开放 12 个顶级 scope 和 2 个敏感子权限。`tool`、`skills`、`kb`、`system` 暂不支持作为开发者 API Key scope。`/api/v1/skills/*` 接口使用单数 `skill` scope,不使用复数 `skills`。 交互式文档中的每个接口也会显示英文标签 `Required scope: ...`;涉及管理员能力时,还会显示 `Conditional sensitive scope: ...`。 @@ -164,3 +164,12 @@ curl -N 'http://localhost:6185/api/v1/chat' \ 交互式 API 文档请查看: - https://docs.astrbot.app/scalar.html + +## 读取统计数据 + +在设置 → OpenAPI 中创建 API Key,选择 `stats` 权限。 + +```sh +curl -H "Authorization: Bearer abk_xxx" "http://localhost:6185/api/v1/stats" +curl -H "Authorization: Bearer abk_xxx" "http://localhost:6185/api/v1/stats/provider-tokens?days=1" +```