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
30 changes: 30 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,29 @@
return typeof obj.id === 'number' && 'result' in obj;
}

/**
* Validate the protocol version in a response.
* Only validates when the response looks like a protocol envelope (has 'id' field).
* 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>;
// Only validate protocol on protocol envelopes (responses with 'id' field)
// This avoids false positives on user data that happens to contain 'protocol' key
if (!('id' in obj)) {
return;
}
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 +195,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 198 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 +203,7 @@
}
if (isPlainObject(value)) {
for (const key of Object.keys(value)) {
const result = findSpecialFloatPath(value[key], buildPath(path, key));

Check warning on line 206 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 +338,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,9 +391,12 @@
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(

Check failure on line 399 in src/runtime/safe-codec.ts

View workflow job for this annotation

GitHub Actions / codec-suite

test/runtime_codec_scientific.test.ts > Scientific Codecs > serializes torch tensors

BridgeExecutionError: RuntimeError: Arrow encoding failed for ndarray ❯ SafeCodec.decodeResponseAsync src/runtime/safe-codec.ts:399:21 ❯ src/runtime/bridge-protocol.ts:207:25 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Serialized Error: { code: undefined, traceback: 'Traceback (most recent call last):\n File "/home/runner/work/tywrap/tywrap/runtime/python_bridge.py", line 280, in serialize_ndarray\n arr = pa.array(obj)\n ^^^^^^^^^^^^^\n File "pyarrow/array.pxi", line 358, in pyarrow.lib.array\n File "pyarrow/array.pxi", line 85, in pyarrow.lib._ndarray_to_array\n File "pyarrow/error.pxi", line 92, in pyarrow.lib.check_status\npyarrow.lib.ArrowInvalid: only handle 1-dimensional arrays\n\nThe above exception was the direct cause of the following exception:\n\nTraceback (most recent call last):\n File "/home/runner/work/tywrap/tywrap/runtime/python_bridge.py", line 824, in main\n mid, result = dispatch_request(msg)\n ^^^^^^^^^^^^^^^^^^^^^\n File "/home/runner/work/tywrap/tywrap/runtime/python_bridge.py", line 747, in dispatch_request\n result = handle_call(params)\n ^^^^^^^^^^^^^^^^^^^\n File "/home/runner/work/tywrap/tywrap/runtime/python_bridge.py", line 627, in handle_call\n return serialize(res)\n ^^^^^^^^^^^^^^\n File "/home/runner/work/tywrap/tywrap/runtime/python_bridge.py", line 589, in serialize\n return serialize_torch_tensor(obj)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File "/home/runner/work/tywrap/tywrap/runtime/python_bridge.py", line 520, in serialize_torch_tensor\n \'value\': serialize_ndarray(arr),\n ^^^^^^^^^^^^^^^^^^^^^^\n File "/home/runner/work/tywrap/tywrap/runtime/python_bridge.py", line 297, in serialize_ndarray\n raise RuntimeError(\'Arrow encoding failed for ndarray\') from exc\nRuntimeError: Arrow encoding failed for ndarray\n' }
`${parsed.error.type}: ${parsed.error.message}`
);
error.traceback = parsed.error.traceback;
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
55 changes: 55 additions & 0 deletions test/safe-codec.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -681,3 +681,58 @@ 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/);
});

it('does not validate protocol on non-envelope responses', () => {
// User data that happens to contain 'protocol' key should not trigger validation
// Only responses with 'id' field are treated as protocol envelopes
const payload = JSON.stringify({ protocol: 'http', url: 'https://example.com' });
const result = codec.decodeResponse<{ protocol: string; url: string }>(payload);
expect(result).toEqual({ protocol: 'http', url: 'https://example.com' });
});
});
Loading