Fix built-in modules for flows exec operation (#17866)

* Fix built-in modules in flows exec

* Tiny ocd patch
This commit is contained in:
ian
2023-03-21 23:46:03 +08:00
committed by GitHub
parent 022d77d5d9
commit 7b256e769c
2 changed files with 35 additions and 2 deletions

View File

@@ -101,7 +101,28 @@ test('Executes function when valid', () => {
).resolves.toEqual({ result: 'start test' });
});
test('Allows modules that are whitelisted', () => {
test('Allows built-in modules that are whitelisted', () => {
const testCode = `
const crypto = require('crypto');
module.exports = async function (data) {
return {
result: crypto.createHash('sha256').update('directus').digest('hex'),
};
};
`;
expect(
config.handler({ code: testCode }, {
data: {},
env: {
FLOWS_EXEC_ALLOWED_MODULES: 'crypto',
},
} as any)
).resolves.toEqual({ result: '943e891bf6042f2db8926493c0f94e45b72cb58a21145fdfa3c23b5c057e4b2d' });
});
test('Allows external modules that are whitelisted', () => {
const testCode = `
const bytes = require('bytes');

View File

@@ -1,5 +1,6 @@
import { defineOperationApi, toArray } from '@directus/shared/utils';
import { NodeVM, NodeVMOptions, VMScript } from 'vm2';
import { isBuiltin } from 'node:module';
type Options = {
code: string;
@@ -9,6 +10,8 @@ export default defineOperationApi<Options>({
id: 'exec',
handler: async ({ code }, { data, env }) => {
const allowedModules = env.FLOWS_EXEC_ALLOWED_MODULES ? toArray(env.FLOWS_EXEC_ALLOWED_MODULES) : [];
const allowedModulesBuiltIn: string[] = [];
const allowedModulesExternal: string[] = [];
const allowedEnv = data.$env ?? {};
const opts: NodeVMOptions = {
@@ -17,10 +20,19 @@ export default defineOperationApi<Options>({
env: allowedEnv,
};
for (const module of allowedModules) {
if (isBuiltin(module)) {
allowedModulesBuiltIn.push(module);
} else {
allowedModulesExternal.push(module);
}
}
if (allowedModules.length > 0) {
opts.require = {
builtin: allowedModulesBuiltIn,
external: {
modules: allowedModules,
modules: allowedModulesExternal,
transitive: false,
},
};