feat(security): add read-only scopes for remaining resources

This commit is contained in:
whyour committed 2026-11-03 00:57:47 +08:00
1 parent be8721204b
commit 866c7f4b98
12 files changed
+172 -12

No files matched your search

+19 -1
View File
@@ -24,7 +24,25 @@ export interface AppToken {
expiration: number;
}
export type AppScope = 'envs' | 'envs:read' | 'crons' | 'configs' | 'configs:read' | 'scripts' | 'scripts:read' | 'logs' | 'system' | 'dashboard';
export type AppScope =
| 'crons'
| 'crons:read'
| 'subscriptions'
| 'subscriptions:read'
| 'envs'
| 'envs:read'
| 'configs'
| 'configs:read'
| 'scripts'
| 'scripts:read'
| 'logs'
| 'logs:read'
| 'dependencies'
| 'dependencies:read'
| 'dashboard'
| 'dashboard:read'
| 'system'
| 'apps';
export interface AppInstance extends Model<App, App>, App {}
export const AppModel = sequelize.define<AppInstance>('App', {
+18 -6
View File
@@ -113,13 +113,25 @@ export default ({ app }: { app: Application }) => {
const key = keyMatch && keyMatch[1];
const isReadRequest =
['GET', 'HEAD'].includes(req.method) ||
(key === 'scripts' &&
(['GET', 'HEAD'].includes(req.method) &&
!(
key === 'crons' && /^\/open\/crons\/import\/?$/.test(pathLower)
)) ||
(['scripts', 'logs'].includes(key || '') &&
req.method === 'POST' &&
/^\/open\/scripts\/download\/?$/.test(pathLower));
/^\/open\/(?:scripts|logs)\/download\/?$/.test(pathLower));
const hasNamespaceScope =
doc.scopes.includes(key as AppScope) ||
(['envs', 'configs', 'scripts'].includes(key || '') &&
([
'crons',
'subscriptions',
'envs',
'configs',
'scripts',
'logs',
'dependencies',
'dashboard',
].includes(key || '') &&
doc.scopes.includes(`${key}:read` as AppScope) &&
isReadRequest);
if (!hasNamespaceScope) {
@@ -131,11 +143,11 @@ export default ({ app }: { app: Application }) => {
// The built-in system app still needs its local CLI maintenance API.
const appRouteAllowed =
(key !== 'system' ||
key !== 'system' ||
doc.name === 'system' ||
((req.method === 'GET' || req.method === 'HEAD') &&
(pathLower === '/open/system' || pathLower === '/open/system/')) ||
(req.method === 'PUT' && pathLower === '/open/system/notify'));
(req.method === 'PUT' && pathLower === '/open/system/notify');
if (!appRouteAllowed) {
const err = new UnauthorizedError('credentials_bad_scheme', {
message: t('暂无权限'),
+1 -1
View File
@@ -68,7 +68,7 @@ Protected requests use `Authorization: Bearer <token>`. Two credential sources a
### Application login
Create a dedicated panel application with the required scopes, such as crons or subscriptions. Existing `envs`, `configs`, and `scripts` scopes retain read and write access; `scripts` also permits running and stopping scripts. For read-only access, use `envs:read`, `configs:read`, or `scripts:read` respectively. Script download uses POST but is available to `scripts:read`. `login` and `auth login` are equivalent. Interactive login hides the Client Secret; secret command-line arguments are not supported.
Create a dedicated panel application with the required scopes. Existing scopes retain their original permissions. For read-only access, use `crons:read`, `subscriptions:read`, `envs:read`, `configs:read`, `scripts:read`, `dependencies:read`, `logs:read`, or `dashboard:read`. Script and log downloads use POST but are available to their read-only scopes. `GET /crons/import` writes tasks and is excluded from `crons:read`. `login` and `auth login` are equivalent. Interactive login hides the Client Secret; secret command-line arguments are not supported.
```sh
ql login --url https://ql.example.com
+1 -1
View File
@@ -68,7 +68,7 @@ ql api request PUT /open/crons/run --data '[12,13]' --json
### 应用凭据登录
在面板创建专用应用,按需授予 crons、subscriptions 等权限。现有 `envs`、`configs`、`scripts` scope 保留读写能力,`scripts` 还可运行和停止脚本;仅读取时分别选用 `envs:read`、`configs:read`、`scripts:read`。脚本下载虽然使用 POST,也允许 `scripts:read`。`login` 与 `auth login` 等价;交互输入 Client ID 和不回显的 Client Secret,密钥不支持命令行参数。
在面板创建专用应用,按需授予 crons、subscriptions 等权限。旧 scope 保留原有权限;仅读取时可选用 `crons:read`、`subscriptions:read`、`envs:read`、`configs:read`、`scripts:read`、`dependencies:read`、`logs:read`、`dashboard:read`。脚本和日志下载虽使用 POST,也允许对应只读权限;`GET /crons/import` 会写入任务,不属于只读操作。`login` 与 `auth login` 等价;交互输入 Client ID 和不回显的 Client Secret,密钥不支持命令行参数。
```sh
ql login --url https://ql.example.com
@@ -6,13 +6,13 @@ The catalogue covers 146 active routes in the current backend. `ql api routes --
## 认证与权限 / Authentication and permissions
常规使用 `ql login` 的应用凭据。scope 通常对应 /open 后首个路径段:crons、subscriptions、envs、configs、scripts、logs、dependencies、system、dashboard 等。旧的 `envs`、`configs`、`scripts` 保留原有完整权限;仅读取时分别使用 `envs:read`、`configs:read`、`scripts:read`。`scripts:read` 包含使用 POST 的脚本下载,不包含保存、上传、删除、历史恢复、运行或停止。外部应用的 `system` scope 仅允许读取系统状态和发送通知。应用管理需要 apps;user、health、update 等路由同样接受服务端权限校验。面板 UI 当前没有列出全部这些 scope,不能把路由存在理解成现有应用已获授权。
常规使用 `ql login` 的应用凭据。scope 通常对应 /open 后首个路径段:crons、subscriptions、envs、configs、scripts、logs、dependencies、system、dashboard 等。旧 scope 保留原有权限;上述资源除 system 外可选用对应的 `:read` scope。`crons:read` 不包含会写入任务的 `GET /crons/import`;`scripts:read`、`logs:read` 包含使用 POST 的下载,不包含写入、删除或执行。`dashboard:read` 不允许 POST 统计上报。外部应用的 `system` scope 仅允许读取系统状态和发送通知。应用管理需要 apps;`GET /apps` 会返回 Client Secret,因此不提供 `apps:read`。user、health、update 等路由同样接受服务端权限校验。路由存在不代表现有应用已获授权。
认证步骤、环境变量优先级、应用登录、面板会话与双因素验证、退出行为,统一见 [认证参考](panel.md#authentication)。应用管理可用 apps 权限的应用或授权面板会话;QL_URL/QL_ACCESS_TOKEN 不保存、不刷新,不自动退回应用配置。
See the [authentication reference](panel.md#authentication) for application login, direct-token precedence, owner sessions/2FA and logout. App management accepts apps-scoped credentials or an authorized owner session. Direct tokens are not saved/refreshed and never fall back to application configuration.
Existing `envs`, `configs`, and `scripts` scopes retain full access. Use `envs:read`, `configs:read`, or `scripts:read` for read-only access. `scripts:read` includes script download (POST), but excludes saves, uploads, deletion, history restore, run, and stop. External `system` applications may only read system status and send notifications.
Existing scopes retain their original access. Use the resource's `:read` scope for read-only access to crons, subscriptions, envs, configs, scripts, dependencies, logs, or dashboard. `crons:read` excludes the mutating `GET /crons/import`; `scripts:read` and `logs:read` include downloads (POST), but exclude writes, deletion, and execution. `dashboard:read` excludes statistics reporting (POST). External `system` applications may only read system status and send notifications. `GET /apps` returns Client Secrets, so there is no `apps:read` scope.
`auth status --scope <scope>` tests a representative read; update has no read endpoint and is not offered by status. This does not prove permission for every write. `app list/create/update/reset-secret` 默认隐藏 client_secret/tokens;只有明确需要凭据时才加 --show-secrets,并避免把输出记录到共享日志。其他资源/通用请求可能含环境值、配置、脚本、订阅凭据和会话,按敏感数据处理。
+5
View File
@@ -110,6 +110,11 @@ export async function auth(
'envs:read': 'envs',
'configs:read': 'configs/files',
'scripts:read': 'scripts',
'crons:read': 'crons?page=1&size=1',
'subscriptions:read': 'subscriptions',
'dependencies:read': 'dependencies',
'logs:read': 'logs',
'dashboard:read': 'dashboard/overview',
dashboard: 'dashboard/overview',
} as Record<string, string>
)[scope] ?? scope,
+5
View File
@@ -29,6 +29,11 @@ export const commands: readonly CommandSpec[] = [
'envs:read',
'configs:read',
'scripts:read',
'crons:read',
'subscriptions:read',
'dependencies:read',
'logs:read',
'dashboard:read',
].filter((scope) => !['auth', 'update'].includes(scope)),
},
},
+8 -1
View File
@@ -82,7 +82,9 @@ async function fixture(t) {
data: { data: [{ id: 12, name: 'example' }], total: 1 },
});
else if (
['/panel/open/envs', '/panel/open/configs/files', '/panel/open/scripts']
['/panel/open/envs', '/panel/open/configs/files', '/panel/open/scripts',
'/panel/open/subscriptions', '/panel/open/dependencies',
'/panel/open/logs', '/panel/open/dashboard/overview']
.includes(url.pathname)
)
json({ code: 200, data: [] });
@@ -164,6 +166,11 @@ test('compiled entry: login aliases, private storage, status, refresh and local
['envs:read', '/panel/open/envs'],
['configs:read', '/panel/open/configs/files'],
['scripts:read', '/panel/open/scripts'],
['crons:read', '/panel/open/crons'],
['subscriptions:read', '/panel/open/subscriptions'],
['dependencies:read', '/panel/open/dependencies'],
['logs:read', '/panel/open/logs'],
['dashboard:read', '/panel/open/dashboard/overview'],
]) {
const checked = await f.invoke(['auth', 'status', '--scope', scope, '--json']);
assert.equal(checked.code, 0, checked.err);
+5
View File
@@ -112,6 +112,7 @@
"代理端口": "Proxy Port",
"以后再说": "Later",
"仪表盘": "Dashboard",
"仪表盘(只读)": "Dashboard (read only)",
"任务": "Task",
"任务数": "Tasks",
"任务未运行": "Task not running",
@@ -122,6 +123,7 @@
"使用手机应用扫描二维码,或者输入秘钥": "Scan the QR code with the mobile app or enter the key",
"依赖文件": "Dependency Files",
"依赖管理": "Dependency Management",
"依赖管理(只读)": "Dependencies (read only)",
"依赖类型": "Dependency Type",
"依赖缓存": "Dependency cache",
"依赖设置": "Dependence Settings",
@@ -230,6 +232,7 @@
"完成设置": "Finish Setup",
"定时": "Schedule",
"定时任务": "Scheduled Tasks",
"定时任务(只读)": "Scheduled Tasks (read only)",
"定时任务并发数": "Concurrent Scheduled Tasks",
"定时类型": "Schedule Type",
"定时规则": "Schedule Rule",
@@ -333,6 +336,7 @@
"日志名称只能包含中文、字母、数字、下划线、连字符、点和路径分隔符": "Log name can only contain Chinese characters, letters, numbers, underscores, hyphens, dots, and path separators",
"日志文件": "Log files",
"日志管理": "Log Management",
"日志管理(只读)": "Logs (read only)",
"时": "hour(s)",
"时区": "Timezone",
"是": "Yes",
@@ -512,6 +516,7 @@
"视图管理": "View Management",
"订阅": "Subscription",
"订阅管理": "Subscription Management",
"订阅管理(只读)": "Subscriptions (read only)",
"设置": "Settings",
"访问密钥": "Access Key",
"语言": "Language",
+5
View File
@@ -111,6 +111,7 @@
"代理端口": "代理端口",
"以后再说": "以后再说",
"仪表盘": "仪表盘",
"仪表盘(只读)": "仪表盘(只读)",
"任务": "任务",
"任务数": "任务数",
"任务未运行": "任务未运行",
@@ -121,6 +122,7 @@
"使用手机应用扫描二维码,或者输入秘钥": "使用手机应用扫描二维码,或者输入秘钥",
"依赖文件": "依赖文件",
"依赖管理": "依赖管理",
"依赖管理(只读)": "依赖管理(只读)",
"依赖类型": "依赖类型",
"依赖缓存": "依赖缓存",
"依赖设置": "依赖设置",
@@ -229,6 +231,7 @@
"完成设置": "完成设置",
"定时": "定时",
"定时任务": "定时任务",
"定时任务(只读)": "定时任务(只读)",
"定时任务并发数": "定时任务并发数",
"定时类型": "定时类型",
"定时规则": "定时规则",
@@ -332,6 +335,7 @@
"日志名称只能包含中文、字母、数字、下划线、连字符、点和路径分隔符": "日志名称只能包含中文、字母、数字、下划线、连字符、点和路径分隔符",
"日志文件": "日志文件",
"日志管理": "日志管理",
"日志管理(只读)": "日志管理(只读)",
"时": "时",
"时区": "时区",
"是": "是",
@@ -512,6 +516,7 @@
"视图管理": "视图管理",
"订阅": "订阅",
"订阅管理": "订阅管理",
"订阅管理(只读)": "订阅管理(只读)",
"设置": "设置",
"访问密钥": "访问密钥",
"语言": "语言",
+25
View File
@@ -20,6 +20,10 @@ export default {
name: intl.get('定时任务'),
value: 'crons',
},
{
name: intl.get('定时任务(只读)'),
value: 'crons:read',
},
{
name: intl.get('环境变量'),
value: 'envs',
@@ -32,6 +36,10 @@ export default {
name: intl.get('订阅管理'),
value: 'subscriptions',
},
{
name: intl.get('订阅管理(只读)'),
value: 'subscriptions:read',
},
{
name: intl.get('配置文件'),
value: 'configs',
@@ -52,10 +60,18 @@ export default {
name: intl.get('日志管理'),
value: 'logs',
},
{
name: intl.get('日志管理(只读)'),
value: 'logs:read',
},
{
name: intl.get('依赖管理'),
value: 'dependencies',
},
{
name: intl.get('依赖管理(只读)'),
value: 'dependencies:read',
},
{
name: intl.get('系统信息'),
value: 'system',
@@ -64,20 +80,29 @@ export default {
name: intl.get('仪表盘'),
value: 'dashboard',
},
{
name: intl.get('仪表盘(只读)'),
value: 'dashboard:read',
},
],
scopesMap: {
crons: intl.get('定时任务'),
'crons:read': intl.get('定时任务(只读)'),
envs: intl.get('环境变量'),
'envs:read': intl.get('环境变量(只读)'),
subscriptions: intl.get('订阅管理'),
'subscriptions:read': intl.get('订阅管理(只读)'),
configs: intl.get('配置文件'),
'configs:read': intl.get('配置文件(只读)'),
scripts: intl.get('脚本管理'),
'scripts:read': intl.get('脚本(只读)'),
logs: intl.get('日志管理'),
'logs:read': intl.get('日志管理(只读)'),
dependencies: intl.get('依赖管理'),
'dependencies:read': intl.get('依赖管理(只读)'),
system: intl.get('系统信息'),
dashboard: intl.get('仪表盘'),
'dashboard:read': intl.get('仪表盘(只读)'),
},
notificationModes: [
{ value: 'gotify', label: 'Gotify' },
+78
View File
@@ -89,9 +89,21 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
tokens: [{ value: 'internal-system', expiration: Date.now() / 1000 + 3600 }],
},
];
for (const scope of ['crons', 'subscriptions', 'dependencies', 'logs', 'dashboard']) {
for (const suffix of ['', ':read']) {
apps.push({
scopes: [`${scope}${suffix}`],
tokens: [{
value: `${scope}${suffix}-app`,
expiration: Date.now() / 1000 + 3600,
}],
});
}
}
let resetCalls = 0;
let commandCalls = 0;
let envWriteCalls = 0;
let scopedMutationCalls = 0;
let initialized = 0;
const User = class {};
const Script = class {
@@ -166,6 +178,27 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
envWriteCalls++;
res.json({ code: 200 });
});
for (const route of [
'/crons', '/subscriptions', '/dependencies', '/logs', '/dashboard/overview',
]) {
router.get(route, (_req, res) => res.json({ code: 200 }));
}
for (const [method, route] of [
['put', '/crons/run'],
['put', '/subscriptions/run'],
['post', '/dependencies'],
['delete', '/logs'],
['post', '/dashboard/record'],
['get', '/crons/import'],
]) {
router[method](route, (_req, res) => {
scopedMutationCalls++;
res.json({ code: 200 });
});
}
router.post('/logs/download', (_req, res) =>
res.json({ code: 200, data: 'downloaded' }),
);
router.get('/system', (_req, res) => res.json({ code: 200 }));
router.put('/system/notify', (_req, res) => res.json({ code: 200 }));
router.put('/system/auth/reset', (_req, res) => {
@@ -270,6 +303,51 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
200,
);
assert.equal(envWriteCalls, 1);
for (const [scope, readPath, method, writePath] of [
['crons', '/crons', 'PUT', '/crons/run'],
['subscriptions', '/subscriptions', 'PUT', '/subscriptions/run'],
['dependencies', '/dependencies', 'POST', '/dependencies'],
['logs', '/logs', 'DELETE', '/logs'],
['dashboard', '/dashboard/overview', 'POST', '/dashboard/record'],
]) {
for (const prefix of ['/open', '/panel/open']) {
assert.equal(
(await request(`${prefix}${readPath}`, `${scope}:read-app`)).body.code,
200,
);
assert.equal(
(await request(`${prefix}${writePath}`, `${scope}:read-app`, method))
.status,
401,
);
}
assert.equal(
(await request(`/open${writePath}`, `${scope}-app`, method)).body.code,
200,
);
}
assert.equal(scopedMutationCalls, 5);
for (const prefix of ['/open', '/panel/open']) {
assert.equal(
(await request(`${prefix}/crons/import`, 'crons:read-app')).status,
401,
);
assert.equal(
(await request(`${prefix}/logs/download`, 'logs:read-app', 'POST'))
.body.data,
'downloaded',
);
}
const importedWithHead = await fetch(
`http://127.0.0.1:${server.address().port}/open/crons/import`,
{ method: 'HEAD', headers: { Authorization: 'Bearer crons:read-app' } },
);
assert.equal(importedWithHead.status, 401);
assert.equal(
(await request('/open/crons/import', 'crons-app')).body.code,
200,
);
assert.equal(scopedMutationCalls, 6);
assert.equal(
(await request('/open/configs/detail?path=normal.txt', 'env-app')).status,
401,