Skip to content

Commit 5eeff36

Browse files
fix(contract): validate event payloads and compare the advertised contract version
isMesheryExtensionEvent narrowed on the type discriminant alone, so a known literal carrying a renamed or absent payload passed the guard and subscribers read undefined off it - the same silent skew the literal map exists to prevent. It now checks each event's required payload fields via a table the union completeness-guards, while tolerating extra fields so additive changes stay compatible. contractVersion was documented as a loud handshake but only ever excluded from 'unrecognized', never compared. reportInjectedCapabilities now reports a contractVersionMismatch, which fails satisfaction and is named in the diagnostic. An absent version stays the supported legacy case: hosts deployed before the handshake predate the field rather than disagreeing about it. Signed-off-by: Ahmed Jamil <[email protected]>
1 parent f5c34f0 commit 5eeff36

2 files changed

Lines changed: 198 additions & 15 deletions

File tree

‎src/__testing__/mesheryExtensionContract.test.ts‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,64 @@ describe('Meshery extension contract — event literals', () => {
6363
expect(isMesheryExtensionEvent('OPEN_DESIGN_IN_EXTENSION')).toBe(false);
6464
expect(isMesheryExtensionEvent({})).toBe(false);
6565
});
66+
67+
it('rejects a known literal carrying a payload this build cannot read', () => {
68+
// The rename half of the same skew: the host keeps publishing a literal we
69+
// recognise but renames the field inside it, so every subscriber reads
70+
// undefined. Narrowing on the discriminant alone would call this valid and
71+
// hand the subscriber a payload that throws on first property access.
72+
const type = MESHERY_EXTENSION_EVENT.OpenDesignInExtension;
73+
74+
expect(isMesheryExtensionEvent({ type, data: null })).toBe(false);
75+
expect(isMesheryExtensionEvent({ type })).toBe(false);
76+
expect(isMesheryExtensionEvent({ type, data: {} })).toBe(false);
77+
// `designId` renamed to `id` - recognised literal, unreadable payload.
78+
expect(isMesheryExtensionEvent({ type, data: { id: 'd', designName: 'n' } })).toBe(false);
79+
expect(isMesheryExtensionEvent({ type, data: { designId: 1, designName: 'n' } })).toBe(false);
80+
});
81+
82+
it('accepts a valid payload for every event literal', () => {
83+
const valid: Record<(typeof MESHERY_EXTENSION_EVENT_TYPES)[number], unknown> = {
84+
K8S_CONTEXTS_UPDATED: { selectedK8sContexts: ['ctx'] },
85+
OPEN_VIEW_SCOPED_TO_DESIGN: { designId: 'd', designName: 'n' },
86+
OPEN_DESIGN_IN_EXTENSION: { designId: 'd', designName: 'n' },
87+
OPEN_VIEW_IN_EXTENSION: { viewId: 'v', viewName: 'n' },
88+
MERGE_DESIGN: { id: 'i', name: 'n' },
89+
DISPATCH_TO_MESHERY_STORE: { type: 'redux/action' },
90+
FeatureRequiresUserAccount: { feature: 'f' },
91+
MISSING_PERMISSION: { keyId: 'k' },
92+
MISSING_CAPABILITY: { capabilityId: 'c' }
93+
};
94+
95+
for (const type of MESHERY_EXTENSION_EVENT_TYPES) {
96+
expect(isMesheryExtensionEvent({ type, data: valid[type] })).toBe(true);
97+
}
98+
});
99+
100+
it('tolerates extra payload fields so additive changes stay compatible', () => {
101+
// Only a rename or removal is a contract break. A newer host adding a field
102+
// to a payload must not make an older bundle reject the whole event.
103+
expect(
104+
isMesheryExtensionEvent({
105+
type: MESHERY_EXTENSION_EVENT.MergeDesign,
106+
data: { id: 'i', name: 'n', addedByANewerHost: true }
107+
})
108+
).toBe(true);
109+
expect(
110+
isMesheryExtensionEvent({
111+
type: MESHERY_EXTENSION_EVENT.DispatchToMesheryStore,
112+
data: { type: 'redux/action', payload: { a: 1 } }
113+
})
114+
).toBe(true);
115+
});
116+
117+
it('does not mistake an inherited Object member for a payload check', () => {
118+
// The check table is a plain object, so an event whose `type` names something
119+
// on Object.prototype must not resolve to an inherited function and pass.
120+
expect(isMesheryExtensionEvent({ type: 'toString', data: {} })).toBe(false);
121+
expect(isMesheryExtensionEvent({ type: 'constructor', data: {} })).toBe(false);
122+
expect(isMesheryExtensionEvent({ type: 'hasOwnProperty', data: {} })).toBe(false);
123+
});
66124
});
67125

