Skip to content

Commit 058ecd8

Browse files
committed
fix(sdk-ts): address review feedback on exec, forward, and auth transport
Settle exec's `done` promise before yielding the exit event so a consumer that breaks on exit no longer leaves it pending forever, and give it a lone rejection handler plus a finally-settle so a stream error or early abandon can never surface as an unhandled rejection or a hang. Attach an 'error' listener to each accepted forward socket synchronously, before forwardConnection awaits CreateSshSession; a peer reset in that window previously emitted an unhandled 'error' and crashed the process. Reject ambiguous or unsafe transport configs at buildTransport: oidcToken and edgeToken together (silently OIDC-only), and any auth token sent over plaintext http:// to a non-loopback host unless allowInsecureAuth is set. Wrap versionPin so a non-u64 expectedResourceVersion raises SdkError('invalid_config') instead of a raw BigInt SyntaxError, and raise the Node engine floor to >=20.3 for AbortSignal.any(). Signed-off-by: Max Dubrinsky <mdubrinsky@nvidia.com>
1 parent 4cda0d4 commit 058ecd8

5 files changed

Lines changed: 240 additions & 4 deletions

File tree

‎sdk/typescript/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
"README.md"
3131
],
3232
"engines": {
33-
"node": ">=20"
33+
"node": ">=20.3"
3434
},
3535
"scripts": {
3636
"gen": "buf generate",

‎sdk/typescript/src/client.test.ts‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,61 @@ describe('execInteractive', () => {
315315
});
316316
});
317317

