@buildanagent/harness 0.1.0-alpha.28 → 0.1.0-alpha.30

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.
Files changed (113) hide show
  1. package/README.md +152 -5
  2. package/dist/context/file-spill.d.ts +11 -1
  3. package/dist/context/file-spill.js +23 -8
  4. package/dist/context/file-spill.js.map +1 -1
  5. package/dist/context/spill.d.ts +5 -1
  6. package/dist/context/spill.js +6 -2
  7. package/dist/context/spill.js.map +1 -1
  8. package/dist/credentials/addresses.d.ts +11 -0
  9. package/dist/credentials/addresses.js +41 -2
  10. package/dist/credentials/addresses.js.map +1 -1
  11. package/dist/credentials/allowlist.d.ts +22 -2
  12. package/dist/credentials/allowlist.js +74 -17
  13. package/dist/credentials/allowlist.js.map +1 -1
  14. package/dist/credentials/egress-policy.d.ts +69 -0
  15. package/dist/credentials/egress-policy.js +170 -0
  16. package/dist/credentials/egress-policy.js.map +1 -0
  17. package/dist/credentials/egress-proxy.d.ts +13 -1
  18. package/dist/credentials/egress-proxy.js +179 -11
  19. package/dist/credentials/egress-proxy.js.map +1 -1
  20. package/dist/credentials/git-route.d.ts +68 -0
  21. package/dist/credentials/git-route.js +288 -0
  22. package/dist/credentials/git-route.js.map +1 -0
  23. package/dist/credentials/index.d.ts +5 -1
  24. package/dist/credentials/index.js +5 -1
  25. package/dist/credentials/index.js.map +1 -1
  26. package/dist/credentials/scrub.d.ts +7 -0
  27. package/dist/credentials/scrub.js +22 -0
  28. package/dist/credentials/scrub.js.map +1 -1
  29. package/dist/errors.d.ts +14 -7
  30. package/dist/errors.js +13 -6
  31. package/dist/errors.js.map +1 -1
  32. package/dist/sandbox/base.d.ts +11 -1
  33. package/dist/sandbox/base.js +14 -0
  34. package/dist/sandbox/base.js.map +1 -1
  35. package/dist/sandbox/docker/index.d.ts +8 -2
  36. package/dist/sandbox/docker/index.js +63 -14
  37. package/dist/sandbox/docker/index.js.map +1 -1
  38. package/dist/sandbox/errors.d.ts +30 -2
  39. package/dist/sandbox/errors.js +36 -1
  40. package/dist/sandbox/errors.js.map +1 -1
  41. package/dist/sandbox/escalation-table.d.ts +38 -0
  42. package/dist/sandbox/escalation-table.js +95 -0
  43. package/dist/sandbox/escalation-table.js.map +1 -0
  44. package/dist/sandbox/escalation.d.ts +191 -0
  45. package/dist/sandbox/escalation.js +370 -0
  46. package/dist/sandbox/escalation.js.map +1 -0
  47. package/dist/sandbox/host-files.d.ts +2 -0
  48. package/dist/sandbox/host-files.js +10 -0
  49. package/dist/sandbox/host-files.js.map +1 -1
  50. package/dist/sandbox/index.d.ts +9 -4
  51. package/dist/sandbox/index.js +8 -3
  52. package/dist/sandbox/index.js.map +1 -1
  53. package/dist/sandbox/policy.d.ts +49 -0
  54. package/dist/sandbox/policy.js +149 -0
  55. package/dist/sandbox/policy.js.map +1 -0
  56. package/dist/sandbox/process.js +1 -1
  57. package/dist/sandbox/process.js.map +1 -1
  58. package/dist/sandbox/srt/index.d.ts +5 -2
  59. package/dist/sandbox/srt/index.js +27 -8
  60. package/dist/sandbox/srt/index.js.map +1 -1
  61. package/dist/sandbox/srt/settings.d.ts +17 -5
  62. package/dist/sandbox/srt/settings.js +53 -0
  63. package/dist/sandbox/srt/settings.js.map +1 -1
  64. package/dist/sandbox/types.d.ts +41 -4
  65. package/dist/sandbox/types.js.map +1 -1
  66. package/dist/sandbox/widen.d.ts +10 -0
  67. package/dist/sandbox/widen.js +150 -0
  68. package/dist/sandbox/widen.js.map +1 -0
  69. package/dist/session/approvals.d.ts +30 -1
  70. package/dist/session/approvals.js +12 -4
  71. package/dist/session/approvals.js.map +1 -1
  72. package/dist/session/code-call.d.ts +15 -1
  73. package/dist/session/code-call.js +2 -1
  74. package/dist/session/code-call.js.map +1 -1
  75. package/dist/session/escalation-log.d.ts +65 -0
  76. package/dist/session/escalation-log.js +84 -0
  77. package/dist/session/escalation-log.js.map +1 -0
  78. package/dist/session/rebuild.js +12 -3
  79. package/dist/session/rebuild.js.map +1 -1
  80. package/dist/testing/fake-sandbox.d.ts +21 -3
  81. package/dist/testing/fake-sandbox.js +157 -8
  82. package/dist/testing/fake-sandbox.js.map +1 -1
  83. package/dist/testing/sandbox-conformance.js +108 -1
  84. package/dist/testing/sandbox-conformance.js.map +1 -1
  85. package/dist/tools/builtins/bash.d.ts +9 -0
  86. package/dist/tools/builtins/bash.js +75 -0
  87. package/dist/tools/builtins/bash.js.map +1 -0
  88. package/dist/tools/builtins/builtins.d.ts +38 -0
  89. package/dist/tools/builtins/builtins.js +48 -0
  90. package/dist/tools/builtins/builtins.js.map +1 -0
  91. package/dist/tools/builtins/descriptions.d.ts +69 -0
  92. package/dist/tools/builtins/descriptions.js +94 -0
  93. package/dist/tools/builtins/descriptions.js.map +1 -0
  94. package/dist/tools/builtins/fetch.d.ts +12 -0
  95. package/dist/tools/builtins/fetch.js +157 -0
  96. package/dist/tools/builtins/fetch.js.map +1 -0
  97. package/dist/tools/builtins/files.d.ts +27 -0
  98. package/dist/tools/builtins/files.js +274 -0
  99. package/dist/tools/builtins/files.js.map +1 -0
  100. package/dist/tools/builtins/paths.d.ts +30 -0
  101. package/dist/tools/builtins/paths.js +62 -0
  102. package/dist/tools/builtins/paths.js.map +1 -0
  103. package/dist/tools/builtins/results.d.ts +15 -0
  104. package/dist/tools/builtins/results.js +31 -0
  105. package/dist/tools/builtins/results.js.map +1 -0
  106. package/dist/tools/builtins/search.d.ts +18 -0
  107. package/dist/tools/builtins/search.js +217 -0
  108. package/dist/tools/builtins/search.js.map +1 -0
  109. package/dist/tools/index.d.ts +6 -2
  110. package/dist/tools/index.js +5 -2
  111. package/dist/tools/index.js.map +1 -1
  112. package/llms.txt +52 -0
  113. package/package.json +5 -5
@@ -9,6 +9,7 @@
9
9
  import { HarnessError } from "../errors.js";
10
10
  import { isAddressLiteral, isPublicAddress } from "./addresses.js";
11
11
  import { isAllowed, parseAllow, parseRoutes, } from "./allowlist.js";