68126
describe('Meshery extension contract — injected capabilities', () => {
@@ -172,4 +230,59 @@ describe('Meshery extension contract — version', () => {
172230
expect(Number.isInteger(MESHERY_EXTENSION_CONTRACT_VERSION)).toBe(true);
173231
expect(MESHERY_EXTENSION_CONTRACT_VERSION).toBeGreaterThan(0);
174232
});
233+
234+
it('treats a matching advertised version as compatible', () => {
235+
const report = reportInjectedCapabilities({
236+
...satisfyingInjectProps(),
237+
contractVersion: MESHERY_EXTENSION_CONTRACT_VERSION
238+
});
239+
240+
expect(report.contractVersionMismatch).toBeNull();
241+
expect(isInjectedCapabilityReportSatisfied(report)).toBe(true);
242+
});
243+
244+
it('treats a host that advertises no version as the supported legacy case', () => {
245+
// Every host deployed before this handshake existed. They predate the field
246+
// rather than disagreeing about it, so flagging them would make the report
247+
// fire everywhere at once and teach maintainers to ignore it.
248+
const report = reportInjectedCapabilities(satisfyingInjectProps());
249+
250+
expect(report.contractVersionMismatch).toBeNull();
251+
expect(isInjectedCapabilityReportSatisfied(report)).toBe(true);
252+
expect(describeInjectedCapabilityReport(report)).toBeNull();
253+
});
254+
255+
it('fails the handshake loudly when the advertised version differs', () => {
256+
const report = reportInjectedCapabilities({
257+
...satisfyingInjectProps(),
258+
contractVersion: MESHERY_EXTENSION_CONTRACT_VERSION + 1
259+
});
260+
261+
expect(report.contractVersionMismatch).toEqual({
262+
host: MESHERY_EXTENSION_CONTRACT_VERSION + 1,
263+
extension: MESHERY_EXTENSION_CONTRACT_VERSION
264+
});
265+
// Every capability is present, so nothing else in the report would catch this.
266+
expect(report.missing).toEqual([]);
267+
expect(isInjectedCapabilityReportSatisfied(report)).toBe(false);
268+
269+
const message = describeInjectedCapabilityReport(report);
270+
expect(message).toContain(`v${MESHERY_EXTENSION_CONTRACT_VERSION + 1}`);
271+
expect(message).toContain(`v${MESHERY_EXTENSION_CONTRACT_VERSION}`);
272+
});
273+
274+
it('treats a non-numeric advertised version as a mismatch rather than trusting it', () => {
275+
// `injectProps` is untrusted input; a version we cannot compare is not a
276+
// version we may assume matches.
277+
const report = reportInjectedCapabilities({
278+
...satisfyingInjectProps(),
279+
contractVersion: `${MESHERY_EXTENSION_CONTRACT_VERSION}`
280+
});
281+
282+
expect(report.contractVersionMismatch).toEqual({
283+
host: `${MESHERY_EXTENSION_CONTRACT_VERSION}`,
284+
extension: MESHERY_EXTENSION_CONTRACT_VERSION
285+
});
286+
expect(isInjectedCapabilityReportSatisfied(report)).toBe(false);
287+
});
175288
});

‎src/actors/mesheryExtensionContract.ts‎

Lines changed: 85 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -156,18 +156,60 @@ export const MESHERY_EXTENSION_EVENT_TYPES = Object.values(
156156
MESHERY_EXTENSION_EVENT
157157
) as readonly MesheryExtensionEventType[];
158158

