hammerkit 2.1.0-next.1 → 2.1.0-next.11

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 (54) hide show
  1. package/build.schema.json +126 -28
  2. package/dist/cli.js +5 -0
  3. package/dist/dashboard/assets/graph-canvas-D6GMgkoe.js +8 -0
  4. package/dist/dashboard/assets/index-BNq9j5Jo.js +23 -0
  5. package/dist/dashboard/assets/index-DP3_hKOe.css +2 -0
  6. package/dist/dashboard/index.html +2 -2
  7. package/dist/docker/item-network.js +6 -5
  8. package/dist/docker/remove-orphaned-containers.js +5 -4
  9. package/dist/environment/replace-env-variables.js +8 -5
  10. package/dist/environment/run-source-envs.js +2 -1
  11. package/dist/executer/check-readiness.js +8 -4
  12. package/dist/executer/docker-healthcheck.js +73 -0
  13. package/dist/executer/docker-service.js +21 -15
  14. package/dist/kubernetes/ensure-kubernetes-deployment-exists.js +62 -14
  15. package/dist/network/healthcheck-request.js +38 -0
  16. package/dist/optimizer/work-task-cache-description.js +5 -3
  17. package/dist/planner/image-build.js +5 -0
  18. package/dist/planner/service-definition.js +2 -1
  19. package/dist/planner/utils/append-work-service.js +12 -4
  20. package/dist/planner/utils/dependency-outputs.js +7 -6
  21. package/dist/planner/validate.js +41 -0
  22. package/dist/planner/work-healthcheck.js +23 -2
  23. package/dist/planner/work-runtime-docker.js +24 -1
  24. package/dist/planner/work-runtime-kubernetes.js +37 -16
  25. package/dist/planner/work-secret.js +33 -11
  26. package/dist/planner/work-service-id.js +30 -6
  27. package/dist/planner/work-service.js +2 -2
  28. package/dist/program.js +19 -1
  29. package/dist/remote/annotations.js +8 -2
  30. package/dist/remote/bundle.js +4 -2
  31. package/dist/remote/remote-work-commands.js +5 -3
  32. package/dist/schema/build-file-base-task-schema.js +16 -1
  33. package/dist/schema/build-file-image-build-schema.js +5 -8
  34. package/dist/schema/build-file-service-container-healthcheck.js +25 -7
  35. package/dist/schema/reference-parser.js +108 -43
  36. package/dist/schema/work-scope-parser.js +8 -0
  37. package/dist/secrets/prefetch-secrets.js +20 -1
  38. package/dist/server/definitions-api.js +62 -8
  39. package/dist/server/kubernetes-sandbox-storage.js +3 -2
  40. package/dist/server/overview.js +73 -9
  41. package/dist/server/paging.js +167 -0
  42. package/dist/server/plan.js +16 -1
  43. package/dist/server/run-source-environment.js +1 -1
  44. package/dist/server/sandbox-files-api.js +27 -12
  45. package/dist/server/sandbox-files.js +3 -2
  46. package/dist/server/sandbox-pod.js +1 -1
  47. package/dist/server/sandboxes-api.js +116 -19
  48. package/dist/server/sandboxes.js +19 -3
  49. package/dist/server/server.js +75 -13
  50. package/dist/server/task-order.js +56 -0
  51. package/package.json +1 -1
  52. package/dist/dashboard/assets/graph-canvas-DtJSpova.js +0 -8
  53. package/dist/dashboard/assets/index-BndChMep.css +0 -2
  54. package/dist/dashboard/assets/index-DRSwIRXd.js +0 -17
