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

This commit is contained in:
whyour committed 2026-11-02 23:10:58 +08:00
1 parent a5f22f8d44
commit b0f15241d2
17 files changed
+364 -30

No files matched your search

@@ -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 =
+110 -6
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 });
@@ -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', {
+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,