12
+ import { basicCarries, basicHeader, gitEndpoint, PushReader, pushVerdict } from "./git-route.js";
12
13
  function nodeModules() {
13
14
  if (typeof process === "undefined" || typeof process.getBuiltinModule !== "function") {
14
15
  throw new HarnessError("invalid_egress_options", "the egress proxy needs Node's network modules, which this runtime lacks");
@@ -36,6 +37,12 @@ const HOP_BY_HOP = new Set([
36
37
  "host",
37
38
  ]);
38
39
  const DEFAULT_IDLE_MS = 120_000;
40
+ const DEFAULT_PUSH_CHECK_MS = 60_000;
41
+ // How much of a refused request's unread body is discarded, and for how long, before its connection is closed.
42
+ const LINGER_BYTES = 1024 * 1024;
43
+ const LINGER_MS = 1000;
44
+ // The longest delay a timer takes; past it, `setTimeout` fires at once.
45
+ const MAX_TIMER_MS = 2_147_483_647;
39
46
  // What Node refuses in a header value: anything but tab, printable ASCII and the Latin-1 range. A secret with a line break
40
47
  // or another control character would split or break the request, so it is refused before it is sent.
41
48
  const INVALID_HEADER_VALUE = /[^\t\x20-\x7e\x80-\xff]/;
@@ -47,6 +54,27 @@ const refusal = (status, reason) => ({
47
54
  body: undefined,
48
55
  reason,
49
56
  });
57
+ /**
58
+ * The answer to a git request whose credential is missing or wrong, or `undefined` when its HTTP Basic password is the
59
+ * route's sentinel. A missing one gets 401 with a Basic challenge, so git asks its credential helper.
60
+ */
61
+ function gitCredentialRefusal(presented, sentinel) {
62
+ if (presented === undefined) {
63
+ return { ...refusal(401, "git_credential_missing"), headers: { "www-authenticate": 'Basic realm="egress"' } };
64
+ }
65
+ return typeof presented === "string" && basicCarries(presented, sentinel) ? undefined : refusal(403, "bad_sentinel");
66
+ }
67
+ /**
68
+ * Checks a timeout option and returns the value to use: `fallback` when it is unset, or a whole number of milliseconds
69
+ * from `min` to the longest delay a timer takes. The message names the option and never quotes the value.
70
+ */
71
+ function timeoutOption(name, ms, min, fallback) {
72
+ if (ms === undefined)
73
+ return fallback;
74
+ if (typeof ms === "number" && Number.isInteger(ms) && ms >= min && ms <= MAX_TIMER_MS)
75
+ return ms;
76
+ throw new HarnessError("invalid_egress_options", `${name} must be a whole number of milliseconds from ${min} to ${MAX_TIMER_MS}`);
77
+ }
50
78
  class EgressGate {
51
79
  modules;
52
80
  allow;
@@ -56,12 +84,17 @@ class EgressGate {
56
84
  unsafe;
57
85
  sockets = new Set();
58
86
  requests = new Set();
87
+ pushCheckMs;
88
+ // 0 means no idle timeout, as it does for `socket.setTimeout`.
89
+ idleMs;
59
90
  origin = "";
60
91
  constructor(modules, options) {
61
92
  this.modules = modules;
62
93
  this.options = options;
94
+ this.idleMs = timeoutOption("idleTimeoutMs", options.idleTimeoutMs, 0, DEFAULT_IDLE_MS);
95
+ this.pushCheckMs = timeoutOption("pushCheckTimeoutMs", options.pushCheckTimeoutMs, 1, DEFAULT_PUSH_CHECK_MS);
63
96
  this.allow = parseAllow(options.allow);
64
- this.routes = new Map(parseRoutes(options.routes ?? []).map((route) => [route.route, route]));
97
+ this.routes = new Map(parseRoutes(options.routes ?? [], this.allow).map((route) => [route.route, route]));
65
98
  this.unsafe = new Set(options.unsafeAllowAddresses ?? []);
66
99
  for (const route of this.routes.keys()) {
67
100
  this.sentinels[route] = `sentinel_${modules.crypto.randomBytes(18).toString("base64url")}`;
@@ -143,7 +176,7 @@ class EgressGate {
143
176
  this.track(upstream);
144
177
  // A client that leaves before the tunnel is up takes the connection attempt with it.
145
178
  client.once("close", () => upstream.destroy());
146
- upstream.setTimeout(this.options.idleTimeoutMs ?? DEFAULT_IDLE_MS, () => upstream.destroy(Object.assign(new Error("idle"), { code: "ETIMEDOUT" })));
179
+ upstream.setTimeout(this.idleMs, () => upstream.destroy(Object.assign(new Error("idle"), { code: "ETIMEDOUT" })));
147
180
  upstream.once("error", (error) => {
148
181
  if (established)
149
182
  client.destroy();
@@ -208,10 +241,9 @@ class EgressGate {
208
241
  method: request.method ?? "GET",
209
242
  route: undefined,
210
243
  };
211
- this.routeRequest(request.method ?? "GET", url, request.headers, request, gone.signal).then((reply) => this.finish(response, reply.reply, reply.base), () => this.finish(response, refusal(502, "request_failed"), base));
244
+ this.routeRequest(request.method ?? "GET", url, request.headers, request, gone.signal).then((reply) => this.finish(response, reply.reply, reply.base, request), () => this.finish(response, refusal(502, "request_failed"), base, request));
212
245
  }
213
- finish(response, reply, base) {
214
- response.writeHead(reply.status, reply.headers);
246
+ finish(response, reply, base, request) {
215
247
  let bytes = 0;
216
248
  const report = () => this.record({
217
249
  ...base,
@@ -219,6 +251,12 @@ class EgressGate {
219
251
  bytes,
220
252
  ...(reply.reason === undefined ? {} : { reason: reply.reason }),
221
253
  });
254
+ if (reply.body === undefined && reply.status >= 400 && request !== undefined && !request.complete) {
255
+ this.refuseAndClose(request, response, reply);
256
+ report();
257
+ return;
258
+ }
259
+ response.writeHead(reply.status, reply.headers);
222
260
  if (reply.body === undefined) {
223
261
  response.end(reply.status === 403 || reply.status >= 400 ? `${reply.reason ?? "refused"}\n` : undefined);
224
262
  report();
@@ -232,6 +270,37 @@ class EgressGate {
232
270
  response.once("close", () => reply.body?.destroy());
233
271
  reply.body.pipe(response);
234
272
  }
273
+ /**
274
+ * Refuses a request whose body has not been read to its end, and closes its connection. Node would otherwise read and
275
+ * discard the rest of the body, a whole pack perhaps, to keep the connection alive. The answer is written whole, with
276
+ * its length and `Connection: close`, and the response is ended, which closes the socket, only after the bytes already
277
+ * on their way are discarded, up to `LINGER_BYTES` or for `LINGER_MS`. Closing a socket with unread bytes resets the
278
+ * connection, and a client that has not yet read the answer would lose it.
279
+ */
280
+ refuseAndClose(request, response, reply) {
281
+ const text = `${reply.reason ?? "refused"}\n`;
282
+ response.writeHead(reply.status, { ...reply.headers, connection: "close", "content-length": String(text.length) });
283
+ response.write(text);
284
+ let discarded = 0;
285
+ const done = () => {
286
+ clearTimeout(timer);
287
+ request.off("data", onData);
288
+ request.off("end", done);
289
+ request.off("close", done);
290
+ request.pause();
291
+ response.end();
292
+ };
293
+ const onData = (chunk) => {
294
+ discarded += chunk.length;
295
+ if (discarded >= LINGER_BYTES)
296
+ done();
297
+ };
298
+ const timer = setTimeout(done, LINGER_MS);
299
+ request.on("data", onData);
300
+ request.once("end", done);
301
+ request.once("close", done);
302
+ request.resume();
303
+ }
235
304
  /**
236
305
  * Resolves a request for `/<route>/…`. It checks the route, the method and the sentinel, swaps in the secret, and
237
306
  * forwards the request to the route's host. A request that fails any check is answered here, and nothing is sent.
@@ -250,17 +319,116 @@ class EgressGate {
250
319
  return { reply: refusal(403, "unknown_route"), base };
251
320
  if (!route.methods.has(method.toUpperCase()))
252
321
  return { reply: refusal(405, "method_not_allowed"), base };
322
+ const target = { path: match[2] ?? "/", query: match[3] ?? "" };
323
+ const reply = route.git === undefined
324
+ ? await this.headerRequest(route, method, target, headers, body, signal)
325
+ : await this.gitRequest(route, route.git, method, target, headers, body, signal);
326
+ return { reply, base };
327
+ }
328
+ /** Resolves a request on a header route: it swaps the sentinel in the route's header for the secret. */
329
+ async headerRequest(route, method, target, headers, body, signal) {
253
330
  const presented = headers[route.header];
254
331
  const sentinel = this.sentinels[route.route] ?? "";
255
332
  if (typeof presented !== "string" || sentinel === "" || !presented.includes(sentinel)) {
256
- return { reply: refusal(403, "bad_sentinel"), base };
333
+ return refusal(403, "bad_sentinel");
257
334
  }
258
335
  const secret = await route.secret().catch(() => "");
259
336
  if (secret === "" || INVALID_HEADER_VALUE.test(secret))
260
- return { reply: refusal(502, "secret_unavailable"), base };
337
+ return refusal(502, "secret_unavailable");
261
338
  const outgoing = this.outgoingHeaders(headers, route, presented.replaceAll(sentinel, () => secret));
262
- const reply = await this.forward(route, method, `${match[2] ?? "/"}${match[3] ?? ""}`, outgoing, body, signal);
263
- return { reply, base };
339
+ return this.forward(route, method, `${target.path}${target.query}`, outgoing, body, signal);
340
+ }
341
+ /**
342
+ * Resolves a request on a git route. The endpoint and repository are checked first, then the sentinel in HTTP Basic,
343
+ * then a push's command list, and only then is the secret read and the request forwarded with it. A missing
344
+ * credential gets 401 with a Basic challenge, so git asks its credential helper for the sentinel.
345
+ */
346
+ async gitRequest(route, filter, method, target, headers, body, signal) {
347
+ const endpoint = gitEndpoint(filter, method, target.path, target.query);
348
+ if ("refused" in endpoint)
349
+ return refusal(403, endpoint.refused);
350
+ const unauthorized = gitCredentialRefusal(headers.authorization, this.sentinels[route.route] ?? "");
351
+ if (unauthorized !== undefined)
352
+ return unauthorized;
353
+ let forwarded = body;
354
+ if (endpoint.service === "git-receive-pack" && endpoint.phase === "rpc") {
355
+ const encoding = headers["content-encoding"];
356
+ if (encoding !== undefined && encoding !== "identity")
357
+ return refusal(403, "git_encoded_push");
358
+ const checked = await this.checkPush(body, filter);
359
+ if ("refused" in checked)
360
+ return refusal(403, checked.refused);
361
+ forwarded = checked.body;
362
+ }
363
+ const secret = await route.secret().catch(() => "");
364
+ if (secret === "" || INVALID_HEADER_VALUE.test(secret))
365
+ return refusal(502, "secret_unavailable");
366
+ const outgoing = this.outgoingHeaders(headers, route, basicHeader(filter.username, secret));
367
+ return this.forward(route, method, `${target.path}${target.query}`, outgoing, forwarded, signal);
368
+ }
369
+ /**
370
+ * Reads a push's command list and checks it, then hands back a body that starts with what was read. `PushReader`
371
+ * reads each chunk once, so the check is linear in the bytes however small the chunks. The check gives up once the
372
+ * body is idle for the idle timeout, which each chunk resets, or once `pushCheckTimeoutMs` has passed since it
373
+ * started, which nothing resets.
374
+ */
375
+ checkPush(body, filter) {
376
+ if (body === undefined)
377
+ return Promise.resolve({ refused: "git_bad_pkt_line" });
378
+ if (body instanceof Uint8Array) {
379
+ const verdict = pushVerdict(body, filter, true);
380
+ return Promise.resolve(verdict === "allowed" ? { body } : { refused: verdict.refused });
381
+ }
382
+ return new Promise((resolve) => {
383
+ const reader = new PushReader(filter);
384
+ const chunks = [];
385
+ const timedOut = () => settle({ refused: "git_timeout" });
386
+ // An idle timeout of 0 is off, so only the deadline ends a quiet body.
387
+ const startIdle = () => (this.idleMs === 0 ? undefined : setTimeout(timedOut, this.idleMs));
388
+ let idle = startIdle();
389
+ const deadline = setTimeout(timedOut, this.pushCheckMs);
390
+ const settle = (outcome) => {
391
+ clearTimeout(idle);
392
+ clearTimeout(deadline);
393
+ body.off("data", onData);
394
+ body.off("end", onEnd);
395
+ body.off("error", onError);
396
+ body.off("close", onError);
397
+ // A refused body is not read further; the answer closes its connection.
398
+ if ("refused" in outcome)
399
+ body.pause();
400
+ resolve(outcome);
401
+ };
402
+ const judge = (verdict, ended) => {
403
+ if (verdict === "incomplete")
404
+ return;
405
+ if (verdict !== "allowed") {
406
+ settle(verdict);
407
+ return;
408
+ }
409
+ const rest = new this.modules.stream.PassThrough();
410
+ for (const chunk of chunks)
411
+ rest.write(chunk);
412
+ settle({ body: rest });
413
+ if (ended)
414
+ rest.end();
415
+ else
416
+ body.pipe(rest);
417
+ };
418
+ const onData = (chunk) => {
419
+ clearTimeout(idle);
420
+ idle = startIdle();
421
+ chunks.push(chunk);
422
+ judge(reader.add(chunk), false);
423
+ };
424
+ const onEnd = () => judge(reader.end(), true);
425
+ const onError = () => settle({ refused: "request_failed" });
426
+ body.on("data", onData);
427
+ body.once("end", onEnd);
428
+ body.once("error", onError);
429
+ // A client that goes away before its command list ends would otherwise hold the check until a timeout.
430
+ body.once("close", onError);
431
+ });
264
432
  }
265
433
  outgoingHeaders(headers, route, credential) {
266
434
  const out = {};
@@ -289,7 +457,7 @@ class EgressGate {
289
457
  signal?.addEventListener("abort", stop, { once: true });
290
458
  upstream.once("close", () => signal?.removeEventListener("abort", stop));
291
459
  this.requests.add(upstream);
292
- upstream.setTimeout(this.options.idleTimeoutMs ?? DEFAULT_IDLE_MS, () => upstream.destroy(new Error("idle")));
460
+ upstream.setTimeout(this.idleMs, () => upstream.destroy(new Error("idle")));
293
461
  upstream.once("close", () => this.requests.delete(upstream));
294
462
  upstream.once("response", (reply) => {
295
463
  const passed = {};
@@ -394,7 +562,7 @@ class EgressGate {
394
562
  this.requests.delete(upstream);
395
563
  request.signal.removeEventListener("abort", abort);
396
564
  });
397
- upstream.setTimeout(this.options.idleTimeoutMs ?? DEFAULT_IDLE_MS, () => upstream.destroy(new Error("idle")));
565
+ upstream.setTimeout(this.idleMs, () => upstream.destroy(new Error("idle")));
398
566
  upstream.once("response", (reply) => {
399
567
  let bytes = 0;
400
568
  reply.on("data", (chunk) => {
@@ -1 +1 @@
1
- {"version":3,"file":"egress-proxy.js","sourceRoot":"","sources":["../../src/credentials/egress-proxy.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACnE,OAAO,EAGL,SAAS,EAET,UAAU,EACV,WAAW,GACZ,MAAM,gBAAgB,CAAC;AA8ExB,SAAS,WAAW;IAClB,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,OAAO,CAAC,gBAAgB,KAAK,UAAU,EAAE,CAAC;QACrF,MAAM,IAAI,YAAY,CACpB,wBAAwB,EACxB,yEAAyE,CAC1E,CAAC;IACJ,CAAC;IACD,OAAO;QACL,IAAI,EAAE,OAAO,CAAC,gBAAgB,CAAC,WAAW,CAAC;QAC3C,KAAK,EAAE,OAAO,CAAC,gBAAgB,CAAC,YAAY,CAAC;QAC7C,GAAG,EAAE,OAAO,CAAC,gBAAgB,CAAC,UAAU,CAAC;QACzC,GAAG,EAAE,OAAO,CAAC,gBAAgB,CAAC,UAAU,CAAC;QACzC,MAAM,EAAE,OAAO,CAAC,gBAAgB,CAAC,aAAa,CAAC;QAC/C,MAAM,EAAE,OAAO,CAAC,gBAAgB,CAAC,aAAa,CAAC;KAChD,CAAC;AACJ,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;IACzB,YAAY;IACZ,YAAY;IACZ,oBAAoB;IACpB,qBAAqB;IACrB,kBAAkB;IAClB,IAAI;IACJ,SAAS;IACT,mBAAmB;IACnB,SAAS;IACT,MAAM;CACP,CAAC,CAAC;AACH,MAAM,eAAe,GAAG,OAAO,CAAC;AAChC,2HAA2H;AAC3H,qGAAqG;AAC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C,CAAC;QAC7B,IAAI,OAAO,CAAC,UAAU,KAAK,SAAS;YAAE,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC;;YACxE,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAClD,CAAC,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,EAAE,CAAC;IACjC,MAAM,GAAG,GACP,OAAO,CAAC,UAAU,KAAK,SAAS;QAC9B,CAAC,CAAC,QAAQ,OAAO,CAAC,UAAU,EAAE;QAC9B,CAAC,CAAC,oBAAqB,OAA4B,CAAC,IAAI,EAAE,CAAC;IAC/D,IAAI,OAAO,CAAC,UAAU,KAAK,SAAS;QAAE,KAAK,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;IAC3D,OAAO;QACL,GAAG;QACH,GAAG,CAAC,OAAO,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,OAAO,CAAC,UAAU,EAAE,CAAC;QAC/E,SAAS,EAAE,KAAK,CAAC,WAAW,EAAE;QAC9B,KAAK,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,CAAC;QAChD,YAAY,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,YAAY,EAAE;QACxC,KAAK,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC;KACjC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `startEgressProxy()`: the host-side proxy that keeps credentials out of the sandbox. Nothing leaves the sandbox except\n * through it, it refuses everything that isn't on its allowlist, and it logs each request without its headers. A tool\n * that needs a credential sends its request to a local route, such as `http://127.0.0.1:<port>/github/user`, with the\n * route's sentinel where the credential goes. The proxy checks the sentinel and the method, swaps in the real secret and\n * forwards the request over HTTPS. It never intercepts TLS: everything else leaves through `CONNECT` to an\n * allowlisted name, and a name is connected to only at an address the proxy checked. It is Node-only.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { isAddressLiteral, isPublicAddress } from \"./addresses.js\";\nimport {\n type AllowEntry,\n type CredentialRoute,\n isAllowed,\n type ParsedRoute,\n parseAllow,\n parseRoutes,\n} from \"./allowlist.js\";\n\nexport type { CredentialRoute } from \"./allowlist.js\";\n\n/** One line of the egress log. It names the host and the outcome, and never holds a header, a body or a secret. */\nexport interface EgressRecord {\n /** When the request ended, as an ISO 8601 string. */\n readonly time: string;\n /** `connect` for a tunnel, `route` for a credential route and `fetch` for an in-process call. */\n readonly kind: \"connect\" | \"route\" | \"fetch\";\n /** The host the request was for. */\n readonly host: string;\n readonly port: number;\n readonly method: string;\n /** The status the sandbox saw: 200 for an established tunnel, 403 for a refusal, 502 for a failed connection. */\n readonly status: number;\n /** The bytes that went both ways, 0 for a refusal. */\n readonly bytes: number;\n /** The route's name, for a route request. */\n readonly route?: string | undefined;\n /** Why a request was refused or failed, as a short code such as `not_allowed` or `address_refused`. */\n readonly reason?: string;\n}\n\n/** The options of `startEgressProxy()`. */\nexport interface EgressProxyOptions {\n /** The names a tunnel or an in-process fetch may reach: `example.com`, `*.example.com`, or either with `:port`. */\n readonly allow: readonly string[];\n /** The credential routes. Without any, the proxy only tunnels. */\n readonly routes?: readonly CredentialRoute[];\n /** Receives one record for each request. A throw from it is ignored. */\n readonly log: (record: EgressRecord) => void;\n /** Listens on this Unix socket instead of a port on `127.0.0.1`, so a container can mount it (`dockerSandbox`'s `proxySocket`). */\n readonly socketPath?: string;\n /** Extra certificate authorities to trust for the routes' hosts and for the fetch, such as a test's own. */\n readonly ca?: string | Uint8Array | readonly (string | Uint8Array)[];\n /** Resolves a name to its addresses. Defaults to the system resolver. Every address it returns is checked. */\n readonly resolve?: (host: string) => Promise<readonly string[]>;\n /**\n * Addresses that skip the public-address check. This exists so a test can reach a server on `127.0.0.1`. Never set it\n * for a real run: the check is what keeps a name that points at the host's own network from being reached.\n */\n readonly unsafeAllowAddresses?: readonly string[];\n /** Ends a tunnel or a forwarded request that is idle this long. Defaults to 120000. */\n readonly idleTimeoutMs?: number;\n}\n\n/** A running egress proxy. */\nexport interface EgressProxy {\n /**\n * Where the sandbox sends its requests: give it as `HTTPS_PROXY`, and join a route's name to it for a route. On a Unix\n * socket it is `unix:<path>`, which is not a proxy URL: the program that uses the socket connects to it itself.\n */\n readonly url: string;\n /** The Unix socket the proxy listens on, when it was started with `socketPath`. */\n readonly socketPath?: string;\n /** For each route, the placeholder the sandbox puts where the credential goes. The real secret never leaves the host. */\n readonly sentinels: Readonly<Record<string, string>>;\n /**\n * Fetches `input` for an in-process tool, under the same allowlist. A host that isn't on it rejects with `egress_denied`.\n * A route is reached at `${proxy.url}/<route>/…`, or at `http://egress.proxy/<route>/…`, which also works on a Unix socket.\n */\n fetch(input: string | URL, init?: RequestInit): Promise<Response>;\n /** The routes' secrets now, for `scrubSecrets()`. */\n knownSecrets(): Promise<readonly string[]>;\n /** Stops listening and ends every open tunnel and request. */\n close(): Promise<void>;\n}\n\ntype Modules = {\n readonly http: typeof import(\"node:http\");\n readonly https: typeof import(\"node:https\");\n readonly net: typeof import(\"node:net\");\n readonly dns: typeof import(\"node:dns\");\n readonly crypto: typeof import(\"node:crypto\");\n readonly stream: typeof import(\"node:stream\");\n};\n\nfunction nodeModules(): Modules {\n if (typeof process === \"undefined\" || typeof process.getBuiltinModule !== \"function\") {\n throw new HarnessError(\n \"invalid_egress_options\",\n \"the egress proxy needs Node's network modules, which this runtime lacks\",\n );\n }\n return {\n http: process.getBuiltinModule(\"node:http\"),\n https: process.getBuiltinModule(\"node:https\"),\n net: process.getBuiltinModule(\"node:net\"),\n dns: process.getBuiltinModule(\"node:dns\"),\n crypto: process.getBuiltinModule(\"node:crypto\"),\n stream: process.getBuiltinModule(\"node:stream\"),\n };\n}\n\n// Headers that belong to one connection, and are never passed on to the next.\nconst HOP_BY_HOP = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"proxy-connection\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n \"host\",\n]);\nconst DEFAULT_IDLE_MS = 120_000;\n// What Node refuses in a header value: anything but tab, printable ASCII and the Latin-1 range. A secret with a line break\n// or another control character would split or break the request, so it is refused before it is sent.\nconst INVALID_HEADER_VALUE = /[^\\t\\x20-\\x7e\\x80-\\xff]/;\n// The origin an in-process tool uses for a route, in either mode, because a Unix socket has no address of its own.\nconst ROUTE_ORIGIN = \"http://egress.proxy\";\n\n/** What a request for a route resolves to, before it is written to a socket or wrapped in a `Response`. */\ninterface RouteReply {\n readonly status: number;\n readonly headers: Record<string, string | string[]>;\n readonly body: import(\"node:stream\").Readable | undefined;\n readonly reason?: string;\n}\n\nconst refusal = (status: number, reason: string): RouteReply => ({\n status,\n headers: { \"content-type\": \"text/plain\" },\n body: undefined,\n reason,\n});\n\nclass EgressGate {\n private readonly modules: Modules;\n private readonly allow: readonly AllowEntry[];\n private readonly routes: ReadonlyMap<string, ParsedRoute>;\n private readonly sentinels: Record<string, string> = {};\n private readonly options: EgressProxyOptions;\n private readonly unsafe: ReadonlySet<string>;\n private readonly sockets = new Set<import(\"node:net\").Socket>();\n private readonly requests = new Set<import(\"node:http\").ClientRequest>();\n private origin = \"\";\n\n constructor(modules: Modules, options: EgressProxyOptions) {\n this.modules = modules;\n this.options = options;\n this.allow = parseAllow(options.allow);\n this.routes = new Map(parseRoutes(options.routes ?? []).map((route) => [route.route, route]));\n this.unsafe = new Set(options.unsafeAllowAddresses ?? []);\n for (const route of this.routes.keys()) {\n this.sentinels[route] = `sentinel_${modules.crypto.randomBytes(18).toString(\"base64url\")}`;\n }\n }\n\n setOrigin(origin: string): void {\n this.origin = origin;\n }\n\n sentinelMap(): Readonly<Record<string, string>> {\n return this.sentinels;\n }\n\n private record(record: Omit<EgressRecord, \"time\">): void {\n try {\n this.options.log({ time: new Date().toISOString(), ...record });\n } catch {\n // A logger that throws must not take the proxy down.\n }\n }\n\n /** A `lookup` for `net` and `https`: it resolves in the proxy, checks every address, and connects only to those. */\n private readonly checkedLookup = (\n hostname: string,\n lookupOptions: { all?: boolean },\n callback: (error: Error | null, address?: unknown, family?: number) => void,\n ): void => {\n const resolve =\n this.options.resolve ??\n (async (host: string) =>\n (await this.modules.dns.promises.lookup(host, { all: true })).map((found) => found.address));\n resolve(hostname).then(\n (addresses) => {\n const refused = addresses.length === 0 || addresses.some((a) => !isPublicAddress(a) && !this.unsafe.has(a));\n if (refused) {\n callback(\n Object.assign(new Error(`${hostname} resolves to an address the proxy refuses`), {\n code: \"EGRESS_ADDRESS\",\n }),\n );\n return;\n }\n const family = (address: string) => (address.includes(\":\") ? 6 : 4);\n if (lookupOptions.all === true) {\n callback(\n null,\n addresses.map((address) => ({ address, family: family(address) })),\n );\n } else {\n callback(null, addresses[0], family(addresses[0] ?? \"\"));\n }\n },\n (error: unknown) => callback(error as Error),\n );\n };\n\n private reasonOf(error: unknown): string {\n const code = (error as { code?: string }).code;\n if (code === \"EGRESS_ADDRESS\") return \"address_refused\";\n return code === \"ETIMEDOUT\" ? \"timeout\" : \"connect_failed\";\n }\n\n /** The host and port of a `CONNECT` target, or `undefined` for one that isn't `host:port`. */\n private parseTarget(target: string): { host: string; port: number } | undefined {\n const match = /^(\\[[0-9a-fA-F:.]+\\]|[^:[\\]]+):([0-9]{1,5})$/.exec(target);\n if (match === null) return undefined;\n const host = (match[1] ?? \"\").toLowerCase().replace(/\\.$/, \"\");\n const port = Number(match[2]);\n return port >= 1 && port <= 65535 ? { host, port } : undefined;\n }\n\n /** Handles one `CONNECT`: allow-checks the name, then tunnels to the address the proxy checked. */\n handleConnect(request: import(\"node:http\").IncomingMessage, client: import(\"node:net\").Socket, head: Buffer): void {\n this.track(client);\n const target = this.parseTarget(request.url ?? \"\");\n const host = target?.host ?? \"(invalid)\";\n const port = target?.port ?? 0;\n const deny = (reason: string, status = 403) => {\n client.end(`HTTP/1.1 ${status} ${status === 403 ? \"Forbidden\" : \"Bad Gateway\"}\\r\\nConnection: close\\r\\n\\r\\n`);\n this.record({ kind: \"connect\", host, port, method: \"CONNECT\", status, bytes: 0, reason });\n };\n const refusedBecause =\n target === undefined\n ? \"bad_target\"\n : isAddressLiteral(host)\n ? \"address_literal\"\n : isAllowed(this.allow, host, port)\n ? undefined\n : \"not_allowed\";\n if (refusedBecause !== undefined) {\n deny(refusedBecause);\n return;\n }\n let established = false;\n const upstream = this.modules.net.connect({ host, port, lookup: this.checkedLookup as never });\n this.track(upstream);\n // A client that leaves before the tunnel is up takes the connection attempt with it.\n client.once(\"close\", () => upstream.destroy());\n upstream.setTimeout(this.options.idleTimeoutMs ?? DEFAULT_IDLE_MS, () =>\n upstream.destroy(Object.assign(new Error(\"idle\"), { code: \"ETIMEDOUT\" })),\n );\n upstream.once(\"error\", (error) => {\n if (established) client.destroy();\n else deny(this.reasonOf(error), 502);\n upstream.destroy();\n });\n upstream.once(\"connect\", () => {\n established = true;\n client.write(\"HTTP/1.1 200 Connection Established\\r\\n\\r\\n\");\n if (head.length > 0) upstream.write(head);\n upstream.pipe(client);\n client.pipe(upstream);\n const done = () => {\n client.destroy();\n upstream.destroy();\n };\n client.once(\"close\", done);\n upstream.once(\"close\", () => {\n this.record({\n kind: \"connect\",\n host,\n port,\n method: \"CONNECT\",\n status: 200,\n bytes: upstream.bytesRead + upstream.bytesWritten,\n });\n done();\n });\n });\n client.once(\"error\", () => upstream.destroy());\n }\n\n private track(socket: import(\"node:net\").Socket): void {\n if (this.sockets.has(socket)) return;\n this.sockets.add(socket);\n socket.once(\"close\", () => this.sockets.delete(socket));\n socket.on(\"error\", () => {});\n }\n\n /** Handles one request that isn't a `CONNECT`: a route request, or a refusal of anything else. */\n handleRequest(request: import(\"node:http\").IncomingMessage, response: import(\"node:http\").ServerResponse): void {\n this.track(request.socket);\n const url = request.url ?? \"\";\n if (!url.startsWith(\"/\")) {\n // A proxy request in absolute form: only a tunnel may leave, so the name is not even looked at.\n this.finish(response, refusal(403, \"only_connect\"), {\n kind: \"route\",\n host: \"(proxy request)\",\n port: 0,\n method: request.method ?? \"\",\n });\n return;\n }\n // A client that goes away takes the upstream request with it, so a credential isn't spent for nobody.\n const gone = new AbortController();\n response.once(\"close\", () => gone.abort());\n const base = {\n kind: \"route\" as const,\n host: \"(route)\",\n port: 0,\n method: request.method ?? \"GET\",\n route: undefined,\n };\n this.routeRequest(request.method ?? \"GET\", url, request.headers, request, gone.signal).then(\n (reply) => this.finish(response, reply.reply, reply.base),\n () => this.finish(response, refusal(502, \"request_failed\"), base),\n );\n }\n\n private finish(\n response: import(\"node:http\").ServerResponse,\n reply: RouteReply,\n base: Pick<EgressRecord, \"kind\" | \"host\" | \"port\" | \"method\" | \"route\">,\n ): void {\n response.writeHead(reply.status, reply.headers);\n let bytes = 0;\n const report = () =>\n this.record({\n ...base,\n status: reply.status,\n bytes,\n ...(reply.reason === undefined ? {} : { reason: reply.reason }),\n });\n if (reply.body === undefined) {\n response.end(reply.status === 403 || reply.status >= 400 ? `${reply.reason ?? \"refused\"}\\n` : undefined);\n report();\n return;\n }\n reply.body.on(\"data\", (chunk: Buffer) => {\n bytes += chunk.length;\n });\n reply.body.once(\"close\", report);\n reply.body.once(\"error\", () => response.destroy());\n response.once(\"close\", () => reply.body?.destroy());\n reply.body.pipe(response);\n }\n\n /**\n * Resolves a request for `/<route>/…`. It checks the route, the method and the sentinel, swaps in the secret, and\n * forwards the request to the route's host. A request that fails any check is answered here, and nothing is sent.\n */\n async routeRequest(\n method: string,\n rawPath: string,\n headers: Record<string, string | string[] | undefined>,\n body: import(\"node:stream\").Readable | Uint8Array | undefined,\n signal?: AbortSignal,\n ): Promise<{ reply: RouteReply; base: Pick<EgressRecord, \"kind\" | \"host\" | \"port\" | \"method\" | \"route\"> }> {\n const match = /^\\/([^/?#]+)(\\/[^?#]*)?(\\?[^#]*)?$/.exec(rawPath);\n const route = match === null ? undefined : this.routes.get(match[1] ?? \"\");\n const base = {\n kind: \"route\" as const,\n host: route?.hostname ?? \"(no route)\",\n port: route?.port ?? 0,\n method,\n route: route?.route,\n };\n if (route === undefined || match === null) return { reply: refusal(403, \"unknown_route\"), base };\n if (!route.methods.has(method.toUpperCase())) return { reply: refusal(405, \"method_not_allowed\"), base };\n const presented = headers[route.header];\n const sentinel = this.sentinels[route.route] ?? \"\";\n if (typeof presented !== \"string\" || sentinel === \"\" || !presented.includes(sentinel)) {\n return { reply: refusal(403, \"bad_sentinel\"), base };\n }\n const secret = await route.secret().catch(() => \"\");\n if (secret === \"\" || INVALID_HEADER_VALUE.test(secret)) return { reply: refusal(502, \"secret_unavailable\"), base };\n const outgoing = this.outgoingHeaders(\n headers,\n route,\n presented.replaceAll(sentinel, () => secret),\n );\n const reply = await this.forward(route, method, `${match[2] ?? \"/\"}${match[3] ?? \"\"}`, outgoing, body, signal);\n return { reply, base };\n }\n\n private outgoingHeaders(\n headers: Record<string, string | string[] | undefined>,\n route: ParsedRoute,\n credential: string,\n ): Record<string, string | string[]> {\n const out: Record<string, string | string[]> = {};\n for (const [name, value] of Object.entries(headers)) {\n if (value !== undefined && !HOP_BY_HOP.has(name)) out[name] = value;\n }\n out[route.header] = credential;\n out.host = route.port === 443 ? route.hostname : `${route.hostname}:${route.port}`;\n return out;\n }\n\n private forward(\n route: ParsedRoute,\n method: string,\n path: string,\n headers: Record<string, string | string[]>,\n body: import(\"node:stream\").Readable | Uint8Array | undefined,\n signal?: AbortSignal,\n ): Promise<RouteReply> {\n return new Promise((resolve) => {\n let upstream: import(\"node:http\").ClientRequest;\n try {\n upstream = this.openRoute(route, method, path, headers);\n } catch {\n resolve(refusal(502, \"request_invalid\"));\n return;\n }\n const stop = () => upstream.destroy(new Error(\"client gone\"));\n if (signal?.aborted === true) stop();\n else signal?.addEventListener(\"abort\", stop, { once: true });\n upstream.once(\"close\", () => signal?.removeEventListener(\"abort\", stop));\n this.requests.add(upstream);\n upstream.setTimeout(this.options.idleTimeoutMs ?? DEFAULT_IDLE_MS, () => upstream.destroy(new Error(\"idle\")));\n upstream.once(\"close\", () => this.requests.delete(upstream));\n upstream.once(\"response\", (reply) => {\n const passed: Record<string, string | string[]> = {};\n for (const [name, value] of Object.entries(reply.headers)) {\n if (value !== undefined && !HOP_BY_HOP.has(name)) passed[name] = value;\n }\n resolve({ status: reply.statusCode ?? 502, headers: passed, body: reply });\n });\n upstream.once(\"error\", (error) => resolve(refusal(502, this.reasonOf(error))));\n if (body === undefined) upstream.end();\n else if (body instanceof Uint8Array) upstream.end(body);\n else body.pipe(upstream);\n });\n }\n\n /** Opens the HTTPS request to a route's host, which throws for a header or path Node refuses. */\n private openRoute(\n route: ParsedRoute,\n method: string,\n path: string,\n headers: Record<string, string | string[]>,\n ): import(\"node:http\").ClientRequest {\n return this.modules.https.request({\n host: route.hostname,\n port: route.port,\n servername: route.hostname,\n method,\n path,\n headers,\n agent: false,\n lookup: this.checkedLookup as never,\n ...(this.options.ca === undefined ? {} : { ca: this.options.ca as never }),\n });\n }\n\n /** An in-process fetch under the same allowlist, with the same address checks and pinned connection. */\n async fetch(input: string | URL, init?: RequestInit): Promise<Response> {\n const request = new Request(input, init);\n request.signal.throwIfAborted();\n const url = new URL(request.url);\n const host = url.hostname.toLowerCase().replace(/\\.$/, \"\");\n const port = url.port === \"\" ? 443 : Number(url.port);\n const bodyBytes =\n request.method === \"GET\" || request.method === \"HEAD\" ? undefined : new Uint8Array(await request.arrayBuffer());\n if (url.origin === ROUTE_ORIGIN || (this.origin !== \"\" && url.origin === this.origin)) {\n return this.fetchRoute(request, url, bodyBytes);\n }\n const refuse = (reason: string): never => {\n this.record({ kind: \"fetch\", host, port, method: request.method, status: 403, bytes: 0, reason });\n throw new HarnessError(\"egress_denied\", `the egress proxy refused ${url.host}: ${reason}`);\n };\n if (url.protocol !== \"https:\") return refuse(\"only_https\");\n if (isAddressLiteral(host)) return refuse(\"address_literal\");\n if (!isAllowed(this.allow, host, port)) return refuse(\"not_allowed\");\n return this.sendFetch(request, url, host, port, bodyBytes);\n }\n\n private async fetchRoute(request: Request, url: URL, body: Uint8Array | undefined): Promise<Response> {\n const headers: Record<string, string> = {};\n request.headers.forEach((value, name) => {\n headers[name.toLowerCase()] = value;\n });\n const path = `${url.pathname}${url.search}`;\n const { reply, base } = await this.routeRequest(request.method, path, headers, body, request.signal);\n const stream = reply.body;\n let bytes = 0;\n stream?.on(\"data\", (chunk: Buffer) => {\n bytes += chunk.length;\n });\n const finished = () =>\n this.record({\n ...base,\n status: reply.status,\n bytes,\n ...(reply.reason === undefined ? {} : { reason: reply.reason }),\n });\n if (stream === undefined) finished();\n else stream.once(\"close\", finished);\n return this.toResponse(reply.status, reply.headers, stream);\n }\n\n private sendFetch(\n request: Request,\n url: URL,\n host: string,\n port: number,\n body: Uint8Array | undefined,\n ): Promise<Response> {\n return new Promise((resolve, reject) => {\n const headers: Record<string, string> = {};\n request.headers.forEach((value, name) => {\n if (!HOP_BY_HOP.has(name.toLowerCase())) headers[name] = value;\n });\n const upstream = this.modules.https.request({\n host,\n port,\n servername: host,\n method: request.method,\n path: `${url.pathname}${url.search}`,\n headers: { ...headers, host: url.host },\n agent: false,\n lookup: this.checkedLookup as never,\n ...(this.options.ca === undefined ? {} : { ca: this.options.ca as never }),\n });\n this.requests.add(upstream);\n const abort = () => upstream.destroy(request.signal.reason as Error);\n request.signal.addEventListener(\"abort\", abort, { once: true });\n upstream.once(\"close\", () => {\n this.requests.delete(upstream);\n request.signal.removeEventListener(\"abort\", abort);\n });\n upstream.setTimeout(this.options.idleTimeoutMs ?? DEFAULT_IDLE_MS, () => upstream.destroy(new Error(\"idle\")));\n upstream.once(\"response\", (reply) => {\n let bytes = 0;\n reply.on(\"data\", (chunk: Buffer) => {\n bytes += chunk.length;\n });\n // The record is written when the response is done with, which also covers one that is never read to its end.\n reply.once(\"close\", () =>\n this.record({ kind: \"fetch\", host, port, method: request.method, status: reply.statusCode ?? 0, bytes }),\n );\n resolve(this.toResponse(reply.statusCode ?? 502, reply.headers as Record<string, string | string[]>, reply));\n });\n upstream.once(\"error\", (error) => {\n if (request.signal.aborted) {\n reject(request.signal.reason);\n return;\n }\n const reason = this.reasonOf(error);\n this.record({ kind: \"fetch\", host, port, method: request.method, status: 502, bytes: 0, reason });\n reject(\n new HarnessError(\"egress_denied\", `the egress proxy could not reach ${url.host}: ${reason}`, {\n cause: error,\n }),\n );\n });\n upstream.end(body);\n });\n }\n\n private toResponse(\n status: number,\n headers: Record<string, string | string[]>,\n stream: import(\"node:stream\").Readable | undefined,\n ): Response {\n const out = new Headers();\n for (const [name, value] of Object.entries(headers)) {\n for (const one of Array.isArray(value) ? value : [value]) out.append(name, one);\n }\n const bodiless = stream === undefined || [101, 204, 205, 304].includes(status);\n // A response with no body is drained, so its socket and its log record don't wait for a reader that never comes.\n if (bodiless) stream?.resume();\n const web = bodiless ? null : (this.modules.stream.Readable.toWeb(stream) as ReadableStream);\n return new Response(web, { status, headers: out });\n }\n\n async knownSecrets(): Promise<readonly string[]> {\n const secrets = await Promise.all([...this.routes.values()].map((route) => route.secret().catch(() => \"\")));\n return [...new Set(secrets.filter((secret) => secret !== \"\"))];\n }\n\n close(server: import(\"node:http\").Server): Promise<void> {\n return new Promise((resolve) => {\n for (const socket of this.sockets) socket.destroy();\n for (const request of this.requests) request.destroy();\n server.close(() => resolve());\n server.closeAllConnections();\n });\n }\n}\n\n/**\n * Starts the egress proxy on `127.0.0.1` with a port the system picks, or on `socketPath`. The allowlist and routes are\n * checked first, and a bad entry throws `invalid_egress_options`. Give the sandbox `proxy.url` as `HTTPS_PROXY`, and\n * give a tool that needs a credential the route's URL and its sentinel.\n */\nexport async function startEgressProxy(options: EgressProxyOptions): Promise<EgressProxy> {\n const modules = nodeModules();\n const proxy = new EgressGate(modules, options);\n const server = modules.http.createServer((request, response) => proxy.handleRequest(request, response));\n server.on(\"connect\", (request, socket, head) => proxy.handleConnect(request, socket as never, head));\n server.on(\"clientError\", (_error, socket) => socket.destroy());\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n if (options.socketPath === undefined) server.listen(0, \"127.0.0.1\", resolve);\n else server.listen(options.socketPath, resolve);\n });\n const address = server.address();\n const url =\n options.socketPath !== undefined\n ? `unix:${options.socketPath}`\n : `http://127.0.0.1:${(address as { port: number }).port}`;\n if (options.socketPath === undefined) proxy.setOrigin(url);\n return {\n url,\n ...(options.socketPath === undefined ? {} : { socketPath: options.socketPath }),\n sentinels: proxy.sentinelMap(),\n fetch: (input, init) => proxy.fetch(input, init),\n knownSecrets: () => proxy.knownSecrets(),\n close: () => proxy.close(server),\n };\n}\n"]}
1
+ {"version":3,"file":"egress-proxy.js","sourceRoot":"","sources":["../../src/credentials/egress-proxy.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACnE,OAAO,EAGL,SAAS,EAET,UAAU,EACV,WAAW,GACZ,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,YAAY,EAAE,WAAW,EAAuB,WAAW,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AA0FtH,SAAS,WAAW;IAClB,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,OAAO,CAAC,gBAAgB,KAAK,UAAU,EAAE,CAAC;QACrF,MAAM,IAAI,YAAY,CACpB,wBAAwB,EACxB,yEAAyE,CAC1E,CAAC;IACJ,CAAC;IACD,OAAO;QACL,IAAI,EAAE,OAAO,CAAC,gBAAgB,CAAC,WAAW,CAAC;QAC3C,KAAK,EAAE,OAAO,CAAC,gBAAgB,CAAC,YAAY,CAAC;QAC7C,GAAG,EAAE,OAAO,CAAC,gBAAgB,CAAC,UAAU,CAAC;QACzC,GAAG,EAAE,OAAO,CAAC,gBAAgB,CAAC,UAAU,CAAC;QACzC,MAAM,EAAE,OAAO,CA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AAC,GAAG,CAAC,CAAC;IAC3D,OAAO;QACL,GAAG;QACH,GAAG,CAAC,OAAO,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,OAAO,CAAC,UAAU,EAAE,CAAC;QAC/E,SAAS,EAAE,KAAK,CAAC,WAAW,EAAE;QAC9B,KAAK,EAAE,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,CAAC;QAChD,YAAY,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,YAAY,EAAE;QACxC,KAAK,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC;KACjC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `startEgressProxy()`: the host-side proxy that keeps credentials out of the sandbox. Nothing leaves the sandbox except\n * through it, it refuses everything that isn't on its allowlist, and it logs each request without its headers. A tool\n * that needs a credential sends its request to a local route, such as `http://127.0.0.1:<port>/github/user`, with the\n * route's sentinel where the credential goes. The proxy checks the sentinel and the method, swaps in the real secret and\n * forwards the request over HTTPS. It never intercepts TLS: everything else leaves through `CONNECT` to an\n * allowlisted name, and a name is connected to only at an address the proxy checked. It is Node-only.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { isAddressLiteral, isPublicAddress } from \"./addresses.js\";\nimport {\n type AllowEntry,\n type CredentialRoute,\n isAllowed,\n type ParsedRoute,\n parseAllow,\n parseRoutes,\n} from \"./allowlist.js\";\nimport { basicCarries, basicHeader, type GitRouteFilter, gitEndpoint, PushReader, pushVerdict } from \"./git-route.js\";\n\nexport type { CredentialRoute } from \"./allowlist.js\";\n\n/** One line of the egress log. It names the host and the outcome, and never holds a header, a body or a secret. */\nexport interface EgressRecord {\n /** When the request ended, as an ISO 8601 string. */\n readonly time: string;\n /** `connect` for a tunnel, `route` for a credential route and `fetch` for an in-process call. */\n readonly kind: \"connect\" | \"route\" | \"fetch\";\n /** The host the request was for. */\n readonly host: string;\n readonly port: number;\n readonly method: string;\n /** The status the sandbox saw: 200 for an established tunnel, 403 for a refusal, 502 for a failed connection. */\n readonly status: number;\n /** The bytes that went both ways, 0 for a refusal. */\n readonly bytes: number;\n /** The route's name, for a route request. */\n readonly route?: string | undefined;\n /** Why a request was refused or failed, as a short code such as `not_allowed` or `address_refused`. */\n readonly reason?: string;\n}\n\n/** The options of `startEgressProxy()`. */\nexport interface EgressProxyOptions {\n /** The names a tunnel or an in-process fetch may reach: `example.com`, `*.example.com`, or either with `:port`. */\n readonly allow: readonly string[];\n /** The credential routes. Without any, the proxy only tunnels. */\n readonly routes?: readonly CredentialRoute[];\n /** Receives one record for each request. A throw from it is ignored. */\n readonly log: (record: EgressRecord) => void;\n /** Listens on this Unix socket instead of a port on `127.0.0.1`, so a container can mount it (`dockerSandbox`'s `proxySocket`). */\n readonly socketPath?: string;\n /** Extra certificate authorities to trust for the routes' hosts and for the fetch, such as a test's own. */\n readonly ca?: string | Uint8Array | readonly (string | Uint8Array)[];\n /** Resolves a name to its addresses. Defaults to the system resolver. Every address it returns is checked. */\n readonly resolve?: (host: string) => Promise<readonly string[]>;\n /**\n * Addresses that skip the public-address check. This exists so a test can reach a server on `127.0.0.1`. Never set it\n * for a real run: the check is what keeps a name that points at the host's own network from being reached.\n */\n readonly unsafeAllowAddresses?: readonly string[];\n /**\n * Ends a tunnel, a forwarded request or a push check that is idle this long. A whole number of milliseconds from 0 to\n * 2,147,483,647, where 0 turns the idle timeout off, as it does for a socket; anything else throws\n * `invalid_egress_options` when the proxy starts. Defaults to 120000.\n */\n readonly idleTimeoutMs?: number;\n /**\n * The longest a push's command list may take to arrive, from the start of its body, however often bytes come. The\n * clock starts once and is never reset, so a client that sends a byte just inside the idle timeout is still cut off;\n * a push that takes longer is refused with `git_timeout`. Only the command list is timed, not the pack after it. A\n * whole number of milliseconds from 1 to 2,147,483,647; anything else throws `invalid_egress_options` when the proxy\n * starts. Defaults to 60000.\n */\n readonly pushCheckTimeoutMs?: number;\n}\n\n/** A running egress proxy. */\nexport interface EgressProxy {\n /**\n * Where the sandbox sends its requests: give it as `HTTPS_PROXY`, and join a route's name to it for a route. On a Unix\n * socket it is `unix:<path>`, which is not a proxy URL: the program that uses the socket connects to it itself.\n */\n readonly url: string;\n /** The Unix socket the proxy listens on, when it was started with `socketPath`. */\n readonly socketPath?: string;\n /** For each route, the placeholder the sandbox puts where the credential goes. The real secret never leaves the host. */\n readonly sentinels: Readonly<Record<string, string>>;\n /**\n * Fetches `input` for an in-process tool, under the same allowlist. A host that isn't on it rejects with `egress_denied`.\n * A route is reached at `${proxy.url}/<route>/…`, or at `http://egress.proxy/<route>/…`, which also works on a Unix socket.\n */\n fetch(input: string | URL, init?: RequestInit): Promise<Response>;\n /** The routes' secrets now, for `scrubSecrets()`. */\n knownSecrets(): Promise<readonly string[]>;\n /** Stops listening and ends every open tunnel and request. */\n close(): Promise<void>;\n}\n\ntype Modules = {\n readonly http: typeof import(\"node:http\");\n readonly https: typeof import(\"node:https\");\n readonly net: typeof import(\"node:net\");\n readonly dns: typeof import(\"node:dns\");\n readonly crypto: typeof import(\"node:crypto\");\n readonly stream: typeof import(\"node:stream\");\n};\n\nfunction nodeModules(): Modules {\n if (typeof process === \"undefined\" || typeof process.getBuiltinModule !== \"function\") {\n throw new HarnessError(\n \"invalid_egress_options\",\n \"the egress proxy needs Node's network modules, which this runtime lacks\",\n );\n }\n return {\n http: process.getBuiltinModule(\"node:http\"),\n https: process.getBuiltinModule(\"node:https\"),\n net: process.getBuiltinModule(\"node:net\"),\n dns: process.getBuiltinModule(\"node:dns\"),\n crypto: process.getBuiltinModule(\"node:crypto\"),\n stream: process.getBuiltinModule(\"node:stream\"),\n };\n}\n\n// Headers that belong to one connection, and are never passed on to the next.\nconst HOP_BY_HOP = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"proxy-connection\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n \"host\",\n]);\nconst DEFAULT_IDLE_MS = 120_000;\nconst DEFAULT_PUSH_CHECK_MS = 60_000;\n// How much of a refused request's unread body is discarded, and for how long, before its connection is closed.\nconst LINGER_BYTES = 1024 * 1024;\nconst LINGER_MS = 1000;\n// The longest delay a timer takes; past it, `setTimeout` fires at once.\nconst MAX_TIMER_MS = 2_147_483_647;\n// What Node refuses in a header value: anything but tab, printable ASCII and the Latin-1 range. A secret with a line break\n// or another control character would split or break the request, so it is refused before it is sent.\nconst INVALID_HEADER_VALUE = /[^\\t\\x20-\\x7e\\x80-\\xff]/;\n// The origin an in-process tool uses for a route, in either mode, because a Unix socket has no address of its own.\nconst ROUTE_ORIGIN = \"http://egress.proxy\";\n\n/** What a request for a route resolves to, before it is written to a socket or wrapped in a `Response`. */\ninterface RouteReply {\n readonly status: number;\n readonly headers: Record<string, string | string[]>;\n readonly body: import(\"node:stream\").Readable | undefined;\n readonly reason?: string;\n}\n\nconst refusal = (status: number, reason: string): RouteReply => ({\n status,\n headers: { \"content-type\": \"text/plain\" },\n body: undefined,\n reason,\n});\n\n/**\n * The answer to a git request whose credential is missing or wrong, or `undefined` when its HTTP Basic password is the\n * route's sentinel. A missing one gets 401 with a Basic challenge, so git asks its credential helper.\n */\nfunction gitCredentialRefusal(presented: string | string[] | undefined, sentinel: string): RouteReply | undefined {\n if (presented === undefined) {\n return { ...refusal(401, \"git_credential_missing\"), headers: { \"www-authenticate\": 'Basic realm=\"egress\"' } };\n }\n return typeof presented === \"string\" && basicCarries(presented, sentinel) ? undefined : refusal(403, \"bad_sentinel\");\n}\n\n/**\n * Checks a timeout option and returns the value to use: `fallback` when it is unset, or a whole number of milliseconds\n * from `min` to the longest delay a timer takes. The message names the option and never quotes the value.\n */\nfunction timeoutOption(name: string, ms: unknown, min: number, fallback: number): number {\n if (ms === undefined) return fallback;\n if (typeof ms === \"number\" && Number.isInteger(ms) && ms >= min && ms <= MAX_TIMER_MS) return ms;\n throw new HarnessError(\n \"invalid_egress_options\",\n `${name} must be a whole number of milliseconds from ${min} to ${MAX_TIMER_MS}`,\n );\n}\n\nclass EgressGate {\n private readonly modules: Modules;\n private readonly allow: readonly AllowEntry[];\n private readonly routes: ReadonlyMap<string, ParsedRoute>;\n private readonly sentinels: Record<string, string> = {};\n private readonly options: EgressProxyOptions;\n private readonly unsafe: ReadonlySet<string>;\n private readonly sockets = new Set<import(\"node:net\").Socket>();\n private readonly requests = new Set<import(\"node:http\").ClientRequest>();\n private readonly pushCheckMs: number;\n // 0 means no idle timeout, as it does for `socket.setTimeout`.\n private readonly idleMs: number;\n private origin = \"\";\n\n constructor(modules: Modules, options: EgressProxyOptions) {\n this.modules = modules;\n this.options = options;\n this.idleMs = timeoutOption(\"idleTimeoutMs\", options.idleTimeoutMs, 0, DEFAULT_IDLE_MS);\n this.pushCheckMs = timeoutOption(\"pushCheckTimeoutMs\", options.pushCheckTimeoutMs, 1, DEFAULT_PUSH_CHECK_MS);\n this.allow = parseAllow(options.allow);\n this.routes = new Map(parseRoutes(options.routes ?? [], this.allow).map((route) => [route.route, route]));\n this.unsafe = new Set(options.unsafeAllowAddresses ?? []);\n for (const route of this.routes.keys()) {\n this.sentinels[route] = `sentinel_${modules.crypto.randomBytes(18).toString(\"base64url\")}`;\n }\n }\n\n setOrigin(origin: string): void {\n this.origin = origin;\n }\n\n sentinelMap(): Readonly<Record<string, string>> {\n return this.sentinels;\n }\n\n private record(record: Omit<EgressRecord, \"time\">): void {\n try {\n this.options.log({ time: new Date().toISOString(), ...record });\n } catch {\n // A logger that throws must not take the proxy down.\n }\n }\n\n /** A `lookup` for `net` and `https`: it resolves in the proxy, checks every address, and connects only to those. */\n private readonly checkedLookup = (\n hostname: string,\n lookupOptions: { all?: boolean },\n callback: (error: Error | null, address?: unknown, family?: number) => void,\n ): void => {\n const resolve =\n this.options.resolve ??\n (async (host: string) =>\n (await this.modules.dns.promises.lookup(host, { all: true })).map((found) => found.address));\n resolve(hostname).then(\n (addresses) => {\n const refused = addresses.length === 0 || addresses.some((a) => !isPublicAddress(a) && !this.unsafe.has(a));\n if (refused) {\n callback(\n Object.assign(new Error(`${hostname} resolves to an address the proxy refuses`), {\n code: \"EGRESS_ADDRESS\",\n }),\n );\n return;\n }\n const family = (address: string) => (address.includes(\":\") ? 6 : 4);\n if (lookupOptions.all === true) {\n callback(\n null,\n addresses.map((address) => ({ address, family: family(address) })),\n );\n } else {\n callback(null, addresses[0], family(addresses[0] ?? \"\"));\n }\n },\n (error: unknown) => callback(error as Error),\n );\n };\n\n private reasonOf(error: unknown): string {\n const code = (error as { code?: string }).code;\n if (code === \"EGRESS_ADDRESS\") return \"address_refused\";\n return code === \"ETIMEDOUT\" ? \"timeout\" : \"connect_failed\";\n }\n\n /** The host and port of a `CONNECT` target, or `undefined` for one that isn't `host:port`. */\n private parseTarget(target: string): { host: string; port: number } | undefined {\n const match = /^(\\[[0-9a-fA-F:.]+\\]|[^:[\\]]+):([0-9]{1,5})$/.exec(target);\n if (match === null) return undefined;\n const host = (match[1] ?? \"\").toLowerCase().replace(/\\.$/, \"\");\n const port = Number(match[2]);\n return port >= 1 && port <= 65535 ? { host, port } : undefined;\n }\n\n /** Handles one `CONNECT`: allow-checks the name, then tunnels to the address the proxy checked. */\n handleConnect(request: import(\"node:http\").IncomingMessage, client: import(\"node:net\").Socket, head: Buffer): void {\n this.track(client);\n const target = this.parseTarget(request.url ?? \"\");\n const host = target?.host ?? \"(invalid)\";\n const port = target?.port ?? 0;\n const deny = (reason: string, status = 403) => {\n client.end(`HTTP/1.1 ${status} ${status === 403 ? \"Forbidden\" : \"Bad Gateway\"}\\r\\nConnection: close\\r\\n\\r\\n`);\n this.record({ kind: \"connect\", host, port, method: \"CONNECT\", status, bytes: 0, reason });\n };\n const refusedBecause =\n target === undefined\n ? \"bad_target\"\n : isAddressLiteral(host)\n ? \"address_literal\"\n : isAllowed(this.allow, host, port)\n ? undefined\n : \"not_allowed\";\n if (refusedBecause !== undefined) {\n deny(refusedBecause);\n return;\n }\n let established = false;\n const upstream = this.modules.net.connect({ host, port, lookup: this.checkedLookup as never });\n this.track(upstream);\n // A client that leaves before the tunnel is up takes the connection attempt with it.\n client.once(\"close\", () => upstream.destroy());\n upstream.setTimeout(this.idleMs, () => upstream.destroy(Object.assign(new Error(\"idle\"), { code: \"ETIMEDOUT\" })));\n upstream.once(\"error\", (error) => {\n if (established) client.destroy();\n else deny(this.reasonOf(error), 502);\n upstream.destroy();\n });\n upstream.once(\"connect\", () => {\n established = true;\n client.write(\"HTTP/1.1 200 Connection Established\\r\\n\\r\\n\");\n if (head.length > 0) upstream.write(head);\n upstream.pipe(client);\n client.pipe(upstream);\n const done = () => {\n client.destroy();\n upstream.destroy();\n };\n client.once(\"close\", done);\n upstream.once(\"close\", () => {\n this.record({\n kind: \"connect\",\n host,\n port,\n method: \"CONNECT\",\n status: 200,\n bytes: upstream.bytesRead + upstream.bytesWritten,\n });\n done();\n });\n });\n client.once(\"error\", () => upstream.destroy());\n }\n\n private track(socket: import(\"node:net\").Socket): void {\n if (this.sockets.has(socket)) return;\n this.sockets.add(socket);\n socket.once(\"close\", () => this.sockets.delete(socket));\n socket.on(\"error\", () => {});\n }\n\n /** Handles one request that isn't a `CONNECT`: a route request, or a refusal of anything else. */\n handleRequest(request: import(\"node:http\").IncomingMessage, response: import(\"node:http\").ServerResponse): void {\n this.track(request.socket);\n const url = request.url ?? \"\";\n if (!url.startsWith(\"/\")) {\n // A proxy request in absolute form: only a tunnel may leave, so the name is not even looked at.\n this.finish(response, refusal(403, \"only_connect\"), {\n kind: \"route\",\n host: \"(proxy request)\",\n port: 0,\n method: request.method ?? \"\",\n });\n return;\n }\n // A client that goes away takes the upstream request with it, so a credential isn't spent for nobody.\n const gone = new AbortController();\n response.once(\"close\", () => gone.abort());\n const base = {\n kind: \"route\" as const,\n host: \"(route)\",\n port: 0,\n method: request.method ?? \"GET\",\n route: undefined,\n };\n this.routeRequest(request.method ?? \"GET\", url, request.headers, request, gone.signal).then(\n (reply) => this.finish(response, reply.reply, reply.base, request),\n () => this.finish(response, refusal(502, \"request_failed\"), base, request),\n );\n }\n\n private finish(\n response: import(\"node:http\").ServerResponse,\n reply: RouteReply,\n base: Pick<EgressRecord, \"kind\" | \"host\" | \"port\" | \"method\" | \"route\">,\n request?: import(\"node:http\").IncomingMessage,\n ): void {\n let bytes = 0;\n const report = () =>\n this.record({\n ...base,\n status: reply.status,\n bytes,\n ...(reply.reason === undefined ? {} : { reason: reply.reason }),\n });\n if (reply.body === undefined && reply.status >= 400 && request !== undefined && !request.complete) {\n this.refuseAndClose(request, response, reply);\n report();\n return;\n }\n response.writeHead(reply.status, reply.headers);\n if (reply.body === undefined) {\n response.end(reply.status === 403 || reply.status >= 400 ? `${reply.reason ?? \"refused\"}\\n` : undefined);\n report();\n return;\n }\n reply.body.on(\"data\", (chunk: Buffer) => {\n bytes += chunk.length;\n });\n reply.body.once(\"close\", report);\n reply.body.once(\"error\", () => response.destroy());\n response.once(\"close\", () => reply.body?.destroy());\n reply.body.pipe(response);\n }\n\n /**\n * Refuses a request whose body has not been read to its end, and closes its connection. Node would otherwise read and\n * discard the rest of the body, a whole pack perhaps, to keep the connection alive. The answer is written whole, with\n * its length and `Connection: close`, and the response is ended, which closes the socket, only after the bytes already\n * on their way are discarded, up to `LINGER_BYTES` or for `LINGER_MS`. Closing a socket with unread bytes resets the\n * connection, and a client that has not yet read the answer would lose it.\n */\n private refuseAndClose(\n request: import(\"node:http\").IncomingMessage,\n response: import(\"node:http\").ServerResponse,\n reply: RouteReply,\n ): void {\n const text = `${reply.reason ?? \"refused\"}\\n`;\n response.writeHead(reply.status, { ...reply.headers, connection: \"close\", \"content-length\": String(text.length) });\n response.write(text);\n let discarded = 0;\n const done = () => {\n clearTimeout(timer);\n request.off(\"data\", onData);\n request.off(\"end\", done);\n request.off(\"close\", done);\n request.pause();\n response.end();\n };\n const onData = (chunk: Uint8Array) => {\n discarded += chunk.length;\n if (discarded >= LINGER_BYTES) done();\n };\n const timer = setTimeout(done, LINGER_MS);\n request.on(\"data\", onData);\n request.once(\"end\", done);\n request.once(\"close\", done);\n request.resume();\n }\n\n /**\n * Resolves a request for `/<route>/…`. It checks the route, the method and the sentinel, swaps in the secret, and\n * forwards the request to the route's host. A request that fails any check is answered here, and nothing is sent.\n */\n async routeRequest(\n method: string,\n rawPath: string,\n headers: Record<string, string | string[] | undefined>,\n body: import(\"node:stream\").Readable | Uint8Array | undefined,\n signal?: AbortSignal,\n ): Promise<{ reply: RouteReply; base: Pick<EgressRecord, \"kind\" | \"host\" | \"port\" | \"method\" | \"route\"> }> {\n const match = /^\\/([^/?#]+)(\\/[^?#]*)?(\\?[^#]*)?$/.exec(rawPath);\n const route = match === null ? undefined : this.routes.get(match[1] ?? \"\");\n const base = {\n kind: \"route\" as const,\n host: route?.hostname ?? \"(no route)\",\n port: route?.port ?? 0,\n method,\n route: route?.route,\n };\n if (route === undefined || match === null) return { reply: refusal(403, \"unknown_route\"), base };\n if (!route.methods.has(method.toUpperCase())) return { reply: refusal(405, \"method_not_allowed\"), base };\n const target = { path: match[2] ?? \"/\", query: match[3] ?? \"\" };\n const reply =\n route.git === undefined\n ? await this.headerRequest(route, method, target, headers, body, signal)\n : await this.gitRequest(route, route.git, method, target, headers, body, signal);\n return { reply, base };\n }\n\n /** Resolves a request on a header route: it swaps the sentinel in the route's header for the secret. */\n private async headerRequest(\n route: ParsedRoute,\n method: string,\n target: { readonly path: string; readonly query: string },\n headers: Record<string, string | string[] | undefined>,\n body: import(\"node:stream\").Readable | Uint8Array | undefined,\n signal?: AbortSignal,\n ): Promise<RouteReply> {\n const presented = headers[route.header];\n const sentinel = this.sentinels[route.route] ?? \"\";\n if (typeof presented !== \"string\" || sentinel === \"\" || !presented.includes(sentinel)) {\n return refusal(403, \"bad_sentinel\");\n }\n const secret = await route.secret().catch(() => \"\");\n if (secret === \"\" || INVALID_HEADER_VALUE.test(secret)) return refusal(502, \"secret_unavailable\");\n const outgoing = this.outgoingHeaders(\n headers,\n route,\n presented.replaceAll(sentinel, () => secret),\n );\n return this.forward(route, method, `${target.path}${target.query}`, outgoing, body, signal);\n }\n\n /**\n * Resolves a request on a git route. The endpoint and repository are checked first, then the sentinel in HTTP Basic,\n * then a push's command list, and only then is the secret read and the request forwarded with it. A missing\n * credential gets 401 with a Basic challenge, so git asks its credential helper for the sentinel.\n */\n private async gitRequest(\n route: ParsedRoute,\n filter: GitRouteFilter,\n method: string,\n target: { readonly path: string; readonly query: string },\n headers: Record<string, string | string[] | undefined>,\n body: import(\"node:stream\").Readable | Uint8Array | undefined,\n signal?: AbortSignal,\n ): Promise<RouteReply> {\n const endpoint = gitEndpoint(filter, method, target.path, target.query);\n if (\"refused\" in endpoint) return refusal(403, endpoint.refused);\n const unauthorized = gitCredentialRefusal(headers.authorization, this.sentinels[route.route] ?? \"\");\n if (unauthorized !== undefined) return unauthorized;\n let forwarded = body;\n if (endpoint.service === \"git-receive-pack\" && endpoint.phase === \"rpc\") {\n const encoding = headers[\"content-encoding\"];\n if (encoding !== undefined && encoding !== \"identity\") return refusal(403, \"git_encoded_push\");\n const checked = await this.checkPush(body, filter);\n if (\"refused\" in checked) return refusal(403, checked.refused);\n forwarded = checked.body;\n }\n const secret = await route.secret().catch(() => \"\");\n if (secret === \"\" || INVALID_HEADER_VALUE.test(secret)) return refusal(502, \"secret_unavailable\");\n const outgoing = this.outgoingHeaders(headers, route, basicHeader(filter.username, secret));\n return this.forward(route, method, `${target.path}${target.query}`, outgoing, forwarded, signal);\n }\n\n /**\n * Reads a push's command list and checks it, then hands back a body that starts with what was read. `PushReader`\n * reads each chunk once, so the check is linear in the bytes however small the chunks. The check gives up once the\n * body is idle for the idle timeout, which each chunk resets, or once `pushCheckTimeoutMs` has passed since it\n * started, which nothing resets.\n */\n private checkPush(\n body: import(\"node:stream\").Readable | Uint8Array | undefined,\n filter: GitRouteFilter,\n ): Promise<{ readonly refused: string } | { readonly body: import(\"node:stream\").Readable | Uint8Array }> {\n if (body === undefined) return Promise.resolve({ refused: \"git_bad_pkt_line\" });\n if (body instanceof Uint8Array) {\n const verdict = pushVerdict(body, filter, true);\n return Promise.resolve(verdict === \"allowed\" ? { body } : { refused: (verdict as { refused: string }).refused });\n }\n return new Promise((resolve) => {\n const reader = new PushReader(filter);\n const chunks: Uint8Array[] = [];\n const timedOut = () => settle({ refused: \"git_timeout\" });\n // An idle timeout of 0 is off, so only the deadline ends a quiet body.\n const startIdle = () => (this.idleMs === 0 ? undefined : setTimeout(timedOut, this.idleMs));\n let idle = startIdle();\n const deadline = setTimeout(timedOut, this.pushCheckMs);\n const settle = (outcome: { refused: string } | { body: import(\"node:stream\").Readable }) => {\n clearTimeout(idle);\n clearTimeout(deadline);\n body.off(\"data\", onData);\n body.off(\"end\", onEnd);\n body.off(\"error\", onError);\n body.off(\"close\", onError);\n // A refused body is not read further; the answer closes its connection.\n if (\"refused\" in outcome) body.pause();\n resolve(outcome);\n };\n const judge = (verdict: ReturnType<PushReader[\"add\"]>, ended: boolean) => {\n if (verdict === \"incomplete\") return;\n if (verdict !== \"allowed\") {\n settle(verdict);\n return;\n }\n const rest = new this.modules.stream.PassThrough();\n for (const chunk of chunks) rest.write(chunk);\n settle({ body: rest });\n if (ended) rest.end();\n else body.pipe(rest);\n };\n const onData = (chunk: Uint8Array) => {\n clearTimeout(idle);\n idle = startIdle();\n chunks.push(chunk);\n judge(reader.add(chunk), false);\n };\n const onEnd = () => judge(reader.end(), true);\n const onError = () => settle({ refused: \"request_failed\" });\n body.on(\"data\", onData);\n body.once(\"end\", onEnd);\n body.once(\"error\", onError);\n // A client that goes away before its command list ends would otherwise hold the check until a timeout.\n body.once(\"close\", onError);\n });\n }\n\n private outgoingHeaders(\n headers: Record<string, string | string[] | undefined>,\n route: ParsedRoute,\n credential: string,\n ): Record<string, string | string[]> {\n const out: Record<string, string | string[]> = {};\n for (const [name, value] of Object.entries(headers)) {\n if (value !== undefined && !HOP_BY_HOP.has(name)) out[name] = value;\n }\n out[route.header] = credential;\n out.host = route.port === 443 ? route.hostname : `${route.hostname}:${route.port}`;\n return out;\n }\n\n private forward(\n route: ParsedRoute,\n method: string,\n path: string,\n headers: Record<string, string | string[]>,\n body: import(\"node:stream\").Readable | Uint8Array | undefined,\n signal?: AbortSignal,\n ): Promise<RouteReply> {\n return new Promise((resolve) => {\n let upstream: import(\"node:http\").ClientRequest;\n try {\n upstream = this.openRoute(route, method, path, headers);\n } catch {\n resolve(refusal(502, \"request_invalid\"));\n return;\n }\n const stop = () => upstream.destroy(new Error(\"client gone\"));\n if (signal?.aborted === true) stop();\n else signal?.addEventListener(\"abort\", stop, { once: true });\n upstream.once(\"close\", () => signal?.removeEventListener(\"abort\", stop));\n this.requests.add(upstream);\n upstream.setTimeout(this.idleMs, () => upstream.destroy(new Error(\"idle\")));\n upstream.once(\"close\", () => this.requests.delete(upstream));\n upstream.once(\"response\", (reply) => {\n const passed: Record<string, string | string[]> = {};\n for (const [name, value] of Object.entries(reply.headers)) {\n if (value !== undefined && !HOP_BY_HOP.has(name)) passed[name] = value;\n }\n resolve({ status: reply.statusCode ?? 502, headers: passed, body: reply });\n });\n upstream.once(\"error\", (error) => resolve(refusal(502, this.reasonOf(error))));\n if (body === undefined) upstream.end();\n else if (body instanceof Uint8Array) upstream.end(body);\n else body.pipe(upstream);\n });\n }\n\n /** Opens the HTTPS request to a route's host, which throws for a header or path Node refuses. */\n private openRoute(\n route: ParsedRoute,\n method: string,\n path: string,\n headers: Record<string, string | string[]>,\n ): import(\"node:http\").ClientRequest {\n return this.modules.https.request({\n host: route.hostname,\n port: route.port,\n servername: route.hostname,\n method,\n path,\n headers,\n agent: false,\n lookup: this.checkedLookup as never,\n ...(this.options.ca === undefined ? {} : { ca: this.options.ca as never }),\n });\n }\n\n /** An in-process fetch under the same allowlist, with the same address checks and pinned connection. */\n async fetch(input: string | URL, init?: RequestInit): Promise<Response> {\n const request = new Request(input, init);\n request.signal.throwIfAborted();\n const url = new URL(request.url);\n const host = url.hostname.toLowerCase().replace(/\\.$/, \"\");\n const port = url.port === \"\" ? 443 : Number(url.port);\n const bodyBytes =\n request.method === \"GET\" || request.method === \"HEAD\" ? undefined : new Uint8Array(await request.arrayBuffer());\n if (url.origin === ROUTE_ORIGIN || (this.origin !== \"\" && url.origin === this.origin)) {\n return this.fetchRoute(request, url, bodyBytes);\n }\n const refuse = (reason: string): never => {\n this.record({ kind: \"fetch\", host, port, method: request.method, status: 403, bytes: 0, reason });\n throw new HarnessError(\"egress_denied\", `the egress proxy refused ${url.host}: ${reason}`);\n };\n if (url.protocol !== \"https:\") return refuse(\"only_https\");\n if (isAddressLiteral(host)) return refuse(\"address_literal\");\n if (!isAllowed(this.allow, host, port)) return refuse(\"not_allowed\");\n return this.sendFetch(request, url, host, port, bodyBytes);\n }\n\n private async fetchRoute(request: Request, url: URL, body: Uint8Array | undefined): Promise<Response> {\n const headers: Record<string, string> = {};\n request.headers.forEach((value, name) => {\n headers[name.toLowerCase()] = value;\n });\n const path = `${url.pathname}${url.search}`;\n const { reply, base } = await this.routeRequest(request.method, path, headers, body, request.signal);\n const stream = reply.body;\n let bytes = 0;\n stream?.on(\"data\", (chunk: Buffer) => {\n bytes += chunk.length;\n });\n const finished = () =>\n this.record({\n ...base,\n status: reply.status,\n bytes,\n ...(reply.reason === undefined ? {} : { reason: reply.reason }),\n });\n if (stream === undefined) finished();\n else stream.once(\"close\", finished);\n return this.toResponse(reply.status, reply.headers, stream);\n }\n\n private sendFetch(\n request: Request,\n url: URL,\n host: string,\n port: number,\n body: Uint8Array | undefined,\n ): Promise<Response> {\n return new Promise((resolve, reject) => {\n const headers: Record<string, string> = {};\n request.headers.forEach((value, name) => {\n if (!HOP_BY_HOP.has(name.toLowerCase())) headers[name] = value;\n });\n const upstream = this.modules.https.request({\n host,\n port,\n servername: host,\n method: request.method,\n path: `${url.pathname}${url.search}`,\n headers: { ...headers, host: url.host },\n agent: false,\n lookup: this.checkedLookup as never,\n ...(this.options.ca === undefined ? {} : { ca: this.options.ca as never }),\n });\n this.requests.add(upstream);\n const abort = () => upstream.destroy(request.signal.reason as Error);\n request.signal.addEventListener(\"abort\", abort, { once: true });\n upstream.once(\"close\", () => {\n this.requests.delete(upstream);\n request.signal.removeEventListener(\"abort\", abort);\n });\n upstream.setTimeout(this.idleMs, () => upstream.destroy(new Error(\"idle\")));\n upstream.once(\"response\", (reply) => {\n let bytes = 0;\n reply.on(\"data\", (chunk: Buffer) => {\n bytes += chunk.length;\n });\n // The record is written when the response is done with, which also covers one that is never read to its end.\n reply.once(\"close\", () =>\n this.record({ kind: \"fetch\", host, port, method: request.method, status: reply.statusCode ?? 0, bytes }),\n );\n resolve(this.toResponse(reply.statusCode ?? 502, reply.headers as Record<string, string | string[]>, reply));\n });\n upstream.once(\"error\", (error) => {\n if (request.signal.aborted) {\n reject(request.signal.reason);\n return;\n }\n const reason = this.reasonOf(error);\n this.record({ kind: \"fetch\", host, port, method: request.method, status: 502, bytes: 0, reason });\n reject(\n new HarnessError(\"egress_denied\", `the egress proxy could not reach ${url.host}: ${reason}`, {\n cause: error,\n }),\n );\n });\n upstream.end(body);\n });\n }\n\n private toResponse(\n status: number,\n headers: Record<string, string | string[]>,\n stream: import(\"node:stream\").Readable | undefined,\n ): Response {\n const out = new Headers();\n for (const [name, value] of Object.entries(headers)) {\n for (const one of Array.isArray(value) ? value : [value]) out.append(name, one);\n }\n const bodiless = stream === undefined || [101, 204, 205, 304].includes(status);\n // A response with no body is drained, so its socket and its log record don't wait for a reader that never comes.\n if (bodiless) stream?.resume();\n const web = bodiless ? null : (this.modules.stream.Readable.toWeb(stream) as ReadableStream);\n return new Response(web, { status, headers: out });\n }\n\n async knownSecrets(): Promise<readonly string[]> {\n const secrets = await Promise.all([...this.routes.values()].map((route) => route.secret().catch(() => \"\")));\n return [...new Set(secrets.filter((secret) => secret !== \"\"))];\n }\n\n close(server: import(\"node:http\").Server): Promise<void> {\n return new Promise((resolve) => {\n for (const socket of this.sockets) socket.destroy();\n for (const request of this.requests) request.destroy();\n server.close(() => resolve());\n server.closeAllConnections();\n });\n }\n}\n\n/**\n * Starts the egress proxy on `127.0.0.1` with a port the system picks, or on `socketPath`. The allowlist and routes are\n * checked first, and a bad entry throws `invalid_egress_options`. Give the sandbox `proxy.url` as `HTTPS_PROXY`, and\n * give a tool that needs a credential the route's URL and its sentinel.\n */\nexport async function startEgressProxy(options: EgressProxyOptions): Promise<EgressProxy> {\n const modules = nodeModules();\n const proxy = new EgressGate(modules, options);\n const server = modules.http.createServer((request, response) => proxy.handleRequest(request, response));\n server.on(\"connect\", (request, socket, head) => proxy.handleConnect(request, socket as never, head));\n server.on(\"clientError\", (_error, socket) => socket.destroy());\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n if (options.socketPath === undefined) server.listen(0, \"127.0.0.1\", resolve);\n else server.listen(options.socketPath, resolve);\n });\n const address = server.address();\n const url =\n options.socketPath !== undefined\n ? `unix:${options.socketPath}`\n : `http://127.0.0.1:${(address as { port: number }).port}`;\n if (options.socketPath === undefined) proxy.setOrigin(url);\n return {\n url,\n ...(options.socketPath === undefined ? {} : { socketPath: options.socketPath }),\n sentinels: proxy.sentinelMap(),\n fetch: (input, init) => proxy.fetch(input, init),\n knownSecrets: () => proxy.knownSecrets(),\n close: () => proxy.close(server),\n };\n}\n"]}
@@ -0,0 +1,68 @@
1
+ /** What a git route lets through. */
2
+ export interface GitRouteFilter {
3
+ /** The repositories the route reaches, as `owner/name`. Compared without case, as GitHub does. */
4
+ readonly repositories: readonly string[];
5
+ /**
6
+ * The branches a push may create or update, as `refs/heads/<name>` or a prefix ending in `/*`, such as
7
+ * `refs/heads/agent/*`. Leave it empty to refuse every push. A deletion and a tag are always refused.
8
+ */
9
+ readonly pushRefs: readonly string[];
10
+ /** Whether a fetch or clone may read the repositories. A fetch is not limited by ref. */
11
+ readonly fetch: boolean;
12
+ /** The user name sent with the credential in HTTP Basic, such as `x-access-token` for a GitHub App token. */
13
+ readonly username: string;
14
+ }
15
+ /** A git request the route accepts: which service, and whether it is the ref advertisement or the request itself. */
16
+ export interface GitEndpoint {
17
+ readonly service: "git-receive-pack" | "git-upload-pack";
18
+ readonly phase: "advertise" | "rpc";
19
+ }
20
+ /** The most bytes of a push's command list, before its flush, that the route reads. A longer list is refused. */
21
+ export declare const GIT_MAX_COMMAND_BYTES: number;
22
+ /** The most ref updates in one push. */
23
+ export declare const GIT_MAX_COMMANDS = 64;
24
+ /** Whether `name` is a ref name git itself would accept, by `git check-ref-format`'s rules, under `refs/`. */
25
+ export declare function isValidRefName(name: string): boolean;
26
+ /** Throws unless every field of a git route's filter is usable. The message names the field, never its value. */
27
+ export declare function checkGitFilter(filter: GitRouteFilter): void;
28
+ /**
29
+ * The git endpoint a request is for, or the reason it is refused. `path` is the part after the route's name, and
30
+ * `query` is the search part with its `?`, or empty.
31
+ */
32
+ export declare function gitEndpoint(filter: GitRouteFilter, method: string, path: string, query: string): GitEndpoint | {
33
+ readonly refused: string;
34
+ };
35
+ /** A push check's verdict so far: `incomplete` until the command list reaches its flush, or the route's verdict. */
36
+ export type PushCheckVerdict = "incomplete" | "allowed" | {
37
+ readonly refused: string;
38
+ };
39
+ /**
40
+ * Reads the command list at the start of a push body as the body arrives, in pieces of any size, and gives the route's
41
+ * verdict once it can. The work is linear in the bytes received: pieces are joined only once they hold the next
42
+ * pkt-line's header or the whole line, and a line already read is never read again. A list whose lines end past
43
+ * `GIT_MAX_COMMAND_BYTES` is refused as soon as a header says so, however the body is split.
44
+ */
45
+ export declare class PushReader {
46
+ #private;
47
+ constructor(filter: GitRouteFilter);
48
+ /** Reads the next piece of the body and returns the verdict so far. Bytes after a verdict are not read. */
49
+ add(chunk: Uint8Array): PushCheckVerdict;
50
+ /** Says the body has ended and returns the final verdict: a list still incomplete is refused. */
51
+ end(): "allowed" | {
52
+ readonly refused: string;
53
+ };
54
+ }
55
+ /**
56
+ * The route's verdict on the start of a push body: `incomplete` while the command list hasn't reached its flush,
57
+ * `allowed` once every command creates or updates a ref the patterns allow, or the reason it is refused. A body that is
58
+ * exactly one flush packet, the probe git sends before a large push, is `allowed` once it has ended, because it updates
59
+ * no ref; a byte after that flush is refused. `ended` says the body has no more bytes, so a list still incomplete is
60
+ * refused. A list whose lines end past `GIT_MAX_COMMAND_BYTES` is refused, whether or not its flush has arrived.
61
+ */
62
+ export declare function pushVerdict(bytes: Uint8Array, filter: GitRouteFilter, ended: boolean): "incomplete" | "allowed" | {
63
+ readonly refused: string;
64
+ };
65
+ /** Whether an `Authorization` header is HTTP Basic whose password is exactly `sentinel`. */
66
+ export declare function basicCarries(header: string | undefined, sentinel: string): boolean;
67
+ /** The `Authorization` value that carries `secret` as the password of `username`. */
68
+ export declare function basicHeader(username: string, secret: string): string;