318+
describe('exec done settlement', () => {
319+
it('resolves done even when the consumer breaks right after the exit event', async () => {
320+
const sandbox = client({
321+
getSandbox: () => readySandbox('sb', 'sb-id'),
322+
// eslint-disable-next-line require-yield
323+
execSandboxInteractive: async function* () {
324+
yield { payload: { case: 'stdout', value: { data: enc('hi') } } };
325+
yield { payload: { case: 'exit', value: { exitCode: 3 } } };
326+
},
327+
});
328+
const session = await sandbox.execInteractive('sb', ['bash']);
329+
for await (const event of session.output) {
330+
if ('type' in event) break; // break on exit: the generator never resumes
331+
}
332+
// Without settling `done` before the exit yield, this would hang forever.
333+
expect(await session.done).toBe(3);
334+
});
335+
336+
it('rejects done and throws from output when the stream errors before exit', async () => {
337+
const sandbox = client({
338+
getSandbox: () => readySandbox('sb', 'sb-id'),
339+
execSandboxInteractive: async function* () {
340+
yield { payload: { case: 'stdout', value: { data: enc('partial') } } };
341+
throw new ConnectError('boom', Code.Internal);
342+
},
343+
});
344+
const session = await sandbox.execInteractive('sb', ['bash']);
345+
await expect(
346+
(async () => {
347+
for await (const _event of session.output) {
348+
// drain until the stream error surfaces
349+
}
350+
})(),
351+
).rejects.toMatchObject({ code: 'rpc' });
352+
await expect(session.done).rejects.toMatchObject({ code: 'rpc' });
353+
});
354+
355+
it('rejects done when the consumer abandons output before an exit event', async () => {
356+
const sandbox = client({
357+
getSandbox: () => readySandbox('sb', 'sb-id'),
358+
// eslint-disable-next-line require-yield
359+
execSandboxInteractive: async function* () {
360+
yield { payload: { case: 'stdout', value: { data: enc('one') } } };
361+
yield { payload: { case: 'stdout', value: { data: enc('two') } } };
362+
yield { payload: { case: 'exit', value: { exitCode: 0 } } };
363+
},
364+
});
365+
const session = await sandbox.execInteractive('sb', ['bash']);
366+
for await (const event of session.output) {
367+
if (!('type' in event)) break; // abandon on the first chunk, before exit
368+
}
369+
await expect(session.done).rejects.toMatchObject({ code: 'rpc' });
370+
});
371+
});
372+
318373
describe('providers', () => {
319374
it('attach/detach assemble the request and map the changed flag + sandbox ref', async () => {
320375
let attachReq: {
@@ -516,6 +571,14 @@ describe('config / policy', () => {
516571
});
517572
expect(result.settingsRevision).toBe('11');
518573
});
574+
575+
it('rejects a non-u64 expectedResourceVersion with invalid_config (no raw SyntaxError)', async () => {
576+
// versionPin runs during request assembly, before any RPC is issued.
577+
const sandbox = client({});
578+
await expect(
579+
sandbox.setPolicy('sb', { version: 1, networkPolicies: {} }, { expectedResourceVersion: 'not-a-number' }),
580+
).rejects.toMatchObject({ code: 'invalid_config' });
581+
});
519582
});
520583

521584
describe('ssh sessions', () => {
@@ -731,6 +794,53 @@ describe('forward', () => {
731794
await handle.close();
732795
await handle.closed;
733796
});
797+
798+
// Fix #7: the accepted socket must have an 'error' handler before
799+
// forwardConnection awaits createSshSession, or a peer reset in that window
800+
// emits an unhandled 'error' and crashes the process.
801+
it('survives a forwarded socket that resets during the session-mint window', async () => {
802+
let releaseSession: (() => void) | undefined;
803+
const gate = new Promise<void>((resolve) => {
804+
releaseSession = resolve;
805+
});
806+
const sandbox = client({
807+
getSandbox: () => readySandbox('sb', 'sb-id-reset'),
808+
createSshSession: async () => {
809+
// Hold the RPC open so the accepted socket sits in the pre-handler window.
810+
await gate;
811+
return {
812+
sandboxId: 'sb-id-reset',
813+
token: 'reset-tok',
814+
gatewayHost: 'gw',
815+
gatewayPort: 443,
816+
gatewayScheme: 'https',
817+
hostKeyFingerprint: '',
818+
expiresAtMs: 0n,
819+
};
820+
},
821+
// biome-ignore lint/correctness/useYield: the socket is reset before any frame is relayed
822+
forwardTcp: async function* () {
823+
return;
824+
},
825+
revokeSshSession: () => ({ revoked: true }),
826+
});
827+
828+
const handle = await sandbox.forward('sb', { targetPort: 9000 });
829+
await new Promise<void>((resolve) => {
830+
const socket = net.connect(handle.localPort, handle.localHost, () => {
831+
// Abort mid-mint; the server-side accepted socket may see an
832+
// ECONNRESET 'error' before forwardConnection attaches its handlers.
833+
socket.destroy(new Error('peer reset'));
834+
setTimeout(resolve, 30);
835+
});
836+
socket.on('error', () => {}); // ignore the client-side reset
837+
});
838+
839+
releaseSession?.();
840+
// The listener still shuts down cleanly after the aborted connection.
841+
await handle.close();
842+
await handle.closed;
843+
});
734844
});
735845

736846
// The lowercase enum-name unions in client.ts are a hand-maintained mirror of

‎sdk/typescript/src/client.ts‎

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,19 @@ function updateConfigResult(resp: UpdateConfigResponse): UpdateConfigResult {
364364
// current version, backward-compatible). A mismatch surfaces as Aborted →
365365
// SdkError code 'aborted'.
366366
function versionPin(value: string | undefined): bigint {
367-
return value ? BigInt(value) : 0n;
367+
if (!value) return 0n;
368+
let pin: bigint;
369+
try {
370+
pin = BigInt(value);
371+
} catch {
372+
// BigInt() throws a raw SyntaxError on non-integer input; keep the SdkError
373+
// taxonomy intact so callers' errorCode() checks still match.
374+
throw new SdkError('invalid_config', `expectedResourceVersion is not a u64: '${value}'`);
375+
}
376+
if (pin < 0n) {
377+
throw new SdkError('invalid_config', `expectedResourceVersion is not a u64: '${value}'`);
378+
}
379+
return pin;
368380
}
369381

370382
const FORWARD_CHUNK = 64 * 1024;
@@ -729,6 +741,23 @@ export class SandboxClient {
729741
resolveDone = resolve;
730742
rejectDone = reject;
731743
});
744+
// `done` may settle before (or without) anyone awaiting it. A lone handler
745+
// keeps an unobserved rejection from surfacing as an unhandledRejection;
746+
// real awaiters still receive it through their own handler.
747+
void done.catch(() => {});
748+
// Settle exactly once. The exit code wins; error/abandonment only apply
749+
// when no exit was observed.
750+
let settled = false;
751+
const settleExit = (code: number): void => {
752+
if (settled) return;
753+
settled = true;
754+
resolveDone(code);
755+
};
756+
const settleError = (err: unknown): void => {
757+
if (settled) return;
758+
settled = true;
759+
rejectDone(err);
760+
};
732761

733762
async function* output(): AsyncGenerator<ExecStreamEvent, void, void> {
734763
let sawExit = false;
@@ -749,8 +778,11 @@ export class SandboxClient {
749778
break;
750779
case 'exit':
751780
sawExit = true;
781+
// Settle `done` before yielding: a consumer that breaks on the
782+
// exit event abandons the generator at the yield, so anything
783+
// after it would never run.
784+
settleExit(event.payload.value.exitCode);
752785
yield { type: 'exit', exitCode: event.payload.value.exitCode };
753-
resolveDone(event.payload.value.exitCode);
754786
break;
755787
}
756788
}
@@ -759,10 +791,13 @@ export class SandboxClient {
759791
}
760792
} catch (e) {
761793
const err = e instanceof SdkError ? e : fromConnect(e);
762-
rejectDone(err);
794+
settleError(err);
763795
throw err;
764796
} finally {
765797
input.end();
798+
// Consumer abandoned the stream before an exit event (early break or
799+
// return): settle `done` so it can never hang.
800+
settleError(new SdkError('rpc', 'exec output abandoned before exit'));
766801
}
767802
}
768803

