fix(security): preserve legacy scopes and add read-only access

This commit is contained in:
whyour committed 2026-11-03 00:18:53 +08:00
1 parent b0f15241d2
commit be8721204b
13 files changed
+141 -43

No files matched your search

+1 -1
View File
@@ -24,7 +24,7 @@ export interface AppToken {
expiration: number;
}
export type AppScope = 'envs' | 'envs:write' | 'crons' | 'configs' | 'scripts' | 'logs' | 'system' | 'dashboard';
export type AppScope = 'envs' | 'envs:read' | 'crons' | 'configs' | 'configs:read' | 'scripts' | 'scripts:read' | 'logs' | 'system' | 'dashboard';
export interface AppInstance extends Model<App, App>, App {}
export const AppModel = sequelize.define<AppInstance>('App', {
+8 -7
View File
@@ -112,9 +112,16 @@ export default ({ app }: { app: Application }) => {
const keyMatch = pathLower.match(/\/open\/([a-z]+)\/*/);
const key = keyMatch && keyMatch[1];
const isReadRequest =
['GET', 'HEAD'].includes(req.method) ||
(key === 'scripts' &&
req.method === 'POST' &&
/^\/open\/scripts\/download\/?$/.test(pathLower));
const hasNamespaceScope =
doc.scopes.includes(key as AppScope) ||
(key === 'envs' && doc.scopes.includes('envs:write'));
(['envs', 'configs', 'scripts'].includes(key || '') &&
doc.scopes.includes(`${key}:read` as AppScope) &&
isReadRequest);
if (!hasNamespaceScope) {
const err = new UnauthorizedError('credentials_bad_scheme', {
message: t('暂无权限'),
@@ -122,14 +129,8 @@ export default ({ app }: { app: Application }) => {
return next(err);
}
// Config files can contain task hooks and shell code. External app
// tokens may read them, but only panel credentials may write them.
// The built-in system app still needs its local CLI maintenance API.
const appRouteAllowed =
(key !== 'envs' ||
['GET', 'HEAD'].includes(req.method) ||
doc.scopes.includes('envs:write')) &&
(key !== 'configs' || ['GET', 'HEAD'].includes(req.method)) &&
(key !== 'system' ||
doc.name === 'system' ||
((req.method === 'GET' || req.method === 'HEAD') &&
+2 -2
View File
@@ -48,7 +48,7 @@ The CLI also supports task/subscription CRUD, application and secret management,
```sh
ql task create --name demo --command 'task demo.js' --schedule '0 0 * * *' --json
ql subscription create --type public-repo --url https://example.com/repo.git --alias demo --schedule-type crontab --schedule '0 0 * * *' --json
ql app create --name agent --scopes crons,subscriptions,envs:write --show-secrets --json
ql app create --name agent --scopes crons,subscriptions,envs --show-secrets --json
ql env create --data @envs.json --json
ql api request PUT /open/crons/run --data '[12,13]' --json
```
@@ -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. `envs` only permits reading environment variables. Creating, changing, importing or enabling them requires `envs:write`, which can affect task execution. `configs` only permits reading configuration files. `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, 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.
```sh
ql login --url https://ql.example.com
+2 -2
View File
@@ -48,7 +48,7 @@ ql auth logout --json
```sh
ql task create --name demo --command 'task demo.js' --schedule '0 0 * * *' --json
ql subscription create --type public-repo --url https://example.com/repo.git --alias demo --schedule-type crontab --schedule '0 0 * * *' --json
ql app create --name agent --scopes crons,subscriptions,envs:write --show-secrets --json
ql app create --name agent --scopes crons,subscriptions,envs --show-secrets --json
ql env create --data @envs.json --json
ql api request PUT /open/crons/run --data '[12,13]' --json
```
@@ -68,7 +68,7 @@ ql api request PUT /open/crons/run --data '[12,13]' --json
### 应用凭据登录
在面板创建专用应用,按需授予 crons、subscriptions 等权限。`envs` 仅允许读取环境变量;创建、修改、导入或启用环境变量需要 `envs:write`,该权限可影响任务执行。`configs` 仅允许读取配置文件。`login` 与 `auth login` 等价;交互输入 Client ID 和不回显的 Client Secret,密钥不支持命令行参数。
在面板创建专用应用,按需授予 crons、subscriptions 等权限。现有 `envs`、`configs`、`scripts` scope 保留读写能力,`scripts` 还可运行和停止脚本;仅读取时分别选用 `envs:read`、`configs:read`、`scripts:read`。脚本下载虽然使用 POST,也允许 `scripts:read`。`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` 仅允许读取;写入须授予 `envs:write`,它同时包含读取能力且可影响任务执行。`configs` 对应用令牌仅允许读取,保存配置需要面板会话。外部应用的 `system` scope 仅允许读取系统状态和发送通知。应用管理需要 apps;user、health、update 等路由同样接受服务端权限校验。面板 UI 当前没有列出全部这些 scope,不能把路由存在理解成现有应用已获授权。
常规使用 `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,不能把路由存在理解成现有应用已获授权。
认证步骤、环境变量优先级、应用登录、面板会话与双因素验证、退出行为,统一见 [认证参考](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.
The `envs` scope is read only. Grant `envs:write` for environment changes; it also permits reads and can affect task execution. Application tokens with `configs` may read configuration, while saving requires a panel session. External `system` applications may only read system status and send notifications.
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.
`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,并避免把输出记录到共享日志。其他资源/通用请求可能含环境值、配置、脚本、订阅凭据和会话,按敏感数据处理。
@@ -42,7 +42,7 @@ ql subscription create --type public-repo --url https://example.com/repo.git --a
ql subscription update 5 --data @subscription.json --json
ql subscription delete 5 --query '{"force":true}' --json
ql app create --name agent --scopes crons,subscriptions --show-secrets --json
ql app update 3 --name agent --scopes crons,subscriptions,envs:write --json
ql app update 3 --name agent --scopes crons,subscriptions,envs --json
ql app reset-secret 3 --show-secrets --json
ql env create --data @envs.json --json
ql env update 8 --data '{"name":"EXAMPLE","value":"value"}' --json
@@ -51,7 +51,7 @@ ql script get --query '{"file":"demo.js","path":""}' --json
ql script history-list --query '{"filename":"demo.js","path":""}' --json
ql script history-detail --query '{"filename":"demo.js","path":"","id":"VERSION_UUID"}' --json
ql script history-restore --data '{"filename":"demo.js","path":"","id":"VERSION_UUID","expectedHash":"CURRENT_SHA256"}' --json
# Requires a panel session token.
# Requires the full configs scope or a panel session token.
ql config save --data '{"name":"example.sh","content":"# example"}' --json
ql config get --query '{"path":"example.sh"}' --json
ql log download --data '{"filename":"example.log","path":"example"}' --output ./example.log --json
+3
View File
@@ -107,6 +107,9 @@ export async function auth(
{
crons: 'crons?page=1&size=1',
configs: 'configs/files',
'envs:read': 'envs',
'configs:read': 'configs/files',
'scripts:read': 'scripts',
dashboard: 'dashboard/overview',
} as Record<string, string>
)[scope] ?? scope,
+3
View File
@@ -26,6 +26,9 @@ export const commands: readonly CommandSpec[] = [
default: 'crons',
choices: [
...new Set(openOperations.map((op) => op.path.split('/')[0]!)),
'envs:read',
'configs:read',
'scripts:read',
].filter((scope) => !['auth', 'update'].includes(scope)),
},
},
+3 -3
View File
@@ -28,11 +28,11 @@ const fs = require('node:fs/promises');
assert.equal(result.status, 0, args.slice(0, 2).join(' ') + ': ' + result.stderr);
return JSON.parse(result.stdout).data;
};
const app = cli(['app', 'create', '--name', 'cli-fixture', '--scopes', 'crons,subscriptions,envs:write,configs,scripts,logs,dependencies,system,dashboard,apps', '--show-secrets'], true);
const app = cli(['app', 'create', '--name', 'cli-fixture', '--scopes', 'crons,subscriptions,envs,configs,scripts,logs,dependencies,system,dashboard,apps', '--show-secrets'], true);
assert.ok(app.client_id && app.client_secret);
cli(['login', '--url', url], false, { QL_CLIENT_ID: app.client_id, QL_CLIENT_SECRET: app.client_secret });
cli(['auth', 'status', '--scope', 'apps']);
cli(['app', 'update', String(app.id), '--name', 'cli-updated', '--scopes', 'crons,subscriptions,envs:write,configs,scripts,logs,dependencies,system,dashboard,apps']);
cli(['app', 'update', String(app.id), '--name', 'cli-updated', '--scopes', 'crons,subscriptions,envs,configs,scripts,logs,dependencies,system,dashboard,apps']);
assert.ok(cli(['app', 'list']).every(item => !('client_secret' in item) && !('tokens' in item)));
const task = cli(['task', 'create', '--name', 'cli-task', '--command', 'echo OPENAPI_FIXTURE', '--schedule', '0 0 * * *']);
cli(['task', 'update', String(task.id), '--name', 'cli-task-updated', '--command', 'echo OPENAPI_UPDATED', '--schedule', '0 1 * * *']);
@@ -48,7 +48,7 @@ const fs = require('node:fs/promises');
cli(['env', 'delete', String(env.id)]);
cli(['script', 'create', '--data', '{"filename":"cli-openapi.js","content":"console.log(1)","path":""}']);
assert.equal(cli(['script', 'get', '--query', '{"file":"cli-openapi.js"}']), 'console.log(1)');
cli(['config', 'save', '--data', '{"name":"cli-openapi.sh","content":"# fixture"}'], true);
cli(['config', 'save', '--data', '{"name":"cli-openapi.sh","content":"# fixture"}']);
assert.equal(cli(['config', 'get', '--query', '{"path":"cli-openapi.sh"}']), '# fixture');
cli(['log', 'list']); cli(['dependency', 'list']);
cli(['task', 'delete', String(task.id)]); cli(['subscription', 'delete', String(sub.id)]);
+15
View File
@@ -81,6 +81,11 @@ async function fixture(t) {
code: 200,
data: { data: [{ id: 12, name: 'example' }], total: 1 },
});
else if (
['/panel/open/envs', '/panel/open/configs/files', '/panel/open/scripts']
.includes(url.pathname)
)
json({ code: 200, data: [] });
else if (
['/panel/open/crons/run', '/panel/open/crons/stop'].includes(
url.pathname,
@@ -155,6 +160,16 @@ test('compiled entry: login aliases, private storage, status, refresh and local
assert.equal(JSON.parse(status.out).data.scopeChecked, 'crons');
assert.doesNotMatch(status.out, /test-secret|test-token/);
assert.equal(f.requests.at(-1).url.pathname, '/panel/open/crons');
for (const [scope, pathname] of [
['envs:read', '/panel/open/envs'],
['configs:read', '/panel/open/configs/files'],
['scripts:read', '/panel/open/scripts'],
]) {
const checked = await f.invoke(['auth', 'status', '--scope', scope, '--json']);
assert.equal(checked.code, 0, checked.err);
assert.equal(JSON.parse(checked.out).data.scopeChecked, scope);
assert.equal(f.requests.at(-1).url.pathname, pathname);
}
const config = JSON.parse(fs.readFileSync(f.file));
config.expiration = 1;
fs.writeFileSync(f.file, JSON.stringify(config));
+1 -1
View File
@@ -414,7 +414,6 @@
"状态": "Status",
"环境变量": "Environment variable",
"环境变量(只读)": "Environment variables (read only)",
"环境变量写入(含读取,可影响任务执行)": "Write environment variables (includes read; can affect task execution)",
"生成数据中...": "Generating data...",
"用于访问所有私有仓库的全局SSH私钥": "Global SSH private key for accessing all private repositories",
"用户令牌,扫描登录后 我的—>设置->令牌 中获取,参考 https://www.weplusbot.com/": "Token, which can be obtained after scanning and logging in, is available under 'My Account' -> 'Settings' -> 'Tokens'. Please refer to the instructions for detailed steps: https://www.weplusbot.com/",
@@ -498,6 +497,7 @@
"脚本执行时的工作目录,留空则自动检测。相对路径基于 scripts 目录,也支持绝对路径": "Working directory for script execution. Leave blank for auto-detection. Relative paths are based on the scripts directory. Absolute paths are also supported.",
"脚本文件": "Script files",
"脚本管理": "Script Management",
"脚本(只读)": "Scripts (read only)",
"自动删除任务": "Automatically Delete Tasks",
"自动拆分": "Auto Split",
"自动添加任务": "Automatically Add Tasks",
+1 -1
View File
@@ -414,7 +414,6 @@
"状态": "状态",
"环境变量": "环境变量",
"环境变量(只读)": "环境变量(只读)",
"环境变量写入(含读取,可影响任务执行)": "环境变量写入(含读取,可影响任务执行)",
"生成数据中...": "生成数据中...",
"用于访问所有私有仓库的全局SSH私钥": "用于访问所有私有仓库的全局SSH私钥",
"用户令牌,扫描登录后 我的—>设置->令牌 中获取,参考 https://www.weplusbot.com/": "用户令牌,扫描登录后 我的—>设置->令牌 中获取,参考 https://www.weplusbot.com/",
@@ -498,6 +497,7 @@
"脚本执行时的工作目录,留空则自动检测。相对路径基于 scripts 目录,也支持绝对路径": "脚本执行时的工作目录,留空则自动检测。相对路径基于 scripts 目录,也支持绝对路径",
"脚本文件": "脚本文件",
"脚本管理": "脚本管理",
"脚本(只读)": "脚本(只读)",
"自动删除任务": "自动删除任务",
"自动拆分": "自动拆分",
"自动添加任务": "自动添加任务",
+17 -7
View File
@@ -21,25 +21,33 @@ export default {
value: 'crons',
},
{
name: intl.get('环境变量(只读)'),
name: intl.get('环境变量'),
value: 'envs',
},
{
name: intl.get('环境变量写入(含读取,可影响任务执行)'),
value: 'envs:write',
name: intl.get('环境变量(只读)'),
value: 'envs:read',
},
{
name: intl.get('订阅管理'),
value: 'subscriptions',
},
{
name: intl.get('配置文件(只读)'),
name: intl.get('配置文件'),
value: 'configs',
},
{
name: intl.get('配置文件(只读)'),
value: 'configs:read',
},
{
name: intl.get('脚本管理'),
value: 'scripts',
},
{
name: intl.get('脚本(只读)'),
value: 'scripts:read',
},
{
name: intl.get('日志管理'),
value: 'logs',
@@ -59,11 +67,13 @@ export default {
],
scopesMap: {
crons: intl.get('定时任务'),
envs: intl.get('环境变量(只读)'),
'envs:write': intl.get('环境变量写入(含读取,可影响任务执行)'),
envs: intl.get('环境变量'),
'envs:read': intl.get('环境变量(只读)'),
subscriptions: intl.get('订阅管理'),
configs: intl.get('配置文件(只读)'),
configs: intl.get('配置文件'),
'configs:read': intl.get('配置文件(只读)'),
scripts: intl.get('脚本管理'),
'scripts:read': intl.get('脚本(只读)'),
logs: intl.get('日志管理'),
dependencies: intl.get('依赖管理'),
system: intl.get('系统信息'),
+81 -15
View File
@@ -52,6 +52,10 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
scopes: ['configs'],
tokens: [{ value: 'config-app', expiration: Date.now() / 1000 + 3600 }],
},
{
scopes: ['configs:read'],
tokens: [{ value: 'config-read-app', expiration: Date.now() / 1000 + 3600 }],
},
{
scopes: ['configs', 'scripts'],
tokens: [
@@ -62,13 +66,17 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
scopes: ['scripts'],
tokens: [{ value: 'script-app', expiration: Date.now() / 1000 + 3600 }],
},
{
scopes: ['scripts:read'],
tokens: [{ value: 'script-read-app', expiration: Date.now() / 1000 + 3600 }],
},
{
scopes: ['envs'],
tokens: [{ value: 'env-app', expiration: Date.now() / 1000 + 3600 }],
},
{
scopes: ['envs:write'],
tokens: [{ value: 'env-write-app', expiration: Date.now() / 1000 + 3600 }],
scopes: ['envs:read'],
tokens: [{ value: 'env-read-app', expiration: Date.now() / 1000 + 3600 }],
},
{
name: 'external-system',
@@ -86,6 +94,15 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
let envWriteCalls = 0;
let initialized = 0;
const User = class {};
const Script = class {
getFile(folder, filename) {
return fs.promises.readFile(path.join(config.scriptPath, folder, filename), 'utf8');
}
checkFilePath(folder, filename) {
return path.join(config.scriptPath, folder || '', filename);
}
};
const script = new Script();
const user = {
initializeUser: async () => {
initialized++;
@@ -108,7 +125,7 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
},
'../config/serverEnv': { serveEnv: (_req, res) => res.end() },
'../services/user': User,
'../services/script': class {},
'../services/script': Script,
'../data/open': {},
'../data/system': {},
typedi: { Service: () => (x) => x },
@@ -129,7 +146,8 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
mocks.typedi = {
...mocks.typedi,
Container: {
get: (x) => (x === User ? user : x === History ? history : configService),
get: (x) =>
x === User ? user : x === History ? history : x === Script ? script : configService,
},
};
mocks['../api'] = () => {
@@ -235,10 +253,10 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
assert.equal((await request(`${prefix}/envs`)).status, 401, prefix);
}
assert.equal((await request('/open/envs', 'env-app')).body.code, 200);
assert.equal((await request('/open/envs', 'env-write-app')).body.code, 200);
assert.equal((await request('/open/envs', 'env-read-app')).body.code, 200);
for (const prefix of ['/open', '/panel/open']) {
assert.equal(
(await request(`${prefix}/envs`, 'env-app', 'POST', [
(await request(`${prefix}/envs`, 'env-read-app', 'POST', [
{ name: 'SAFE_VALUE', value: 'kept' },
])).status,
401,
@@ -246,7 +264,7 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
}
assert.equal(envWriteCalls, 0);
assert.equal(
(await request('/open/envs', 'env-write-app', 'POST', [
(await request('/open/envs', 'env-app', 'POST', [
{ name: 'SAFE_VALUE', value: 'kept' },
])).body.code,
200,
@@ -261,10 +279,15 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
.data,
'normal',
);
assert.equal(
(await request('/open/configs/detail?path=normal.txt', 'config-read-app'))
.body.data,
'normal',
);
for (const prefix of ['/open', '/panel/open']) {
for (const name of ['normal.txt', 'config.sh', 'task_before.sh']) {
assert.equal(
(await request(`${prefix}/configs/save`, 'config-app', 'POST', {
(await request(`${prefix}/configs/save`, 'config-read-app', 'POST', {
name,
content: 'untrusted',
})).status,
@@ -319,8 +342,8 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
name: 'grpc/client.key',
content: 'changed',
})
).status,
401,
).body.code,
403,
);
assert.equal(
fs.readFileSync(path.join(tmp, 'config/grpc/client.key'), 'utf8'),
@@ -346,7 +369,7 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
content: 'overwrite',
},
);
assert.equal(denied.status, 401);
assert.equal(denied.body.code, 403);
assert.equal(fs.existsSync(path.join(tmp, 'scripts/test.js')), false);
}
assert.equal(
@@ -355,8 +378,8 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
name: scriptName,
content: 'authorized script',
})
).status,
401,
).body.code,
403,
);
assert.equal(fs.existsSync(path.join(tmp, 'scripts/test.js')), false);
assert.equal(
@@ -370,8 +393,8 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
name: 'normal.txt',
content: 'normal config',
})
).status,
401,
).body.code,
200,
);
assert.equal(
(await request('/api/configs/save', valid, 'POST', {
@@ -400,6 +423,15 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
).status,
401,
);
assert.equal(
(
await request(`${prefix}/scripts`, 'script-read-app', 'POST', {
filename: 'test.js',
content: 'unauthorized',
})
).status,
401,
);
assert.equal(
(
await request(`${prefix}/scripts`, 'script-app', 'POST', {
@@ -414,4 +446,38 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
'authorized script',
);
}
assert.equal(
(await request('/open/scripts/detail?file=test.js', 'script-read-app')).body
.data,
'authorized script',
);
const downloaded = await fetch(
`http://127.0.0.1:${server.address().port}/open/scripts/download`,
{
method: 'POST',
headers: {
Authorization: 'Bearer script-read-app',
'Content-Type': 'application/json',
},
body: JSON.stringify({ filename: 'test.js' }),
},
);
assert.equal(downloaded.status, 200);
assert.equal(await downloaded.text(), 'authorized script');
for (const method of ['PUT', 'DELETE']) {
assert.equal(
(await request('/open/scripts', 'script-read-app', method, {
filename: 'test.js', content: 'unauthorized',
})).status,
401,
);
}
for (const path of ['run', 'stop', 'rename', 'history/restore']) {
assert.equal(
(await request(`/open/scripts/${path}`, 'script-read-app', 'PUT', {
filename: 'test.js', content: 'unauthorized',
})).status,
401,
);
}
});