@@ -0,0 +1,167 @@
1
+ "use strict";
2
+ /**
3
+ * The pages of a list the API answers, and the values its filters can take.
4
+ *
5
+ * A list asked with `limit` answers that many at most, and `next` while more remain: the
6
+ * `cursor` that asks for the page after it. A cursor is opaque to callers. Without `limit` a
7
+ * list answers everything, as before lists were paged.
8
+ *
9
+ * A list asked with `values=<field>` answers the values that field has instead, each with how
10
+ * many of the list have it, narrowed by `search` and paged the same way: what a filter offers
11
+ * to choose from.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.hasText = exports.readText = exports.readList = exports.countValues = exports.parseValues = exports.answerPage = exports.pageByPosition = exports.pageByKey = exports.newestFirst = exports.parsePage = exports.ListParamError = exports.VALUES_LIMIT = exports.MAX_LIMIT = void 0;
15
+ // the most a page holds
16
+ exports.MAX_LIMIT = 200;
17
+ // the values of a field a page holds when the caller names no limit
18
+ exports.VALUES_LIMIT = 50;
19
+ // A parameter of a list that is not right: the caller is answered 400 with the message.
20
+ class ListParamError extends Error {
21
+ }
22
+ exports.ListParamError = ListParamError;
23
+ // `limit` and `cursor`: undefined when the caller names no limit, and gets everything.
24
+ function parsePage(params, fallback) {
25
+ const limit = params.get('limit');
26
+ const cursor = params.get('cursor') ?? undefined;
27
+ if (limit === null) {
28
+ if (cursor !== undefined && fallback === undefined) {
29
+ throw new ListParamError('cursor: only with limit');
30
+ }
31
+ return fallback === undefined ? undefined : { limit: fallback, ...(cursor !== undefined ? { cursor } : {}) };
32
+ }
33
+ if (!/^\d+$/.test(limit) || Number(limit) < 1 || Number(limit) > exports.MAX_LIMIT) {
34
+ throw new ListParamError(`limit: a number from 1 to ${exports.MAX_LIMIT}`);
35
+ }
36
+ return { limit: Number(limit), ...(cursor !== undefined ? { cursor } : {}) };
37
+ }
38
+ exports.parsePage = parsePage;
39
+ function encode(value) {
40
+ return Buffer.from(JSON.stringify(value)).toString('base64url');
41
+ }
42
+ function decode(cursor) {
43
+ try {
44
+ return JSON.parse(Buffer.from(cursor, 'base64url').toString());
45
+ }
46
+ catch {
47
+ throw new ListParamError('cursor: not one this server answered');
48
+ }
49
+ }
50
+ const before = (a, b) => a[0] < b[0] || (a[0] === b[0] && a[1] < b[1]);
51
+ function newestFirst(items, keyOf) {
52
+ return [...items].sort((a, b) => {
53
+ const x = keyOf(a);
54
+ const y = keyOf(b);
55
+ return before(x, y) ? 1 : before(y, x) ? -1 : 0;
56
+ });
57
+ }
58
+ exports.newestFirst = newestFirst;
59
+ /**
60
+ * A page of a list ordered newest first, by the time `keyOf` gives (newestFirst, or the order
61
+ * it was kept in): the cursor names the last one answered, by its time and id, so what is
62
+ * added meanwhile does not repeat one. When the last one answered is gone, the page goes on
63
+ * with the ones older than it.
64
+ */
65
+ function pageByKey(items, page, keyOf) {
66
+ let start = 0;
67
+ if (page.cursor !== undefined) {
68
+ const after = decode(page.cursor);
69
+ if (!Array.isArray(after) || after.length !== 2 || !after.every((part) => typeof part === 'string')) {
70
+ throw new ListParamError('cursor: not one this server answered');
71
+ }
72
+ const [at, id] = after;
73
+ const last = items.findIndex((item) => keyOf(item)[1] === id);
74
+ start = last >= 0 ? last + 1 : items.findIndex((item) => keyOf(item)[0] < at);
75
+ if (start < 0) {
76
+ return { items: [] };
77
+ }
78
+ }
79
+ const answered = items.slice(start, start + page.limit);
80
+ const more = start + page.limit < items.length;
81
+ return { items: answered, ...(more ? { next: encode(keyOf(answered[answered.length - 1])) } : {}) };
82
+ }
83
+ exports.pageByKey = pageByKey;
84
+ // A page of a list in an order of its own, such as numbers sorted by a column: by position.
85
+ function pageByPosition(items, page) {
86
+ let start = 0;
87
+ if (page.cursor !== undefined) {
88
+ const at = decode(page.cursor);
89
+ if (typeof at !== 'object' || at === null || !Number.isSafeInteger(at.at)) {
90
+ throw new ListParamError('cursor: not one this server answered');
91
+ }
92
+ start = Math.max(0, at.at);
93
+ }
94
+ const end = start + page.limit;
95
+ return { items: items.slice(start, end), ...(end < items.length ? { next: encode({ at: end }) } : {}) };
96
+ }
97
+ exports.pageByPosition = pageByPosition;
98
+ // The answer of a page: the list under its name, and `next` while more remain.
99
+ function answerPage(name, page) {
100
+ return { [name]: page.items, ...(page.next ? { next: page.next } : {}) };
101
+ }
102
+ exports.answerPage = answerPage;
103
+ // `values`, `search`, `limit` and `cursor`: undefined when the caller asks for the list.
104
+ function parseValues(params, fields) {
105
+ const field = params.get('values');
106
+ if (field === null) {
107
+ return undefined;
108
+ }
109
+ if (!fields.includes(field)) {
110
+ throw new ListParamError(`values: one of ${fields.join(', ')}`);
111
+ }
112
+ const search = params.get('search')?.trim().slice(0, 200);
113
+ return {
114
+ field: field,
115
+ ...(search ? { search } : {}),
116
+ page: parsePage(params, exports.VALUES_LIMIT),
117
+ };
118
+ }
119
+ exports.parseValues = parseValues;
120
+ /**
121
+ * The values `of` gives the items, each with how many items have it: the most first, then by
122
+ * name, or in the order of `order`; narrowed by the search and paged by position.
123
+ */
124
+ function countValues(items, of, request, order) {
125
+ const counts = new Map();
126
+ for (const item of items) {
127
+ const seen = new Set();
128
+ for (const found of of(item)) {
129
+ const { value, name } = typeof found === 'string' ? { value: found, name: undefined } : found;
130
+ if (seen.has(value)) {
131
+ continue;
132
+ }
133
+ seen.add(value);
134
+ const counted = counts.get(value) ?? { value, count: 0, ...(name ? { name } : {}) };
135
+ counted.count++;
136
+ counts.set(value, counted);
137
+ }
138
+ }
139
+ const needle = request.search?.toLowerCase();
140
+ const values = [...counts.values()]
141
+ .filter((counted) => !needle || counted.value.toLowerCase().includes(needle) || (counted.name ?? '').toLowerCase().includes(needle))
142
+ .sort((a, b) => order ? order.indexOf(a.value) - order.indexOf(b.value) : b.count - a.count || a.value.localeCompare(b.value));
143
+ return pageByPosition(values, request.page);
144
+ }
145
+ exports.countValues = countValues;
146
+ // The values of a filter the caller names: the parameter repeated, `state=queued&state=running`.
147
+ function readList(params, name) {
148
+ const values = params
149
+ .getAll(name)
150
+ .map((value) => value.trim())
151
+ .filter(Boolean);
152
+ return values.length > 0 ? values : undefined;
153
+ }
154
+ exports.readList = readList;
155
+ // the text a list is searched for: `q`, at most 200 characters
156
+ function readText(params) {
157
+ const text = params.get('q')?.trim().slice(0, 200);
158
+ return text ? text : undefined;
159
+ }
160
+ exports.readText = readText;
161
+ // Whether any of the values has the text in it, in any case.
162
+ function hasText(values, text) {
163
+ const needle = text.toLowerCase();
164
+ return values.some((value) => !!value && value.toLowerCase().includes(needle));
165
+ }
166
+ exports.hasText = hasText;
167
+ //# sourceMappingURL=paging.js.map
@@ -19,6 +19,7 @@ const parse_error_1 = require("../schema/parse-error");
19
19
  const task_arguments_1 = require("../planner/utils/task-arguments");