@@ -807,6 +842,11 @@ export class SandboxClient {
807842
const server = net.createServer((socket) => {
808843
sockets.add(socket);
809844
socket.on('close', () => sockets.delete(socket));
845+
// Guard the window before forwardConnection attaches its own handlers
846+
// (it first awaits createSshSession). Without a synchronous 'error'
847+
// listener a peer reset here emits an unhandled 'error' and crashes the
848+
// process; forwardConnection's catch still tears the socket down.
849+
socket.on('error', () => {});
810850
void this.forwardConnection(socket, sandboxId, name, targetHost, targetPort);
811851
});
812852

‎sdk/typescript/src/transport.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,45 @@ describe('buildTransport mTLS pairing', () => {
5151
expect(transport).toBeTruthy();
5252
});
5353
});
54+
55+
describe('buildTransport token exclusivity', () => {
56+
it('throws when both oidcToken and edgeToken are set', () => {
57+
const fn = () => buildTransport({ gateway: 'https://gw.local', oidcToken: 'a', edgeToken: 'b' });
58+
expect(fn).toThrow(/mutually exclusive/);
59+
try {
60+
fn();
61+
} catch (e) {
62+
expect(errorCode(e)).toBe('invalid_config');
63+
}
64+
});
65+
});
66+
67+
describe('buildTransport plaintext auth guard', () => {
68+
it('rejects a token over http:// to a non-loopback host', () => {
69+
const fn = () => buildTransport({ gateway: 'http://gw.remote:8080', oidcToken: 'a' });
70+
expect(fn).toThrow(/non-loopback/);
71+
try {
72+
fn();
73+
} catch (e) {
74+
expect(errorCode(e)).toBe('invalid_config');
75+
}
76+
});
77+
78+
it('allows a token over http:// to loopback hosts', () => {
79+
expect(buildTransport({ gateway: 'http://127.0.0.1:8080', oidcToken: 'a' })).toBeTruthy();
80+
expect(buildTransport({ gateway: 'http://[::1]:8080', edgeToken: 'a' })).toBeTruthy();
81+
expect(buildTransport({ gateway: 'http://localhost:8080', oidcToken: 'a' })).toBeTruthy();
82+
});
83+
84+
it('allows a token over http:// to a remote host when allowInsecureAuth is set', () => {
85+
expect(buildTransport({ gateway: 'http://gw.remote:8080', oidcToken: 'a', allowInsecureAuth: true })).toBeTruthy();
86+
});
87+
88+
it('allows a token over https:// to any host', () => {
89+
expect(buildTransport({ gateway: 'https://gw.remote', oidcToken: 'a' })).toBeTruthy();
90+
});
91+
92+
it('allows a tokenless http:// gateway to any host', () => {
93+
expect(buildTransport({ gateway: 'http://gw.remote:8080' })).toBeTruthy();
94+
});
95+
});

