From b0f15241d225ebc0972304d86bcf024d0125a96b Mon Sep 17 00:00:00 2001 From: whyour Date: Mon, 2 Nov 2026 23:10:58 +0800 Subject: [PATCH] fix(security): restrict task environment controls and app scopes --- back/data/open.ts | 2 +- back/loaders/express.ts | 25 +++- back/loaders/initData.ts | 5 +- back/services/env.ts | 25 +++- back/shared/i18n.ts | 1 + back/shared/taskEnvName.ts | 58 +++++++++ cli/README.en.md | 4 +- cli/README.md | 4 +- cli/skills/qinglong-cli/references/openapi.md | 7 +- cli/test/linux/openapi.cjs | 6 +- src/locales/en-US.json | 6 + src/locales/zh-CN.json | 6 + src/pages/env/index.tsx | 26 +++- src/utils/config.ts | 13 +- test/back/advisory-input-security.test.cjs | 78 ++++++++++++ test/back/http-security.test.cjs | 116 +++++++++++++++++- test/back/restart-instance-recovery.test.cjs | 12 +- 17 files changed, 364 insertions(+), 30 deletions(-) create mode 100644 back/shared/taskEnvName.ts diff --git a/back/data/open.ts b/back/data/open.ts index f508c70b..2d5ed9b3 100644 --- a/back/data/open.ts +++ b/back/data/open.ts @@ -24,7 +24,7 @@ export interface AppToken { expiration: number; } -export type AppScope = 'envs' | 'crons' | 'configs' | 'scripts' | 'logs' | 'system' | 'dashboard'; +export type AppScope = 'envs' | 'envs:write' | 'crons' | 'configs' | 'scripts' | 'logs' | 'system' | 'dashboard'; export interface AppInstance extends Model, App {} export const AppModel = sequelize.define('App', { diff --git a/back/loaders/express.ts b/back/loaders/express.ts index aa28079f..d8168643 100644 --- a/back/loaders/express.ts +++ b/back/loaders/express.ts @@ -112,7 +112,30 @@ export default ({ app }: { app: Application }) => { const keyMatch = pathLower.match(/\/open\/([a-z]+)\/*/); const key = keyMatch && keyMatch[1]; - if (!doc.scopes.includes(key as AppScope)) { + const hasNamespaceScope = + doc.scopes.includes(key as AppScope) || + (key === 'envs' && doc.scopes.includes('envs:write')); + if (!hasNamespaceScope) { + const err = new UnauthorizedError('credentials_bad_scheme', { + message: t('暂无权限'), + }); + 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') && + (pathLower === '/open/system' || pathLower === '/open/system/')) || + (req.method === 'PUT' && pathLower === '/open/system/notify')); + if (!appRouteAllowed) { const err = new UnauthorizedError('credentials_bad_scheme', { message: t('暂无权限'), }); diff --git a/back/loaders/initData.ts b/back/loaders/initData.ts index 7e36171b..40f1642e 100644 --- a/back/loaders/initData.ts +++ b/back/loaders/initData.ts @@ -222,6 +222,9 @@ export default async () => { } } catch { } + // Replace legacy task environment files before recovered tasks can run. + await envService.set_envs(); + // 初始化保存一次ck和定时任务数据 cronClient.readiness.configure(async () => { await cronService.autosave_crontab(true); @@ -229,8 +232,6 @@ export default async () => { }); await cronClient.readiness.recover(); - await envService.set_envs(); - const authInfo = await userService.getAuthInfo(); await shareStore.updateAuthInfo(authInfo); await openService.refreshApps(); diff --git a/back/services/env.ts b/back/services/env.ts index 351fa594..00f1ab1f 100644 --- a/back/services/env.ts +++ b/back/services/env.ts @@ -14,12 +14,17 @@ import { } from '../data/env'; import { writeFileWithLock } from '../shared/utils'; import { sequelize } from '../data'; +import { + assertAllowedTaskEnvName, + isAllowedTaskEnvName, +} from '../shared/taskEnvName'; @Service() export default class EnvService { constructor(@Inject('logger') private logger: winston.Logger) { } public async create(payloads: Env[]): Promise { + payloads.forEach((payload) => assertAllowedTaskEnvName(payload.name)); const envs = await this.envs(); let position = initPosition; if ( @@ -52,6 +57,7 @@ export default class EnvService { public async update(payload: Env): Promise { const doc = await this.getDb({ id: payload.id }); const tab = new Env({ ...doc, ...payload }); + assertAllowedTaskEnvName(tab.name); const newDoc = await this.updateDb(tab); await this.set_envs(); return newDoc; @@ -151,7 +157,10 @@ export default class EnvService { ['position', 'DESC'], ['createdAt', 'ASC'], ]); - return result; + return result.map((env) => ({ + ...env, + securityBlocked: !isAllowedTaskEnvName(env.name), + })); } catch (error) { throw error; } @@ -182,11 +191,14 @@ export default class EnvService { } public async enabled(ids: number[]) { + const docs = await EnvModel.findAll({ where: { id: ids } }); + docs.forEach((doc) => assertAllowedTaskEnvName(doc.name)); await EnvModel.update({ status: EnvStatus.normal }, { where: { id: ids } }); await this.set_envs(); } public async updateNames({ ids, name }: { ids: number[]; name: string }) { + assertAllowedTaskEnvName(name); await EnvModel.update({ name }, { where: { id: ids } }); await this.set_envs(); } @@ -242,6 +254,13 @@ export default class EnvService { name: { [Op.not]: null }, status: EnvStatus.normal, }); + const invalid = envs.filter((env) => !isAllowedTaskEnvName(env.name)); + if (invalid.length > 0) { + this.logger.warn( + 'Skipped reserved environment variables in task files: %s', + JSON.stringify(invalid.map((env) => ({ id: env.id, name: env.name }))), + ); + } const groups = groupBy(envs, 'name'); let env_string = ''; let js_env_string = ''; @@ -250,8 +269,8 @@ export default class EnvService { if (Object.prototype.hasOwnProperty.call(groups, key)) { const group = groups[key]; - // 忽略不符合bash要求的环境变量名称 - if (/^[a-zA-Z_][0-9a-zA-Z_]*$/.test(key)) { + // Ignore invalid and reserved names, including legacy database rows. + if (isAllowedTaskEnvName(key)) { let value = group .map((x) => x.value) .join('&') diff --git a/back/shared/i18n.ts b/back/shared/i18n.ts index 78e3e8b1..243b2bf4 100644 --- a/back/shared/i18n.ts +++ b/back/shared/i18n.ts @@ -23,6 +23,7 @@ const messages: Record> = { '代理层数不能超过 20': 'Proxy hop count cannot exceed 20', '环境变量 QL_TRUST_PROXY 已生效,系统设置不可覆盖': 'QL_TRUST_PROXY is active and cannot be overridden by system settings', + 环境变量名称不可使用: 'Environment variable name is reserved or invalid', 系统配置不存在: 'System configuration does not exist', '历史版本仅支持不超过 1 MiB 的 UTF-8 文本脚本': 'Version history only supports UTF-8 text scripts up to 1 MiB', diff --git a/back/shared/taskEnvName.ts b/back/shared/taskEnvName.ts new file mode 100644 index 00000000..3d5f8aec --- /dev/null +++ b/back/shared/taskEnvName.ts @@ -0,0 +1,58 @@ +import { t } from './i18n'; + +// These names control the task runner or the interpreters it starts. Values +// managed through the environment API must remain task data, not executable +// configuration. +const reservedNames = new Set([ + 'TASK_BEFORE', + 'TASK_AFTER', + 'PATH', + 'HOME', + 'SHELL', + 'ENV', + 'BASH_ENV', + 'BASHOPTS', + 'SHELLOPTS', + 'IFS', + 'CDPATH', + 'GLOBIGNORE', + 'PROMPT_COMMAND', + 'PS4', + 'NODE_OPTIONS', + 'NODE_PATH', + 'PREV_NODE_OPTIONS', + 'PREV_NODE_PATH', + 'PREV_PYTHONPATH', + 'GIT_SSH', + 'GIT_SSH_COMMAND', + 'GIT_ASKPASS', + 'GIT_EXEC_PATH', + 'GIT_TEMPLATE_DIR', + 'SSH_ASKPASS', +]); + +export function isAllowedTaskEnvName(name: unknown): name is string { + if (typeof name !== 'string' || !/^[a-zA-Z_][0-9a-zA-Z_]*$/.test(name)) { + return false; + } + + const upper = name.toUpperCase(); + return ( + !reservedNames.has(upper) && + !upper.startsWith('QL') && + !upper.startsWith('FILE_') && + !upper.startsWith('DIR_') && + !upper.startsWith('LD_') && + !upper.startsWith('DYLD_') && + !upper.startsWith('PYTHON') && + !upper.startsWith('GIT_CONFIG_') + ); +} + +export function assertAllowedTaskEnvName(name: unknown): asserts name is string { + if (!isAllowedTaskEnvName(name)) { + throw Object.assign(new Error(t('环境变量名称不可使用')), { + status: 400, + }); + } +} diff --git a/cli/README.en.md b/cli/README.en.md index 0887b449..c6825388 100644 --- a/cli/README.en.md +++ b/cli/README.en.md @@ -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 --show-secrets --json +ql app create --name agent --scopes crons,subscriptions,envs:write --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 `. Two credential sources a ### Application login -Create a dedicated panel application with the required scopes, such as crons, subscriptions or envs. `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. `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. ```sh ql login --url https://ql.example.com diff --git a/cli/README.md b/cli/README.md index 335b0ac1..f63301e2 100644 --- a/cli/README.md +++ b/cli/README.md @@ -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 --show-secrets --json +ql app create --name agent --scopes crons,subscriptions,envs:write --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 等权限。`login` 与 `auth login` 等价;交互输入 Client ID 和不回显的 Client Secret,密钥不支持命令行参数。 +在面板创建专用应用,按需授予 crons、subscriptions 等权限。`envs` 仅允许读取环境变量;创建、修改、导入或启用环境变量需要 `envs:write`,该权限可影响任务执行。`configs` 仅允许读取配置文件。`login` 与 `auth login` 等价;交互输入 Client ID 和不回显的 Client Secret,密钥不支持命令行参数。 ```sh ql login --url https://ql.example.com diff --git a/cli/skills/qinglong-cli/references/openapi.md b/cli/skills/qinglong-cli/references/openapi.md index e6c25c80..96269c8a 100644 --- a/cli/skills/qinglong-cli/references/openapi.md +++ b/cli/skills/qinglong-cli/references/openapi.md @@ -6,12 +6,14 @@ 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 等。应用管理需要 apps;user、health、update 等路由同样接受服务端权限校验。面板 UI 当前没有列出全部这些 scope,不能把路由存在理解成现有应用已获授权。 +常规使用 `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,不能把路由存在理解成现有应用已获授权。 认证步骤、环境变量优先级、应用登录、面板会话与双因素验证、退出行为,统一见 [认证参考](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. + `auth status --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,并避免把输出记录到共享日志。其他资源/通用请求可能含环境值、配置、脚本、订阅凭据和会话,按敏感数据处理。 App results omit client_secret/tokens unless --show-secrets is explicit. Other resources and raw responses may contain sensitive values. Handle them accordingly. @@ -40,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 --json +ql app update 3 --name agent --scopes crons,subscriptions,envs:write --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 @@ -49,6 +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. 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 diff --git a/cli/test/linux/openapi.cjs b/cli/test/linux/openapi.cjs index 20271f65..13a141cd 100644 --- a/cli/test/linux/openapi.cjs +++ b/cli/test/linux/openapi.cjs @@ -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,configs,scripts,logs,dependencies,system,dashboard,apps', '--show-secrets'], true); + const app = cli(['app', 'create', '--name', 'cli-fixture', '--scopes', 'crons,subscriptions,envs:write,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,configs,scripts,logs,dependencies,system,dashboard,apps']); + cli(['app', 'update', String(app.id), '--name', 'cli-updated', '--scopes', 'crons,subscriptions,envs:write,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"}']); + cli(['config', 'save', '--data', '{"name":"cli-openapi.sh","content":"# fixture"}'], true); 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)]); diff --git a/src/locales/en-US.json b/src/locales/en-US.json index 58991a4d..6f64710c 100644 --- a/src/locales/en-US.json +++ b/src/locales/en-US.json @@ -188,6 +188,8 @@ "可用,你使用的版本为": "available, the version you are using is", "同时删除关联任务和脚本": "Delete associated tasks and scripts as well", "名称": "Name", + "名称受限": "Restricted name", + "名称受限,未注入任务": "Restricted name; not injected into tasks", "名称不能为保留关键字": "The name cannot be a reserved keyword", "吗": "?", "否": "No", @@ -411,6 +413,8 @@ "版本": "Version", "状态": "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/", @@ -513,6 +517,7 @@ "语言": "Language", "请": "Please", "请先按如下方式修复:": "Please fix it as follows:", + "请先修改环境变量名称": "Rename the environment variable first", "请求体格式key1: value1,多个换行分割。url或者body中必须包含$title,$content可选,对应api内容的位置": "Request body format: key1: value1 (separate multiple keys with line breaks). URL or body must contain $title, $content is optional and corresponds to the API content position.", "请求头Content-Type": "Request Header Content-Type", "请求头格式Custom-Header1: Header1,多个换行分割": "Request header format: Custom-Header1: Header1 (separate multiple headers with line breaks)", @@ -606,6 +611,7 @@ "邮箱服务名称,比如126、163、Gmail、QQ等,支持列表https://github.com/nodemailer/nodemailer/blob/master/lib/well-known/services.json": "Email service name, e.g., 126, 163, Gmail, QQ, etc. Supported list: https://github.com/nodemailer/nodemailer/blob/master/lib/well-known/services.json", "邮箱认证地址": "Email address for SMTP authentication", "配置文件": "Configuration Files", + "配置文件(只读)": "Configuration files (read only)", "重启": "Restart", "重命名": "Rename", "重新下载": "Redownload", diff --git a/src/locales/zh-CN.json b/src/locales/zh-CN.json index a5c6a1e5..41776ac3 100644 --- a/src/locales/zh-CN.json +++ b/src/locales/zh-CN.json @@ -187,6 +187,8 @@ "可用,你使用的版本为": "可用,你使用的版本为", "同时删除关联任务和脚本": "同时删除关联任务和脚本", "名称": "名称", + "名称受限": "名称受限", + "名称受限,未注入任务": "名称受限,未注入任务", "名称不能为保留关键字": "名称不能为保留关键字", "吗": "吗", "否": "否", @@ -411,6 +413,8 @@ "版本": "版本", "状态": "状态", "环境变量": "环境变量", + "环境变量(只读)": "环境变量(只读)", + "环境变量写入(含读取,可影响任务执行)": "环境变量写入(含读取,可影响任务执行)", "生成数据中...": "生成数据中...", "用于访问所有私有仓库的全局SSH私钥": "用于访问所有私有仓库的全局SSH私钥", "用户令牌,扫描登录后 我的—>设置->令牌 中获取,参考 https://www.weplusbot.com/": "用户令牌,扫描登录后 我的—>设置->令牌 中获取,参考 https://www.weplusbot.com/", @@ -513,6 +517,7 @@ "语言": "语言", "请": "请", "请先按如下方式修复:": "请先按如下方式修复:", + "请先修改环境变量名称": "请先修改环境变量名称", "请求体格式key1: value1,多个换行分割。url或者body中必须包含$title,$content可选,对应api内容的位置": "请求体格式key1: value1,多个换行分割。url或者body中必须包含$title,$content可选,对应api内容的位置", "请求头Content-Type": "请求头Content-Type", "请求头格式Custom-Header1: Header1,多个换行分割": "请求头格式Custom-Header1: Header1,多个换行分割", @@ -606,6 +611,7 @@ "邮箱服务名称,比如126、163、Gmail、QQ等,支持列表https://github.com/nodemailer/nodemailer/blob/master/lib/well-known/services.json": "邮箱服务名称,比如126、163、Gmail、QQ等,支持列表https://github.com/nodemailer/nodemailer/blob/master/lib/well-known/services.json", "邮箱认证地址": "邮箱认证地址", "配置文件": "配置文件", + "配置文件(只读)": "配置文件(只读)", "重启": "重启", "重命名": "重命名", "重新下载": "重新下载", diff --git a/src/pages/env/index.tsx b/src/pages/env/index.tsx index 8968786c..52fd152c 100644 --- a/src/pages/env/index.tsx +++ b/src/pages/env/index.tsx @@ -174,7 +174,7 @@ const Env = () => { title: intl.get('状态'), key: 'status', dataIndex: 'status', - width: 100, + width: 170, filters: [ { text: intl.get('已启用'), @@ -192,6 +192,13 @@ const Env = () => { {intl.get(Status[record.status])} + {record.securityBlocked && ( + + + {intl.get('名称受限')} + + + )} ); }, @@ -202,6 +209,8 @@ const Env = () => { width: 160, render: (text: string, record: any, index: number) => { const isPc = !isPhone; + const isBlockedEnable = + record.status === Status.已禁用 && record.securityBlocked; return ( @@ -212,7 +221,9 @@ const Env = () => { { }; const enabledOrDisabledEnv = (record: any, index: number) => { + if (record.status === Status.已禁用 && record.securityBlocked) { + message.error(intl.get('请先修改环境变量名称')); + return; + } Modal.confirm({ title: intl.get('确认操作', { operation: @@ -538,6 +553,13 @@ const Env = () => { }; const operateEnvs = (operationStatus: number) => { + if ( + operationStatus === 0 && + value.some((env) => selectedRowIds.includes(env.id) && env.securityBlocked) + ) { + message.error(intl.get('请先修改环境变量名称')); + return; + } Modal.confirm({ title: intl.get('确认操作', { operation: intl.get(OperationName[operationStatus]), diff --git a/src/utils/config.ts b/src/utils/config.ts index 11fb25a7..e8aba7a0 100644 --- a/src/utils/config.ts +++ b/src/utils/config.ts @@ -21,15 +21,19 @@ export default { value: 'crons', }, { - name: intl.get('环境变量'), + name: intl.get('环境变量(只读)'), value: 'envs', }, + { + name: intl.get('环境变量写入(含读取,可影响任务执行)'), + value: 'envs:write', + }, { name: intl.get('订阅管理'), value: 'subscriptions', }, { - name: intl.get('配置文件'), + name: intl.get('配置文件(只读)'), value: 'configs', }, { @@ -55,9 +59,10 @@ export default { ], scopesMap: { crons: intl.get('定时任务'), - envs: intl.get('环境变量'), + envs: intl.get('环境变量(只读)'), + 'envs:write': intl.get('环境变量写入(含读取,可影响任务执行)'), subscriptions: intl.get('订阅管理'), - configs: intl.get('配置文件'), + configs: intl.get('配置文件(只读)'), scripts: intl.get('脚本管理'), logs: intl.get('日志管理'), dependencies: intl.get('依赖管理'), diff --git a/test/back/advisory-input-security.test.cjs b/test/back/advisory-input-security.test.cjs index d4318b52..6327a680 100644 --- a/test/back/advisory-input-security.test.cjs +++ b/test/back/advisory-input-security.test.cjs @@ -43,6 +43,84 @@ test('environment values remain literal when the generated JavaScript loads', as ); }); +test('environment API rejects execution controls and legacy rows stay out of task files', async () => { + const output = {}; + let writes = 0; + const warnings = []; + const legacy = [ + { id: 1, name: 'task_before', value: 'touch /tmp/untrusted' }, + { id: 2, name: 'NODE_OPTIONS', value: '--require /tmp/untrusted.js' }, + { id: 3, name: 'PREV_NODE_OPTIONS', value: '--import=data:text/javascript,bad' }, + { id: 4, name: 'GIT_SSH_COMMAND', value: 'sh -c bad' }, + { id: 5, name: 'PATH', value: '/tmp/untrusted' }, + { id: 6, name: 'file_task_before', value: '/tmp/untrusted.sh' }, + { id: 7, name: 'SAFE_VALUE', value: 'kept' }, + { id: 8, name: 'bad\nname', value: 'untrusted' }, + ]; + const Env = load(path.resolve('back/services/env.ts'), { + typedi: decorators, + '../config': { envFile: 'sh', jsEnvFile: 'js', pyEnvFile: 'py' }, + '../data/env': { + Env: class { constructor(value) { Object.assign(this, value); } }, + EnvModel: { + update: async (value, query) => { + writes++; + }, + findAll: async () => [legacy[0]], + }, + EnvStatus: { normal: 0, disabled: 1 }, + }, + '../data': { sequelize: { literal: (value) => value } }, + '../shared/utils': { + writeFileWithLock: async (file, value) => { output[file] = value; }, + }, + }).default; + const service = new Env({ + ...logger, + warn: (...args) => warnings.push(args), + }); + service.envs = async () => legacy; + service.insert = async () => { writes++; return []; }; + service.getDb = async () => ({ id: 1, name: 'SAFE_VALUE', value: 'kept' }); + service.updateDb = async () => { writes++; return {}; }; + + for (const name of ['task_before', 'PREV_NODE_OPTIONS', 'GIT_SSH_COMMAND']) { + await assert.rejects( + service.create([ + { name: 'SAFE_VALUE', value: 'ok' }, + { name, value: 'untrusted' }, + ]), + /环境变量名称不可使用/, + ); + } + await assert.rejects( + service.update({ id: 1, name: 'BASH_ENV', value: '/tmp/untrusted.sh' }), + /环境变量名称不可使用/, + ); + await assert.rejects( + service.updateNames({ ids: [1], name: 'PYTHONPATH' }), + /环境变量名称不可使用/, + ); + assert.equal(writes, 0); + + await service.set_envs(); + assert.equal(writes, 0); + assert.equal(warnings.length, 1); + assert.match(warnings[0][1], /GIT_SSH_COMMAND/); + assert.equal(warnings[0][1].includes('\n'), false); + await assert.rejects(service.enabled([1]), /环境变量名称不可使用/); + assert.equal(writes, 0); + delete service.envs; + service.find = async () => legacy; + const listed = await service.envs(); + assert.equal(listed[0].securityBlocked, true); + assert.equal(listed[6].securityBlocked, false); + for (const contents of Object.values(output)) { + assert.doesNotMatch(contents, /task_before|NODE_OPTIONS|GIT_SSH_COMMAND|PATH/); + assert.match(contents, /SAFE_VALUE/); + } +}); + test('subscription shell parameters round trip without expansion or command substitution', () => { const { formatCommand } = load(path.resolve('back/config/subscription.ts')); const payload = diff --git a/test/back/http-security.test.cjs b/test/back/http-security.test.cjs index c98045c1..a7872410 100644 --- a/test/back/http-security.test.cjs +++ b/test/back/http-security.test.cjs @@ -13,6 +13,7 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec fs.mkdirSync(path.join(tmp, dir), { recursive: true }); fs.writeFileSync(path.join(tmp, 'config/grpc/client.key'), 'SENTINEL'); fs.writeFileSync(path.join(tmp, 'config/normal.txt'), 'normal'); + fs.writeFileSync(path.join(tmp, 'config/config.sh'), 'original'); const secret = 'http-security-test'; const valid = jwt.sign({}, secret, { algorithm: 'HS384', expiresIn: '1h' }); const expired = jwt.sign({}, secret, { algorithm: 'HS384', expiresIn: -1 }); @@ -65,7 +66,24 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec scopes: ['envs'], tokens: [{ value: 'env-app', expiration: Date.now() / 1000 + 3600 }], }, + { + scopes: ['envs:write'], + tokens: [{ value: 'env-write-app', expiration: Date.now() / 1000 + 3600 }], + }, + { + name: 'external-system', + scopes: ['system'], + tokens: [{ value: 'system-app', expiration: Date.now() / 1000 + 3600 }], + }, + { + name: 'system', + scopes: ['system'], + tokens: [{ value: 'internal-system', expiration: Date.now() / 1000 + 3600 }], + }, ]; + let resetCalls = 0; + let commandCalls = 0; + let envWriteCalls = 0; let initialized = 0; const User = class {}; const user = { @@ -126,6 +144,20 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec historyCache, ).default(router); router.get('/envs', (_req, res) => res.json({ code: 200 })); + router.post('/envs', (_req, res) => { + envWriteCalls++; + res.json({ code: 200 }); + }); + 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) => { + resetCalls++; + res.json({ code: 200 }); + }); + router.put('/system/command-run', (_req, res) => { + commandCalls++; + res.json({ code: 200 }); + }); return router; }; const app = express(); @@ -203,6 +235,23 @@ 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); + for (const prefix of ['/open', '/panel/open']) { + assert.equal( + (await request(`${prefix}/envs`, 'env-app', 'POST', [ + { name: 'SAFE_VALUE', value: 'kept' }, + ])).status, + 401, + ); + } + assert.equal(envWriteCalls, 0); + assert.equal( + (await request('/open/envs', 'env-write-app', 'POST', [ + { name: 'SAFE_VALUE', value: 'kept' }, + ])).body.code, + 200, + ); + assert.equal(envWriteCalls, 1); assert.equal( (await request('/open/configs/detail?path=normal.txt', 'env-app')).status, 401, @@ -212,6 +261,53 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec .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', { + name, + content: 'untrusted', + })).status, + 401, + ); + } + } + assert.equal(fs.readFileSync(path.join(tmp, 'config/config.sh'), 'utf8'), 'original'); + assert.equal((await request('/open/system', 'system-app')).body.code, 200); + assert.equal( + (await request('/open/system/notify', 'system-app', 'PUT', { + title: 'title', + content: 'content', + })).body.code, + 200, + ); + for (const prefix of ['/open', '/panel/open']) { + assert.equal( + (await request(`${prefix}/system/auth/reset`, 'system-app', 'PUT', { + password: 'changed', + })).status, + 401, + ); + assert.equal( + (await request(`${prefix}/system/command-run`, 'system-app', 'PUT', { + command: 'id', + })).status, + 401, + ); + } + assert.equal(resetCalls, 0); + assert.equal(commandCalls, 0); + assert.equal( + (await request('/open/system/auth/reset', 'internal-system', 'PUT', { + retries: 0, + })).body.code, + 200, + ); + assert.equal( + (await request('/api/system/auth/reset', valid, 'PUT', { retries: 0 })).body.code, + 200, + ); + assert.equal(resetCalls, 2); assert.equal( (await request('/open/configs/detail?path=grpc/client.key', 'config-app')) .body.code, @@ -223,8 +319,8 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec name: 'grpc/client.key', content: 'changed', }) - ).body.code, - 403, + ).status, + 401, ); assert.equal( fs.readFileSync(path.join(tmp, 'config/grpc/client.key'), 'utf8'), @@ -250,7 +346,7 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec content: 'overwrite', }, ); - assert.equal(denied.body.code, 403); + assert.equal(denied.status, 401); assert.equal(fs.existsSync(path.join(tmp, 'scripts/test.js')), false); } assert.equal( @@ -259,8 +355,8 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec name: scriptName, content: 'authorized script', }) - ).body.code, - 403, + ).status, + 401, ); assert.equal(fs.existsSync(path.join(tmp, 'scripts/test.js')), false); assert.equal( @@ -274,9 +370,17 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec name: 'normal.txt', content: 'normal config', }) - ).body.code, + ).status, + 401, + ); + assert.equal( + (await request('/api/configs/save', valid, 'POST', { + name: 'config.sh', + content: 'owner config', + })).body.code, 200, ); + assert.equal(fs.readFileSync(path.join(tmp, 'config/config.sh'), 'utf8'), 'owner config'); assert.equal( ( await request('/api/configs/save', valid, 'POST', { diff --git a/test/back/restart-instance-recovery.test.cjs b/test/back/restart-instance-recovery.test.cjs index ac0f78bd..00a4d6e7 100644 --- a/test/back/restart-instance-recovery.test.cjs +++ b/test/back/restart-instance-recovery.test.cjs @@ -24,8 +24,9 @@ test('startup closes interrupted instances without inventing exit codes or rewri { id: 4, status: 3, started_at: 100, finished_at: 130, exit_code: 7 }, ]); const systemConfig = { info: { lang: 'en-US' } }; + const startupEvents = []; const service = { - set_envs: async () => {}, + set_envs: async () => { startupEvents.push('environment'); }, getAuthInfo: async () => ({}), initializeSystemApp: async () => {}, refreshApps: async () => {}, @@ -70,7 +71,10 @@ test('startup closes interrupted instances without inventing exit codes or rewri '../shared/i18n': { setLang() {} }, './logger': {}, '../schedule/client': { - readiness: { configure() {}, recover: async () => {} }, + readiness: { + configure() {}, + recover: async () => { startupEvents.push('scheduler'); }, + }, }, }).default; // Dependency installation is unrelated to startup reconciliation. @@ -82,6 +86,7 @@ test('startup closes interrupted instances without inventing exit codes or rewri } finally { global.setTimeout = originalTimeout; } + assert.deepEqual(startupEvents, ['environment', 'scheduler']); const rows = await instances.findAll({ order: [['id', 'ASC']], raw: true }); assert.equal(rows[0].status, 2); assert.ok( @@ -109,6 +114,9 @@ test('startup closes interrupted instances without inventing exit codes or rewri } finally { global.setTimeout = originalTimeout; } + assert.deepEqual(startupEvents, [ + 'environment', 'scheduler', 'environment', 'scheduler', + ]); assert.deepEqual( await instances.findAll({ order: [['id', 'ASC']], raw: true }), rows,