159+
const isRecord = (value: unknown): value is Record<string, unknown> =>
160+
typeof value === 'object' && value !== null;
161+
162+
const isString = (value: unknown): value is string => typeof value === 'string';
163+
164+
const isStringArray = (value: unknown): value is string[] =>
165+
Array.isArray(value) && value.every(isString);
166+
159167
/**
160-
* Narrows an event received from the bus to a known contract member.
168+
* Payload check per event literal, keyed by the literal itself.
169+
*
170+
* The type discriminant alone is not the contract - the payload shape is half of
171+
* it. A host that renames `designId` to `id` keeps publishing a literal this
172+
* build recognises while every subscriber reads `undefined`, which is the same
173+
* silent no-op the literal map exists to prevent. Checking only required fields
174+
* (never rejecting extra ones) keeps additive payload changes compatible while
175+
* making a rename or removal visible.
176+
*
177+
* `satisfies Record<MesheryExtensionEventType, ...>` is the completeness guard:
178+
* adding a member to `MesheryExtensionEvent` without a check here fails to
179+
* compile, so this table cannot drift behind the union.
180+
*/
181+
const MESHERY_EXTENSION_EVENT_DATA_CHECKS = {
182+
K8S_CONTEXTS_UPDATED: data => isStringArray(data.selectedK8sContexts),
183+
OPEN_VIEW_SCOPED_TO_DESIGN: data => isString(data.designId) && isString(data.designName),
184+
OPEN_DESIGN_IN_EXTENSION: data => isString(data.designId) && isString(data.designName),
185+
OPEN_VIEW_IN_EXTENSION: data => isString(data.viewId) && isString(data.viewName),
186+
MERGE_DESIGN: data => isString(data.id) && isString(data.name),
187+
DISPATCH_TO_MESHERY_STORE: data =>
188+
isString(data.type) && (data.payload === undefined || isRecord(data.payload)),
189+
FeatureRequiresUserAccount: data => isString(data.feature),
190+
MISSING_PERMISSION: data => isString(data.keyId),
191+
MISSING_CAPABILITY: data => isString(data.capabilityId)
192+
} as const satisfies Record<MesheryExtensionEventType, (data: Record<string, unknown>) => boolean>;
193+
194+
/**
195+
* Narrows an event received from the bus to a known contract member, checking
196+
* both the type discriminant and the payload it promises to carry.
161197
*
162198
* Subscribers must treat a `false` result as a defect to report, not as something
163-
* to ignore: it means the publisher is emitting a literal this build has never
164-
* heard of, which is exactly the host/extension skew that used to present as a
165-
* silently dead feature.
199+
* to ignore. It means the publisher is emitting either a literal this build has
200+
* never heard of or a payload this build cannot read - both are the host/extension
201+
* skew that used to present as a silently dead feature, and both call for the same
202+
* response: say so loudly rather than no-op.
166203
*/
167-
export const isMesheryExtensionEvent = (event: unknown): event is MesheryExtensionEvent =>
168-
typeof event === 'object' &&
169-
event !== null &&
170-
MESHERY_EXTENSION_EVENT_TYPES.includes((event as { type: MesheryExtensionEventType }).type);
204+
export const isMesheryExtensionEvent = (event: unknown): event is MesheryExtensionEvent => {
205+
if (!isRecord(event)) return false;
206+
const type = event.type as MesheryExtensionEventType;
207+
// Membership is checked against the literal array before indexing the check
208+
// table, so a payload carrying `type: 'toString'` cannot reach an inherited
209+
// Object.prototype member and be mistaken for a validator.
210+
if (!MESHERY_EXTENSION_EVENT_TYPES.includes(type)) return false;
211+
return isRecord(event.data) && MESHERY_EXTENSION_EVENT_DATA_CHECKS[type](event.data);
212+
};
171213

172214
/* -------------------------------------------------------------------------- */
173215
/* Injected capabilities */
@@ -249,6 +291,18 @@ export const MESHERY_EXTENSION_HANDSHAKE_FIELDS = ['contractVersion'] as const;
249291

