mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(appsync): reject regex literals without misreading division (#7343)
This commit is contained in:
1 parent
b63e4a5bb9
commit
56efb188b1
5 files changed
+678
-59
No files matched your search
+1
-1
@@ -237,7 +237,7 @@ public class NodeAppSyncJsRuntime implements AppSyncJsRuntime, ContainerTeardown
|
||||
* rather than quoted into the shell: it contains the quotes, backticks and newlines of the
|
||||
* {@code @aws-appsync/utils} shim it writes, none of which survive shell interpolation.
|
||||
*/
|
||||
private String startCommand() {
|
||||
String startCommand() {
|
||||
String encoded = Base64.getEncoder().encodeToString(serverScript().getBytes(StandardCharsets.UTF_8));
|
||||
return "echo " + encoded + " | base64 -d > " + SERVER_PATH + " && exec node " + SERVER_PATH;
|
||||
}
|
||||
|
||||
@@ -456,75 +456,303 @@ const BANNED_CONSTRUCTS = [
|
||||
[/(?<![.\w$])Promise(?![\w$])/, 'promises']
|
||||
];
|
||||
|
||||
// Replaces the contents of comments, strings, template text and regex literals with spaces, so a
|
||||
// keyword inside one is not mistaken for code. Offsets are preserved, which keeps line numbers
|
||||
// honest. Expressions inside a template hole stay as code, because that is what they are.
|
||||
// Keep offsets while hiding text that is not executable JavaScript. Template holes are scanned
|
||||
// separately so braces and slashes in template text or regex character classes cannot close one.
|
||||
function blankLiterals(src) {
|
||||
const out = src.split('');
|
||||
let regexStart = -1;
|
||||
const wordAt = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u;
|
||||
const numberAt = /^(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*(?:\.[\d_]*)?|\.[\d_]+)(?:[eE][+-]?[\d_]+)?)(?:n)?/;
|
||||
const regexPrefixWords = new Set([
|
||||
'return', 'throw', 'case', 'delete', 'void', 'typeof', 'instanceof', 'new',
|
||||
'in', 'await', 'yield', 'else', 'do', 'var', 'let', 'const', 'export',
|
||||
'default', 'import', 'function', 'extends'
|
||||
]);
|
||||
const controlWords = new Set(['if', 'while', 'for', 'switch', 'catch', 'with']);
|
||||
const blank = (from, to) => {
|
||||
for (let i = from; i < to && i < out.length; i++) {
|
||||
if (out[i] !== '\n') out[i] = ' ';
|
||||
}
|
||||
};
|
||||
let i = 0;
|
||||
while (i < src.length) {
|
||||
const c = src[i];
|
||||
const next = src[i + 1];
|
||||
if (c === '/' && next === '/') {
|
||||
const end = src.indexOf('\n', i);
|
||||
const stop = end === -1 ? src.length : end;
|
||||
blank(i, stop);
|
||||
i = stop;
|
||||
continue;
|
||||
}
|
||||
if (c === '/' && next === '*') {
|
||||
const end = src.indexOf('*/', i + 2);
|
||||
const stop = end === -1 ? src.length : end + 2;
|
||||
blank(i, stop);
|
||||
i = stop;
|
||||
continue;
|
||||
}
|
||||
if (c === "'" || c === '"') {
|
||||
let j = i + 1;
|
||||
while (j < src.length && src[j] !== c) {
|
||||
if (src[j] === '\\') j++;
|
||||
j++;
|
||||
|
||||
function scanTemplate(start) {
|
||||
let i = start + 1;
|
||||
let textStart = start;
|
||||
while (i < src.length) {
|
||||
if (src[i] === '\\') { i += 2; continue; }
|
||||
if (src[i] === '`') {
|
||||
blank(textStart, i + 1);
|
||||
return i + 1;
|
||||
}
|
||||
if (src[i] === '$' && src[i + 1] === '{') {
|
||||
blank(textStart, i + 2);
|
||||
i = scanCode(i + 2, true);
|
||||
textStart = i;
|
||||
continue;
|
||||
}
|
||||
blank(i + 1, j);
|
||||
i = j + 1;
|
||||
continue;
|
||||
}
|
||||
if (c === String.fromCharCode(96)) {
|
||||
i++;
|
||||
let j = i;
|
||||
while (j < src.length) {
|
||||
if (src[j] === '\\') { j += 2; continue; }
|
||||
if (src[j] === String.fromCharCode(96)) { blank(i, j); i = j + 1; break; }
|
||||
if (src[j] === '$' && src[j + 1] === '{') { blank(i, j); i = j + 2; break; }
|
||||
j++;
|
||||
}
|
||||
if (j >= src.length) { blank(i, src.length); i = src.length; }
|
||||
continue;
|
||||
}
|
||||
i++;
|
||||
blank(textStart, src.length);
|
||||
return src.length;
|
||||
}
|
||||
return out.join('');
|
||||
|
||||
function scanCode(start, inTemplateHole) {
|
||||
let i = start;
|
||||
let canEndExpression = false;
|
||||
let lastToken = '';
|
||||
let lastControlWord = '';
|
||||
let memberName = false;
|
||||
let pendingFunctionExpression = null;
|
||||
let functionBodyExpression = null;
|
||||
let switchBodyPending = false;
|
||||
let statementStart = true;
|
||||
let labelCandidate = false;
|
||||
let caseLabelDepth = null;
|
||||
let caseTernaryDepth = 0;
|
||||
let statementColon = false;
|
||||
let bracketDepth = 0;
|
||||
const parens = [];
|
||||
const braces = [];
|
||||
const switchBodies = [];
|
||||
const atCaseLabelDepth = () => caseLabelDepth !== null
|
||||
&& caseLabelDepth.braces === braces.length
|
||||
&& caseLabelDepth.parens === parens.length
|
||||
&& caseLabelDepth.brackets === bracketDepth;
|
||||
while (i < src.length) {
|
||||
const c = src[i];
|
||||
const next = src[i + 1];
|
||||
if (/\s/.test(c)) {
|
||||
if (/[\r\n\u2028\u2029]/.test(c)) {
|
||||
if (lastToken === 'return') lastToken = ';';
|
||||
if (canEndExpression || lastToken === ';') statementStart = true;
|
||||
}
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (c === '/' && next === '/') {
|
||||
let stop = i + 2;
|
||||
while (stop < src.length && !/[\r\n\u2028\u2029]/.test(src[stop])) stop++;
|
||||
blank(i, stop);
|
||||
i = stop;
|
||||
continue;
|
||||
}
|
||||
if (c === '/' && next === '*') {
|
||||
const end = src.indexOf('*/', i + 2);
|
||||
const stop = end === -1 ? src.length : end + 2;
|
||||
blank(i, stop);
|
||||
i = stop;
|
||||
continue;
|
||||
}
|
||||
if (c === '"' || c === "'") {
|
||||
let j = i + 1;
|
||||
while (j < src.length && src[j] !== c) {
|
||||
if (src[j] === '\\') j++;
|
||||
j++;
|
||||
}
|
||||
j = Math.min(j + 1, src.length);
|
||||
blank(i, j);
|
||||
i = j;
|
||||
canEndExpression = true;
|
||||
lastToken = 'value';
|
||||
statementStart = false;
|
||||
labelCandidate = false;
|
||||
} else if (c === '`') {
|
||||
i = scanTemplate(i);
|
||||
canEndExpression = true;
|
||||
lastToken = 'value';
|
||||
statementStart = false;
|
||||
labelCandidate = false;
|
||||
} else if (c === '/' && !canEndExpression) {
|
||||
let j = i + 1;
|
||||
let inClass = false;
|
||||
let closed = false;
|
||||
while (j < src.length && !/[\r\n\u2028\u2029]/.test(src[j])) {
|
||||
if (src[j] === '\\') { j += 2; continue; }
|
||||
if (src[j] === '[') inClass = true;
|
||||
else if (src[j] === ']') inClass = false;
|
||||
else if (src[j] === '/' && !inClass) { j++; closed = true; break; }
|
||||
j++;
|
||||
}
|
||||
if (closed) {
|
||||
while (j < src.length && /[a-z]/i.test(src[j])) j++;
|
||||
if (regexStart === -1) regexStart = i;
|
||||
}
|
||||
blank(i, j);
|
||||
i = j;
|
||||
canEndExpression = true;
|
||||
lastToken = 'value';
|
||||
statementStart = false;
|
||||
labelCandidate = false;
|
||||
} else if (c === '/') {
|
||||
i += next === '=' ? 2 : 1;
|
||||
canEndExpression = false;
|
||||
lastToken = '/';
|
||||
statementStart = false;
|
||||
labelCandidate = false;
|
||||
} else if (c === '}' && inTemplateHole && braces.length === 0) {
|
||||
blank(i, i + 1);
|
||||
return i + 1;
|
||||
} else if (c === '(') {
|
||||
parens.push(pendingFunctionExpression === null ? lastControlWord
|
||||
: pendingFunctionExpression ? 'function-expression' : 'function-declaration');
|
||||
pendingFunctionExpression = null;
|
||||
i++;
|
||||
canEndExpression = false;
|
||||
lastToken = '(';
|
||||
statementStart = false;
|
||||
labelCandidate = false;
|
||||
} else if (c === ')') {
|
||||
const context = parens.pop();
|
||||
if (context === 'function-expression' || context === 'function-declaration') {
|
||||
functionBodyExpression = context === 'function-expression';
|
||||
}
|
||||
switchBodyPending = context === 'switch';
|
||||
canEndExpression = context === '';
|
||||
i++;
|
||||
lastToken = ')';
|
||||
statementStart = controlWords.has(context);
|
||||
labelCandidate = false;
|
||||
} else if (c === '[') {
|
||||
bracketDepth++;
|
||||
i++;
|
||||
canEndExpression = false;
|
||||
lastToken = '[';
|
||||
statementStart = false;
|
||||
labelCandidate = false;
|
||||
} else if (c === ']') {
|
||||
bracketDepth--;
|
||||
i++;
|
||||
canEndExpression = true;
|
||||
lastToken = ']';
|
||||
statementStart = false;
|
||||
labelCandidate = false;
|
||||
} else if (c === '{') {
|
||||
const afterOperator = ['=', '(', '[', ',', ':', 'return', 'case', '?', '??', '&', '|',
|
||||
'+', '-', '*', '/', '%', '!', '~', '^', '<', '>'].includes(lastToken);
|
||||
const expressionBrace = functionBodyExpression
|
||||
?? (afterOperator && !(lastToken === ':' && statementColon));
|
||||
braces.push(expressionBrace);
|
||||
switchBodies.push(switchBodyPending);
|
||||
switchBodyPending = false;
|
||||
functionBodyExpression = null;
|
||||
i++;
|
||||
canEndExpression = false;
|
||||
lastToken = '{';
|
||||
statementStart = !expressionBrace;
|
||||
labelCandidate = false;
|
||||
statementColon = false;
|
||||
} else if (c === '}') {
|
||||
const expressionBrace = braces.pop() ?? false;
|
||||
switchBodies.pop();
|
||||
canEndExpression = expressionBrace;
|
||||
i++;
|
||||
lastToken = '}';
|
||||
statementStart = !expressionBrace;
|
||||
labelCandidate = false;
|
||||
} else if (c === '.' || (c === '?' && next === '.')) {
|
||||
i += c === '?' ? 2 : 1;
|
||||
canEndExpression = false;
|
||||
lastToken = '.';
|
||||
memberName = true;
|
||||
statementStart = false;
|
||||
labelCandidate = false;
|
||||
} else if (c === ':') {
|
||||
const atCaseLevel = atCaseLabelDepth();
|
||||
const caseSeparator = atCaseLevel && caseTernaryDepth === 0;
|
||||
statementColon = caseSeparator || labelCandidate;
|
||||
if (caseSeparator) caseLabelDepth = null;
|
||||
if (atCaseLevel && !caseSeparator) caseTernaryDepth--;
|
||||
i++;
|
||||
canEndExpression = false;
|
||||
lastToken = ':';
|
||||
statementStart = statementColon;
|
||||
labelCandidate = false;
|
||||
} else {
|
||||
const word = wordAt.exec(src.slice(i));
|
||||
const number = !word && numberAt.exec(src.slice(i));
|
||||
if (word) {
|
||||
const value = word[0];
|
||||
const atStatementStart = statementStart;
|
||||
if (value === 'function' && !memberName) {
|
||||
pendingFunctionExpression = ['=', '(', '[', ',', ':', 'return', '?', '&', '|', '>']
|
||||
.includes(lastToken);
|
||||
}
|
||||
const keyword = !memberName && regexPrefixWords.has(value);
|
||||
const forOf = value === 'of' && parens.at(-1) === 'for'
|
||||
&& canEndExpression && !memberName;
|
||||
canEndExpression = !keyword && !forOf;
|
||||
if (atStatementStart && switchBodies.at(-1)
|
||||
&& (value === 'case' || value === 'default')) {
|
||||
caseLabelDepth = { braces: braces.length, parens: parens.length,
|
||||
brackets: bracketDepth };
|
||||
caseTernaryDepth = 0;
|
||||
}
|
||||
labelCandidate = atStatementStart && !memberName
|
||||
&& value !== 'case' && value !== 'default';
|
||||
statementStart = value === 'else' || value === 'do';
|
||||
lastControlWord = !memberName && controlWords.has(value) ? value : '';
|
||||
lastToken = value;
|
||||
i += value.length;
|
||||
} else if (number) {
|
||||
i += number[0].length;
|
||||
canEndExpression = true;
|
||||
lastToken = 'value';
|
||||
statementStart = false;
|
||||
labelCandidate = false;
|
||||
} else if ((c === '+' && next === '+') || (c === '-' && next === '-')) {
|
||||
i += 2;
|
||||
lastToken = c + next;
|
||||
statementStart = false;
|
||||
labelCandidate = false;
|
||||
} else if (c === '?' && next === '?') {
|
||||
i += 2;
|
||||
canEndExpression = false;
|
||||
lastToken = '??';
|
||||
statementStart = false;
|
||||
labelCandidate = false;
|
||||
} else {
|
||||
i++;
|
||||
canEndExpression = false;
|
||||
lastToken = c;
|
||||
if (c === '?' && atCaseLabelDepth()) caseTernaryDepth++;
|
||||
statementStart = c === ';';
|
||||
labelCandidate = false;
|
||||
}
|
||||
}
|
||||
if (lastToken !== '.') memberName = false;
|
||||
if (lastToken !== 'if' && lastToken !== 'while' && lastToken !== 'for'
|
||||
&& lastToken !== 'switch' && lastToken !== 'catch' && lastToken !== 'with') {
|
||||
lastControlWord = '';
|
||||
}
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
scanCode(0, false);
|
||||
return { scanned: out.join(''), regexStart };
|
||||
}
|
||||
|
||||
function unsupportedConstruct(description, line) {
|
||||
return {
|
||||
message: 'Unsupported in the APPSYNC_JS runtime: ' + description + ' (line ' + line
|
||||
+ '). AWS runs resolvers on a restricted JavaScript runtime, not Node, so this code '
|
||||
+ 'would be rejected on deploy.',
|
||||
type: 'UnsupportedFeature'
|
||||
};
|
||||
}
|
||||
|
||||
function validateAppSyncSubset(code) {
|
||||
const scanned = blankLiterals(code);
|
||||
const literals = blankLiterals(code);
|
||||
const lineNumber = (index) => code.slice(0, index).split(/\r\n|[\r\n\u2028\u2029]/).length;
|
||||
for (const [pattern, description] of BANNED_CONSTRUCTS) {
|
||||
const match = pattern.exec(scanned);
|
||||
const match = pattern.exec(literals.scanned);
|
||||
if (match) {
|
||||
const line = code.slice(0, match.index).split('\n').length;
|
||||
return {
|
||||
message: 'Unsupported in the APPSYNC_JS runtime: ' + description + ' (line ' + line
|
||||
+ '). AWS runs resolvers on a restricted JavaScript runtime, not Node, so this code '
|
||||
+ 'would be rejected on deploy.',
|
||||
type: 'UnsupportedFeature'
|
||||
};
|
||||
return unsupportedConstruct(description, lineNumber(match.index));
|
||||
}
|
||||
}
|
||||
if (literals.regexStart !== -1) {
|
||||
return unsupportedConstruct('regular expressions', lineNumber(literals.regexStart));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
+327
-2
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.appsync;
|
||||
|
||||
import com.fasterxml.jackson.core.io.JsonStringEncoder;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.github.hectorvent.floci.testing.SidecarContainersProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
@@ -52,7 +53,26 @@ class AppSyncJsResolverDockerIntegrationTest {
|
||||
asyncResolver: String
|
||||
importsNode: String
|
||||
loops: String
|
||||
withStatement: String
|
||||
misplacedAwait: String
|
||||
misplacedYield: String
|
||||
malformedSyntax: String
|
||||
keywordsInText: String
|
||||
regexLiteral: String
|
||||
regexKeyword: String
|
||||
regexClassThenUnsupported: String
|
||||
regexDivision: String
|
||||
forOfIdentifierDivision: String
|
||||
regexAfterCaseBlock(n: Int): String
|
||||
regexAfterLabelBlock: String
|
||||
commentCr: String
|
||||
commentLineSeparator: String
|
||||
commentParagraphSeparator: String
|
||||
divisionAfterFunction: String
|
||||
divisionAfterObject: String
|
||||
taggedRawInvalidEscape: String
|
||||
taggedRawInvalidEscapeHole: String
|
||||
untaggedInvalidEscape: String
|
||||
normalizeString: String
|
||||
}
|
||||
""";
|
||||
@@ -159,6 +179,35 @@ class AppSyncJsResolverDockerIntegrationTest {
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String WITH_RESOLVER = """
|
||||
export function request(ctx) {
|
||||
with (ctx) { return { payload: { value: "nope" } }; }
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String AWAIT_RESOLVER = """
|
||||
export function request(ctx) {
|
||||
await 1;
|
||||
return { payload: { value: "nope" } };
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String YIELD_RESOLVER = """
|
||||
export function request(ctx) {
|
||||
yield 1;
|
||||
return { payload: { value: "nope" } };
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String MALFORMED_RESOLVER = """
|
||||
export function request(ctx) {
|
||||
// with await yield
|
||||
const text = "with";
|
||||
const value = ;
|
||||
return { payload: { value } };
|
||||
}
|
||||
""";
|
||||
|
||||
/** The same keywords, but only inside a string, a comment and a template: still valid. */
|
||||
private static final String KEYWORDS_IN_TEXT_RESOLVER = """
|
||||
export function request(ctx) {
|
||||
@@ -171,6 +220,119 @@ class AppSyncJsResolverDockerIntegrationTest {
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String REGEX_KEYWORD_RESOLVER = """
|
||||
export function request(ctx) {
|
||||
return { payload: { value: /while/.test("while") } };
|
||||
}
|
||||
export function response(ctx) {
|
||||
return String(ctx.result.value);
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String REGEX_LITERAL_RESOLVER = """
|
||||
export function request(ctx) {
|
||||
return { payload: { value: /foo/.test("foo") } };
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String REGEX_CLASS_UNSUPPORTED_RESOLVER = """
|
||||
export function request(ctx) {
|
||||
return { payload: { value: /[//]/.test("/") && this.value } };
|
||||
}
|
||||
export function response(ctx) {
|
||||
return ctx.result.value;
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String REGEX_DIVISION_RESOLVER = """
|
||||
export function request(ctx) {
|
||||
const sum = (value) => value;
|
||||
return { payload: { value: `${sum(6) / 2}% vs ${sum(8) / 2}%` } };
|
||||
}
|
||||
export function response(ctx) {
|
||||
return ctx.result.value;
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String FOR_OF_IDENTIFIER_DIVISION_RESOLVER = """
|
||||
export function request(ctx) {
|
||||
const of = 8;
|
||||
for (const value of [of / 2 / 2]) {
|
||||
return { payload: { value: String(value) } };
|
||||
}
|
||||
}
|
||||
export function response(ctx) {
|
||||
return ctx.result.value;
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String REGEX_AFTER_CASE_BLOCK_RESOLVER = """
|
||||
export function request(ctx) {
|
||||
switch (ctx.args.n) { case 1: {} /foo/.test("foo"); }
|
||||
return { payload: { value: "unreachable" } };
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String REGEX_AFTER_LABEL_BLOCK_RESOLVER = """
|
||||
export function request(ctx) {
|
||||
label: {} /foo/.test("foo");
|
||||
return { payload: { value: "unreachable" } };
|
||||
}
|
||||
""";
|
||||
|
||||
static final String COMMENT_CR_RESOLVER = """
|
||||
export function request(ctx) {
|
||||
// comment\rwhile(false) {}
|
||||
return { payload: { value: "unreachable" } };
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String COMMENT_LINE_SEPARATOR_RESOLVER =
|
||||
"export function request(ctx) { // comment" + Character.toString(0x2028)
|
||||
+ "const pattern = /foo/; return { payload: { value: pattern.test('foo') } }; }";
|
||||
|
||||
private static final String COMMENT_PARAGRAPH_SEPARATOR_RESOLVER =
|
||||
"export function request(ctx) { // comment" + Character.toString(0x2029)
|
||||
+ "return { payload: { value: this } }; }";
|
||||
|
||||
private static final String DIVISION_AFTER_FUNCTION_RESOLVER = """
|
||||
export function request(ctx) {
|
||||
const value = function() {} / 2;
|
||||
while (false) {}
|
||||
return { payload: { value } };
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String DIVISION_AFTER_OBJECT_RESOLVER = """
|
||||
export function request(ctx) {
|
||||
const value = true ? { x: 1 } / this : 2;
|
||||
return { payload: { value } };
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String TAGGED_RAW_INVALID_ESCAPE_RESOLVER = """
|
||||
export function request(ctx) {
|
||||
const raw = (parts) => parts.raw[0];
|
||||
return { payload: { value: raw`\\x while` } };
|
||||
}
|
||||
export function response(ctx) {
|
||||
return ctx.result.value;
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String TAGGED_RAW_INVALID_ESCAPE_HOLE_RESOLVER = """
|
||||
export function request(ctx) {
|
||||
const raw = (parts, value) => value;
|
||||
return { payload: { value: raw`\\x while ${(() => { while (false) {} return 1; })()}` } };
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String UNTAGGED_INVALID_ESCAPE_RESOLVER = """
|
||||
export function request(ctx) {
|
||||
return { payload: { value: `\\x while` } };
|
||||
}
|
||||
""";
|
||||
|
||||
private String apiId;
|
||||
private String apiKey;
|
||||
private static final String NORMALIZE_STRING_RESOLVER = """
|
||||
@@ -214,7 +376,34 @@ class AppSyncJsResolverDockerIntegrationTest {
|
||||
createUnitResolver(apiId, "Query", "asyncResolver", "local", ASYNC_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "importsNode", "local", NODE_IMPORT_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "loops", "local", WHILE_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "withStatement", "local", WITH_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "misplacedAwait", "local", AWAIT_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "misplacedYield", "local", YIELD_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "malformedSyntax", "local", MALFORMED_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "keywordsInText", "local", KEYWORDS_IN_TEXT_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "regexLiteral", "local", REGEX_LITERAL_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "regexKeyword", "local", REGEX_KEYWORD_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "regexClassThenUnsupported", "local",
|
||||
REGEX_CLASS_UNSUPPORTED_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "regexDivision", "local", REGEX_DIVISION_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "forOfIdentifierDivision", "local",
|
||||
FOR_OF_IDENTIFIER_DIVISION_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "regexAfterCaseBlock", "local", REGEX_AFTER_CASE_BLOCK_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "regexAfterLabelBlock", "local", REGEX_AFTER_LABEL_BLOCK_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "commentCr", "local", COMMENT_CR_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "commentLineSeparator", "local", COMMENT_LINE_SEPARATOR_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "commentParagraphSeparator", "local",
|
||||
COMMENT_PARAGRAPH_SEPARATOR_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "divisionAfterFunction", "local",
|
||||
DIVISION_AFTER_FUNCTION_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "divisionAfterObject", "local",
|
||||
DIVISION_AFTER_OBJECT_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "taggedRawInvalidEscape", "local",
|
||||
TAGGED_RAW_INVALID_ESCAPE_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "taggedRawInvalidEscapeHole", "local",
|
||||
TAGGED_RAW_INVALID_ESCAPE_HOLE_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "untaggedInvalidEscape", "local",
|
||||
UNTAGGED_INVALID_ESCAPE_RESOLVER);
|
||||
createUnitResolver(apiId, "Query", "normalizeString", "local", NORMALIZE_STRING_RESOLVER);
|
||||
}
|
||||
|
||||
@@ -375,6 +564,29 @@ class AppSyncJsResolverDockerIntegrationTest {
|
||||
.body("errors[0].message", containsString("while"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void strictModeFailuresKeepTheirUnsupportedFeatureDiagnostics() {
|
||||
query("{ withStatement }")
|
||||
.statusCode(200)
|
||||
.body("errors[0].errorType", equalTo("UnsupportedFeature"))
|
||||
.body("errors[0].message", containsString("with statements"));
|
||||
query("{ misplacedAwait }")
|
||||
.statusCode(200)
|
||||
.body("errors[0].errorType", equalTo("UnsupportedFeature"))
|
||||
.body("errors[0].message", containsString("await"));
|
||||
query("{ misplacedYield }")
|
||||
.statusCode(200)
|
||||
.body("errors[0].errorType", equalTo("UnsupportedFeature"))
|
||||
.body("errors[0].message", containsString("generators"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedCodeWithBannedWordsOnlyInLiteralsRemainsSyntaxError() {
|
||||
query("{ malformedSyntax }")
|
||||
.statusCode(200)
|
||||
.body("errors[0].errorType", equalTo("SyntaxError"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSameKeywordsInStringsAndCommentsAreNotRefused() {
|
||||
// The check would be worse than useless if it rejected valid resolvers, so the scan blanks
|
||||
@@ -385,6 +597,119 @@ class AppSyncJsResolverDockerIntegrationTest {
|
||||
.body("data.keywordsInText", equalTo("try catch class while ok"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRegexLiteralIsReportedAsUnsupported() {
|
||||
query("{ regexLiteral }")
|
||||
.statusCode(200)
|
||||
.body("data.regexLiteral", nullValue())
|
||||
.body("errors[0].errorType", equalTo("UnsupportedFeature"))
|
||||
.body("errors[0].message", containsString("regular expressions"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeywordInsideARegexLiteralIsReportedAsUnsupportedRegex() {
|
||||
query("{ regexKeyword }")
|
||||
.statusCode(200)
|
||||
.body("data.regexKeyword", nullValue())
|
||||
.body("errors[0].errorType", equalTo("UnsupportedFeature"))
|
||||
.body("errors[0].message", containsString("regular expressions"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void slashesInsideARegexCharacterClassCannotHideUnsupportedCode() {
|
||||
query("{ regexClassThenUnsupported }")
|
||||
.statusCode(200)
|
||||
.body("data.regexClassThenUnsupported", nullValue())
|
||||
.body("errors[0].errorType", equalTo("UnsupportedFeature"))
|
||||
.body("errors[0].message", containsString("this"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void divisionInsideTwoTemplateInterpolationsIsNotReadAsRegex() {
|
||||
query("{ regexDivision }")
|
||||
.statusCode(200)
|
||||
.body("errors", nullValue())
|
||||
.body("data.regexDivision", equalTo("3% vs 4%"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIdentifierNamedOfInsideAForOfIterableKeepsDivisionOperators() {
|
||||
query("{ forOfIdentifierDivision }")
|
||||
.statusCode(200)
|
||||
.body("errors", nullValue())
|
||||
.body("data.forOfIdentifierDivision", equalTo("2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void regexAfterCaseAndLabelBlocksIsRefused() {
|
||||
query("{ regexAfterCaseBlock(n: 1) }")
|
||||
.statusCode(200)
|
||||
.body("data.regexAfterCaseBlock", nullValue())
|
||||
.body("errors[0].errorType", equalTo("UnsupportedFeature"))
|
||||
.body("errors[0].message", containsString("regular expressions"));
|
||||
query("{ regexAfterLabelBlock }")
|
||||
.statusCode(200)
|
||||
.body("data.regexAfterLabelBlock", nullValue())
|
||||
.body("errors[0].errorType", equalTo("UnsupportedFeature"))
|
||||
.body("errors[0].message", containsString("regular expressions"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyJavaScriptLineTerminatorEndsALineComment() {
|
||||
query("{ commentCr }")
|
||||
.statusCode(200)
|
||||
.body("errors[0].errorType", equalTo("UnsupportedFeature"))
|
||||
.body("errors[0].message", containsString("while loops"));
|
||||
query("{ commentLineSeparator }")
|
||||
.statusCode(200)
|
||||
.body("errors[0].errorType", equalTo("UnsupportedFeature"))
|
||||
.body("errors[0].message", containsString("regular expressions"));
|
||||
query("{ commentParagraphSeparator }")
|
||||
.statusCode(200)
|
||||
.body("errors[0].errorType", equalTo("UnsupportedFeature"))
|
||||
.body("errors[0].message", containsString("this"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void divisionAfterFunctionExpressionDoesNotHideLaterUnsupportedCode() {
|
||||
query("{ divisionAfterFunction }")
|
||||
.statusCode(200)
|
||||
.body("errors[0].errorType", equalTo("UnsupportedFeature"))
|
||||
.body("errors[0].message", containsString("while loops"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void divisionAfterTernaryObjectDoesNotHideLaterUnsupportedCode() {
|
||||
query("{ divisionAfterObject }")
|
||||
.statusCode(200)
|
||||
.body("errors[0].errorType", equalTo("UnsupportedFeature"))
|
||||
.body("errors[0].message", containsString("this"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidEscapeInTaggedRawTemplateDoesNotExposeKeywordsToSubsetScan() {
|
||||
query("{ taggedRawInvalidEscape }")
|
||||
.statusCode(200)
|
||||
.body("errors", nullValue())
|
||||
.body("data.taggedRawInvalidEscape", equalTo("\\x while"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidEscapeInUntaggedTemplateRemainsSyntaxError() {
|
||||
query("{ untaggedInvalidEscape }")
|
||||
.statusCode(200)
|
||||
.body("errors[0].errorType", equalTo("SyntaxError"))
|
||||
.body("errors[0].message", containsString("escape sequence"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidEscapeInTaggedRawTemplateStillScansExpressions() {
|
||||
query("{ taggedRawInvalidEscapeHole }")
|
||||
.statusCode(200)
|
||||
.body("errors[0].errorType", equalTo("UnsupportedFeature"))
|
||||
.body("errors[0].message", containsString("while loops"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFieldWithNoResolverStillResolvesFromItsParent() {
|
||||
// Message.id and Message.name have no resolvers of their own: they come off the objects the
|
||||
@@ -509,7 +834,7 @@ class AppSyncJsResolverDockerIntegrationTest {
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private static String escape(String value) {
|
||||
return value.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n");
|
||||
static String escape(String value) {
|
||||
return new String(JsonStringEncoder.getInstance().quoteAsString(value));
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package io.github.hectorvent.floci.services.appsync;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class AppSyncJsResolverDockerJsonTest {
|
||||
|
||||
@Test
|
||||
void carriageReturnResolverCodeRemainsValidJson() throws Exception {
|
||||
String code = AppSyncJsResolverDockerIntegrationTest.COMMENT_CR_RESOLVER;
|
||||
String request = "{\"code\":\"" + AppSyncJsResolverDockerIntegrationTest.escape(code) + "\"}";
|
||||
|
||||
assertEquals(code, new ObjectMapper().readTree(request).get("code").asText());
|
||||
}
|
||||
}
|
||||
+54
-5
@@ -25,6 +25,7 @@ import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -122,17 +123,35 @@ class NodeAppSyncJsRuntimeTest {
|
||||
assertTrue(requestedPaths.contains("/evaluate"), "the evaluation goes to the configured URL");
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchCommandCarriesOnlyTheServerWithinTheShellArgumentLimit() throws IOException {
|
||||
String command = runtime.startCommand();
|
||||
assertTrue(command.length() < 128 * 1024, "container command exceeds Linux MAX_ARG_STRLEN");
|
||||
|
||||
String[] sections = command.split("echo ");
|
||||
assertEquals(2, sections.length);
|
||||
assertTrue(sections[1].contains("| base64 -d > /tmp/floci-appsync-js-runtime.mjs"));
|
||||
assertEquals(resource("appsync/appsync-js-runtime.mjs"), decode(sections[1]));
|
||||
}
|
||||
|
||||
private static String resource(String path) throws IOException {
|
||||
try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(path)) {
|
||||
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
|
||||
private static String decode(String section) {
|
||||
String encoded = section.substring(0, section.indexOf(' '));
|
||||
return new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSurvivingSidecarIsAdoptedThroughTheNetworkItWasCreatedOn() throws IOException {
|
||||
when(jsRuntime.url()).thenReturn(Optional.empty());
|
||||
when(jsRuntime.containerName()).thenReturn("appsync-js-runtime-test");
|
||||
when(jsRuntime.dockerNetwork()).thenReturn(Optional.of("js-net"));
|
||||
when(containerBuilder.resolveDockerNetwork(Optional.of("js-net"))).thenReturn(Optional.of("js-net"));
|
||||
String digest;
|
||||
try (InputStream in = Thread.currentThread().getContextClassLoader()
|
||||
.getResourceAsStream("appsync/appsync-js-runtime.mjs")) {
|
||||
digest = Digests.sha256Hex(new String(in.readAllBytes(), StandardCharsets.UTF_8)).substring(0, 16);
|
||||
}
|
||||
String digest = Digests.sha256Hex(resource("appsync/appsync-js-runtime.mjs")).substring(0, 16);
|
||||
Container survivor = mock(Container.class);
|
||||
when(survivor.getId()).thenReturn("survivor");
|
||||
when(survivor.getLabels()).thenReturn(Map.of("io.floci.appsync.js-runtime.script", digest));
|
||||
@@ -147,6 +166,36 @@ class NodeAppSyncJsRuntimeTest {
|
||||
verify(lifecycleManager, never()).createAndStart(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSidecarWithAnOldScriptDigestIsReplaced() throws IOException {
|
||||
when(jsRuntime.url()).thenReturn(Optional.empty());
|
||||
when(jsRuntime.image()).thenReturn("node:22-alpine");
|
||||
when(jsRuntime.containerName()).thenReturn("appsync-js-runtime-test");
|
||||
when(jsRuntime.port()).thenReturn(0);
|
||||
when(jsRuntime.startTimeoutSeconds()).thenReturn(5);
|
||||
when(jsRuntime.dockerNetwork()).thenReturn(Optional.empty());
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(false);
|
||||
|
||||
Container stale = mock(Container.class);
|
||||
when(stale.getId()).thenReturn("old-script");
|
||||
when(stale.getLabels()).thenReturn(Map.of(
|
||||
"io.floci.appsync.js-runtime.script", "old-script-digest"));
|
||||
when(lifecycleManager.findByName(anyString())).thenReturn(Optional.of(stale));
|
||||
|
||||
ContainerBuilder.Builder builder =
|
||||
mock(ContainerBuilder.Builder.class, withSettings().defaultAnswer(Answers.RETURNS_SELF));
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
|
||||
when(builder.build()).thenReturn(new ContainerSpec("test-image"));
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("new-script",
|
||||
Map.of(4600, new EndpointInfo("127.0.0.1", server.getAddress().getPort()))));
|
||||
|
||||
runtime.ensureStarted();
|
||||
|
||||
verify(lifecycleManager).stopAndRemove("old-script", null);
|
||||
verify(lifecycleManager, never()).adopt(anyString(), any(), any());
|
||||
verify(lifecycleManager).createAndStart(any());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The window the concurrency fix closes: a failing evaluation used to clear containerId without
|
||||
|
||||
Reference in new issue
Block a user