Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(sdk): require the key validation route of every SDK

Yudhi Armyndharis74bb7024a1b4
diff --git a/scripts/check-contract-shapes.mjs b/scripts/check-contract-shapes.mjs
index c165e42c8..4acc088d8 100644
--- a/scripts/check-contract-shapes.mjs
+++ b/scripts/check-contract-shapes.mjs
@@ -1357,7 +1357,7 @@ export function unexposedResources(readme) {
const end = readme.indexOf('Everything else the gateway publishes', start);
if (start < 0 || end < 0) {
throw new Error(
- 'sdk/README.md: could not find the "Deliberately not exposed" paragraph, so the schema coverage check cannot derive its scope.',
+ 'sdk/README.md: could not find the "Deliberately not exposed" paragraph, so the gates that derive their scope from it cannot run.',
);
}
const paragraph = readme.slice(start, end).replace(/\([^)]*\)/g, '');
@@ -1368,6 +1368,19 @@ export function unexposedResources(readme) {
return new Set(names);
}
+/**
+ * Whether the README leaves a contract path unexposed: its resource is listed, or it lies under a listed
+ * path such as `auth/api-keys` (and `/api/auth/api-keys-other` does not). Shared with check-sdk-coverage.mjs.
+ */
+export function isUnexposedPath(path, unexposed) {
+ const shape = path.replace(/\{[^}]*\}/g, '*');
+ const resource = /^\/api\/sessions\/\*\/([^/]+)/.exec(shape)?.[1] ?? /^\/api\/([^/*]+)/.exec(shape)?.[1] ?? '';
+ if (unexposed.has(resource) || unexposed.has(resource.replace(/-rules$/, ''))) return true;
+ return [...unexposed].some(
+ entry => entry.includes('/') && (shape === `/api/${entry}` || shape.startsWith(`/api/${entry}/`)),
+ );
+}
+
/**
* Every schema an exposed operation sends or returns, nested ones included: request bodies and 2xx
* responses only, so the shared error envelope is not asked for. A nested schema counts because a
@@ -1386,12 +1399,8 @@ export function exposedSchemas(openapi, unexposed) {
}
Object.values(node).forEach(visit);
};
- const prefixes = [...unexposed].filter(entry => entry.includes('/')).map(entry => `/api/${entry}`);
for (const [path, item] of Object.entries(openapi.paths)) {
- const shape = path.replace(/\{[^}]*\}/g, '*');
- const resource = /^\/api\/sessions\/\*\/([^/]+)/.exec(shape)?.[1] ?? /^\/api\/([^/*]+)/.exec(shape)?.[1] ?? '';
- if (unexposed.has(resource) || unexposed.has(resource.replace(/-rules$/, ''))) continue;
- if (prefixes.some(prefix => shape === prefix || shape.startsWith(`${prefix}/`))) continue;
+ if (isUnexposedPath(path, unexposed)) continue;
for (const operation of Object.values(item)) {
if (!operation || typeof operation !== 'object') continue;
visit(operation.requestBody);
diff --git a/scripts/check-sdk-coverage.mjs b/scripts/check-sdk-coverage.mjs
index df9a9cd93..03800ea39 100644
--- a/scripts/check-sdk-coverage.mjs
+++ b/scripts/check-sdk-coverage.mjs
@@ -32,6 +32,7 @@
import { readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { isUnexposedPath, unexposedResources } from './check-contract-shapes.mjs';
// fileURLToPath, not URL.pathname: the latter stays percent-encoded, so a checkout under a path
// containing a space resolves to a directory that does not exist and every read here fails with
@@ -167,26 +168,6 @@ const SDKS = [
{ name: 'go', dir: 'sdk/go', exts: ['.go'], harvest: harvestGo },
];
-/**
- * The resources sdk/README.md declares deliberately unexposed, read from the README rather than
- * restated here: a hand-copied second list is the thing this whole line of work keeps finding.
- */
-function excludedResources() {
- const readme = readFileSync(join(root, 'sdk/README.md'), 'utf8');
- const start = readme.indexOf('Deliberately **not** exposed');
- const end = readme.indexOf('Everything else the gateway publishes', start);
- if (start < 0 || end < 0) {
- throw new Error('sdk/README.md: could not find the "Deliberately not exposed" paragraph — the gate cannot derive its exclusion list.');
- }
- const names = [...readme.slice(start, end).matchAll(/`([^`]+)`/g)].map((m) => m[1].split('/')[0].trim());
- if (names.length < 8) throw new Error(`sdk/README.md: parsed only ${names.length} excluded resources, expected the full list.`);
- return new Set(names);
-}
-
-// The resource a path belongs to: the segment after `/api/`, or after a session id.
-const resourceOf = (path) =>
- /^\/api\/sessions\/\*\/([^/]+)/.exec(path)?.[1] ?? /^\/api\/([^/*]+)/.exec(path)?.[1] ?? '';
-
/**
* A harvested path whose final segment is a wildcard MAY cover its concrete siblings: the client
* reaches that family through one builder with the last segment as a variable (`send-${type}`).
@@ -206,15 +187,14 @@ const covers = (built, path) => {
return isRouteNameFamily(family) && built.families.has(family);
};
-const excluded = excludedResources();
+// Read the way the shape gate reads it (entries as written, a parenthetical ignored, `auth/api-keys` a path
+// prefix): cutting every entry to its first segment made all of /api/auth unexposed, key validation included.
+const excluded = unexposedResources(readFileSync(join(root, 'sdk/README.md'), 'utf8'));
const contract = [...new Set(Object.keys(JSON.parse(readFileSync(join(root, 'openapi.json'), 'utf8')).paths).map(normalize))];
/** Every shape the contract publishes, including the excluded resources — a wildcard is explained by
* a by-id route whether or not the SDKs are asked to expose it. */
const contractShapes = new Set(contract);
-const inScope = contract.filter((p) => {
- const resource = resourceOf(p);
- return !excluded.has(resource) && !excluded.has(resource.replace(/-rules$/, ''));
-});
+const inScope = contract.filter((p) => !isUnexposedPath(p, excluded));
const errors = [];
const built = {};
diff --git a/scripts/check-sdk-coverage.spec.mjs b/scripts/check-sdk-coverage.spec.mjs
index 3a659f3a2..db575dbec 100644
--- a/scripts/check-sdk-coverage.spec.mjs
+++ b/scripts/check-sdk-coverage.spec.mjs
@@ -1,7 +1,7 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
-import { mkdtempSync, rmSync, symlinkSync } from 'node:fs';
+import { cpSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -49,3 +49,42 @@ test('a run through a symlinked path still reports', () => {
rmSync(dir, { recursive: true, force: true });
}
});
+
+test('the key validation route is required of every SDK, the key management routes are not', () => {
+ // sdk/README.md lists `auth/api-keys` as unexposed and says key validation itself is exposed. The scope used to
+ // cut every entry to its first segment, which made all of /api/auth unexposed, so an SDK without its auth()
+ // method kept the gate green. The gate runs on a copy of the sources it reads, with the PHP auth() emptied.
+ const repo = fileURLToPath(new URL('..', import.meta.url));
+ const dir = mkdtempSync(join(tmpdir(), 'sdk-coverage-copy-'));
+ try {
+ for (const path of [
+ 'scripts/check-sdk-coverage.mjs',
+ 'scripts/check-contract-shapes.mjs',
+ 'openapi.json',
+ 'sdk/README.md',
+ 'sdk/javascript/src',
+ 'sdk/python/openwa',
+ 'sdk/php/src',
+ 'sdk/java/src/main',
+ 'sdk/go',
+ ]) {
+ cpSync(join(repo, path), join(dir, path), { recursive: true });
+ }
+ const run = () =>
+ spawnSync(process.execPath, [join(dir, 'scripts', 'check-sdk-coverage.mjs')], { encoding: 'utf8' });
+ const whole = run();
+ assert.equal(whole.status, 0, whole.stdout + whole.stderr);
+
+ const client = join(dir, 'sdk', 'php', 'src', 'Client.php');
+ const source = readFileSync(client, 'utf8');
+ const call = "return $this->http->request('POST', '/api/auth/validate') ?? [];";
+ assert.ok(source.includes(call), 'the PHP auth() call has moved: move this anchor');
+ writeFileSync(client, source.replace(call, 'return [];'));
+ const without = run();
+ assert.equal(without.status, 1, without.stdout + without.stderr);
+ assert.match(without.stderr, /\/api\/auth\/validate .*built by no method in: php/);
+ assert.doesNotMatch(without.stderr, /\/api\/auth\/api-keys/);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});