Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,46 @@ describe('getMongoshCommand', () => {
);
});
}

const encodings = [
['$(value)', '%24(value)'],
['`value`', '%60value%60'],
['";value', '%22;value'],
['\\', '%5C'],
['!value', '%21value'],
['\u201Cvalue\u201D', '%E2%80%9Cvalue%E2%80%9D'],
[';', ';'],
["it's", "it's"],
];

for (const [input, encoded] of encodings) {
it(`encodes ${JSON.stringify(input)} as ${encoded}`, () => {
const getCommand = (connectionString: string) =>
getMongoshCommand({
id: 'test',
connectionOptions: { connectionString },
}).command;

expect(getCommand(`mongodb://h${input}:27017/`)).to.equal(
`mongosh "mongodb://h${encoded}:27017/" --file mockdatascript.js`
);
expect(getCommand(`mongodb://localhost/db${input}`)).to.equal(
`mongosh "mongodb://localhost/db${encoded}" --file mockdatascript.js`
);
expect(getCommand(`mongodb://localhost/?appName=${input}`)).to.equal(
`mongosh "mongodb://localhost/?appName=${encoded}" --file mockdatascript.js`
);
});
}

it('round-trips to the same URI after decoding', () => {
const { command } = getMongoshCommand({
id: 'test',
connectionOptions: {
connectionString: 'mongodb://localhost/db?appName=$(x)%60\\',
},
});
const quoted = command.match(/^mongosh "([^"]*)"/)?.[1] as string;
expect(new URL(quoted).searchParams.get('appName')).to.equal('$(x)`\\');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ import ConnectionString, {
} from 'mongodb-connection-string-url';
import { DEFAULT_CONNECTION_STRING_FALLBACK } from './constants';

// Percent-encodes characters that bash/zsh and PowerShell treat specially
// inside double quotes, so the argument stays literal and drivers decode it
// back to the same URI.
function encodeShell(uri: string) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Maybe encodeShell is a bit vague name for what it's actually doing. Maybe something like escapeForShellDoubleQuotes can describe better what's doing here 🤔

return uri.replace(/["$`\\!]|[^\x20-\x7e]/gu, (char) =>
// encodeURIComponent leaves "!" as is.
char === '!' ? '%21' : encodeURIComponent(char)
);
}

export function getMongoshCommand(connectionInfo: ConnectionInfo) {
const isAtlas = !!connectionInfo.atlasMetadata;
const uri =
Expand Down Expand Up @@ -42,7 +52,7 @@ export function getMongoshCommand(connectionInfo: ConnectionInfo) {

const command = [
'mongosh',
`"${connectionString}"`,
`"${encodeShell(connectionString)}"`,
...(needsUsername ? ['--username', '"<your-username>"'] : []),
'--file',
'mockdatascript.js',
Expand Down
Loading