hammerkit 2.0.0-next.2 → 2.0.0-next.20

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 (111) hide show
  1. package/dist/cache/backends/registry/registry-client.js +8 -2
  2. package/dist/cache/explain.js +7 -5
  3. package/dist/cache/last-resolved.js +11 -0
  4. package/dist/cli.js +4 -1
  5. package/dist/dashboard/assets/graph-canvas-DLioOiRN.css +1 -0
  6. package/dist/dashboard/assets/graph-canvas-HmkW_-XJ.js +8 -0
  7. package/dist/dashboard/assets/index-gIBDC_m8.css +2 -0
  8. package/dist/dashboard/assets/index-vE22S5E_.js +17 -0
  9. package/dist/dashboard/index.html +3 -3
  10. package/dist/dashboard/logo.png +0 -0
  11. package/dist/docker/item-network.js +51 -18
  12. package/dist/docker/package.js +85 -76
  13. package/dist/docker/server-tools.js +96 -0
  14. package/dist/docker/stream.js +15 -7
  15. package/dist/environment/replace-env-variables.js +1 -1
  16. package/dist/environment/run-source-envs.js +18 -0
  17. package/dist/executer/check-container-binds.js +158 -0
  18. package/dist/executer/docker-service.js +42 -3
  19. package/dist/executer/docker-task.js +21 -5
  20. package/dist/executer/execute-command.js +9 -15
  21. package/dist/executer/execute-work-task.js +14 -2
  22. package/dist/executer/execute-work-tree.js +2 -1
  23. package/dist/executer/execution-steps.js +3 -2
  24. package/dist/executer/local-task.js +3 -0
  25. package/dist/executer/print-container-options.js +10 -10
  26. package/dist/executer/process-manager.js +84 -5
  27. package/dist/executer/scheduler/enqueue-next.js +6 -1
  28. package/dist/executer/scheduler/state-key.js +71 -34
  29. package/dist/executer/task-priority.js +131 -0
  30. package/dist/executer/watch-loop.js +18 -5
  31. package/dist/file/get-file-context.js +5 -1
  32. package/dist/file/stat-beneath.js +66 -0
  33. package/dist/file/within-root.js +13 -4
  34. package/dist/harness/connect.js +1 -6
  35. package/dist/harness/mcp-command.js +1 -1
  36. package/dist/harness/sandbox-client.js +39 -4
  37. package/dist/harness/service-tools.js +2 -2
  38. package/dist/kubernetes/await-running-state.js +98 -18
  39. package/dist/kubernetes/claim-layout.js +10 -1
  40. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +10 -1
  41. package/dist/kubernetes/ensure-persistent-data.js +129 -26
  42. package/dist/kubernetes/follow-pod-logs.js +128 -29
  43. package/dist/kubernetes/kept-claims.js +16 -1
  44. package/dist/kubernetes/network-gate.js +74 -11
  45. package/dist/kubernetes/network-policy.js +35 -13
  46. package/dist/kubernetes/quota-wait.js +97 -0
  47. package/dist/kubernetes/remove-stale-items.js +15 -2
  48. package/dist/kubernetes/restore-kubernetes-data.js +28 -4
  49. package/dist/kubernetes/sandbox-runner.js +3 -4
  50. package/dist/kubernetes/store-kubernetes-data.js +14 -2
  51. package/dist/kubernetes/transfer-tools.js +66 -0
  52. package/dist/kubernetes/volumes.js +78 -14
  53. package/dist/optimizer/calculate-checksum.js +46 -3
  54. package/dist/optimizer/check-key.js +7 -0
  55. package/dist/optimizer/check-keys.js +19 -5
  56. package/dist/optimizer/get-work-cache-stats.js +55 -31
  57. package/dist/optimizer/work-task-cache-description.js +36 -7
  58. package/dist/parser/read-build-file.js +8 -3
  59. package/dist/planner/utils/append-work-service.js +1 -1
  60. package/dist/planner/utils/append-work-task.js +1 -1
  61. package/dist/planner/utils/assert-item-paths.js +6 -7
  62. package/dist/planner/utils/template-value.js +20 -4
  63. package/dist/planner/work-item-executions.js +27 -0
  64. package/dist/planner/work-runtime-docker.js +31 -50
  65. package/dist/planner/work-runtime-kubernetes.js +70 -41
  66. package/dist/planner/work-runtime-local.js +3 -7
  67. package/dist/planner/work-secret.js +135 -13
  68. package/dist/planner/work-tree.js +10 -0
  69. package/dist/remote/collect-bundle.js +9 -1
  70. package/dist/remote/host-config.js +49 -3
  71. package/dist/remote/location.js +5 -5
  72. package/dist/remote/remote-commands.js +12 -14
  73. package/dist/remote/remote-work-commands.js +19 -10
  74. package/dist/schema/schema-parser.js +46 -2
  75. package/dist/schema/work-scope-parser.js +16 -1
  76. package/dist/secrets/secret-catalog.js +8 -1
  77. package/dist/server/capacity.js +71 -41
  78. package/dist/server/dashboard.js +27 -9
  79. package/dist/server/endpoints.js +10 -1
  80. package/dist/server/executor.js +68 -35
  81. package/dist/server/kubernetes-backend.js +29 -4
  82. package/dist/server/kubernetes-sandbox-storage.js +14 -4
  83. package/dist/server/oauth.js +16 -1
  84. package/dist/server/overview.js +80 -11
  85. package/dist/server/plan.js +41 -6
  86. package/dist/server/policy.js +22 -9
  87. package/dist/server/repo-access.js +4 -3
  88. package/dist/server/run-environment.js +5 -2
  89. package/dist/server/run-plan.js +18 -6
  90. package/dist/server/run-source-environment.js +39 -0
  91. package/dist/server/run-worker.js +71 -9
  92. package/dist/server/runs.js +133 -7
  93. package/dist/server/sandbox-files.js +339 -55
  94. package/dist/server/sandbox-patch.js +43 -17
  95. package/dist/server/sandboxes.js +57 -23
  96. package/dist/server/server-config.js +28 -5
  97. package/dist/server/server.js +94 -16
  98. package/dist/server/service-runs.js +50 -5
  99. package/dist/server/sources.js +68 -11
  100. package/dist/server/timings.js +23 -3
  101. package/dist/utils/buffer-context.js +30 -20
  102. package/dist/utils/limit.js +30 -0
  103. package/dist/utils/line-splitter.js +52 -0
  104. package/dist/utils/read-lines.js +65 -0
  105. package/dist/utils/tar.js +51 -1
  106. package/dist/utils/units.js +36 -1
  107. package/dist/utils/web-links.js +34 -0
  108. package/package.json +1 -1
  109. package/dist/dashboard/assets/index-CjnKm5-3.css +0 -2
  110. package/dist/dashboard/assets/index-zPXa4klZ.js +0 -13
  111. package/dist/dashboard/favicon.svg +0 -1
