Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/bson-transpilers/symbols/python/templates.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ Templates:
(str.charAt(0) === '"' && str.charAt(str.length - 1) === '"')) {
newStr = str.substr(1, str.length - 2);
}
return `'${newStr.replace(/\\([\s\S])|(")/g, '\\$1$2')}'`;
return `'${newStr.replace(/\\([\s\S])|(')/g, '\\$1$2')}'`;
}

const pairs = args.map((arg) => {
Expand Down
63 changes: 52 additions & 11 deletions packages/bson-transpilers/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,22 @@ describe('bson transpiler', function () {
});
});

describe('quoting of collection names', function () {
// The delimiter each language's DriverTemplate wraps string literals in.
const DELIMITERS = {
python: "'",
javascript: "'",
ruby: "'",
php: "'",
java: '"',
go: '"',
rust: '"',
};
// The delimiter each language's DriverTemplate wraps string literals in.
const DELIMITERS = {
python: "'",
javascript: "'",
ruby: "'",
php: "'",
java: '"',
go: '"',
rust: '"',
};

/**
* A collection name arrives as a decoded string (Compass hands it the real namespace),
* so a literal backslash must be escaped to survive.
*/
describe('quoting of collection names', function () {
const NAMES = [
"a'b]c",
'a"b]c',
Expand Down Expand Up @@ -109,4 +113,41 @@ describe('bson transpiler', function () {
);
});
});

/**
* An object key arrives as raw source text the user typed, where \b is already a JS
* escape pair and re-escaping it would change the field being queried.
*/
describe('quoting of object keys', function () {
const PWN = String.raw`a': 1}}]; __import__('os').system('echo PWNED'); y=[{ 'm': { 'X`;
// [quote wrapping the key in the shell input, key text inside those quotes]
const KEYS = [
['"', String.raw`a'b`],
["'", String.raw`a"b`],
['"', String.raw`a\\b`],
['"', String.raw`a\'b`],
['"', String.raw`a\"b'c`],
['"', PWN],
];

const emit = (lang, wrap, key) =>
transpilers.shell[lang].compile(
`[{$match: {${wrap}${key}${wrap}: 1}}]`,
false
);

// Keys reach the emitter as raw source text, not as decoded values, so an
// escape the user wrote is passed through. Only a bare delimiter is escaped.
Object.entries({ ...DELIMITERS }).forEach(([lang, quote]) => {
KEYS.forEach(([wrap, key]) => {
it(`${lang}: quotes key ${JSON.stringify(key)}`, function () {
const want = `${quote}${key.replace(/\\[\s\S]|['"]/g, (m) =>
m.length === 2 || m !== quote ? m : `\\${m}`
)}${quote}`;
const got = emit(lang, wrap, key);
assert.ok(got.includes(want), `want ${want} in:\n${got}`);
});
});
});
});
});
Loading