Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions astrbot/dashboard/api/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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))
Expand All @@ -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))
Expand Down
1 change: 1 addition & 0 deletions astrbot/dashboard/services/auth_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@

ALL_OPEN_API_SCOPES = (
*DEFAULT_OPEN_API_SCOPES,
"stats",
CHAT_ADMIN_SCOPE,
CONFIG_EDIT_ADMIN_SCOPE,
)
Expand Down
2 changes: 1 addition & 1 deletion dashboard/src/api/generated/openapi-v1/types.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};
Expand Down
1 change: 1 addition & 0 deletions dashboard/src/i18n/locales/en-US/features/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
1 change: 1 addition & 0 deletions dashboard/src/i18n/locales/ja-JP/features/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,7 @@
"createConfirm": "次の権限を持つ API キーを作成しますか?\n\n{scopes}",
"sensitiveCreateConfirm": "次の高リスク権限を持つ API キーを作成しようとしています:\n\n{scopes}\n\nこの API キーの所持者が管理者権限を取得する可能性があります。続行しますか?",
"scopeDescriptions": {
"stats": "実行状態とトークン使用統計を読み取ります(プラグインとセッションの内訳を含む)。",
"bot": "ボットとプラットフォームの設定を読み取り、管理します。",
"provider": "モデルプロバイダーを読み取り、管理します。",
"persona": "ペルソナを読み取り、管理します。",
Expand Down
1 change: 1 addition & 0 deletions dashboard/src/i18n/locales/ru-RU/features/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,7 @@
"createConfirm": "Создать API-ключ со следующими областями доступа?\n\n{scopes}",
"sensitiveCreateConfirm": "Будет создан API-ключ со следующими высокорисковыми правами:\n\n{scopes}\n\nВладелец может получить административные возможности. Продолжить?",
"scopeDescriptions": {
"stats": "Чтение статистики работы и токенов, включая данные плагинов и сессий.",
"bot": "Чтение и управление конфигурациями бота и платформ.",
"provider": "Чтение и управление провайдерами моделей.",
"persona": "Чтение и управление персонами.",
Expand Down
1 change: 1 addition & 0 deletions dashboard/src/i18n/locales/zh-CN/features/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,7 @@
"createConfirm": "确认创建具有以下权限的 API Key 吗?\n\n{scopes}",
"sensitiveCreateConfirm": "即将创建包含以下高风险权限的 API Key:\n\n{scopes}\n\n持有者可能获得管理员能力。确认继续吗?",
"scopeDescriptions": {
"stats": "读取运行状态和 Token 使用统计(包括插件和会话明细)。",
"bot": "读取和管理机器人及平台配置。",
"provider": "读取和管理模型服务提供商。",
"persona": "读取和管理人格设定。",
Expand Down
1 change: 1 addition & 0 deletions dashboard/src/views/Settings.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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' },
Expand Down
9 changes: 9 additions & 0 deletions docs/en/dev/openapi-scopes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` | — |
11 changes: 10 additions & 1 deletion docs/en/dev/openapi.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: ...`.

Expand Down Expand Up @@ -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"
```
61 changes: 60 additions & 1 deletion docs/public/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": "管理机器人及平台配置。"
Expand Down Expand Up @@ -133,6 +137,9 @@
{
"name": "Conversations"
},
{
"name": "Stats"
},
{
"name": "T2I"
},
Expand Down Expand Up @@ -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": [
Expand Down
1 change: 1 addition & 0 deletions docs/scripts/update_openapi_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"plugin",
"mcp",
"skill",
"stats",
)
PUBLIC_OPEN_API_EXCLUDED_PATHS = {
"/api/v1/live-chat/ws",
Expand Down
9 changes: 9 additions & 0 deletions docs/zh/dev/openapi-scopes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` | — |
11 changes: 10 additions & 1 deletion docs/zh/dev/openapi.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: ...`。

Expand Down Expand Up @@ -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"
```
13 changes: 8 additions & 5 deletions openspec/openapi-v1.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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: 管理机器人及平台配置。
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
69 changes: 69 additions & 0 deletions tests/test_fastapi_v1_dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
3 changes: 3 additions & 0 deletions tests/unit/test_openapi_scope_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading