Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(sdk): gate the key validation response on every client

Yudhi Armyndharis7c6c60d4bd75
diff --git a/scripts/check-contract-shapes.mjs b/scripts/check-contract-shapes.mjs
index 2fbabae5e..0bdf4aa92 100644
--- a/scripts/check-contract-shapes.mjs
+++ b/scripts/check-contract-shapes.mjs
@@ -150,6 +150,7 @@ const MAPPINGS = {
WebhookRedriveResult: 'WebhookRedriveResultDto',
WebhookResponse: 'WebhookResponseDto',
// Payloads that sat outside every mapping until the coverage check required one.
+ AuthValidateResponse: 'ValidateApiKeyResponseDto',
CatalogInfo: 'CatalogDto',
CatalogProduct: 'ProductDto',
ChannelMessageRecord: 'ChannelMessageDto',
@@ -214,11 +215,11 @@ const MAPPINGS = {
* added makes the shrink loud.
*/
const MINIMUM_MAPPED = {
- 'sdk/javascript/src/types.ts': 117,
+ 'sdk/javascript/src/types.ts': 118,
'dashboard/src/services/api.ts': 22,
- 'sdk/python/openwa/types.py': 129,
- 'sdk/go': 130,
- 'sdk/java': 134,
+ 'sdk/python/openwa/types.py': 130,
+ 'sdk/go': 131,
+ 'sdk/java': 135,
};
/** Known drift, deliberately not gated yet — each line is a to-adjudicate follow-up. */
@@ -244,6 +245,8 @@ const EXCLUDED = {
'BY DESIGN: `participants` carries no omitempty so that a non-nil slice always sends the key, empty included, and naming nobody stays a 400 instead of collapsing into the absent key that means every pending request',
StatusRecord:
'Type is a plain string holding text, image, video or voice; a defined type would be a source break for callers that pass it on as a string. The other fields conform',
+ AuthValidateResponse:
+ 'Role is a plain string holding admin, operator or viewer; a defined type would be a source break for callers that pass it on as a string. The other fields conform',
},
'sdk/java': {
UpdateSessionConfigRequest:
@@ -252,6 +255,8 @@ const EXCLUDED = {
'memberAddMode is a String because this record is also the PUT body; the MemberAddMode enum that GroupInfo uses would break callers that pass a string. The other components conform',
StatusRecord:
'type is a String holding text, image, video or voice; an enum would break callers that compare it as a string. The other components conform',
+ AuthValidateResponse:
+ 'role is a String holding admin, operator or viewer; an enum would break callers that compare it as a string. The other components conform',
},
'dashboard/src/services/api.ts': {
Webhook:
@@ -383,6 +388,7 @@ const PYTHON_MAPPING = {
WebhookRedriveResult: 'WebhookRedriveResultDto',
WebhookResponse: 'WebhookResponseDto',
// Payloads that sat outside every mapping until the coverage check required one.
+ AuthValidateResponse: 'ValidateApiKeyResponseDto',
BatchError: 'BatchMessageErrorDto',
BulkOptions: 'BulkMessageOptionsDto',
CatalogInfo: 'CatalogDto',
@@ -514,6 +520,7 @@ const GO_MAPPING = {
WebhookRedriveResult: 'WebhookRedriveResultDto',
WebhookResponse: 'WebhookResponseDto',
// Payloads that sat outside every mapping until the coverage check required one.
+ AuthValidateResponse: 'ValidateApiKeyResponseDto',
BatchError: 'BatchMessageErrorDto',
BulkOptions: 'BulkMessageOptionsDto',
CatalogInfo: 'CatalogDto',
@@ -653,6 +660,7 @@ const JAVA_MAPPING = {
WebhookRedriveResult: 'WebhookRedriveResultDto',
WebhookResponse: 'WebhookResponseDto',
// Payloads that sat outside every mapping until the coverage check required one.
+ AuthValidateResponse: 'ValidateApiKeyResponseDto',
BatchError: 'BatchMessageErrorDto',
Call: 'ChatHistoryCallDto',
CatalogInfo: 'CatalogDto',
@@ -1328,7 +1336,10 @@ export function parseJavaTypes(sources) {
/**
* The resources sdk/README.md declares deliberately unexposed, read from the README rather than
- * restated here, the way check-sdk-coverage.mjs reads it: a hand-copied second list is what drifts.
+ * restated here: a hand-copied second list is what drifts. Entries are kept as written, because
+ * `audit` is a whole resource while `auth/api-keys` is one path under /api/auth, next to the
+ * exposed `auth/validate`. A parenthetical is commentary on the entry before it, and its own
+ * backticks ("key validation itself is the `auth` row above") name no entry.
*/
export function unexposedResources(readme) {
const start = readme.indexOf('Deliberately **not** exposed');
@@ -1338,7 +1349,8 @@ export function unexposedResources(readme) {
'sdk/README.md: could not find the "Deliberately not exposed" paragraph, so the schema coverage check cannot derive its scope.',
);
}
- const names = [...readme.slice(start, end).matchAll(/`([^`]+)`/g)].map(m => m[1].split('/')[0].trim());
+ const paragraph = readme.slice(start, end).replace(/\([^)]*\)/g, '');
+ const names = [...paragraph.matchAll(/`([^`]+)`/g)].map(m => m[1].trim());
if (names.length < 8) {
throw new Error(`sdk/README.md: parsed only ${names.length} unexposed resources, expected the full list.`);
}
@@ -1363,10 +1375,12 @@ 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;
for (const operation of Object.values(item)) {
if (!operation || typeof operation !== 'object') continue;
visit(operation.requestBody);
diff --git a/scripts/check-contract-shapes.spec.mjs b/scripts/check-contract-shapes.spec.mjs
index 3a58e7071..34735f4b6 100644
--- a/scripts/check-contract-shapes.spec.mjs
+++ b/scripts/check-contract-shapes.spec.mjs
@@ -419,19 +419,50 @@ test('schemaCoverageProblems accepts a recorded schema and rejects a record that
assert.ok(stale.some(p => /GoneDto.*no exposed operation/.test(p)));
});
-test('unexposedResources reads the README paragraph and refuses a README it cannot read', () => {
- const names = ['docs', 'auth/*', 'audit', 'settings', 'stats', 'automation', 'infra', 'plugins'];
- const readme = `> Deliberately **not** exposed: ${names.map(n => `\`${n}\``).join(', ')}.\n> Everything else the gateway publishes is exposed.`;
- assert.deepEqual(
- [...unexposedResources(readme)],
- ['docs', 'auth', 'audit', 'settings', 'stats', 'automation', 'infra', 'plugins'],
- );
+test('exposedSchemas reads a README entry with a sub-path as a path prefix, not as the whole resource', () => {
+ // sdk/README.md lists `auth/api-keys` and says key validation itself is exposed. Unexposing the resource
+ // `auth` dropped POST /api/auth/validate too, so its response schema was never required to be compared.
+ // `automation` unexposes the automation-rules routes, whose segment carries a suffix.
+ const spec = {
+ paths: {
+ '/api/auth/validate': { post: { responses: { 200: json(ref('ValidateDto')) } } },
+ '/api/auth/api-keys': { post: { requestBody: json(ref('KeyBodyDto')), responses: { 201: json(ref('KeyDto')) } } },
+ '/api/auth/api-keys/{id}': { get: { responses: { 200: json(ref('KeyDto')) } } },
+ '/api/auth/api-keys-other': { get: { responses: { 200: json(ref('OtherDto')) } } },
+ '/api/sessions/{sessionId}/automation-rules': { get: { responses: { 200: json(ref('RuleDto')) } } },
+ },
+ components: {
+ schemas: Object.fromEntries(
+ ['ValidateDto', 'KeyBodyDto', 'KeyDto', 'OtherDto', 'RuleDto'].map(name => [name, { type: 'object' }]),
+ ),
+ },
+ };
+ // OtherDto stays: a prefix ends at a path segment, so `auth/api-keys` does not cover `auth/api-keys-other`.
+ const found = exposedSchemas(spec, new Set(['auth/api-keys', 'automation']));
+ assert.deepEqual([...found].sort(), ['OtherDto', 'ValidateDto']);
+});
+
+test('unexposedResources reads the README paragraph as written and refuses a README it cannot read', () => {
+ const names = ['docs', 'auth/api-keys', 'audit', 'settings', 'stats', 'automation', 'infra', 'plugins'];
+ // The real README follows `auth/api-keys` with a remark that names the `auth` row of its table.
+ const readme = `> Deliberately **not** exposed: \`docs\`, \`auth/api-keys\` (key validation itself is the \`auth\` row above), ${names
+ .slice(2)
+ .map(n => `\`${n}\``)
+ .join(', ')}.\n> Everything else the gateway publishes is exposed.`;
+ // `auth/api-keys` stays whole: the entry is a path under /api/auth, not the resource `auth`.
+ assert.deepEqual([...unexposedResources(readme)], names);
assert.throws(() => unexposedResources('no such paragraph'), /Deliberately not exposed/);
assert.throws(
() => unexposedResources('Deliberately **not** exposed: `docs`. Everything else the gateway publishes'),
/only 1/,
);
- // The real README must still parse, or the coverage check has lost its scope.
- const real = readFileSync(fileURLToPath(new URL('../sdk/README.md', import.meta.url)), 'utf8');
- assert.ok(unexposedResources(real).has('audit'));
+ // The real README must still parse, or the coverage check has lost its scope: key validation is in it,
+ // the key management routes are not.
+ const real = unexposedResources(readFileSync(fileURLToPath(new URL('../sdk/README.md', import.meta.url)), 'utf8'));
+ assert.ok(real.has('audit'));
+ assert.ok(real.has('auth/api-keys') && !real.has('auth'));
+ const openapi = JSON.parse(readFileSync(fileURLToPath(new URL('../openapi.json', import.meta.url)), 'utf8'));
+ const exposed = exposedSchemas(openapi, real);
+ assert.ok(exposed.has('ValidateApiKeyResponseDto'));
+ assert.ok(!exposed.has('ApiKeyCreatedResponseDto'));
});
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index 4bfb49f6e..40d1e0f75 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -1307,7 +1307,8 @@ export interface HealthReadyResponse {
export interface AuthValidateResponse {
valid: boolean;
- role?: string;
+ /** The key's role; present only when the key is valid. */
+ role?: 'admin' | 'operator' | 'viewer';
engineType?: string;
scoped?: boolean;
}
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index ea61ae6bc..bf2cfd10a 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -1301,9 +1301,15 @@ class HealthReadyResponse(TypedDict):
# ── Auth ──────────────────────────────────────────────────────────
-class AuthValidateResponse(TypedDict, total=False):
+class _AuthValidateRequired(TypedDict):
valid: bool
- role: str
+
+
+# Inherited rather than spelled NotRequired: the class-form annotations of this module are lazy, so the
+# runtime key sets (__optional_keys__) only follow the total flag.
+class AuthValidateResponse(_AuthValidateRequired, total=False):
+ # The key's role; present only when the key is valid.
+ role: Literal["admin", "operator", "viewer"]
engineType: str
scoped: bool