250292
/** Outcome of comparing a host's `injectProps` against the declared contract. */
251293
export type InjectedCapabilityReport = {
294+
/**
295+
* Set when the host advertised a `contractVersion` differing from the one this
296+
* build declares, which means a rename or removal happened on one side. `host`
297+
* is typed `unknown` because it is untrusted input: a host may advertise
298+
* anything, and anything that is not this build's version is a mismatch.
299+
*
300+
* `null` also covers a host that advertises nothing at all - every host
301+
* deployed before the handshake existed. Those predate the field rather than
302+
* disagreeing about it, so they are reported as the supported legacy case
303+
* instead of drowning the report in mismatches the operator cannot act on.
304+
*/
305+
contractVersionMismatch: { host: unknown; extension: number } | null;
252306
/** Contract keys the host did not provide. Each one is a dead feature. */
253307
missing: MesheryExtensionCapability[];
254308
/** Contract hook keys absent from `injectProps.hooks`. */
@@ -283,7 +337,13 @@ export const reportInjectedCapabilities = (
283337
...Object.keys(MESHERY_EXTENSION_DEPRECATED_CAPABILITIES)
284338
]);
285339

340+
const advertisedVersion = provided.contractVersion;
341+
286342
return {
343+
contractVersionMismatch:
344+
advertisedVersion === undefined || advertisedVersion === MESHERY_EXTENSION_CONTRACT_VERSION
345+
? null
346+
: { host: advertisedVersion, extension: MESHERY_EXTENSION_CONTRACT_VERSION },
287347
missing: MESHERY_EXTENSION_CAPABILITIES.filter(key => provided[key] === undefined),
288348
// `hooks` itself being absent is already reported as a missing capability;
289349
// reporting all three hooks again would be noise, so only look inside when
@@ -300,12 +360,15 @@ export const reportInjectedCapabilities = (
300360
};
301361

302362
/**
303-
* True when the host satisfied every declared capability. Deprecated and
304-
* unrecognized keys are informational and do not fail the check — only an
305-
* outright missing capability is a broken contract.
363+
* True when the host advertised a compatible contract version and satisfied every
364+
* declared capability. Deprecated and unrecognized keys are informational and do
365+
* not fail the check - only an outright missing capability, a missing hook, or a
366+
* version disagreement is a broken contract.
306367
*/
307368
export const isInjectedCapabilityReportSatisfied = (report: InjectedCapabilityReport): boolean =>
308-
report.missing.length === 0 && report.missingHooks.length === 0;
369+
report.contractVersionMismatch === null &&
370+
report.missing.length === 0 &&
371+
report.missingHooks.length === 0;
309372

310373
/**
311374
* Renders a report as a single actionable message naming the offending keys.
@@ -317,15 +380,22 @@ export const describeInjectedCapabilityReport = (
317380
if (isInjectedCapabilityReportSatisfied(report)) return null;
318381

319382
const parts: string[] = [];
383+
if (report.contractVersionMismatch !== null) {
384+
const { host, extension } = report.contractVersionMismatch;
385+
parts.push(
386+
`host advertises contract v${String(host)}, this build declares v${extension}` +
387+
' (a rename or removal happened on one side)'
388+
);
389+
}
320390
if (report.missing.length > 0) {
321391
parts.push(`missing capabilities: ${report.missing.join(', ')}`);
322392
}
323393
if (report.missingHooks.length > 0) {
324394
parts.push(`missing hooks: ${report.missingHooks.join(', ')}`);
325395
}
326396
return (
327-
`Meshery host did not satisfy the extension contract (v${MESHERY_EXTENSION_CONTRACT_VERSION}) — ` +
328-
`${parts.join('; ')}. The host and this extension bundle were built against ` +
329-
'different contract versions; features depending on these keys will not work.'
397+
`Meshery host did not satisfy the extension contract (v${MESHERY_EXTENSION_CONTRACT_VERSION}): ` +
398+
`${parts.join('; ')}. Host and extension bundle were built against different ` +
399+
'contract revisions; the features these keys back will not work.'
330400
);
331401
};

0 commit comments

Comments
 (0)