20
20
  const work_network_1 = require("../planner/work-network");
21
21
  const run_source_envs_1 = require("../environment/run-source-envs");
22
+ const prefetch_secrets_1 = require("../secrets/prefetch-secrets");
22
23
  class DefinitionError extends Error {
23
24
  }
24
25
  exports.DefinitionError = DefinitionError;
@@ -167,6 +168,9 @@ function describeSecret(secret) {
167
168
  if (source.type === 'provider') {
168
169
  return { from: `${source.provider}:${source.ref}`, account: source.account, target };
169
170
  }
171
+ if (source.type === 'unavailable') {
172
+ return { from: source.from, account: null, target };
173
+ }
170
174
  return { from: source.type === 'env' ? `env:${source.name}` : `file:${source.path}`, account: null, target };
171
175
  }
172
176
  // What a server refuses to publish. A secret that reads a file or a variable of the
@@ -335,7 +339,14 @@ function toPlan(root, item) {
335
339
  const mounts = (0, work_task_1.isContainerWorkTask)(data) || (0, work_service_1.isContainerWorkService)(data)
336
340
  ? data.mounts.map((mount) => {
337
341
  const inside = insideBundle(root, data.cwd, mount.localPath);
338
- return `${inside.length > 0 ? inside[0] : mount.localPath}:${mount.containerPath}${mount.readOnly ? ':ro' : ''}`;
342
+ const readOnly = mount.readOnly ? ':ro' : '';
343
+ // a mount that names only its source (`- .`) lands at the same path in the container,
344
+ // which is in the directory the server read the bundle in, one of its own each time:
345
+ // such a mount is named as the build file names it
346
+ if (inside.length > 0 && mount.containerPath === (0, path_1.resolve)(data.cwd, mount.localPath)) {
347
+ return `${inside[0]}${readOnly}`;
348
+ }
349
+ return `${inside.length > 0 ? inside[0] : mount.localPath}:${mount.containerPath}${readOnly}`;
339
350
  })
340
351
  : [];
341
352
  const ports = 'ports' in data ? data.ports.map((port) => `${port.hostPort ?? ''}:${port.containerPort}`) : [];
@@ -423,6 +434,10 @@ async function planBundle(bundle, environment, options = {}) {
423
434
  }
424
435
  const context = await (0, reference_parser_1.parseReferences)(ctx, scope, inspected);
425
436
  const workTree = (0, work_scope_parser_1.getWorkContext)(context, options.scope ?? { environmentName: null }, inspected);
437
+ // the server's providers and accounts are the ones that count: a task it could never read
438
+ // a secret of is refused when it is published, and a run when it is planned (only the
439
+ // tasks and services of the run count then)
440
+ (0, prefetch_secrets_1.requireReadableSecrets)(workTree);
426
441
  const items = itemsOf(workTree);
427
442
  if (options.policy) {
428
443
  const policyProblems = findPolicyProblems(items, options.policy, directory);
@@ -9,7 +9,7 @@ const COMMIT = /^[0-9a-f]{40}([0-9a-f]{24})?$/i;
9
9
  // repository, and the branch or tag and the commit it was pinned to, or the repository and the
10
10
  // sandbox. None of them is a credential, so a task that reads them still takes arguments and
11
11
  // keeps its network (see PLAIN_SERVER_ENVS). A sandbox has no commit: its files may hold
12
- // changes. A run from an upload has none of them.
12
+ // changes. A run from an upload has none of them. Each is a name of RUN_SOURCE_ENVS.
13
13
  function runSourceEnvironment(source) {
14
14
  if (source.type === 'ref') {
15
15
  return {
@@ -76,10 +76,14 @@ const searchSchema = zod_1.z.preprocess((body) => {
76
76
  * PUT /v1/sandboxes/<id>/files/<path> write bytes, If-Match: "<sha256>"
77
77
  * POST /v1/sandboxes/<id>/search ripgrep
78
78
  * POST /v1/sandboxes/<id>/edits { dryRun, ops }, all or nothing
79
- * GET /v1/sandboxes/<id>/changes?format=summary|diff|patch
79
+ * GET /v1/sandboxes/<id>/changes?format=summary|diff|patch (diff: &path=… for some files)
80
80
  *
81
81
  * Reading a file works at any time. Writes, and the reads that walk the files (tree, search,
82
82
  * changes), are `409` while a run holds the sandbox.
83
+ *
84
+ * Who may read the sandbox, its owner and who observes, was decided by `handleSandboxes`:
85
+ * reads go as its owner. Writes go as the caller, so the registry answers anybody but the
86
+ * owner `404`.
83
87
  */
84
88
  async function handleSandboxFiles(sandboxes, log, principal, sandbox, action, path, req, res, url) {
85
89
  const who = `iss=${principal.iss} sub=${principal.sub}`;
@@ -99,7 +103,7 @@ async function handleSandboxFiles(sandboxes, log, principal, sandbox, action, pa
99
103
  limit: intParam(url, 'limit'),
100
104
  cursor: url.searchParams.get('cursor') ?? undefined,
101
105
  };
102
- const tree = await sandboxes.read(principal, sandbox.id, (files) => files.tree(query));
106
+ const tree = await sandboxes.read(sandbox.owner, sandbox.id, (files) => files.tree(query));
103
107
  (0, http_1.send)(res, 200, tree);
104
108
  }
105
109
  else if (action === 'search') {
@@ -107,7 +111,7 @@ async function handleSandboxFiles(sandboxes, log, principal, sandbox, action, pa
107
111
  return (0, http_1.send)(res, 405, { error: 'method not allowed' }, { allow: 'POST' });
108
112
  }
109
113
  const query = parse(searchSchema, await (0, http_1.readJson)(req));
110
- (0, http_1.send)(res, 200, await sandboxes.read(principal, sandbox.id, (files) => files.search(query)));
114
+ (0, http_1.send)(res, 200, await sandboxes.read(sandbox.owner, sandbox.id, (files) => files.search(query)));
111
115
  }
112
116
  else if (action === 'edits') {
113
117
  if (method !== 'POST') {
@@ -124,7 +128,7 @@ async function handleSandboxFiles(sandboxes, log, principal, sandbox, action, pa
124
128
  if (method !== 'GET') {
125
129
  return (0, http_1.send)(res, 405, { error: 'method not allowed' }, { allow: 'GET' });
126
130
  }
127
- await handleChanges(sandboxes, principal, sandbox, res, url);
131
+ await handleChanges(sandboxes, sandbox, res, url);
128
132
  }
129
133
  }
130
134
  catch (e) {
@@ -140,9 +144,10 @@ async function handleSandboxFiles(sandboxes, log, principal, sandbox, action, pa
140
144
  exports.handleSandboxFiles = handleSandboxFiles;
141
145
  async function handleFile(sandboxes, log, principal, sandbox, path, req, res, url) {
142
146
  const method = req.method;
143
- const files = sandboxes.files(principal, sandbox.id);
147
+ // reading, as its owner
148
+ const files = () => sandboxes.files(sandbox.owner, sandbox.id);
144
149
  if (method === 'HEAD') {
145
- const stat = await files.stat(path);
150
+ const stat = await files().stat(path);
146
151
  if (!stat) {
147
152
  res.writeHead(404, { 'cache-control': 'no-store' });
148
153
  res.end();
@@ -153,11 +158,11 @@ async function handleFile(sandboxes, log, principal, sandbox, path, req, res, ur
153
158
  }
154
159
  else if (method === 'GET') {
155
160
  if (url.searchParams.has('stat')) {
156
- const stat = await files.stat(path);
161
+ const stat = await files().stat(path);
157
162
  return stat ? (0, http_1.send)(res, 200, stat) : (0, http_1.send)(res, 404, { error: `${path} does not exist` });
158
163
  }
159
164
  if (url.searchParams.has('raw')) {
160
- const raw = await files.raw(path);
165
+ const raw = await files().raw(path);
161
166
  const headers = { ...statHeaders(raw.stat), 'content-type': 'application/octet-stream' };
162
167
  if (raw.content) {
163
168
  res.writeHead(200, { ...headers, etag: `"${raw.sha256}"` });
@@ -179,7 +184,7 @@ async function handleFile(sandboxes, log, principal, sandbox, path, req, res, ur
179
184
  });
180
185
  return;
181
186
  }
182
- (0, http_1.send)(res, 200, await files.read(path, { offset: intParam(url, 'offset'), limit: intParam(url, 'limit') }));
187
+ (0, http_1.send)(res, 200, await files().read(path, { offset: intParam(url, 'offset'), limit: intParam(url, 'limit') }));
183
188
  }
184
189
  else if (method === 'PUT') {
185
190
  const content = await readBytes(req, sandbox_files_1.MAX_FILE_BYTES);
@@ -198,10 +203,12 @@ async function handleFile(sandboxes, log, principal, sandbox, path, req, res, ur
198
203
  (0, http_1.send)(res, 405, { error: 'method not allowed' }, { allow: 'GET, HEAD, PUT' });
199
204
  }
200
205
  }
201
- async function handleChanges(sandboxes, principal, sandbox, res, url) {
206
+ // the most files one diff may name
207
+ const MAX_DIFF_PATHS = 100;
208
+ async function handleChanges(sandboxes, sandbox, res, url) {
202
209
  const format = url.searchParams.get('format') ?? 'summary';
203
210
  if (format === 'summary') {
204
- const files = await sandboxes.read(principal, sandbox.id, (files) => files.changes());
211
+ const files = await sandboxes.read(sandbox.owner, sandbox.id, (files) => files.changes());
205
212
  return (0, http_1.send)(res, 200, { commit: sandbox.commit, files });
206
213
  }
207
214
  if (format !== 'diff' && format !== 'patch') {
@@ -212,7 +219,15 @@ async function handleChanges(sandboxes, principal, sandbox, res, url) {
212
219
  email: textParam(url, 'email') ?? 'hammerkit@localhost',
213
220
  message: textParam(url, 'message', 4000, true) ?? `Changes of sandbox ${sandbox.id}`,
214
221
  };
215
- const text = await sandboxes.read(principal, sandbox.id, (files) => files.diff(format, author));
222
+ // the diff of some files only, as a list of changes opens one; a rename names both its paths
223
+ const paths = url.searchParams.getAll('path');
224
+ if (paths.length > 0 && format !== 'diff') {
225
+ return (0, http_1.send)(res, 400, { error: 'path: only a diff takes paths, a patch is whole' });
226
+ }
227
+ if (paths.length > MAX_DIFF_PATHS || paths.some((path) => path === '' || path.length > 4096 || path.includes('\0'))) {
228
+ return (0, http_1.send)(res, 400, { error: `path: at most ${MAX_DIFF_PATHS}, each a path of the sandbox` });
229
+ }
230
+ const text = await sandboxes.read(sandbox.owner, sandbox.id, (files) => files.diff(format, author, paths.length > 0 ? paths : undefined));
216
231
  res.writeHead(200, { 'content-type': 'text/x-diff; charset=utf-8', 'cache-control': 'no-store' });
217
232
  res.end(text);
218
233
  }
@@ -822,10 +822,11 @@ class HostSandboxFiles {
822
822
  return files;
823
823
  });
824
824
  }
825
- async diff(format, author) {
825
+ async diff(format, author, paths) {
826
826
  return this.withFilesIndex(async (run) => {
827
827
  if (format === 'diff') {
828
- return run(['diff', '--cached', '-M', 'HEAD'], 'read', { maxBuffer: this.maxChangesBytes });
828
+ const only = paths && paths.length > 0 ? ['--', ...paths.map((path) => `:(literal)${path}`)] : [];
829
+ return run(['diff', '--cached', '-M', 'HEAD', ...only], 'read', { maxBuffer: this.maxChangesBytes });
829
830
  }
830
831
  // a commit of the changes on top of the commit the sandbox is at, which no branch
831
832
  // points to, written out as `git format-patch` writes it
@@ -80,7 +80,7 @@ async function answer(storage, directory, request, out) {
80
80
  case 'changes':
81
81
  return send(await files().changes());
82
82
  case 'diff':
83
- return send(await files().diff(request.format, request.author));
83
+ return send(await files().diff(request.format, request.author, request.paths));
84
84
  case 'commit':
85
85
  return send((await storage.commit(key, request.author, AbortSignal.timeout(10 * 60000))) ?? null);
86
86
  case 'move':
@@ -8,6 +8,7 @@ const repo_1 = require("./repo");
8
8
  const runs_1 = require("./runs");
9
9
  const sandbox_files_api_1 = require("./sandbox-files-api");
10
10
  const sandboxes_1 = require("./sandboxes");
11
+ const paging_1 = require("./paging");
11
12
  const refSchema = zod_1.z.string().min(1).max(200);
12
13
  const createSchema = zod_1.z
13
14
  .object({
@@ -45,7 +46,11 @@ const pushSchema = zod_1.z
45
46
  * The sandboxes of a caller: checkouts on the server that runs work on.
46
47
  *
47
48
  * POST /v1/sandboxes { repo, ref } fetch a branch into a new sandbox
48
- * GET /v1/sandboxes the caller's sandboxes, their limits and usage
49
+ * GET /v1/sandboxes the caller's sandboxes, their limits and usage;
50
+ * `?scope=all` everybody's, with `observe`; `owner`,
51
+ * `repo` and `ref` narrow them, `limit` and `cursor`
52
+ * page them the last used first, `values=<field>`
53
+ * answers the values of a filter (paging.ts)
49
54
  * GET /v1/sandboxes/<id> one sandbox
50
55
  * DELETE /v1/sandboxes/<id> cancel its runs and remove it
51
56
  * POST /v1/sandboxes/<id>/fetch { ref } move a sandbox without changes to a branch's commit
@@ -53,7 +58,10 @@ const pushSchema = zod_1.z
53
58
  * ... /v1/sandboxes/<id>/tree, files/<path>, search, edits, changes: its files, see
54
59
  * `handleSandboxFiles`
55
60
  *
56
- * A sandbox is its owner's: anybody else gets `404`.
61
+ * A sandbox is its owner's: anybody else gets `404`. Who observes (`observe` on an
62
+ * entitlement) may read every sandbox, as they read every run: list them, and get one, its
63
+ * tree, files, search and changes. Everything that changes a sandbox or runs on it stays
64
+ * its owner's, and is `404` to them too.
57
65
  */
58
66
  async function handleSandboxes(config, sandboxes, repos, log, principal, req, res, url) {
59
67
  const match = /^\/v1\/sandboxes(?:\/([^/]+)(?:\/(fetch|push|tree|search|edits|changes)|\/(files)\/(.+))?)?$/.exec(url.pathname);
@@ -64,15 +72,28 @@ async function handleSandboxes(config, sandboxes, repos, log, principal, req, re
64
72
  const action = named ?? files;
65
73
  const method = req.method;
66
74
  const who = `iss=${principal.iss} sub=${principal.sub}`;
75
+ const show = (sandbox) => view(config, sandboxes, principal, sandbox);
67
76
  try {
68
77
  if (!id) {
69
78
  if (method === 'GET') {
70
- const limits = sandboxes.limits;
71
- (0, http_1.send)(res, 200, {
72
- sandboxes: sandboxes.list(principal).map((sandbox) => view(sandboxes, sandbox)),
73
- limits: { count: limits.count, bytes: limits.bytes },
74
- used: sandboxes.usage(principal),
75
- });
79
+ const scope = url.searchParams.get('scope') ?? 'mine';
80
+ if (scope !== 'mine' && scope !== 'all') {
81
+ (0, http_1.send)(res, 400, { error: 'scope: mine or all' });
82
+ return true;
83
+ }
84
+ if (scope === 'all' && !(0, policy_1.getGrant)(config.entitlements, principal).observe) {
85
+ (0, http_1.send)(res, 403, { error: 'scope all needs an entitlement with observe' });
86
+ return true;
87
+ }
88
+ try {
89
+ listSandboxes(config, sandboxes, principal, scope, url.searchParams, res, show);
90
+ }
91
+ catch (e) {
92
+ if (!(e instanceof paging_1.ListParamError)) {
93
+ throw e;
94
+ }
95
+ (0, http_1.send)(res, 400, { error: e.message });
96
+ }
76
97
  }
77
98
  else if (method === 'POST') {
78
99
  const body = parse(createSchema, await (0, http_1.readJson)(req));
@@ -84,21 +105,29 @@ async function handleSandboxes(config, sandboxes, repos, log, principal, req, re
84
105
  }
85
106
  const sandbox = await sandboxes.create(principal, body.repo, body.ref);
86
107
  log(`sandbox create ${sandbox.id} ${who} repo=${sandbox.repo} commit=${sandbox.commit} bytes=${sandbox.bytes}`);
87
- (0, http_1.send)(res, 201, view(sandboxes, sandbox));
108
+ (0, http_1.send)(res, 201, show(sandbox));
88
109
  }
89
110
  else {
90
111
  (0, http_1.send)(res, 405, { error: 'method not allowed' }, { allow: 'GET, POST' });
91
112
  }
92
113
  return true;
93
114
  }
94
- const sandbox = runs_1.SANDBOX_ID_PATTERN.test(id) ? sandboxes.get(principal, id) : undefined;
115
+ const known = runs_1.SANDBOX_ID_PATTERN.test(id);
116
+ const own = known ? sandboxes.get(principal, id) : undefined;
117
+ const observes = (0, policy_1.getGrant)(config.entitlements, principal).observe;
118
+ const reading = isRead(action, method);
119
+ // who observes reads the sandbox of anybody; a change is for its owner, and else not found
120
+ const sandbox = own ?? (known && observes && reading ? sandboxes.peek(id) : undefined);
95
121
  if (!sandbox) {
96
122
  (0, http_1.send)(res, 404, { error: 'not found' });
97
123
  return true;
98
124
  }
99
125
  if (action && action !== 'fetch' && action !== 'push') {
100
- // the caller may have lost the repository, or the sandbox's branch, since they created it
101
- const refused = (0, policy_1.decideSandbox)((0, policy_1.getGrant)(config.entitlements, principal), sandbox.repo, sandbox.ref, (repo) => repos.readable(repo));
126
+ // the owner may have lost the repository, or the sandbox's branch, since they created
127
+ // it; who observes reads it all the same
128
+ const refused = own && !(observes && reading)
129
+ ? (0, policy_1.decideSandbox)((0, policy_1.getGrant)(config.entitlements, principal), sandbox.repo, sandbox.ref, (repo) => repos.readable(repo))
130
+ : undefined;
102
131
  if (refused) {
103
132
  log(`refuse sandbox ${action} ${id} ${who}: ${refused.error}`);
104
133
  (0, http_1.send)(res, refused.status, { error: refused.error });
@@ -133,15 +162,15 @@ async function handleSandboxes(config, sandboxes, repos, log, principal, req, re
133
162
  if ('branch' in body) {
134
163
  const pushed = await sandboxes.push(principal, id, body.branch, { ...author(principal), message: body.message }, (0, policy_1.sandboxPushBranches)(grant, sandbox.repo));
135
164
  log(`sandbox push ${id} ${who} branch=${body.branch} commit=${pushed.commit}`);
136
- (0, http_1.send)(res, 200, { branch: body.branch, commit: pushed.commit, sandbox: view(sandboxes, pushed) });
165
+ (0, http_1.send)(res, 200, { branch: body.branch, commit: pushed.commit, sandbox: show(pushed) });
137
166
  return true;
138
167
  }
139
168
  const fetched = await sandboxes.fetch(principal, id, body.ref);
140
169
  log(`sandbox fetch ${id} ${who} ref=${body.ref} commit=${fetched.commit}`);
141
- (0, http_1.send)(res, 200, view(sandboxes, fetched));
170
+ (0, http_1.send)(res, 200, show(fetched));
142
171
  }
143
172
  else if (method === 'GET') {
144
- (0, http_1.send)(res, 200, view(sandboxes, sandbox));
173
+ (0, http_1.send)(res, 200, show(sandbox));
145
174
  }
146
175
  else if (method === 'DELETE') {
147
176
  // a caller who lost the entitlement can still delete what they keep
@@ -206,11 +235,79 @@ function author(principal) {
206
235
  return { name, email: `${local}@${host}` };
207
236
  }
208
237
  exports.author = author;
209
- // What the owner sees: everything but the owner, and the run that holds it.
210
- function view(sandboxes, sandbox) {
238
+ /**
239
+ * Whether a request only reads a sandbox, which who observes may: the sandbox, its tree, a
240
+ * file, a search and its changes. Edits, a write of a file, a fetch, a push and a delete
241
+ * change it.
242
+ */
243
+ function isRead(action, method) {
244
+ switch (action) {
245
+ case undefined:
246
+ return method === 'GET';
247
+ case 'tree':
248
+ case 'changes':
249
+ return method === 'GET';
250
+ case 'files':
251
+ return method === 'GET' || method === 'HEAD';
252
+ case 'search':
253
+ // ripgrep's query is a body
254
+ return method === 'POST';
255
+ default:
256
+ return false;
257
+ }
258
+ }
259
+ // A sandbox as the caller sees it, and the run that holds it: their own without its owner,
260
+ // one of somebody else (who observes) with whose it is, as a run of somebody else names it.
261
+ function view(config, sandboxes, principal, sandbox) {
211
262
  const { owner, ...visible } = sandbox;
212
- void owner;
213
263
  const run = sandboxes.holder(sandbox.id);
214
- return { ...visible, busy: run !== undefined, run: run ?? null };
264
+ const mine = owner.iss === principal.iss && owner.sub === principal.sub;
265
+ const name = owner.name ?? (0, policy_1.subjectName)(config.entitlements, owner);
266
+ return {
267
+ ...visible,
268
+ ...(mine ? {} : { owner: { iss: owner.iss, sub: owner.sub, ...(name ? { name } : {}) } }),
269
+ busy: run !== undefined,
270
+ run: run ?? null,
271
+ };
272
+ }
273
+ // what the sandboxes page narrows by, and GET /v1/sandboxes?values= answers the values of
274
+ const SANDBOX_FIELDS = ['owner', 'repo', 'ref'];
275
+ function parseSandboxFilter(params) {
276
+ return Object.fromEntries(SANDBOX_FIELDS.map((field) => [field, (0, paging_1.readList)(params, field)]).filter(([, values]) => values));
277
+ }
278
+ function filterSandboxes(sandboxes, filter) {
279
+ return sandboxes.filter((sandbox) => (!filter.owner || filter.owner.includes(sandbox.owner.sub)) &&
280
+ (!filter.repo || filter.repo.includes(sandbox.repo)) &&
281
+ (!filter.ref || filter.ref.includes(sandbox.ref)));
282
+ }
283
+ // the last used first, as the sandboxes page shows them
284
+ const sandboxKey = (sandbox) => [sandbox.lastUsedAt, sandbox.id];
285
+ function pageOfSandboxes(sandboxes, page, show) {
286
+ const answered = (0, paging_1.pageByKey)((0, paging_1.newestFirst)(sandboxes, sandboxKey), page, sandboxKey);
287
+ return { ...answered, items: answered.items.map(show) };
288
+ }
289
+ // GET /v1/sandboxes: the sandboxes of the scope that the filters let through, a page of them,
290
+ // or the values of a filter.
291
+ function listSandboxes(config, sandboxes, principal, scope, params, res, show) {
292
+ const filter = parseSandboxFilter(params);
293
+ const values = (0, paging_1.parseValues)(params, SANDBOX_FIELDS);
294
+ const page = values ? undefined : (0, paging_1.parsePage)(params);
295
+ const listed = scope === 'all' ? sandboxes.all() : sandboxes.list(principal);
296
+ const nameOf = (owner) => owner.name ?? (0, policy_1.subjectName)(config.entitlements, owner);
297
+ if (values) {
298
+ // a value of the field is counted over the sandboxes the other filters let through
299
+ const { field } = values;
300
+ const counted = (0, paging_1.countValues)(filterSandboxes(listed, { ...filter, [field]: undefined }), (sandbox) => [field === 'owner' ? { value: sandbox.owner.sub, name: nameOf(sandbox.owner) } : sandbox[field]], values);
301
+ (0, http_1.send)(res, 200, (0, paging_1.answerPage)('values', counted));
302
+ return;
303
+ }
304
+ const found = filterSandboxes(listed, filter);
305
+ const limits = sandboxes.limits;
306
+ // the limits and the usage are the caller's, whichever sandboxes they list
307
+ (0, http_1.send)(res, 200, {
308
+ ...(page ? (0, paging_1.answerPage)('sandboxes', pageOfSandboxes(found, page, show)) : { sandboxes: found.map(show) }),
309
+ limits: { count: limits.count, bytes: limits.bytes },
310
+ used: sandboxes.usage(principal),
311
+ });
215
312
  }
216
313
  //# sourceMappingURL=sandboxes-api.js.map
@@ -6,6 +6,7 @@ const promises_1 = require("fs/promises");
6
6
  const path_1 = require("path");
7
7
  const units_1 = require("../utils/units");
8
8
  const git_checkout_1 = require("./git-checkout");
9
+ const oauth_1 = require("./oauth");
9
10
  const runs_1 = require("./runs");
10
11
  const repo_1 = require("./repo");
11
12
  const sandbox_storage_1 = require("./sandbox-storage");
@@ -22,7 +23,8 @@ class SandboxError extends Error {
22
23
  exports.SandboxError = SandboxError;
23
24
  /**
24
25
  * The sandboxes of a server: who owns which, the limits, and one change at a time per
25
- * sandbox. Everything is scoped to the owner: somebody else's sandbox is "not found".
26
+ * sandbox. Everything is scoped to the owner: somebody else's sandbox is "not found". Only
27
+ * `all` and `peek` show the sandboxes of everybody, for who may read them (`observe`).
26
28
  */
27
29
  class SandboxRegistry {
28
30
  constructor(options) {
@@ -111,6 +113,18 @@ class SandboxRegistry {
111
113
  const sandbox = this.sandboxes.get(id);
112
114
  return sandbox && owns(owner, sandbox) && !this.deleting.has(id) ? copy(sandbox) : undefined;
113
115
  }
116
+ // The sandboxes of everybody, oldest first: what who observes sees.
117
+ all() {
118
+ return [...this.sandboxes.values()]
119
+ .filter((sandbox) => !this.deleting.has(sandbox.id))
120
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt))
121
+ .map(copy);
122
+ }
123
+ // A sandbox of anybody, for who observes: to read, never to change.
124
+ peek(id) {
125
+ const sandbox = this.sandboxes.get(id);
126
+ return sandbox && !this.deleting.has(id) ? copy(sandbox) : undefined;
127
+ }
114
128
  holder(id) {
115
129
  return this.runs.holder(id);
116
130
  }
@@ -188,9 +202,10 @@ class SandboxRegistry {
188
202
  }
189
203
  this.creating.set(id, { owner: { iss: owner.iss, sub: owner.sub }, bytes });
190
204
  const at = this.timestamp();
205
+ const name = (0, oauth_1.displayName)(owner);
191
206
  const sandbox = {
192
207
  id,
193
- owner: { iss: owner.iss, sub: owner.sub },
208
+ owner: { iss: owner.iss, sub: owner.sub, ...(name ? { name } : {}) },
194
209
  repo,
195
210
  ref,
196
211
  commit,
@@ -548,8 +563,9 @@ function owns(owner, sandbox) {
548
563
  const of = 'owner' in sandbox ? sandbox.owner : sandbox;
549
564
  return of.iss === owner.iss && of.sub === owner.sub;
550
565
  }
566
+ // what the storage keeps a sandbox by: its owner's identity, not the name they had
551
567
  function keyOf(sandbox) {
552
- return { id: sandbox.id, owner: sandbox.owner };
568
+ return { id: sandbox.id, owner: { iss: sandbox.owner.iss, sub: sandbox.owner.sub } };
553
569
  }
554
570
  function copy(sandbox) {
555
571
  return {