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
17 changes: 17 additions & 0 deletions packages/backend/src/common/env-interpolation.util.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,23 @@ describe('EnvInterpolation', () => {
const set = interpolateConnectorConfig({ baseUrl: 'https://api.example.com' }, mapping, { ...envVars, XERO_TENANT_ID: 'tenant-1' });
expect(set.endpointMapping.headers!['xero-tenant-id']).toBe('tenant-1');
});

it('keeps the placeholder of an empty setting in a bare JSON body slot', () => {
// Odoo JSON-RPC: `"args":["{{ODOO_DB}}",{{ODOO_UID}},...]`. An empty
// ODOO_UID rendered `["db",,"key"]`, a parse error that named nothing.
const mapping = {
method: 'POST',
path: '/jsonrpc',
bodyTemplate: '{"args":["{{ODOO_DB}}",{{ODOO_UID}},"{{ODOO_KEY}}"],"note":"{{ODOO_NOTE}}"}',
};
const vars = { ODOO_DB: 'db', ODOO_UID: '', ODOO_KEY: 'k"1', ODOO_NOTE: '' };
const empty = interpolateConnectorConfig({ baseUrl: 'https://erp.example.com' }, mapping, vars);
expect(empty.endpointMapping.bodyTemplate).toBe(
'{"args":["db",{{ODOO_UID}},"k\\"1"],"note":""}',
);
const set = interpolateConnectorConfig({ baseUrl: 'https://erp.example.com' }, mapping, { ...vars, ODOO_UID: '7' });
expect(JSON.parse(set.endpointMapping.bodyTemplate!)).toEqual({ args: ['db', 7, 'k"1'], note: '' });
});
});

// ── ReDoS regression ──────────────────────────────────────────────────────
Expand Down
44 changes: 40 additions & 4 deletions packages/backend/src/common/env-interpolation.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,10 +185,12 @@ export function interpolateConnectorConfig(
// the document. Without this, {{VAR}} (and {{amcp.*}}) silently reached
// the target system unresolved.
bodyTemplate: endpointMapping.bodyTemplate
? interpolateString(endpointMapping.bodyTemplate, envVars, {
...options,
...(xmlBody ? { xmlEscape: true } : { jsonEscape: true }),
})
? xmlBody
? interpolateString(endpointMapping.bodyTemplate, envVars, {
...options,
xmlEscape: true,
})
: interpolateJsonBodyTemplate(endpointMapping.bodyTemplate, envVars, options)
: undefined,
headers: endpointMapping.headers
? interpolateToolHeaders(endpointMapping.headers, envVars, options)
Expand All @@ -197,6 +199,40 @@ export function interpolateConnectorConfig(
};
}

/**
* A JSON bodyTemplate, interpolated with JSON escaping, except that a
* variable set to an empty string in a bare (unquoted) slot keeps its
* placeholder. `[{{ODOO_UID}}, ...]` with an empty setting would become
* `[, ...]`: invalid JSON either way, but the placeholder lets the engine
* name the setting that needs a value instead of a bare parse error.
*/
function interpolateJsonBodyTemplate(
template: string,
envVars: Record<string, string>,
options?: InterpolateOptions,
): string {
const jsonOptions = { ...options, jsonEscape: true };
const keepEmpty = new Set(
Object.keys(envVars ?? {}).filter((k) => typeof envVars[k] === 'string' && envVars[k].trim() === ''),
);
if (keepEmpty.size === 0) return interpolateString(template, envVars, jsonOptions);
return template.replace(VAR_PATTERN, (match, varName, offset: number) => {
if (keepEmpty.has(varName.trim()) && isBareJsonSlot(template, offset, match.length)) return match;
return interpolateString(match, envVars, jsonOptions);
});
}

/** True when the placeholder at `offset` is not inside a JSON string. */
function isBareJsonSlot(template: string, offset: number, length: number): boolean {
let before = offset - 1;
while (before >= 0 && /\s/.test(template[before])) before--;
let after = offset + length;
while (after < template.length && /\s/.test(template[after])) after++;
const prev = before >= 0 ? template[before] : '';
const next = after < template.length ? template[after] : '';
return /[:,[]/.test(prev) && /[,\]}]/.test(next);
}

/** A value that is exactly one `{{VAR}}` placeholder. */
const ONLY_VARIABLE = /^\{\{([^{}]+)\}\}$/;

Expand Down
6 changes: 6 additions & 0 deletions packages/backend/src/connectors/engines/rest.engine.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2480,6 +2480,12 @@ describe('RestEngine — bodyTemplate that will not parse', () => {
expect(err.message).not.toMatch(/No value was supplied/);
});

it('names a connector setting that has no value', async () => {
const err: any = await call('{"args":["db",{{ODOO_UID}},"${model}"]}', { model: 'res.partner' }).catch((e) => e);
expect(err.message).toMatch(/The connector setting `ODOO_UID` has no value/);
expect(err.message).not.toMatch(/No value was supplied/);
});

it('never repeats a rendered value, which may be a credential', async () => {
const err: any = await call('{"t": "${token}",,}', {
token: 'super-secret',
Expand Down
22 changes: 19 additions & 3 deletions packages/backend/src/connectors/engines/rest.engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -525,9 +525,14 @@ export class RestEngine {
// placeholders that had nothing to substitute: that is the usual
// cause and the only part that is safe to repeat.
const missing = missingTemplateParams(template, templateParams);
const hint = missing.length
? ` No value was supplied for ${missing.map((m) => `\`\${${m}}\``).join(', ')}, which is the usual cause.`
: '';
const settings = unresolvedSettings(template);
const hint =
(missing.length
? ` No value was supplied for ${missing.map((m) => `\`\${${m}}\``).join(', ')}, which is the usual cause.`
: '') +
(settings.length
? ` The connector setting${settings.length > 1 ? 's' : ''} ${settings.map((s) => `\`${s}\``).join(', ')} ${settings.length > 1 ? 'have' : 'has'} no value: fill ${settings.length > 1 ? 'them' : 'it'} in on the connector page.`
: '');
throw new Error(
`bodyTemplate produced invalid JSON after interpolation (${jsonParseErrorKind(e)}).${hint}`,
);
Expand Down Expand Up @@ -2784,6 +2789,17 @@ function missingTemplateParams(
return [...referenced].filter((name) => params[name] === undefined);
}

/**
* Connector settings (`{{NAME}}`) still in a bodyTemplate after the env vars
* were applied: interpolation keeps the placeholder of a setting that is
* missing, or empty in a bare JSON slot. Names only, never values.
*/
function unresolvedSettings(template: string): string[] {
const names = new Set<string>();
for (const m of template.matchAll(/\{\{\s*([A-Za-z_][\w.]*)\s*\}\}/g)) names.add(m[1]);
return [...names];
}

/**
* Render an XML body template (`bodyEncoding: "xml"`): every `${name}` becomes
* the parameter's value, XML-escaped; a missing one becomes empty. No quoting
Expand Down
Loading