Repository navigation
Expand file tree
/
Copy pathacme-container-sandbox.mjs
More file actions
320 lines (309 loc) · 11.1 KB
/
Copy pathacme-container-sandbox.mjs
File metadata and controls
320 lines (309 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
// AcmeCode's custom sandbox adapter (`sandbox.provider: custom`): commands
// run in a container of the organization's sandbox service, with the
// developer's project bind-mounted, so the workspace is `shared`: the file
// tools and the shell touch the same files. The service owns isolation;
// PiShip keeps policy, approvals, audit, the approved environment, and the
// timeout and cancellation of every command. An adapter is one file that
// imports nothing but @piship/adapter-sdk and Node built-ins.
//
// The service is `sandbox.endpoint`, and it takes the API key a person stores
// with `<command> sandbox login` (`sandbox.credential: stored`). PiShip
// binds that key to the user and to the endpoint's origin; this adapter
// honors the origin rule too: it sends the key only to an origin it was
// issued for, never to a URL a response names, and never follows a redirect.
import {
defineSandboxAdapter,
isPiShipError,
PiShipError,
withTimeout,
} from "@piship/adapter-sdk";
const STATUS_TIMEOUT_MS = 10_000;
// Creating a sandbox may pull the image the first time.
const CREATE_TIMEOUT_MS = 180_000;
const DISPOSE_TIMEOUT_MS = 20_000;
const MAX_JSON_BYTES = 65_536;
const MAX_LINE_BYTES = 1_048_576;
function unavailable(message, options = {}) {
return new PiShipError("SANDBOX_UNAVAILABLE", message, {
component: "sandbox",
...options,
});
}
function originOf(url) {
try {
return new URL(url).origin;
} catch {
return undefined;
}
}
/** What a caller of `available()` may be told: never more than a fixed reason. */
function reasonOf(error) {
if (isPiShipError(error)) {
if (error.code === "SANDBOX_UNAVAILABLE") return error.message;
return `the sandbox service is not reachable (${error.code})`;
}
return "the sandbox service is unreachable";
}
export default defineSandboxAdapter((context) => {
const endpoint = context.endpoint;
// The origins the credential may go to. PiShip passes the ones a stored
// credential was issued for; without them, only the endpoint's own.
const origins =
context.credentialOrigins ?? (endpoint ? [originOf(endpoint)] : []);
/**
* One request to the service. The credential is read for this request only
* and set as the bearer, after checking the URL is on an origin it may go
* to. A 401 or 403 is reported to PiShip, which marks a stored credential
* rejected (it never resolves true for one, so nothing is repeated), and
* fails the call without ever repeating the response's text.
*/
async function call(method, path, options = {}) {
if (!endpoint) throw unavailable("sandbox.endpoint is not set");
const url = new URL(
path,
endpoint.endsWith("/") ? endpoint : `${endpoint}/`,
);
const headers = {
accept: "application/json, application/x-ndjson",
...(options.body === undefined
? {}
: { "content-type": "application/json" }),
};
const secret = await context.credential?.();
if (secret !== undefined) {
if (!origins.includes(url.origin))
throw unavailable(
"the sandbox credential is not sent to an origin it was not issued for",
);
headers.authorization = `Bearer ${secret}`;
}
const signal =
options.timeoutMs === undefined
? options.signal
: withTimeout(options.timeoutMs, options.signal);
let response;
try {
response = await context.fetch(url, {
method,
headers,
redirect: "manual",
...(options.body === undefined
? {}
: { body: JSON.stringify(options.body) }),
...(signal ? { signal } : {}),
});
} catch (error) {
// PiShip's cancellation passes through as it came, and a network or TLS
// policy refusal keeps its code. Never build a message from any other
// transport error: it can quote the Authorization header.
if (options.signal?.aborted) throw options.signal.reason ?? error;
if (isPiShipError(error)) throw error;
throw unavailable("the sandbox service is unreachable", {
retryable: true,
});
}
if (response.ok) return response;
await refuse(response);
}
/** An answer's text, at most `MAX_JSON_BYTES` of it; the rest is dropped. */
async function boundedText(response) {
if (!response.body) return "";
const reader = response.body.getReader();
const decoder = new TextDecoder();
let text = "";
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
text += decoder.decode(value, { stream: true });
if (text.length > MAX_JSON_BYTES) {
await reader.cancel().catch(() => undefined);
return text.slice(0, MAX_JSON_BYTES + 1);
}
}
} catch {
throw unavailable("the sandbox service's answer could not be read");
}
return text;
}
async function refuse(response) {
if (response.status === 401 || response.status === 403) {
// Its body may echo the credential: it is never read.
await response.body?.cancel().catch(() => undefined);
await context.credentialRejected?.().catch(() => false);
throw unavailable("the sandbox service refused the sandbox credential", {
userAction: "Store a new sandbox credential with sandbox login",
});
}
// The service's error code is one lowercase word; take nothing else.
let code;
try {
const found = JSON.parse(await boundedText(response))?.error?.code;
if (typeof found === "string" && /^[a-z_]{1,40}$/.test(found))
code = found;
} catch {
// not the service's error body
}
throw unavailable(
`the sandbox service refused the request (HTTP ${response.status}${code ? `, ${code}` : ""})`,
{ retryable: response.status === 429 || response.status >= 500 },
);
}
async function json(response) {
const text = await boundedText(response);
if (text.length > MAX_JSON_BYTES)
throw unavailable("the sandbox service's answer is too large");
try {
return JSON.parse(text);
} catch {
throw unavailable("the sandbox service's answer is not JSON");
}
}
/** Forward a command's output as it arrives; resolve with its exit. */
async function forward(response, io) {
if (!response.body)
throw unavailable("the sandbox service sent no output stream");
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let exit;
const handle = (line) => {
let record;
try {
record = JSON.parse(line);
} catch {
throw unavailable("the sandbox service sent an unreadable answer");
}
if (record?.stream === "stdout" || record?.stream === "stderr") {
const chunk = Buffer.from(String(record.data ?? ""), "base64");
if (record.stream === "stdout") io.onStdout(chunk);
else io.onStderr(chunk);
} else if ("exit" in Object(record)) {
exit = {
exitCode: Number.isInteger(record.exit) ? record.exit : null,
signal: typeof record.signal === "string" ? record.signal : null,
};
}
};
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
for (
let end = buffer.indexOf("\n");
end >= 0;
end = buffer.indexOf("\n")
) {
handle(buffer.slice(0, end));
buffer = buffer.slice(end + 1);
}
if (buffer.length > MAX_LINE_BYTES)
throw unavailable("the sandbox service sent an oversized answer");
}
} catch (error) {
if (io.signal.aborted) throw io.signal.reason ?? error;
if (isPiShipError(error)) throw error;
throw unavailable("the connection to the sandbox service was lost", {
retryable: true,
});
}
if (exit === undefined)
throw unavailable(
"the sandbox service ended the connection before the command finished",
);
return exit;
}
return {
id: "acme-container",
async available() {
if (!endpoint)
return { available: false, reason: "sandbox.endpoint is not set" };
try {
const status = await json(
await call("GET", "v1/status", { timeoutMs: STATUS_TIMEOUT_MS }),
);
return status?.runtime === "ok"
? { available: true }
: {
available: false,
reason: "the sandbox service cannot reach its container runtime",
};
} catch (error) {
return { available: false, reason: reasonOf(error) };
}
},
// Claim only what the service enforces. Each command runs in a container
// that sees this host's files only through the workspace mount and has
// its `.git` read-only, so it claims workspace-confinement and
// git-control-protection, and never host-filesystem-isolation (the
// workspace is reachable) or the filesystem-* planes (PiShip's path
// rules are not applied inside the container). `network: deny` is a
// container with no network at all.
capabilities() {
return {
isolation: "remote",
planes: [
"workspace-confinement",
"git-control-protection",
"network-deny",
"environment-filter",
],
network: ["deny", "allow"],
localProcesses: false,
workspace: { mode: "shared" },
};
},
async prepare(request) {
// Never repeated on failure: a second create could leave two sandboxes.
const { profile } = request;
const created = await json(
await call("POST", "v1/sandboxes", {
body: {
workspace: profile.workspace,
network: profile.network,
writeProtect: {
files: profile.writeProtect.files,
directories: profile.writeProtect.directories,
},
},
timeoutMs: CREATE_TIMEOUT_MS,
...(request.signal ? { signal: request.signal } : {}),
}),
);
if (
typeof created?.id !== "string" ||
!/^sbx_[0-9a-f]{24}$/.test(created.id)
)
throw unavailable("the sandbox service answered without a sandbox");
const path = `v1/sandboxes/${created.id}`;
let disposed = false;
return {
async exec(command, io) {
if (disposed) throw unavailable("the sandbox was disposed");
if (command.workspacePath === undefined)
throw unavailable("the command runs outside the workspace");
// io.signal is PiShip's timeout and cancellation: the service stops
// the command when this connection ends.
const response = await call("POST", `${path}/exec`, {
body: {
command: command.command,
cwd: command.workspacePath,
env: command.env,
},
signal: io.signal,
});
return forward(response, io);
},
async dispose() {
// Called once and must not throw.
if (disposed) return;
disposed = true;
await call("DELETE", path, { timeoutMs: DISPOSE_TIMEOUT_MS }).catch(
() => undefined,
);
},
};
},
};
});