fix(security): restrict task environment controls and app scopes (#3121)

* fix(security): restrict task environment controls and app scopes

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

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

* fix(security): reject apps scope grants in app API

* fix(security): protect system app and task file boundaries

* fix: block case-variant secret paths and task runner env overrides
This commit is contained in:
whyour authored and GitHub committed 2026-11-03 23:04:43 +08:00
1 parent a5f22f8d44
commit 442ab2c616
28 files changed
+782 -28

No files matched your search

@@ -43,6 +43,104 @@ 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' },
{ id: 9, name: 'work_dir', value: '/tmp/untrusted' },
{ id: 10, name: 'task_shell_params', value: 'other.sh' },
{ id: 11, name: 'which_program', value: 'bash' },
{ id: 12, name: 'script_params', value: 'other.sh' },
{ id: 13, name: 'LOG_DIR', value: '../../config' },
{ id: 14, name: 'EXPORTED_VARIABLES', value: 'PATH' },
{ id: 15, name: 'begin_timestamp', value: 'a[$(printf BAD)]' },
{ id: 16, name: 'is_macos', value: 'a[$(printf BAD)]' },
{ id: 17, name: 'RandomDelayIgnoredMinutes', value: 'a[$(printf BAD)]' },
{ id: 18, name: 'ID', value: '999' },
{ id: 19, name: 'BASH_XTRACEFD', value: '2' },
];
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', 'work_dir',
'task_shell_params', 'which_program', 'script_params', 'LOG_DIR',
'EXPORTED_VARIABLES',
'begin_timestamp', 'is_macos', 'RandomDelayIgnoredMinutes', 'ID',
'BASH_XTRACEFD',
]) {
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|work_dir|task_shell_params|which_program|script_params|LOG_DIR|EXPORTED_VARIABLES|begin_timestamp|is_macos|RandomDelayIgnoredMinutes|ID|BASH_XTRACEFD/,
);
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 =
+69
View File
@@ -0,0 +1,69 @@
const assert = require('node:assert/strict');
const test = require('node:test');
const express = require('express');
const { errors } = require('celebrate');
const path = require('node:path');
const load = require('../helpers/load-security-module.cjs');
test('application API rejects granting apps scope on create and update', async (t) => {
const calls = [];
class OpenService {}
const service = {
create: async (body) => {
calls.push(['create', body]);
return body;
},
update: async (body) => {
calls.push(['update', body]);
return body;
},
};
const route = load(path.join(__dirname, '../../back/api/open.ts'), {
'../services/open': OpenService,
typedi: { Container: { get: () => service } },
}).default;
const app = express();
app.use(express.json());
for (const prefix of ['/api', '/open']) {
const router = express.Router();
route(router);
app.use(prefix, router);
}
app.use(errors());
const server = app.listen(0, '127.0.0.1');
t.after(() => new Promise((resolve) => server.close(resolve)));
await new Promise((resolve, reject) => {
server.once('listening', resolve);
server.once('error', reject);
});
const request = async (prefix, method, body) => {
const response = await fetch(
`http://127.0.0.1:${server.address().port}${prefix}/apps`,
{
method,
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
},
);
return response.status;
};
for (const prefix of ['/api', '/open']) {
assert.equal(
await request(prefix, 'POST', { name: 'new', scopes: ['crons', 'apps'] }),
400,
);
assert.equal(
await request(prefix, 'PUT', { id: 1, scopes: ['apps'] }),
400,
);
assert.equal(
await request(prefix, 'POST', { name: 'new', scopes: ['crons:read'] }),
200,
);
assert.equal(
await request(prefix, 'PUT', { id: 1, scopes: ['crons'] }),
200,
);
}
assert.equal(calls.length, 4);
});
+20
View File
@@ -115,7 +115,9 @@ for (const customData of [false, true]) {
);
for (const name of [
'token.json',
'TOKEN.JSON',
'grpc/client.key',
'Grpc/client.key',
'secret-link',
'data/scripts/secret-link',
'data/scripts/../config/token.json',
@@ -176,5 +178,23 @@ test('log APIs allow configuration-like names while retaining directory boundari
])
assert.equal((await invoke(method, route, values)).code, 403, filename);
}
const hidden = path.join(config.logPath, '.tmp', 'own_user.list');
fs.mkdirSync(path.dirname(hidden), { recursive: true });
fs.writeFileSync(hidden, 'hidden task command');
for (const values of [
{ path: '.tmp', file: 'own_user.list', filename: 'own_user.list' },
{ path: '.TMP', file: 'own_user.list', filename: 'own_user.list' },
{ path: '', file: '.tmp/own_user.list', filename: '.tmp/own_user.list' },
{ path: '', file: '.Tmp/own_user.list', filename: '.Tmp/own_user.list' },
]) {
for (const [method, route] of [
['get', '/detail'],
['post', '/download'],
['delete', '/'],
]) {
assert.equal((await invoke(method, route, values)).code, 403);
}
}
assert.equal(fs.readFileSync(hidden, 'utf8'), 'hidden task command');
assert.equal(fs.readFileSync(secret, 'utf8'), 'PANEL-SECRET');
});
+3
View File
@@ -24,11 +24,14 @@ test('file access enforces directory boundaries, blacklist descendants and symli
'../config-other/secret',
'/etc/passwd',
'grpc/client.key',
'GRPC/client.key',
'alias/client.key',
'outside/new.txt',
'dangling',
'auth.json',
'AUTH.JSON',
'nested/auth.json',
'nested/Auth.Json',
'',
]) {
assert.equal(
+250 -2
View File
@@ -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 });
@@ -51,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: [
@@ -61,13 +66,55 @@ 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:read'],
tokens: [{ value: 'env-read-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 }],
},
];
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 {
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++;
@@ -90,7 +137,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 },
@@ -111,7 +158,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'] = () => {
@@ -126,6 +174,41 @@ 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 });
});
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) => {
resetCalls++;
res.json({ code: 200 });
});
router.put('/system/command-run', (_req, res) => {
commandCalls++;
res.json({ code: 200 });
});
return router;
};
const app = express();
@@ -203,6 +286,68 @@ 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-read-app')).body.code, 200);
for (const prefix of ['/open', '/panel/open']) {
assert.equal(
(await request(`${prefix}/envs`, 'env-read-app', 'POST', [
{ name: 'SAFE_VALUE', value: 'kept' },
])).status,
401,
);
}
assert.equal(envWriteCalls, 0);
assert.equal(
(await request('/open/envs', 'env-app', 'POST', [
{ name: 'SAFE_VALUE', value: 'kept' },
])).body.code,
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,
@@ -212,6 +357,58 @@ 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-read-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,
@@ -277,6 +474,14 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
).body.code,
200,
);
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', {
@@ -296,6 +501,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', {
@@ -310,4 +524,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,
);
}
});
+10 -2
View File
@@ -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,
+16
View File
@@ -397,6 +397,22 @@ for (const mutation of ['resetSecret', 'remove', 'update', 'create']) {
});
}
test('application mutations cannot change or expose the built-in system app', async (t) => {
const state = appsFixture(t);
for (const change of [
() => state.service.resetSecret(1),
() => state.service.update({ id: 1, name: 'system', scopes: ['crons'] }),
() => state.service.update({ id: 2, name: 'system', scopes: ['crons'] }),
() => state.service.remove([1, 2]),
]) {
await assert.rejects(change(), (error) => error.status === 403);
}
assert.equal(state.apps().length, 2);
assert.equal(state.apps()[0].client_secret, 'system-secret');
assert.equal(state.apps()[0].tokens[0].value, 'system-token');
assert.deepEqual(state.cached(), state.apps());
});
test('system initialization preserves active tokens while migrating dashboard scope', async (t) => {
const state = appsFixture(t);
await AppModel.update({ scopes: ['crons', 'system'] }, { where: { id: 1 } });