‎sdk/typescript/src/transport.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,12 @@ export interface ConnectOptions {
3333
edgeToken?: string;
3434
/** Disable TLS verification (dev/debug only). */
3535
insecureSkipVerify?: boolean;
36+
/**
37+
* Permit sending an auth token (oidcToken/edgeToken) over plaintext `http://`
38+
* to a non-loopback host. Off by default: tokens over cleartext to a remote
39+
* host leak credentials on the wire. Loopback hosts are always allowed.
40+
*/
41+
allowInsecureAuth?: boolean;
3642
}
3743

3844
// OIDC bearer takes precedence; otherwise attach the Cloudflare Access header +
@@ -61,8 +67,46 @@ function assertMtlsPair(opts: ConnectOptions): void {
6167
}
6268
}
6369

70+
// oidcToken and edgeToken are documented as mutually exclusive; the interceptor
71+
// silently prefers OIDC when both are set. Reject that ambiguity up front so a
72+
// caller does not think an edge token is in effect when it is being ignored.
73+
function assertTokenExclusivity(opts: ConnectOptions): void {
74+
if (opts.oidcToken !== undefined && opts.edgeToken !== undefined) {
75+
throw new SdkError('invalid_config', 'oidcToken and edgeToken are mutually exclusive');
76+
}
77+
}
78+
79+
function isLoopbackHost(host: string): boolean {
80+
// URL.hostname keeps the brackets on IPv6 literals (e.g. `[::1]`); strip them.
81+
const h = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host;
82+
if (h === 'localhost' || h === '::1') return true;
83+
return /^127(?:\.\d{1,3}){3}$/.test(h);
84+
}
85+
86+
// Attaching a bearer/CF token to a plaintext `http://` request to a non-loopback
87+
// host puts the credential on the wire in the clear. Refuse it unless the caller
88+
// explicitly opts in. Loopback (local-dev / edge-sidecar) is always fine.
89+
function assertTokenTransportSecurity(opts: ConnectOptions): void {
90+
const hasToken = opts.oidcToken !== undefined || opts.edgeToken !== undefined;
91+
if (!hasToken || opts.allowInsecureAuth || opts.gateway.startsWith('https://')) return;
92+
let host: string;
93+
try {
94+
host = new URL(opts.gateway).hostname;
95+
} catch {
96+
return; // A malformed gateway URL surfaces from the transport itself.
97+
}
98+
if (!isLoopbackHost(host)) {
99+
throw new SdkError(
100+
'invalid_config',
101+
`refusing to send an auth token over plaintext http:// to non-loopback host '${host}'; use https:// or set allowInsecureAuth`,
102+
);
103+
}
104+
}
105+
64106
export function buildTransport(opts: ConnectOptions): Transport {
65107
assertMtlsPair(opts);
108+
assertTokenExclusivity(opts);
109+
assertTokenTransportSecurity(opts);
66110
const isTls = opts.gateway.startsWith('https://');
67111
return createGrpcTransport({
68112
baseUrl: opts.gateway,

0 commit comments

Comments
 (0)