@ship.zone/runner 5.2.0 → 5.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/changelog.md +22 -0
- package/dist_rust/runnerworkspace_linux_amd64_musl +0 -0
- package/dist_rust/runnerworkspace_linux_amd64_musl.tsrust-build.json +4 -4
- package/dist_rust/runnerworkspace_linux_arm64_musl +0 -0
- package/dist_rust/runnerworkspace_linux_arm64_musl.tsrust-build.json +4 -4
- package/dist_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/api-client.js +11 -5
- package/dist_ts/cli.js +57 -7
- package/dist_ts/config.js +8 -5
- package/dist_ts/decommission.d.ts +19 -0
- package/dist_ts/decommission.js +122 -0
- package/dist_ts/egress-proxy.d.ts +28 -0
- package/dist_ts/egress-proxy.js +320 -1
- package/dist_ts/errors.d.ts +4 -1
- package/dist_ts/errors.js +7 -2
- package/dist_ts/index.d.ts +1 -0
- package/dist_ts/index.js +2 -1
- package/dist_ts/microvm-executor.d.ts +1 -0
- package/dist_ts/microvm-executor.js +54 -3
- package/dist_ts/runner.js +7 -1
- package/dist_ts/vsock-protocol.d.ts +6 -1
- package/dist_ts/vsock-protocol.js +5 -2
- package/package.json +1 -1
- package/rust/src/cpio.rs +15 -5
- package/rust/src/egress.rs +556 -0
- package/rust/src/guest.rs +128 -23
- package/rust/src/lib.rs +1 -0
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/api-client.ts +14 -3
- package/ts/cli.ts +66 -6
- package/ts/config.ts +9 -4
- package/ts/decommission.ts +167 -0
- package/ts/egress-proxy.ts +355 -0
- package/ts/errors.ts +10 -1
- package/ts/index.ts +1 -0
- package/ts/microvm-executor.ts +64 -2
- package/ts/runner.ts +6 -0
- package/ts/vsock-protocol.ts +8 -2
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import * as plugins from './plugins.js';
|
|
2
|
+
|
|
3
|
+
export interface IDecommissionHostOptions {
|
|
4
|
+
configPath?: string;
|
|
5
|
+
stateDirectory?: string;
|
|
6
|
+
removeSystemdService?: boolean;
|
|
7
|
+
serviceName?: string;
|
|
8
|
+
systemdUnitDir?: string;
|
|
9
|
+
runSystemctl?: (args: string[]) => Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface IDecommissionHostResult {
|
|
13
|
+
removedPaths: string[];
|
|
14
|
+
removedService: boolean;
|
|
15
|
+
warnings: string[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const isSafeRemovalPath = (targetPath: string): boolean => {
|
|
19
|
+
const resolved = plugins.path.resolve(targetPath);
|
|
20
|
+
if (!resolved || resolved === '/' || resolved === '/etc' || resolved === '/var' || resolved === '/var/lib') {
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
return true;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const defaultRunSystemctl = async (args: string[]): Promise<void> => {
|
|
27
|
+
await new Promise<void>((resolve, reject) => {
|
|
28
|
+
const child = plugins.childProcess.spawn('systemctl', args, {
|
|
29
|
+
stdio: 'ignore',
|
|
30
|
+
});
|
|
31
|
+
child.once('error', reject);
|
|
32
|
+
child.once('exit', (code) => {
|
|
33
|
+
if (code === 0) resolve();
|
|
34
|
+
else reject(new Error(`systemctl ${args.join(' ')} exited with status ${code ?? 'null'}`));
|
|
35
|
+
});
|
|
36
|
+
});
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const removeIfExists = async (
|
|
40
|
+
targetPath: string,
|
|
41
|
+
options: { recursive?: boolean } = {},
|
|
42
|
+
removedPaths: string[],
|
|
43
|
+
warnings: string[],
|
|
44
|
+
): Promise<void> => {
|
|
45
|
+
if (!isSafeRemovalPath(targetPath)) {
|
|
46
|
+
warnings.push(`Refused to remove unsafe path: ${targetPath}`);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const resolved = plugins.path.resolve(targetPath);
|
|
50
|
+
try {
|
|
51
|
+
await plugins.fs.lstat(resolved);
|
|
52
|
+
} catch (error) {
|
|
53
|
+
if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') return;
|
|
54
|
+
warnings.push(
|
|
55
|
+
`Could not inspect ${resolved}: ${error instanceof Error ? error.message : String(error)}`,
|
|
56
|
+
);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
try {
|
|
60
|
+
await plugins.fs.rm(resolved, {
|
|
61
|
+
recursive: Boolean(options.recursive),
|
|
62
|
+
force: true,
|
|
63
|
+
});
|
|
64
|
+
removedPaths.push(resolved);
|
|
65
|
+
} catch (error) {
|
|
66
|
+
warnings.push(
|
|
67
|
+
`Could not remove ${resolved}: ${error instanceof Error ? error.message : String(error)}`,
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const removeEmptyDirIfNamed = async (
|
|
73
|
+
dirPath: string,
|
|
74
|
+
expectedBasename: string,
|
|
75
|
+
removedPaths: string[],
|
|
76
|
+
): Promise<void> => {
|
|
77
|
+
const resolved = plugins.path.resolve(dirPath);
|
|
78
|
+
if (!isSafeRemovalPath(resolved) || plugins.path.basename(resolved) !== expectedBasename) {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
const entries = await plugins.fs.readdir(resolved);
|
|
83
|
+
if (entries.length === 0) {
|
|
84
|
+
await plugins.fs.rmdir(resolved);
|
|
85
|
+
removedPaths.push(resolved);
|
|
86
|
+
}
|
|
87
|
+
} catch {
|
|
88
|
+
// Best-effort cleanup of empty parent directory.
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Removes local runner credentials, configuration, state, and (when executed with host privileges)
|
|
94
|
+
* disables and deletes the systemd service unit so a revoked or deleted runner is completely
|
|
95
|
+
* removed from the host. Leaves shared host infrastructure like `smartvm-helper` untouched.
|
|
96
|
+
*/
|
|
97
|
+
export const decommissionRunnerHost = async (
|
|
98
|
+
options: IDecommissionHostOptions,
|
|
99
|
+
): Promise<IDecommissionHostResult> => {
|
|
100
|
+
const removedPaths: string[] = [];
|
|
101
|
+
const warnings: string[] = [];
|
|
102
|
+
let removedService = false;
|
|
103
|
+
|
|
104
|
+
let effectiveStateDir = options.stateDirectory;
|
|
105
|
+
if (!effectiveStateDir && options.configPath) {
|
|
106
|
+
try {
|
|
107
|
+
const raw = await plugins.fs.readFile(options.configPath, 'utf8');
|
|
108
|
+
const parsed = JSON.parse(raw) as { stateDirectory?: unknown };
|
|
109
|
+
if (typeof parsed.stateDirectory === 'string' && parsed.stateDirectory.trim()) {
|
|
110
|
+
effectiveStateDir = parsed.stateDirectory.trim();
|
|
111
|
+
}
|
|
112
|
+
} catch {
|
|
113
|
+
// Config may already be removed or unreadable.
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (effectiveStateDir) {
|
|
118
|
+
await removeIfExists(effectiveStateDir, { recursive: true }, removedPaths, warnings);
|
|
119
|
+
await removeEmptyDirIfNamed(
|
|
120
|
+
plugins.path.dirname(effectiveStateDir),
|
|
121
|
+
'ship-zone-runner',
|
|
122
|
+
removedPaths,
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (options.configPath) {
|
|
127
|
+
await removeIfExists(options.configPath, { recursive: false }, removedPaths, warnings);
|
|
128
|
+
await removeEmptyDirIfNamed(
|
|
129
|
+
plugins.path.dirname(options.configPath),
|
|
130
|
+
'ship-zone-runner',
|
|
131
|
+
removedPaths,
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (options.removeSystemdService) {
|
|
136
|
+
const serviceName = (options.serviceName?.trim() || 'ship-zone-runner').replace(/\.service$/, '');
|
|
137
|
+
const unitDir = options.systemdUnitDir || '/etc/systemd/system';
|
|
138
|
+
const unitPath = plugins.path.join(unitDir, `${serviceName}.service`);
|
|
139
|
+
const runSystemctl = options.runSystemctl ?? defaultRunSystemctl;
|
|
140
|
+
|
|
141
|
+
let unitExists = false;
|
|
142
|
+
try {
|
|
143
|
+
await plugins.fs.lstat(unitPath);
|
|
144
|
+
unitExists = true;
|
|
145
|
+
} catch {
|
|
146
|
+
unitExists = false;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (unitExists) {
|
|
150
|
+
await runSystemctl(['disable', `${serviceName}.service`]).catch((error) => {
|
|
151
|
+
warnings.push(
|
|
152
|
+
`systemctl disable failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
153
|
+
);
|
|
154
|
+
});
|
|
155
|
+
await removeIfExists(unitPath, { recursive: false }, removedPaths, warnings);
|
|
156
|
+
await runSystemctl(['daemon-reload']).catch((error) => {
|
|
157
|
+
warnings.push(
|
|
158
|
+
`systemctl daemon-reload failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
159
|
+
);
|
|
160
|
+
});
|
|
161
|
+
await runSystemctl(['reset-failed', `${serviceName}.service`]).catch(() => {});
|
|
162
|
+
removedService = true;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
return { removedPaths, removedService, warnings };
|
|
167
|
+
};
|
package/ts/egress-proxy.ts
CHANGED
|
@@ -4,6 +4,18 @@ import type { IEgressRule, IImageGrant } from './interfaces.js';
|
|
|
4
4
|
|
|
5
5
|
export const EGRESS_VSOCK_PORT = 1025;
|
|
6
6
|
|
|
7
|
+
export const EGRESS_FRAME_OPEN = 0x01;
|
|
8
|
+
export const EGRESS_FRAME_OPEN_OK = 0x02;
|
|
9
|
+
export const EGRESS_FRAME_OPEN_ERR = 0x03;
|
|
10
|
+
export const EGRESS_FRAME_DATA = 0x04;
|
|
11
|
+
export const EGRESS_FRAME_EOF = 0x05;
|
|
12
|
+
export const EGRESS_FRAME_CLOSE = 0x06;
|
|
13
|
+
|
|
14
|
+
const MAXIMUM_EGRESS_FRAME_BYTES = 256 * 1024;
|
|
15
|
+
const EGRESS_DATA_CHUNK_BYTES = 32 * 1024;
|
|
16
|
+
const MAXIMUM_CONCURRENT_EGRESS_STREAMS = 128;
|
|
17
|
+
const UPSTREAM_DIAL_TIMEOUT_MS = 15_000;
|
|
18
|
+
|
|
7
19
|
const DNS_TYPE_A = 1;
|
|
8
20
|
const DNS_TYPE_AAAA = 28;
|
|
9
21
|
const DNS_CLASS_IN = 1;
|
|
@@ -647,3 +659,346 @@ const readInitialClientBytes = (socket: plugins.net.Socket): Promise<Buffer> =>
|
|
|
647
659
|
socket.once('end', onEnd);
|
|
648
660
|
socket.once('error', onError);
|
|
649
661
|
});
|
|
662
|
+
|
|
663
|
+
const encodeEgressFrame = (streamId: number, kind: number, payload: Uint8Array): Buffer => {
|
|
664
|
+
const frame = Buffer.allocUnsafe(9 + payload.byteLength);
|
|
665
|
+
frame.writeUInt32BE(streamId >>> 0, 0);
|
|
666
|
+
frame[4] = kind;
|
|
667
|
+
frame.writeUInt32BE(payload.byteLength >>> 0, 5);
|
|
668
|
+
if (payload.byteLength > 0) frame.set(payload, 9);
|
|
669
|
+
return frame;
|
|
670
|
+
};
|
|
671
|
+
|
|
672
|
+
interface IMuxStreamState {
|
|
673
|
+
readonly streamId: number;
|
|
674
|
+
readonly host: string;
|
|
675
|
+
readonly port: number;
|
|
676
|
+
readonly destinationIp: string;
|
|
677
|
+
phase: 'inspecting' | 'dialing' | 'open' | 'closed';
|
|
678
|
+
inspectChunks: Buffer[];
|
|
679
|
+
inspectBytes: number;
|
|
680
|
+
inspectTimer?: ReturnType<typeof setTimeout>;
|
|
681
|
+
pendingChunks: Buffer[];
|
|
682
|
+
pendingEof: boolean;
|
|
683
|
+
upstream?: plugins.net.Socket;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/**
|
|
687
|
+
* Host-side multiplexed egress tunnel server bound to a Firecracker microVM's
|
|
688
|
+
* `EGRESS_VSOCK_PORT` (1025) socket. Enforces `EgressAllowlistController` DNS,
|
|
689
|
+
* global-IP, port, TLS SNI, and HTTP Host rules before dialing any upstream socket.
|
|
690
|
+
*/
|
|
691
|
+
export class EgressVsockTunnelServer {
|
|
692
|
+
private readonly streams = new Map<number, IMuxStreamState>();
|
|
693
|
+
private rxBuffer: Buffer = Buffer.alloc(0);
|
|
694
|
+
private closed = false;
|
|
695
|
+
|
|
696
|
+
constructor(
|
|
697
|
+
private readonly tunnelSocket: plugins.net.Socket,
|
|
698
|
+
private readonly controller: EgressAllowlistController,
|
|
699
|
+
private readonly onMessage?: (message: string) => void,
|
|
700
|
+
) {
|
|
701
|
+
tunnelSocket.on('data', (chunk: Buffer) => {
|
|
702
|
+
if (this.closed) return;
|
|
703
|
+
this.rxBuffer = this.rxBuffer.length === 0 ? chunk : Buffer.concat([this.rxBuffer, chunk]);
|
|
704
|
+
this.drainFrames();
|
|
705
|
+
});
|
|
706
|
+
tunnelSocket.once('close', () => this.close());
|
|
707
|
+
tunnelSocket.once('end', () => this.close());
|
|
708
|
+
tunnelSocket.once('error', () => this.close());
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
public close(): void {
|
|
712
|
+
if (this.closed) return;
|
|
713
|
+
this.closed = true;
|
|
714
|
+
for (const stream of this.streams.values()) {
|
|
715
|
+
this.destroyStream(stream, false);
|
|
716
|
+
}
|
|
717
|
+
this.streams.clear();
|
|
718
|
+
if (!this.tunnelSocket.destroyed) {
|
|
719
|
+
this.tunnelSocket.destroy();
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
private sendFrame(streamId: number, kind: number, payload: Uint8Array = Buffer.alloc(0)): void {
|
|
724
|
+
if (this.closed || this.tunnelSocket.destroyed) return;
|
|
725
|
+
try {
|
|
726
|
+
this.tunnelSocket.write(encodeEgressFrame(streamId, kind, payload));
|
|
727
|
+
} catch {
|
|
728
|
+
this.close();
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
private drainFrames(): void {
|
|
733
|
+
while (!this.closed && this.rxBuffer.length >= 9) {
|
|
734
|
+
const streamId = this.rxBuffer.readUInt32BE(0);
|
|
735
|
+
const kind = this.rxBuffer[4];
|
|
736
|
+
const length = this.rxBuffer.readUInt32BE(5);
|
|
737
|
+
if (length > MAXIMUM_EGRESS_FRAME_BYTES) {
|
|
738
|
+
this.onMessage?.('Egress tunnel frame exceeded maximum allowed size; closing tunnel');
|
|
739
|
+
this.close();
|
|
740
|
+
return;
|
|
741
|
+
}
|
|
742
|
+
if (this.rxBuffer.length < 9 + length) return;
|
|
743
|
+
const payload = this.rxBuffer.subarray(9, 9 + length);
|
|
744
|
+
this.rxBuffer = this.rxBuffer.subarray(9 + length);
|
|
745
|
+
this.handleFrame(streamId, kind, payload);
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
private handleFrame(streamId: number, kind: number, payload: Buffer): void {
|
|
750
|
+
if (kind === EGRESS_FRAME_OPEN) {
|
|
751
|
+
void this.handleOpen(streamId, payload);
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
const stream = this.streams.get(streamId);
|
|
755
|
+
if (!stream || stream.phase === 'closed') return;
|
|
756
|
+
|
|
757
|
+
if (kind === EGRESS_FRAME_CLOSE) {
|
|
758
|
+
this.destroyStream(stream, false);
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
761
|
+
if (kind === EGRESS_FRAME_EOF) {
|
|
762
|
+
if (stream.phase === 'inspecting') {
|
|
763
|
+
stream.pendingEof = true;
|
|
764
|
+
this.finishInspection(stream);
|
|
765
|
+
} else if (stream.phase === 'dialing') {
|
|
766
|
+
stream.pendingEof = true;
|
|
767
|
+
} else if (stream.phase === 'open') {
|
|
768
|
+
stream.upstream?.end();
|
|
769
|
+
}
|
|
770
|
+
return;
|
|
771
|
+
}
|
|
772
|
+
if (kind === EGRESS_FRAME_DATA) {
|
|
773
|
+
const copy = Buffer.from(payload);
|
|
774
|
+
if (stream.phase === 'inspecting') {
|
|
775
|
+
stream.inspectChunks.push(copy);
|
|
776
|
+
stream.inspectBytes += copy.length;
|
|
777
|
+
const combined = Buffer.concat(stream.inspectChunks, stream.inspectBytes);
|
|
778
|
+
const ready =
|
|
779
|
+
stream.inspectBytes >= MAXIMUM_INITIAL_INSPECT_BYTES ||
|
|
780
|
+
(stream.port === 443 &&
|
|
781
|
+
combined.length >= 5 &&
|
|
782
|
+
combined[0] === 0x16 &&
|
|
783
|
+
combined.length >= 5 + ((combined[3] << 8) | combined[4])) ||
|
|
784
|
+
(stream.port === 80 && combined.includes('\r\n\r\n')) ||
|
|
785
|
+
(stream.port === 443 && combined[0] !== 0x16);
|
|
786
|
+
if (ready) {
|
|
787
|
+
this.finishInspection(stream);
|
|
788
|
+
}
|
|
789
|
+
} else if (stream.phase === 'dialing') {
|
|
790
|
+
stream.pendingChunks.push(copy);
|
|
791
|
+
} else if (stream.phase === 'open' && stream.upstream && !stream.upstream.destroyed) {
|
|
792
|
+
stream.upstream.write(copy);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
private async handleOpen(streamId: number, payload: Buffer): Promise<void> {
|
|
798
|
+
if (this.closed) return;
|
|
799
|
+
if (this.streams.size >= MAXIMUM_CONCURRENT_EGRESS_STREAMS || this.streams.has(streamId)) {
|
|
800
|
+
this.sendFrame(streamId, EGRESS_FRAME_OPEN_ERR, Buffer.from('Too many concurrent egress streams'));
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
if (payload.length === 0 || payload.length > 1024) {
|
|
804
|
+
this.sendFrame(streamId, EGRESS_FRAME_OPEN_ERR, Buffer.from('Invalid egress OPEN payload'));
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
807
|
+
let parsed: { host?: unknown; port?: unknown };
|
|
808
|
+
try {
|
|
809
|
+
parsed = JSON.parse(payload.toString('utf8')) as { host?: unknown; port?: unknown };
|
|
810
|
+
} catch {
|
|
811
|
+
this.sendFrame(streamId, EGRESS_FRAME_OPEN_ERR, Buffer.from('Malformed egress OPEN JSON'));
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
if (
|
|
815
|
+
typeof parsed.host !== 'string' ||
|
|
816
|
+
typeof parsed.port !== 'number' ||
|
|
817
|
+
!Number.isInteger(parsed.port) ||
|
|
818
|
+
parsed.port < 1 ||
|
|
819
|
+
parsed.port > 65535
|
|
820
|
+
) {
|
|
821
|
+
this.sendFrame(streamId, EGRESS_FRAME_OPEN_ERR, Buffer.from('Invalid egress host or port'));
|
|
822
|
+
return;
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
const host = parsed.host.trim().toLowerCase().replace(/\.$/, '');
|
|
826
|
+
const port = parsed.port;
|
|
827
|
+
if (!host || host.length > 253 || parseIpv4(host) !== undefined || parseIpv6(host) !== undefined) {
|
|
828
|
+
this.sendFrame(streamId, EGRESS_FRAME_OPEN_ERR, Buffer.from('Direct IP literals are not allowed'));
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
const allowedPorts = this.controller.allowedPortsForHost(host);
|
|
833
|
+
if (!allowedPorts || !allowedPorts.has(port)) {
|
|
834
|
+
this.sendFrame(
|
|
835
|
+
streamId,
|
|
836
|
+
EGRESS_FRAME_OPEN_ERR,
|
|
837
|
+
Buffer.from(`Egress denied for ${host}:${port}`),
|
|
838
|
+
);
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
// Resolve via host allowlist controller (filters out all non-global & blocked CIDRs).
|
|
843
|
+
let resolved = await this.controller.resolveQuery(host, DNS_TYPE_A);
|
|
844
|
+
if (resolved.records.length === 0) {
|
|
845
|
+
resolved = await this.controller.resolveQuery(host, DNS_TYPE_AAAA);
|
|
846
|
+
}
|
|
847
|
+
if (this.closed) return;
|
|
848
|
+
if (!resolved.allowed || resolved.records.length === 0) {
|
|
849
|
+
this.sendFrame(
|
|
850
|
+
streamId,
|
|
851
|
+
EGRESS_FRAME_OPEN_ERR,
|
|
852
|
+
Buffer.from(`No globally reachable IP address resolved for ${host}`),
|
|
853
|
+
);
|
|
854
|
+
return;
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
const destinationIp = resolved.records[0].address;
|
|
858
|
+
const needsInspect = port === 443 || port === 80;
|
|
859
|
+
const stream: IMuxStreamState = {
|
|
860
|
+
streamId,
|
|
861
|
+
host,
|
|
862
|
+
port,
|
|
863
|
+
destinationIp,
|
|
864
|
+
phase: needsInspect ? 'inspecting' : 'dialing',
|
|
865
|
+
inspectChunks: [],
|
|
866
|
+
inspectBytes: 0,
|
|
867
|
+
pendingChunks: [],
|
|
868
|
+
pendingEof: false,
|
|
869
|
+
};
|
|
870
|
+
this.streams.set(streamId, stream);
|
|
871
|
+
|
|
872
|
+
if (needsInspect) {
|
|
873
|
+
stream.inspectTimer = setTimeout(() => {
|
|
874
|
+
if (stream.phase === 'inspecting') {
|
|
875
|
+
this.finishInspection(stream);
|
|
876
|
+
}
|
|
877
|
+
}, INITIAL_INSPECT_TIMEOUT_MS);
|
|
878
|
+
this.sendFrame(streamId, EGRESS_FRAME_OPEN_OK);
|
|
879
|
+
} else {
|
|
880
|
+
const decision = this.controller.authorizeConnection(destinationIp, port);
|
|
881
|
+
if (!decision.allowed) {
|
|
882
|
+
this.streams.delete(streamId);
|
|
883
|
+
this.sendFrame(streamId, EGRESS_FRAME_OPEN_ERR, Buffer.from(decision.reason));
|
|
884
|
+
return;
|
|
885
|
+
}
|
|
886
|
+
this.dialUpstream(stream, Buffer.alloc(0), true);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
private finishInspection(stream: IMuxStreamState): void {
|
|
891
|
+
if (stream.phase !== 'inspecting') return;
|
|
892
|
+
if (stream.inspectTimer) {
|
|
893
|
+
clearTimeout(stream.inspectTimer);
|
|
894
|
+
stream.inspectTimer = undefined;
|
|
895
|
+
}
|
|
896
|
+
const initialBytes = Buffer.concat(stream.inspectChunks, stream.inspectBytes);
|
|
897
|
+
stream.inspectChunks = [];
|
|
898
|
+
stream.inspectBytes = 0;
|
|
899
|
+
|
|
900
|
+
const decision = this.controller.authorizeConnection(stream.destinationIp, stream.port, initialBytes);
|
|
901
|
+
if (!decision.allowed) {
|
|
902
|
+
this.destroyStream(stream, true, decision.reason);
|
|
903
|
+
return;
|
|
904
|
+
}
|
|
905
|
+
if (decision.hostname !== stream.host) {
|
|
906
|
+
this.destroyStream(
|
|
907
|
+
stream,
|
|
908
|
+
true,
|
|
909
|
+
`Protocol hostname ${decision.hostname} does not match requested host ${stream.host}`,
|
|
910
|
+
);
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
stream.phase = 'dialing';
|
|
914
|
+
this.dialUpstream(stream, initialBytes, false);
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
private dialUpstream(stream: IMuxStreamState, initialBytes: Buffer, sendOpenOkOnConnect: boolean): void {
|
|
918
|
+
const upstream = plugins.net.createConnection({
|
|
919
|
+
host: stream.destinationIp,
|
|
920
|
+
port: stream.port,
|
|
921
|
+
});
|
|
922
|
+
stream.upstream = upstream;
|
|
923
|
+
upstream.setTimeout(UPSTREAM_DIAL_TIMEOUT_MS, () => {
|
|
924
|
+
if (stream.phase === 'dialing') {
|
|
925
|
+
if (sendOpenOkOnConnect) {
|
|
926
|
+
this.sendFrame(stream.streamId, EGRESS_FRAME_OPEN_ERR, Buffer.from('Upstream dial timed out'));
|
|
927
|
+
this.destroyStream(stream, false);
|
|
928
|
+
} else {
|
|
929
|
+
this.destroyStream(stream, true, 'Upstream dial timed out');
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
});
|
|
933
|
+
|
|
934
|
+
upstream.once('connect', () => {
|
|
935
|
+
if (stream.phase === 'closed' || this.closed) {
|
|
936
|
+
upstream.destroy();
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
upstream.setTimeout(0);
|
|
940
|
+
stream.phase = 'open';
|
|
941
|
+
if (sendOpenOkOnConnect) {
|
|
942
|
+
this.sendFrame(stream.streamId, EGRESS_FRAME_OPEN_OK);
|
|
943
|
+
}
|
|
944
|
+
if (initialBytes.length > 0) upstream.write(initialBytes);
|
|
945
|
+
for (const chunk of stream.pendingChunks) upstream.write(chunk);
|
|
946
|
+
stream.pendingChunks = [];
|
|
947
|
+
if (stream.pendingEof) upstream.end();
|
|
948
|
+
});
|
|
949
|
+
|
|
950
|
+
upstream.on('data', (chunk: Buffer) => {
|
|
951
|
+
if (stream.phase === 'closed' || this.closed) return;
|
|
952
|
+
for (let offset = 0; offset < chunk.length; offset += EGRESS_DATA_CHUNK_BYTES) {
|
|
953
|
+
const slice = chunk.subarray(offset, Math.min(chunk.length, offset + EGRESS_DATA_CHUNK_BYTES));
|
|
954
|
+
this.sendFrame(stream.streamId, EGRESS_FRAME_DATA, slice);
|
|
955
|
+
}
|
|
956
|
+
});
|
|
957
|
+
|
|
958
|
+
upstream.once('end', () => {
|
|
959
|
+
if (stream.phase !== 'closed') {
|
|
960
|
+
this.sendFrame(stream.streamId, EGRESS_FRAME_EOF);
|
|
961
|
+
}
|
|
962
|
+
});
|
|
963
|
+
|
|
964
|
+
upstream.once('error', (error) => {
|
|
965
|
+
if (stream.phase === 'closed') return;
|
|
966
|
+
if (sendOpenOkOnConnect && stream.phase === 'dialing') {
|
|
967
|
+
this.sendFrame(
|
|
968
|
+
stream.streamId,
|
|
969
|
+
EGRESS_FRAME_OPEN_ERR,
|
|
970
|
+
Buffer.from(`Upstream error: ${error.message}`.slice(0, 256)),
|
|
971
|
+
);
|
|
972
|
+
this.destroyStream(stream, false);
|
|
973
|
+
} else {
|
|
974
|
+
this.destroyStream(stream, true, error.message);
|
|
975
|
+
}
|
|
976
|
+
});
|
|
977
|
+
|
|
978
|
+
upstream.once('close', () => {
|
|
979
|
+
if (stream.phase !== 'closed') {
|
|
980
|
+
this.destroyStream(stream, true);
|
|
981
|
+
}
|
|
982
|
+
});
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
private destroyStream(stream: IMuxStreamState, notifyGuest: boolean, reason?: string): void {
|
|
986
|
+
if (stream.phase === 'closed') return;
|
|
987
|
+
stream.phase = 'closed';
|
|
988
|
+
if (stream.inspectTimer) {
|
|
989
|
+
clearTimeout(stream.inspectTimer);
|
|
990
|
+
stream.inspectTimer = undefined;
|
|
991
|
+
}
|
|
992
|
+
this.streams.delete(stream.streamId);
|
|
993
|
+
if (stream.upstream && !stream.upstream.destroyed) {
|
|
994
|
+
stream.upstream.destroy();
|
|
995
|
+
}
|
|
996
|
+
if (notifyGuest && !this.closed) {
|
|
997
|
+
this.sendFrame(
|
|
998
|
+
stream.streamId,
|
|
999
|
+
EGRESS_FRAME_CLOSE,
|
|
1000
|
+
reason ? Buffer.from(reason.slice(0, 256), 'utf8') : Buffer.alloc(0),
|
|
1001
|
+
);
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
}
|
package/ts/errors.ts
CHANGED
|
@@ -46,13 +46,22 @@ export class CoordinatorError extends RunnerError {
|
|
|
46
46
|
}
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
+
export const RUNNER_DECOMMISSIONED_EXIT_CODE = 42;
|
|
50
|
+
|
|
49
51
|
export class AuthenticationError extends CoordinatorError {
|
|
50
|
-
constructor(
|
|
52
|
+
constructor(
|
|
53
|
+
message = 'Runner authentication was rejected',
|
|
54
|
+
public readonly code?: string,
|
|
55
|
+
) {
|
|
51
56
|
super(message, 401);
|
|
52
57
|
this.name = 'AuthenticationError';
|
|
53
58
|
}
|
|
54
59
|
}
|
|
55
60
|
|
|
61
|
+
export const isRunnerDecommissionedError = (error: unknown): error is AuthenticationError =>
|
|
62
|
+
error instanceof AuthenticationError &&
|
|
63
|
+
(error.code === 'runner_revoked' || error.code === 'runner_deleted');
|
|
64
|
+
|
|
56
65
|
export class LeaseLostError extends CoordinatorError {
|
|
57
66
|
constructor(message = 'The job lease is no longer valid') {
|
|
58
67
|
super(message, 409);
|
package/ts/index.ts
CHANGED
|
@@ -2,6 +2,7 @@ export * from './api-client.js';
|
|
|
2
2
|
export * from './artifact-manager.js';
|
|
3
3
|
export * from './cache-manager.js';
|
|
4
4
|
export * from './config.js';
|
|
5
|
+
export * from './decommission.js';
|
|
5
6
|
export * from './egress-proxy.js';
|
|
6
7
|
export * from './errors.js';
|
|
7
8
|
export * from './interfaces.js';
|
package/ts/microvm-executor.ts
CHANGED
|
@@ -36,7 +36,12 @@ import {
|
|
|
36
36
|
parseDigestPinnedImageReference,
|
|
37
37
|
resolveImageReference,
|
|
38
38
|
} from './oci-registry.js';
|
|
39
|
-
import {
|
|
39
|
+
import {
|
|
40
|
+
EGRESS_VSOCK_PORT,
|
|
41
|
+
EgressAllowlistController,
|
|
42
|
+
EgressVsockTunnelServer,
|
|
43
|
+
grantOriginsFromLease,
|
|
44
|
+
} from './egress-proxy.js';
|
|
40
45
|
import { buildNpmrcContent, GUEST_NPMRC_PATH } from './npm-grants.js';
|
|
41
46
|
import {
|
|
42
47
|
ensurePrivateStateDirectory,
|
|
@@ -891,6 +896,27 @@ export class MicroVmExecutor implements IJobExecutor {
|
|
|
891
896
|
);
|
|
892
897
|
}
|
|
893
898
|
|
|
899
|
+
private async connectEgressVsock(
|
|
900
|
+
vm: IMicroVmHandle,
|
|
901
|
+
signal: AbortSignal,
|
|
902
|
+
): Promise<plugins.net.Socket> {
|
|
903
|
+
const deadline = this.now() + vsockConnectTimeoutMs;
|
|
904
|
+
let lastError: unknown;
|
|
905
|
+
while (this.now() < deadline) {
|
|
906
|
+
if (signal.aborted) throw signal.reason;
|
|
907
|
+
try {
|
|
908
|
+
return await vm.connectVsock(EGRESS_VSOCK_PORT);
|
|
909
|
+
} catch (error) {
|
|
910
|
+
lastError = error;
|
|
911
|
+
}
|
|
912
|
+
await new Promise((resolvePromise) => setTimeout(resolvePromise, vsockConnectRetryIntervalMs));
|
|
913
|
+
}
|
|
914
|
+
throw new RunnerError(
|
|
915
|
+
`Timed out waiting for Firecracker guest egress tunnel on vsock port ${EGRESS_VSOCK_PORT}`,
|
|
916
|
+
{ cause: lastError },
|
|
917
|
+
);
|
|
918
|
+
}
|
|
919
|
+
|
|
894
920
|
async execute(context: IExecutionContext): Promise<IExecutionResult> {
|
|
895
921
|
const runtime = await this.verifyRuntime();
|
|
896
922
|
if (context.signal.aborted) {
|
|
@@ -928,6 +954,7 @@ export class MicroVmExecutor implements IJobExecutor {
|
|
|
928
954
|
await this.trackVm(vm.vmId);
|
|
929
955
|
|
|
930
956
|
let guest: GuestVsockClient | undefined;
|
|
957
|
+
let egressTunnel: EgressVsockTunnelServer | undefined;
|
|
931
958
|
let cleaned = false;
|
|
932
959
|
const exportDirs: string[] = [];
|
|
933
960
|
|
|
@@ -935,6 +962,10 @@ export class MicroVmExecutor implements IJobExecutor {
|
|
|
935
962
|
if (cleaned) return;
|
|
936
963
|
cleaned = true;
|
|
937
964
|
const errors: unknown[] = [];
|
|
965
|
+
if (egressTunnel) {
|
|
966
|
+
egressTunnel.close();
|
|
967
|
+
egressTunnel = undefined;
|
|
968
|
+
}
|
|
938
969
|
if (guest) {
|
|
939
970
|
try {
|
|
940
971
|
await Promise.race([
|
|
@@ -973,19 +1004,39 @@ export class MicroVmExecutor implements IJobExecutor {
|
|
|
973
1004
|
await vm.start();
|
|
974
1005
|
guest = await this.connectGuestVsock(vm, context.signal);
|
|
975
1006
|
|
|
1007
|
+
const egressRequested = job.network.mode === 'egress';
|
|
1008
|
+
if (job.network.mode === 'egress') {
|
|
1009
|
+
const egressController = new EgressAllowlistController({
|
|
1010
|
+
allow: job.network.allow,
|
|
1011
|
+
grantOrigins: grantOriginsFromLease(context.lease.grants),
|
|
1012
|
+
blockedCidrs: this.config.oci.egressBlockedCidrs,
|
|
1013
|
+
});
|
|
1014
|
+
const egressSocket = await this.connectEgressVsock(vm, context.signal);
|
|
1015
|
+
egressTunnel = new EgressVsockTunnelServer(egressSocket, egressController);
|
|
1016
|
+
}
|
|
1017
|
+
|
|
976
1018
|
const npmrcContent = context.lease.npmGrants && context.lease.npmGrants.length > 0
|
|
977
1019
|
? buildNpmrcContent(context.lease.npmGrants)
|
|
978
1020
|
: undefined;
|
|
979
1021
|
const profile = job.requirements.executionProfile;
|
|
980
1022
|
|
|
981
|
-
await guest.prepareWorkspace({
|
|
1023
|
+
const preparedWorkspace = await guest.prepareWorkspace({
|
|
982
1024
|
workspaceSizeBytes: workspaceBytes,
|
|
983
1025
|
maximumWorkspaceEntries: workspaceEntries,
|
|
984
1026
|
uid: profile === 'vm' ? 0 : this.user.uid,
|
|
985
1027
|
gid: profile === 'vm' ? 0 : this.user.gid,
|
|
986
1028
|
mode: profile,
|
|
987
1029
|
...(npmrcContent ? { npmrcContent } : {}),
|
|
1030
|
+
...(egressRequested ? { enableEgress: true } : {}),
|
|
988
1031
|
});
|
|
1032
|
+
const egressProxyUrl = egressRequested
|
|
1033
|
+
? preparedWorkspace.egressProxyPort
|
|
1034
|
+
? `http://127.0.0.1:${preparedWorkspace.egressProxyPort}`
|
|
1035
|
+
: undefined
|
|
1036
|
+
: undefined;
|
|
1037
|
+
if (egressRequested && !egressProxyUrl) {
|
|
1038
|
+
throw new RunnerError('Firecracker guest agent failed to initialize egress proxy listener');
|
|
1039
|
+
}
|
|
989
1040
|
|
|
990
1041
|
const packed = await packDirectoryToTar(
|
|
991
1042
|
context.workspacePath,
|
|
@@ -1055,6 +1106,7 @@ export class MicroVmExecutor implements IJobExecutor {
|
|
|
1055
1106
|
})),
|
|
1056
1107
|
timeoutMs: Math.min(buildTimeoutMs, this.config.oci.maximumTimeoutMs),
|
|
1057
1108
|
...(this.config.oci.buildctlPath ? { buildctlPath: this.config.oci.buildctlPath } : {}),
|
|
1109
|
+
...(egressProxyUrl ? { egressProxyUrl } : {}),
|
|
1058
1110
|
},
|
|
1059
1111
|
{
|
|
1060
1112
|
signal: buildAbort.signal,
|
|
@@ -1155,6 +1207,15 @@ export class MicroVmExecutor implements IJobExecutor {
|
|
|
1155
1207
|
if (npmrcContent) {
|
|
1156
1208
|
env.NPM_CONFIG_USERCONFIG = GUEST_NPMRC_PATH;
|
|
1157
1209
|
}
|
|
1210
|
+
if (egressProxyUrl) {
|
|
1211
|
+
env.HTTP_PROXY = egressProxyUrl;
|
|
1212
|
+
env.HTTPS_PROXY = egressProxyUrl;
|
|
1213
|
+
env.http_proxy = egressProxyUrl;
|
|
1214
|
+
env.https_proxy = egressProxyUrl;
|
|
1215
|
+
env.NO_PROXY = 'localhost,127.0.0.1,::1';
|
|
1216
|
+
env.no_proxy = 'localhost,127.0.0.1,::1';
|
|
1217
|
+
env.NODE_USE_ENV_PROXY = '1';
|
|
1218
|
+
}
|
|
1158
1219
|
const workingDirectory = job.execution.workingDirectory ?? '/workspace';
|
|
1159
1220
|
const stepTimeoutMs = Math.min(remainingMs, this.config.oci.maximumTimeoutMs);
|
|
1160
1221
|
|
|
@@ -1174,6 +1235,7 @@ export class MicroVmExecutor implements IJobExecutor {
|
|
|
1174
1235
|
uid: profile === 'vm' ? 0 : this.user.uid,
|
|
1175
1236
|
gid: profile === 'vm' ? 0 : this.user.gid,
|
|
1176
1237
|
rootMode: profile === 'vm',
|
|
1238
|
+
egressEnabled: Boolean(egressProxyUrl),
|
|
1177
1239
|
timeoutMs: stepTimeoutMs,
|
|
1178
1240
|
memoryBytes,
|
|
1179
1241
|
cpus,
|