mirror of
https://github.com/whyour/qinglong.git
synced 2026-12-01 01:39:52 +08:00
fix(security): restrict task environment controls and app scopes
This commit is contained in:
1 parent
a5f22f8d44
commit
b0f15241d2
17 files changed
+364
-30
No files matched your search
+1
-1
@@ -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, App>, App {}
|
||||
export const AppModel = sequelize.define<AppInstance>('App', {
|
||||
|
||||
+24
-1
@@ -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('暂无权限'),
|
||||
});
|
||||
|
||||
@@ -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();
|
||||
|
||||
+22
-3
@@ -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<Env[]> {
|
||||
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<Env> {
|
||||
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('&')
|
||||
|
||||
@@ -23,6 +23,7 @@ const messages: Record<string, Record<string, string>> = {
|
||||
'代理层数不能超过 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',
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user