@@ -6,7 +6,7 @@
6
6
  * file, and each file is changed in memory, so a batch of edits applies fully or not at all.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.MAX_COMPARED_LINES = exports.parsePatch = exports.PatchError = void 0;
9
+ exports.MAX_HUNK_LINE = exports.PatchBudget = exports.MAX_COMPARED_LINES = exports.parsePatch = exports.PatchError = void 0;
10
10
  class PatchError extends Error {
11
11
  }
12
12
  exports.PatchError = PatchError;
@@ -57,16 +57,25 @@ function splice(file, at, block) {
57
57
  function oldSide(block) {
58
58
  return block.filter((line) => line.kind !== '+').map((line) => line.text);
59
59
  }
60
- // Lines one file's patch may compare to place its hunks. A hunk that is nowhere in a large
61
- // file would otherwise be compared with every place in it, its whole length at each.
60
+ // Lines the patches of one batch may compare to place their hunks. A hunk that is nowhere in
61
+ // a large file would otherwise be compared with every place in it, its whole length at each.
62
62
  exports.MAX_COMPARED_LINES = 20000000;
63
- let compared = 0;
64
- function startComparing() {
65
- compared = 0;
63
+ // The comparisons the patches of one batch made so far.
64
+ class PatchBudget {
65
+ constructor(max = exports.MAX_COMPARED_LINES) {
66
+ this.max = max;
67
+ this.compared = 0;
68
+ }
69
+ }
70
+ exports.PatchBudget = PatchBudget;
71
+ // the budget of the patch being applied: applying one is synchronous, so only one is
72
+ let current = new PatchBudget();
73
+ function startComparing(budget) {
74
+ current = budget ?? new PatchBudget();
66
75
  }
67
76
  function compare(path) {
68
- if (++compared > exports.MAX_COMPARED_LINES) {
69
- throw new PatchError(`${path}: the patch's lines were compared with the file ${exports.MAX_COMPARED_LINES} times without finding their place; give its hunks more lines of context or the line numbers of the file as it is`);
77
+ if (++current.compared > current.max) {
78
+ throw new PatchError(`${path}: the patches of this batch were compared with the files ${current.max} times without finding their place; give their hunks more lines of context or the line numbers of the files as they are`);
70
79
  }
71
80
  }
72
81
  function matchesAt(path, lines, at, wanted, same = (a, b) => stripCr(a) === stripCr(b)) {
@@ -176,14 +185,15 @@ function parseHunks(lines, start, path) {
176
185
  break;
177
186
  }
178
187
  const hunk = {
179
- oldStart: Number(header[1]),
180
- oldLength: header[2] === undefined ? 1 : Number(header[2]),
188
+ oldStart: lineNumber(header[1], path, hunks.length),
189
+ oldLength: header[2] === undefined ? 1 : lineNumber(header[2], path, hunks.length),
181
190
  lines: [],
182
191
  oldNoNewline: false,
183
192
  newNoNewline: false,
184
193
  };
194
+ lineNumber(header[3], path, hunks.length);
185
195
  let oldLeft = hunk.oldLength;
186
- let newLeft = header[4] === undefined ? 1 : Number(header[4]);
196
+ let newLeft = header[4] === undefined ? 1 : lineNumber(header[4], path, hunks.length);
187
197
  i++;
188
198
  while (oldLeft > 0 || newLeft > 0) {
189
199
  if (i >= lines.length) {
@@ -220,12 +230,22 @@ function parseHunks(lines, start, path) {
220
230
  }
221
231
  return [hunks, i];
222
232
  }
233
+ // The largest line number or line count a hunk header may name. A file an edit reads has
234
+ // at most MAX_FILE_BYTES, so no file has more lines than that.
235
+ exports.MAX_HUNK_LINE = 1000000000;
236
+ function lineNumber(digits, path, index) {
237
+ const value = Number(digits);
238
+ if (!Number.isSafeInteger(value) || value > exports.MAX_HUNK_LINE) {
239
+ throw new PatchError(`${path}: hunk ${index + 1} names line ${digits.length > 20 ? `${digits.slice(0, 20)}…` : digits}, more than a file has`);
240
+ }
241
+ return value;
242
+ }
223
243
  function filePatch(header, hunks) {
224
244
  const path = header.to ?? header.from ?? '';
225
245
  return {
226
246
  ...header,
227
- apply(content) {
228
- startComparing();
247
+ apply(content, budget) {
248
+ startComparing(budget);
229
249
  const file = splitLines(content);
230
250
  let delta = 0;
231
251
  let cursor = 0;
@@ -255,8 +275,14 @@ function nominal(hunk) {
255
275
  }
256
276
  // The match closest to `expected` at or after `from`, the way git apply moves a hunk
257
277
  // whose lines moved.
258
- function findNear(path, lines, wanted, expected, from) {
278
+ function findNear(path, lines, wanted, wantedAt, from) {
259
279
  const last = lines.length - wanted.length;
280
+ if (last < from) {
281
+ return -1;
282
+ }
283
+ // a line number past the end of the file looks from the end: every place it could be is
284
+ // between `from` and `last`, so the search never walks past them
285
+ const expected = Math.min(Math.max(wantedAt, from), last);
260
286
  for (let distance = 0; expected - distance >= from || expected + distance <= last; distance++) {
261
287
  if (expected - distance >= from && matchesAt(path, lines, expected - distance, wanted)) {
262
288
  return expected - distance;
@@ -414,7 +440,7 @@ function parseApplyPatch(text) {
414
440
  }
415
441
  chunks[chunks.length - 1].lines.push({ kind, text: current.slice(1) });
416
442
  }
417
- files.push({ from: path, to, apply: (content) => applyChunks(path, content, chunks) });
443
+ files.push({ from: path, to, apply: (content, budget) => applyChunks(path, content, chunks, budget) });
418
444
  }
419
445
  else {
420
446
  throw new PatchError(`"${line.slice(0, 80)}" is not an apply_patch line: expected *** Add File:, *** Update File:, *** Delete File: or *** End Patch`);
@@ -430,8 +456,8 @@ const trailing = (a, b) => a.trimEnd() === b.trimEnd();
430
456
  const trimmed = (a, b) => a.trim() === b.trim();
431
457
  // The way apply_patch finds its lines: after the chunk before it, exactly, then with
432
458
  // trailing and then all surrounding whitespace ignored.
433
- function applyChunks(path, content, chunks) {
434
- startComparing();
459
+ function applyChunks(path, content, chunks, budget) {
460
+ startComparing(budget);
435
461
  const file = splitLines(content);
436
462
  let cursor = 0;
437
463
  chunks.forEach((chunk, index) => {
@@ -32,6 +32,9 @@ class SandboxRegistry {
32
32
  // bytes they take once they were measured
33
33
  this.creating = new Map();
34
34
  this.deleting = new Set();
35
+ // the bytes edits take while they are written, so edits of two sandboxes at once both
36
+ // count against their owner's limit and the server's
37
+ this.reserved = new Map();
35
38
  // the measures of runs that are over, which a run's result does not wait for
36
39
  this.measuring = new Map();
37
40
  this.locks = new Map();
@@ -114,9 +117,10 @@ class SandboxRegistry {
114
117
  usage(owner) {
115
118
  const mine = this.list(owner);
116
119
  const creating = [...this.creating.values()].filter((create) => owns(owner, create.owner));
120
+ const reserved = [...this.reserved.values()].filter((reservation) => owns(owner, reservation.owner));
117
121
  return {
118
122
  count: mine.length + creating.length,
119
- bytes: [...mine, ...creating].reduce((sum, sandbox) => sum + sandbox.bytes, 0),
123
+ bytes: [...mine, ...creating, ...reserved].reduce((sum, sandbox) => sum + sandbox.bytes, 0),
120
124
  };
121
125
  }
122
126
  // Waits for the measures of the owner's runs that are over, so their limits hold.
@@ -139,6 +143,9 @@ class SandboxRegistry {
139
143
  * caller's to decide (`decideSandbox`); this checks the limits.
140
144
  */
141
145
  async create(owner, repo, ref) {
146
+ return this.growing(owner, () => this.createGrowing(owner, repo, ref));
147
+ }
148
+ async createGrowing(owner, repo, ref) {
142
149
  const { limits, storage, repos } = this.options;
143
150
  await this.measured(owner);
144
151
  const usage = this.usage(owner);
@@ -211,28 +218,47 @@ class SandboxRegistry {
211
218
  if (!state.clean) {
212
219
  throw new SandboxError(409, `the sandbox ${id} has changes, a fetch would mix them with another commit`);
213
220
  }
214
- const { storage, repos } = this.options;
215
- const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
216
- await this.resolve(sandbox.repo, ref, signal);
217
- const credentials = await repos.credentials(sandbox.repo);
218
- try {
219
- sandbox.commit = await storage.fetch(keyOf(sandbox), {
220
- url: repos.url(sandbox.repo),
221
- ref,
222
- env: credentials.env,
223
- signal,
224
- });
225
- }
226
- catch (e) {
227
- throw new SandboxError(502, repos.scrub(e, credentials.values).message);
228
- }
229
- sandbox.ref = ref;
230
- sandbox.bytes = await storage.usage(keyOf(sandbox));
231
- sandbox.lastUsedAt = this.timestamp();
232
- await this.save(sandbox);
233
- return copy(sandbox);
221
+ // a fetch can make the sandbox larger: not while the owner or the server is full, and
222
+ // one create or fetch of an owner at a time, so fetches at once can not pass it together
223
+ return this.growing(owner, () => this.fetchGrowing(owner, sandbox, ref));
234
224
  });
235
225
  }
226
+ async fetchGrowing(owner, sandbox, ref) {
227
+ const { limits } = this.options;
228
+ await this.measured(owner);
229
+ const used = this.usage(owner).bytes;
230
+ if (used >= limits.bytes) {
231
+ throw new SandboxError(413, `your sandboxes take ${(0, units_1.formatSize)(used)}, your limit is ${(0, units_1.formatSize)(limits.bytes)}: delete one`);
232
+ }
233
+ if (this.total() >= limits.total) {
234
+ throw new SandboxError(507, 'the server has no room for a fetch');
235
+ }
236
+ const { storage, repos } = this.options;
237
+ const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
238
+ await this.resolve(sandbox.repo, ref, signal);
239
+ const credentials = await repos.credentials(sandbox.repo);
240
+ try {
241
+ sandbox.commit = await storage.fetch(keyOf(sandbox), {
242
+ url: repos.url(sandbox.repo),
243
+ ref,
244
+ env: credentials.env,
245
+ signal,
246
+ });
247
+ }
248
+ catch (e) {
249
+ throw new SandboxError(502, repos.scrub(e, credentials.values).message);
250
+ }
251
+ sandbox.ref = ref;
252
+ sandbox.bytes = await storage.usage(keyOf(sandbox));
253
+ sandbox.lastUsedAt = this.timestamp();
254
+ await this.save(sandbox);
255
+ return copy(sandbox);
256
+ }
257
+ // One create or fetch of an owner at a time: what one adds is measured before the next
258
+ // checks the limit.
259
+ growing(owner, fn) {
260
+ return this.withLock(`owner:${JSON.stringify([owner.iss, owner.sub])}`, fn);
261
+ }
236
262
  /**
237
263
  * Commits the changes of a sandbox as its owner and pushes them to a branch the operator
238
264
  * allows (`sources[].push.branches`). The branch must not exist yet, or be one this
@@ -392,6 +418,7 @@ class SandboxRegistry {
392
418
  if (dryRun || plan.files.length === 0) {
393
419
  return plan.files;
394
420
  }
421
+ const reservation = Symbol(id);
395
422
  if (plan.bytes > 0) {
396
423
  const { limits } = this.options;
397
424
  const used = this.usage(owner).bytes;
@@ -401,8 +428,15 @@ class SandboxRegistry {
401
428
  if (this.total() + plan.bytes > limits.total) {
402
429
  throw new SandboxError(507, 'the server has no room for these edits');
403
430
  }
431
+ // taken before anything else can check: no await between the check and this
432
+ this.reserved.set(reservation, { owner: { iss: owner.iss, sub: owner.sub }, bytes: plan.bytes });
433
+ }
434
+ try {
435
+ await plan.commit();
436
+ }
437
+ finally {
438
+ this.reserved.delete(reservation);
404
439
  }
405
- await plan.commit();
406
440
  sandbox.bytes = Math.max(0, sandbox.bytes + plan.bytes);
407
441
  sandbox.lastUsedAt = this.timestamp();
408
442
  await this.save(sandbox);
@@ -483,7 +517,7 @@ class SandboxRegistry {
483
517
  }
484
518
  }
485
519
  total() {
486
- return [...this.sandboxes.values(), ...this.creating.values()].reduce((sum, sandbox) => sum + sandbox.bytes, 0);
520
+ return [...this.sandboxes.values(), ...this.creating.values(), ...this.reserved.values()].reduce((sum, sandbox) => sum + sandbox.bytes, 0);
487
521
  }
488
522
  withLock(id, fn) {
489
523
  const previous = this.locks.get(id) ?? Promise.resolve();
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.detectPlatform = exports.getSecretCatalog = exports.readServerConfig = exports.getServerAccounts = exports.getSandboxRuntimes = exports.serverConfigSchema = exports.sourceSchema = exports.entitlementSchema = exports.endpointGrantSchema = exports.endpointLevelSchema = exports.sandboxGrantSchema = exports.sandboxBranchTypeSchema = exports.buildsLevelSchema = exports.accountLevelSchema = exports.getMaxVolumeSize = exports.DEFAULT_MAX_VOLUME_SIZE = exports.DEFAULT_DENIED_EGRESS = exports.kubernetesPoolSchema = exports.accountSchema = exports.issuerSchema = exports.serverPlatformSchema = void 0;
4
+ const run_source_envs_1 = require("../environment/run-source-envs");
4
5
  const net_1 = require("net");
5
6
  const zod_1 = require("zod");
6
7
  const yaml_1 = require("yaml");
@@ -45,7 +46,10 @@ exports.issuerSchema = zod_1.z
45
46
  scope: zod_1.z.string().min(1).default('openid'),
46
47
  })
47
48
  .strict();
48
- const subjectSchema = zod_1.z.object({ iss: zod_1.z.string().min(1), sub: zod_1.z.string().min(1) }).strict();
49
+ // `name`: how pages name a subject whose tokens name nobody, such as a service account's
50
+ const subjectSchema = zod_1.z
51
+ .object({ iss: zod_1.z.string().min(1), sub: zod_1.z.string().min(1), name: zod_1.z.string().trim().min(1).max(100).optional() })
52
+ .strict();
49
53
  const groupSchema = zod_1.z.object({ iss: zod_1.z.string().min(1), name: zod_1.z.string().min(1) }).strict();
50
54
  const claimsSchema = zod_1.z.object({ iss: zod_1.z.string().min(1), match: zod_1.z.record(zod_1.z.string()) }).strict();
51
55
  // Who: the person or client (`subject`), everyone in a group of an issuer
@@ -295,6 +299,15 @@ const kubernetesBackendSchema = zod_1.z
295
299
  // build file's environment does: hammerkit can't tell from the API, and without it a
296
300
  // task with a limited network fails rather than runs open
297
301
  networkPolicy: zod_1.z.literal('enforced').optional(),
302
+ // what the pods with an open network wait to no longer reach before they start, under
303
+ // `networkPolicy: enforced`: an address and port `deniedEgress` covers that answers without
304
+ // the policy (the metadata endpoint by default), or `false` for no wait
305
+ openNetworkGate: zod_1.z
306
+ .union([
307
+ zod_1.z.literal(false),
308
+ zod_1.z.object({ host: zod_1.z.string().ip({ version: 'v4' }), port: zod_1.z.number().int().min(1).max(65535) }).strict(),
309
+ ])
310
+ .optional(),
298
311
  // `runtimeClass` is a RuntimeClass of a sandbox, such as gvisor; the pods of tasks that
299
312
  // add capabilities run in it
300
313
  capabilities: zod_1.z.object({ allow: capabilitiesAllowSchema, runtimeClass: kubernetesNameSchema }).strict().optional(),
@@ -509,6 +522,15 @@ exports.serverConfigSchema = zod_1.z
509
522
  set: zod_1.z.record(zod_1.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), zod_1.z.string()).default({}),
510
523
  })
511
524
  .strict()
525
+ // what a run is from is the run's: an operator's value would pass for it
526
+ .superRefine((env, ctx) => {
527
+ for (const name of [...env.allow, ...Object.keys(env.set)].filter(run_source_envs_1.isRunSourceEnv)) {
528
+ ctx.addIssue({
529
+ code: zod_1.z.ZodIssueCode.custom,
530
+ message: `${name} is set by the server for each run, from what the run is from`,
531
+ });
532
+ }
533
+ })
512
534
  .default({}),
513
535
  // the most any task or service of a run reaches besides its needs: none, open
514
536
  // or { allow: [hosts] }. A version that asks for more is refused at publish.
@@ -572,8 +594,9 @@ exports.serverConfigSchema = zod_1.z
572
594
  // the most open network a task or service of a run on a sandbox gets, written as
573
595
  // a task's `network`: only the services it needs by default
574
596
  network: network_schema_1.networkSchema.default('none'),
575
- // the variables of `runs.env.allow` an `env:` secret of a run on a sandbox may
576
- // read: none by default, a sandbox holds code nobody reviewed
597
+ // the variables of runs (`runs.env.allow` and `runs.env.set`) an `env:` secret and the
598
+ // `envs` of a build file of a run on a sandbox may read, besides PATH, HOME and CI:
599
+ // none by default, a sandbox holds code nobody reviewed
577
600
  env: zod_1.z
578
601
  .object({ allow: zod_1.z.array(zod_1.z.string().regex(/^[A-Za-z_][A-Za-z0-9_()]*$/)).default([]) })
579
602
  .strict()
@@ -766,11 +789,11 @@ exports.serverConfigSchema = zod_1.z
766
789
  });
767
790
  }
768
791
  config.sandboxes.env.allow.forEach((name, index) => {
769
- if (!config.runs.env.allow.includes(name)) {
792
+ if (!config.runs.env.allow.includes(name) && !Object.prototype.hasOwnProperty.call(config.runs.env.set, name)) {
770
793
  ctx.addIssue({
771
794
  code: zod_1.z.ZodIssueCode.custom,
772
795
  path: ['sandboxes', 'env', 'allow', index],
773
- message: `${name} is not in runs.env.allow, no run can read it`,
796
+ message: `${name} is not in runs.env.allow or runs.env.set, no run can read it`,
774
797
  });
775
798
  }
776
799
  });
@@ -20,6 +20,7 @@ const execute_docker_1 = require("../executer/execute-docker");
20
20
  const timings_1 = require("./timings");
21
21
  const kubernetes_backend_1 = require("./kubernetes-backend");
22
22
  const run_plan_1 = require("./run-plan");
23
+ const run_source_environment_1 = require("./run-source-environment");
23
24
  const work_network_1 = require("../planner/work-network");
24
25
  const run_environment_1 = require("./run-environment");
25
26
  const accounts_api_1 = require("./accounts-api");
@@ -37,6 +38,7 @@ const sandbox_storage_1 = require("./sandbox-storage");
37
38
  const kubernetes_sandbox_storage_1 = require("./kubernetes-sandbox-storage");
38
39
  const sandbox_docker_1 = require("./sandbox-docker");
39
40
  const sandboxes_api_1 = require("./sandboxes-api");
41
+ const plan_1 = require("./plan");
40
42
  const endpoints_1 = require("./endpoints");
41
43
  const service_runs_1 = require("./service-runs");
42
44
  const units_1 = require("../utils/units");
@@ -109,7 +111,7 @@ function streamEvents(registry, config, principal, id, req, res, url) {
109
111
  });
110
112
  }
111
113
  async function handleRuns(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, req, res, url) {
112
- const match = /^\/v1\/runs(?:\/([^/]+)(?:\/(cancel|events|logs|extend))?)?$/.exec(url.pathname);
114
+ const match = /^\/v1\/runs(?:\/([^/]+)(?:\/(cancel|events|logs|extend|wake))?)?$/.exec(url.pathname);
113
115
  if (!match) {
114
116
  return false;
115
117
  }
@@ -129,7 +131,7 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
129
131
  }
130
132
  const runs = filter.scope === 'mine' ? registry.list(principal) : registry.all();
131
133
  (0, http_2.send)(res, 200, {
132
- runs: (0, overview_1.filterRuns)(runs, viewer, filter).map((run) => listRun(registry, viewer, run)),
134
+ runs: (0, overview_1.filterRuns)(runs, viewer, filter).map((run) => listRun(registry, definitions, viewer, run)),
133
135
  });
134
136
  }
135
137
  else if (method === 'POST') {
@@ -148,9 +150,10 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
148
150
  (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'POST' });
149
151
  return true;
150
152
  }
151
- const run = registry.cancel(principal, id, accountsOf(config, principal));
153
+ const grant = (0, policy_1.getGrant)(config.entitlements, principal);
154
+ const run = registry.cancel(principal, id, accountsOf(config, principal), (up) => (0, service_runs_1.mayPublishEndpoints)(grant, up));
152
155
  log(`cancel iss=${principal.iss} sub=${principal.sub} run=${id} found=${Boolean(run)}`);
153
- run ? (0, http_2.send)(res, 200, toRunResponse(run)) : (0, http_2.send)(res, 404, { error: 'not found' });
156
+ run ? (0, http_2.send)(res, 200, answerRun(config, principal, run)) : (0, http_2.send)(res, 404, { error: 'not found' });
154
157
  }
155
158
  else if (action === 'extend') {
156
159
  if (method !== 'POST') {
@@ -159,6 +162,28 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
159
162
  }
160
163
  await extendRun(config, registry, log, principal, id, req, res);
161
164
  }
165
+ else if (action === 'wake') {
166
+ if (method !== 'POST') {
167
+ (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'POST' });
168
+ return true;
169
+ }
170
+ // as a request to one of its endpoints would, with the same check of its owner
171
+ const grant = (0, policy_1.getGrant)(config.entitlements, principal);
172
+ const result = registry.wake(principal, id, (run) => (0, service_runs_1.mayOpenEndpoints)(grant, run), (run) => refuseWake(config, repos, run));
173
+ log(`wake iss=${principal.iss} sub=${principal.sub} run=${id} result=${result.status}`);
174
+ if (result.status === 'not-found') {
175
+ (0, http_2.send)(res, 404, { error: 'not found' });
176
+ }
177
+ else if (result.status === 'not-asleep') {
178
+ (0, http_2.send)(res, 409, { error: `the run is ${result.state}, only a service run that sleeps wakes` });
179
+ }
180
+ else if (result.status === 'refused') {
181
+ (0, http_2.send)(res, 409, { error: result.reason });
182
+ }
183
+ else {
184
+ (0, http_2.send)(res, 200, answerRun(config, principal, result.run));
185
+ }
186
+ }
162
187
  else if (method !== 'GET') {
163
188
  (0, http_2.send)(res, 405, { error: 'method not allowed' }, { allow: 'GET' });
164
189
  }
@@ -205,7 +230,7 @@ async function handleRuns(config, registry, definitions, sources, sandboxes, pla
205
230
  const may = run && (0, overview_1.runActions)(viewer, run);
206
231
  run
207
232
  ? (0, http_2.send)(res, 200, {
208
- ...toRunResponse(run, (0, overview_1.queuePlace)(registry, viewer, run), !(0, overview_1.owns)(viewer, run)),
233
+ ...toRunResponse(run, (0, overview_1.queuePlace)(registry, viewer, run), !(0, overview_1.owns)(viewer, run), viewer.nameOf),
209
234
  ...(may ? { may } : {}),
210
235
  })
211
236
  : (0, http_2.send)(res, 404, { error: 'not found' });
@@ -244,9 +269,18 @@ async function extendRun(config, registry, log, principal, id, req, res) {
244
269
  (0, http_2.send)(res, 409, { error: `the run is ${result.state}, only a service run that is up can be extended` });
245
270
  }
246
271
  else {
247
- (0, http_2.send)(res, 200, toRunResponse(result.run));
272
+ (0, http_2.send)(res, 200, answerRun(config, principal, result.run));
248
273
  }
249
274
  }
275
+ // What a stop, an extend or a wake answers: the run whole for who may read it (its owner, who
276
+ // decides about it, `observe`), else what the list shows of it. Who may only open or publish
277
+ // endpoints of its repository is told how it stands, not its arguments, plan or log.
278
+ function answerRun(config, principal, run) {
279
+ const viewer = (0, overview_1.getViewer)(config, principal);
280
+ return (0, overview_1.mayRead)(viewer, run)
281
+ ? toRunResponse(run, undefined, !(0, overview_1.owns)(viewer, run), viewer.nameOf)
282
+ : (0, overview_1.toListedRun)(viewer, run);
283
+ }
250
284
  // Why the owner of a service run that sleeps may no longer run it, with the entitlements of
251
285
  // the moment: a wake is started by who opens an endpoint, but runs as the owner, as a new
252
286
  // run of theirs would.
@@ -299,18 +333,21 @@ function runsTheSame(run, next) {
299
333
  }
300
334
  exports.runsTheSame = runsTheSame;
301
335
  // A run whole, for its owner and who may read it; who is not its owner is told whose it is.
302
- function toRunResponse(run, queue, named = false) {
336
+ function toRunResponse(run, queue, named = false, nameOf) {
303
337
  const { owner, ...visible } = run;
338
+ const name = owner.name ?? nameOf?.(owner);
304
339
  return {
305
340
  ...visible,
306
- ...(named ? { owner: { iss: owner.iss, sub: owner.sub } } : {}),
341
+ ...(named ? { owner: { iss: owner.iss, sub: owner.sub, ...(name ? { name } : {}) } } : {}),
307
342
  results: run.results ?? {},
308
343
  ...(queue ? { queue } : {}),
309
344
  };
310
345
  }
311
- function listRun(registry, viewer, run) {
312
- return (0, overview_1.toListedRun)(viewer, run, (0, overview_1.queuePlace)(registry, viewer, run));
346
+ function listRun(registry, definitions, viewer, run) {
347
+ return (0, overview_1.toListedRun)(viewer, run, (0, overview_1.queuePlace)(registry, viewer, run), entryOf(definitions));
313
348
  }
349
+ // where in its repository the build file of a version is
350
+ const entryOf = (definitions) => (definition) => definitions.find(definition)?.entry;
314
351
  async function submitRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, req, res) {
315
352
  const parsed = run_request_1.runRequestSchema.safeParse(await (0, http_2.readJson)(req));
316
353
  if (!parsed.success) {
@@ -439,7 +476,13 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
439
476
  let planned;
440
477
  try {
441
478
  // a run on a sandbox may only use the runtimes of `sandboxes.runtimes`
442
- planned = await (0, run_plan_1.planRun)(bundle, request, planning.environment, sandbox ? sandboxes.policy : planning.policy);
479
+ // with what the run is from, as its tasks read it; the commit of a ref follows below
480
+ const from = request.source.type === 'ref'
481
+ ? { type: 'ref', repo: request.source.repo, ref: request.source.ref }
482
+ : sandbox
483
+ ? { type: 'sandbox', id: sandbox.id, repo: sandbox.repo }
484
+ : { type: 'upload' };
485
+ planned = await (0, run_plan_1.planRun)(bundle, request, (0, run_source_environment_1.runPlanningEnvironment)(planning.environment, from), sandbox ? sandboxes.policy : planning.policy);
443
486
  }
444
487
  catch (e) {
445
488
  (0, http_2.send)(res, 400, { error: `the run does not load: ${e instanceof Error ? e.message : String(e)}` });
@@ -502,6 +545,25 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
502
545
  else if (request.source.type === 'upload') {
503
546
  source = request.source;
504
547
  }
548
+ if (source?.type === 'ref') {
549
+ // what the approver reads is what the tasks see, the commit included; who may run it was
550
+ // decided without it and can't change with it
551
+ let pinned;
552
+ try {
553
+ pinned = await (0, run_plan_1.planRun)(bundle, request, (0, run_source_environment_1.runPlanningEnvironment)(planning.environment, source), planning.policy);
554
+ }
555
+ catch (e) {
556
+ (0, http_2.send)(res, 400, { error: `the run does not load: ${e instanceof Error ? e.message : String(e)}` });
557
+ return;
558
+ }
559
+ if (pinned.accounts.join(',') !== planned.accounts.join(',')) {
560
+ const error = `the accounts of the run change with its commit (${pinned.accounts.join(', ')})`;
561
+ log(`refuse run iss=${principal.iss} sub=${principal.sub}: ${error}`);
562
+ (0, http_2.send)(res, 400, { error });
563
+ return;
564
+ }
565
+ planned = pinned;
566
+ }
505
567
  // a service run is named after its branch unless it says, and its endpoints after that
506
568
  const serviceName = request.services.length > 0
507
569
  ? request.name ??
@@ -518,8 +580,11 @@ async function submitRun(config, registry, definitions, sources, sandboxes, plan
518
580
  : undefined;
519
581
  // a run that may sleep keeps what its owner is entitled by, for the check of a wake
520
582
  const claimNames = new Set(config.entitlements.flatMap((entitlement) => Object.keys(entitlement.claims?.match ?? {})));
583
+ const name = (0, oauth_1.displayName)(principal);
521
584
  const owner = {
522
585
  ...principal,
586
+ // how the pages name them, which the claims kept no longer tell
587
+ ...(name ? { name } : {}),
523
588
  claims: Object.fromEntries(Object.entries(principal.claims).filter(([name]) => claimNames.has(name))),
524
589
  };
525
590
  // A service run of the caller of this name that runs the same build file, services and
@@ -671,7 +736,7 @@ async function handleApi(api, principal, req, res, url) {
671
736
  (0, http_2.send)(res, 403, { error: 'you are not entitled to anything on this server' });
672
737
  return;
673
738
  }
674
- (0, http_2.send)(res, 200, (0, overview_1.getOverview)(registry.snapshot(), registry.usage(principal), viewer));
739
+ (0, http_2.send)(res, 200, (0, overview_1.getOverview)(registry.snapshot(), registry.usage(principal), viewer, entryOf(definitions)));
675
740
  return;
676
741
  }
677
742
  if (path === '/v1/capacity' || path === '/v1/tasks') {
@@ -702,7 +767,13 @@ async function handleApi(api, principal, req, res, url) {
702
767
  return;
703
768
  }
704
769
  const runs = (0, overview_1.filterRuns)(registry.all(), viewer, filter).map((run) => (0, overview_1.toListedRun)(viewer, run));
705
- (0, http_2.send)(res, 200, { tasks: (0, timings_1.getTaskStats)(runs, Date.now()) });
770
+ const oldest = (0, timings_1.getOldestCounted)(runs);
771
+ // where in the repository the build file of the last run is, as its version says
772
+ const tasks = (0, timings_1.getTaskStats)(runs, Date.now()).map((stats) => {
773
+ const entry = stats.last.definition ? api.definitions.find(stats.last.definition)?.entry : undefined;
774
+ return entry ? { ...stats, last: { ...stats.last, entry } } : stats;
775
+ });
776
+ (0, http_2.send)(res, 200, { tasks, ...(oldest ? { oldest } : {}) });
706
777
  return;
707
778
  }
708
779
  if (await (0, approvals_api_1.handleApprovals)(config, registry, log, principal, req, res, url)) {
@@ -755,9 +826,14 @@ async function startServer(config, environment, options = {}) {
755
826
  },
756
827
  };
757
828
  const storage = config.storage.directory ?? (0, path_1.join)((0, get_cache_directory_1.getHammerkitDirectory)(), 'server');
758
- const definitions = new definitions_1.DefinitionStore((0, path_1.join)(storage, 'definitions'), planning.environment, {
759
- policy: planning.policy,
760
- });
829
+ // a build file nobody ran yet is read with the names of the variables, not their values
830
+ const definitions = new definitions_1.DefinitionStore((0, path_1.join)(storage, 'definitions'), {
831
+ ...planning.environment,
832
+ hosted: {
833
+ ...planning.environment.hosted,
834
+ buildFileEnvs: (0, plan_1.withSymbolicValues)(planning.environment.processEnvs),
835
+ },
836
+ }, { policy: planning.policy });
761
837
  await definitions.load();
762
838
  const repos = new repo_access_1.RepoAccess(config, planning.environment, options.repos);
763
839
  const sandboxRuntimes = (0, server_config_1.getSandboxRuntimes)(config);
@@ -786,6 +862,8 @@ async function startServer(config, environment, options = {}) {
786
862
  ...planning.policy,
787
863
  envs: config.sandboxes.env.allow,
788
864
  envsFrom: 'sandboxes.env.allow',
865
+ // and what its build files read of the run's variables, `$NAME` in its `envs`
866
+ readableEnvs: config.sandboxes.env.allow,
789
867
  runtimes: sandboxRuntimes,
790
868
  capabilities: config.sandboxes.capabilities,
791
869
  capabilitiesFrom: 'sandboxes.capabilities',
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.mayOpenEndpoints = exports.getRunRepo = exports.toRunEndpoints = exports.refuseEndpoints = exports.getEndpointHosts = exports.getServiceRunName = void 0;
3
+ exports.mayPublishEndpoints = exports.mayOpenEndpoints = exports.getRunRepo = exports.toRunEndpoints = exports.refuseEndpoints = exports.getEndpointHosts = exports.getServiceRunName = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const plan_1 = require("./plan");
6
6
  const policy_1 = require("./policy");
@@ -38,7 +38,9 @@ function containerPorts(plan) {
38
38
  * Why the endpoints of a service run can't be published, or null. Each is a port its
39
39
  * service declares, of a service the run starts. Under a `runs.secretNetwork` below `open`
40
40
  * a service behind an endpoint may not read a secret or a credential of the server: a page
41
- * is a way out that no mask of the log covers.
41
+ * is a way out that no mask of the log covers. Nor may what it is made from or talks to: a
42
+ * task it depends on (its init task too) can leave a value in a file the service serves,
43
+ * and a service it needs can hand one over the connection it answers on.
42
44
  */
43
45
  function refuseEndpoints(request, plan, secretNetworkOpen) {
44
46
  for (const endpoint of request.endpoints) {
@@ -50,14 +52,50 @@ function refuseEndpoints(request, plan, secretNetworkOpen) {
50
52
  const ports = containerPorts(item);
51
53
  return `${endpoint.service} has no port ${endpoint.port}${ports.length > 0 ? `, its ports are ${ports.join(', ')}` : ', it declares none'}`;
52
54
  }
53
- const reads = (0, plan_1.getCredentialReads)(item);
54
- if (!secretNetworkOpen && reads.length > 0) {
55
- return `${endpoint.service} reads ${reads.join(', ')}, it can not be behind an endpoint on this server (runs.secretNetwork): a page could show it`;
55
+ if (secretNetworkOpen) {
56
+ continue;
57
+ }
58
+ for (const { name, path } of reachedFrom(endpoint.service, plan)) {
59
+ const reads = (0, plan_1.getCredentialReads)(plan[name]);
60
+ if (reads.length === 0) {
61
+ continue;
62
+ }
63
+ const what = reads.join(', ');
64
+ if (path.length === 0) {
65
+ return `${name} reads ${what}, it can not be behind an endpoint on this server (runs.secretNetwork): a page could show it`;
66
+ }
67
+ // the way from the service to what reads it: `web needs api, which needs vault`
68
+ const way = path.map((step, index) => `${index === 0 ? '' : ', which '}${step.relation} ${step.name}`).join('');
69
+ return (`${endpoint.service} ${way}, which reads ${what}: ` +
70
+ 'it can not be behind an endpoint on this server (runs.secretNetwork), a page could show it');
56
71
  }
57
72
  }
58
73
  return null;
59
74
  }
60
75
  exports.refuseEndpoints = refuseEndpoints;
76
+ function reachedFrom(service, plan) {
77
+ if (!plan[service]) {
78
+ return [];
79
+ }
80
+ const reached = [{ name: service, path: [] }];
81
+ const seen = new Set([service]);
82
+ for (let index = 0; index < reached.length; index++) {
83
+ const { name, path } = reached[index];
84
+ const item = plan[name];
85
+ const next = [
86
+ ...(item.init ? [{ relation: 'is initialized by', name: item.init }] : []),
87
+ ...(item.deps ?? []).map((dep) => ({ relation: 'depends on', name: dep })),
88
+ ...(item.needs ?? []).map((need) => ({ relation: 'needs', name: need })),
89
+ ];
90
+ for (const step of next) {
91
+ if (plan[step.name] && !seen.has(step.name)) {
92
+ seen.add(step.name);
93
+ reached.push({ name: step.name, path: [...path, step] });
94
+ }
95
+ }
96
+ }
97
+ return reached;
98
+ }
61
99
  function toRunEndpoints(endpoints, hosts, url) {
62
100
  return endpoints.map((endpoint, index) => ({
63
101
  service: endpoint.service,
@@ -79,4 +117,11 @@ function mayOpenEndpoints(grant, run) {
79
117
  return repo !== null && (0, policy_1.endpointLevel)(grant, repo) !== null;
80
118
  }
81
119
  exports.mayOpenEndpoints = mayOpenEndpoints;
120
+ // Who may publish endpoints of the run's repository: they could bring up a run of their own
121
+ // there, so they may stop somebody else's (a preview left running), besides its owner.
122
+ function mayPublishEndpoints(grant, run) {
123
+ const repo = getRunRepo(run);
124
+ return repo !== null && (0, policy_1.endpointLevel)(grant, repo) === 'publish';
125
+ }
126
+ exports.mayPublishEndpoints = mayPublishEndpoints;
82
127
  //# sourceMappingURL=service-runs.js.map