From 5b0d59ebb5f2ba52cd489f14b4d21e467bbbec80 Mon Sep 17 00:00:00 2001 From: Michael Schmidt Date: Fri, 19 Apr 2024 01:39:03 +0200 Subject: [PATCH] Improved validation for `goIntoDirectory` (#2801) --- src/common/types/chainner-builtin.ts | 35 +++++++++++++++++----------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/src/common/types/chainner-builtin.ts b/src/common/types/chainner-builtin.ts index eb8bd0474..2fcefc6b7 100644 --- a/src/common/types/chainner-builtin.ts +++ b/src/common/types/chainner-builtin.ts @@ -416,17 +416,20 @@ export const getParentDirectory = wrapBinary:"|?*\x00-\x1F]/; -const goIntoDirectoryImpl = (basePath: string, relPath: string): string | Error => { +const validateRelPath = (relPath: string): string | undefined => { const isAbsolute = /^[/\\]/.test(relPath) || path.isAbsolute(relPath); if (isAbsolute) { - return new Error('Absolute paths are not allowed as folders.'); + return 'Absolute paths are not allowed as folders.'; } const invalid = INVALID_PATH_CHARS.exec(relPath); if (invalid) { - return new Error(`Invalid character '${invalid[0]}' in folder name.`); + return `Invalid character '${invalid[0]}' in folder name.`; } + return undefined; +}; +const goIntoDirectoryImpl = (basePath: string, relPath: string): string => { const joined = path.join(basePath, relPath); return path.resolve(joined); }; @@ -438,20 +441,24 @@ export const goIntoDirectory = wrapScopedBinary( ): Arg => { const errorDesc = getStructDescriptor(scope, 'Error'); - if (basePath.type === 'literal' && relPath.type === 'literal') { - try { - const result = goIntoDirectoryImpl(basePath.value, relPath.value); - if (typeof result === 'string') { + try { + if (relPath.type === 'literal') { + const error = validateRelPath(relPath.value); + if (error) { + return createInstance(errorDesc, { + message: literal(error), + }); + } + + if (basePath.type === 'literal') { + const result = goIntoDirectoryImpl(basePath.value, relPath.value); return literal(result); } - return createInstance(errorDesc, { - message: literal(result.message), - }); - } catch (e) { - return createInstance(errorDesc, { - message: literal(String(e)), - }); } + } catch (e) { + return createInstance(errorDesc, { + message: literal(String(e)), + }); } return union(StringType.instance, errorDesc.default);