Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
24 changes: 24 additions & 0 deletions src/runtime/safe-codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import { BridgeProtocolError, BridgeExecutionError } from './errors.js';
import { containsSpecialFloat } from './validators.js';
import { decodeValueAsync as decodeArrowValue } from '../utils/codec.js';
import { PROTOCOL_ID } from './transport.js';

// ═══════════════════════════════════════════════════════════════════════════
// TYPES
Expand Down Expand Up @@ -102,7 +103,7 @@
// Check arrays
if (Array.isArray(value)) {
for (let i = 0; i < value.length; i++) {
assertStringKeys(value[i], buildPath(path, i));

Check warning on line 106 in src/runtime/safe-codec.ts

View workflow job for this annotation

GitHub Actions / lint

Function Call Object Injection Sink
}
return;
}
Expand All @@ -122,7 +123,7 @@

// Recurse into object values
for (const key of Object.keys(value)) {
assertStringKeys(value[key], buildPath(path, key));

Check warning on line 126 in src/runtime/safe-codec.ts

View workflow job for this annotation

GitHub Actions / lint

Function Call Object Injection Sink
}
}
}
Expand Down Expand Up @@ -161,6 +162,23 @@
return typeof obj.id === 'number' && 'result' in obj;
}

/**
* Validate the protocol version in a response.
* Throws if protocol is present but doesn't match expected version.
* Allows missing protocol for backwards compatibility.
*/
function validateProtocolVersion(value: unknown): void {
if (value === null || typeof value !== 'object') {
return;
}
const obj = value as Record<string, unknown>;
if ('protocol' in obj && obj.protocol !== PROTOCOL_ID) {
throw new BridgeProtocolError(
`Invalid protocol version: expected "${PROTOCOL_ID}", got "${obj.protocol}"`
);
}
}

/**
* Find the path to a special float in a value structure.
* Returns undefined if no special float is found.
Expand All @@ -171,7 +189,7 @@
}
if (Array.isArray(value)) {
for (let i = 0; i < value.length; i++) {
const result = findSpecialFloatPath(value[i], buildPath(path, i));

Check warning on line 192 in src/runtime/safe-codec.ts

View workflow job for this annotation

GitHub Actions / lint

Function Call Object Injection Sink
if (result !== undefined) {
return result;
}
Expand All @@ -179,7 +197,7 @@
}
if (isPlainObject(value)) {
for (const key of Object.keys(value)) {
const result = findSpecialFloatPath(value[key], buildPath(path, key));

Check warning on line 200 in src/runtime/safe-codec.ts

View workflow job for this annotation

GitHub Actions / lint

Function Call Object Injection Sink
if (result !== undefined) {
return result;
}
Expand Down Expand Up @@ -314,6 +332,9 @@
throw new BridgeProtocolError(`JSON parse failed: ${message}`);
}

// Validate protocol version (if present)
validateProtocolVersion(parsed);

// Check for Python error response
if (isPythonErrorResponse(parsed)) {
const error = new BridgeExecutionError(
Expand Down Expand Up @@ -364,6 +385,9 @@
throw new BridgeProtocolError(`JSON parse failed: ${message}`);
}

// Validate protocol version (if present)
validateProtocolVersion(parsed);

// Check for Python error response
if (isPythonErrorResponse(parsed)) {
const error = new BridgeExecutionError(
Expand Down
4 changes: 1 addition & 3 deletions test/adversarial_playground.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -485,11 +485,9 @@ describeAdversarial('Adversarial playground', () => {
describe('Protocol contract violations', () => {
const fixtureCases: Array<{ script: string; pattern: RegExp; skip?: boolean }> = [
{
// New architecture doesn't validate protocol version field in responses
// This test is skipped as protocol version validation is not implemented
// Protocol version validation implemented in SafeCodec
script: 'wrong_protocol_bridge.py',
pattern: /Invalid protocol/,
skip: true,
},
{
script: 'missing_id_bridge.py',
Expand Down
47 changes: 47 additions & 0 deletions test/safe-codec.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -681,3 +681,50 @@ describe('Edge Cases', () => {
expect(decoded.text).toBe('line1\nline2\ttab\r\nwindows');
});
});

// ═══════════════════════════════════════════════════════════════════════════
// DECODE RESPONSE - PROTOCOL VALIDATION
// ═══════════════════════════════════════════════════════════════════════════

describe('decodeResponse - Protocol Validation', () => {
let codec: SafeCodec;

beforeEach(() => {
codec = new SafeCodec();
});

it('accepts response without protocol field (backwards compatibility)', () => {
const payload = JSON.stringify({ id: 1, result: 42 });
const result = codec.decodeResponse<number>(payload);
expect(result).toBe(42);
});

it('accepts response with correct protocol version', () => {
const payload = JSON.stringify({ id: 1, protocol: 'tywrap/1', result: { data: 'test' } });
const result = codec.decodeResponse<{ data: string }>(payload);
expect(result).toEqual({ data: 'test' });
});

it('rejects response with wrong protocol version', () => {
const payload = JSON.stringify({ id: 1, protocol: 'tywrap/0', result: 42 });
expect(() => codec.decodeResponse(payload)).toThrow(BridgeProtocolError);
expect(() => codec.decodeResponse(payload)).toThrow(/Invalid protocol version/);
});

it('rejects response with unknown protocol', () => {
const payload = JSON.stringify({ id: 1, protocol: 'unknown/1', result: 42 });
expect(() => codec.decodeResponse(payload)).toThrow(BridgeProtocolError);
expect(() => codec.decodeResponse(payload)).toThrow(/expected "tywrap\/1"/);
});

it('validates protocol before extracting error response', () => {
// If protocol is wrong, we should reject before checking for Python errors
const payload = JSON.stringify({
id: 1,
protocol: 'wrong/1',
error: { type: 'ValueError', message: 'test' },
});
expect(() => codec.decodeResponse(payload)).toThrow(BridgeProtocolError);
expect(() => codec.decodeResponse(payload)).toThrow(/Invalid protocol version/);
});
});
Loading