hammerkit 2.2.0-next.5 → 2.2.0-next.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/harness/sandbox-client.js +51 -5
- package/dist/kubernetes/sandbox-runner.js +76 -31
- package/dist/kubernetes/sync-changes.js +9 -2
- package/dist/server/executor.js +83 -15
- package/dist/server/git-checkout.js +74 -2
- package/dist/server/policy.js +46 -1
- package/dist/server/repo-access.js +48 -1
- package/dist/server/run-worker.js +38 -3
- package/dist/server/sandbox-files-api.js +15 -1
- package/dist/server/sandbox-files.js +21 -8
- package/dist/server/server-config.js +16 -0
- package/dist/server/server.js +43 -6
- package/package.json +1 -1
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.request = exports.quotePosix = exports.fetchFailure = exports.toSandboxPath = exports.checkSandboxPath = exports.exitCodeOf = exports.readRunLog = exports.downloadRunArtifact = exports.getRunArtifacts = exports.getRun = exports.followRun = exports.getMoveTarget = exports.lookupChecks = exports.submitRun = exports.FINAL_RUN_STATES = exports.readTextUpTo = exports.oneAtATime = exports.SandboxClient = exports.listPublishedTasks = exports.runCheck = exports.CHECK_DESCRIPTION = exports.getServerConnection = exports.SandboxClientError = exports.MAX_ENDPOINT_BYTES = void 0;
|
|
4
4
|
const crypto_1 = require("crypto");
|
|
5
5
|
const path_1 = require("path");
|
|
6
|
+
const sandbox_patch_1 = require("../server/sandbox-patch");
|
|
6
7
|
const token_source_1 = require("../remote/token-source");
|
|
7
8
|
const reconnect_1 = require("./reconnect");
|
|
8
9
|
const fs_1 = require("fs");
|
|
@@ -339,20 +340,38 @@ class SandboxClient {
|
|
|
339
340
|
// The ops of an edit as they go to the server, with the paths the server checks. The first op on
|
|
340
341
|
// a file carries the hash the agent read of it. The server checks a file as the edit has changed
|
|
341
342
|
// it so far, so an op after one that changed its file, a move's destination included, or after a
|
|
342
|
-
// patch
|
|
343
|
+
// patch that changed it, carries none. A patch carries the hash of each file it reads, and a
|
|
344
|
+
// patch this client cannot read leaves the files of the batch unknown, so the ops after it carry
|
|
345
|
+
// none. An invalid path goes as it is.
|
|
343
346
|
withHashes(ops) {
|
|
344
347
|
const changed = new Set();
|
|
345
|
-
let
|
|
348
|
+
let unknown = false;
|
|
346
349
|
return ops.map((op) => {
|
|
347
350
|
if (op.op === 'patch') {
|
|
348
|
-
|
|
349
|
-
|
|
351
|
+
const files = patchFiles(op.patch);
|
|
352
|
+
if (files === undefined) {
|
|
353
|
+
unknown = true;
|
|
354
|
+
return op;
|
|
355
|
+
}
|
|
356
|
+
const hashes = {};
|
|
357
|
+
for (const key of files.read) {
|
|
358
|
+
const hash = !unknown && !changed.has(key) ? this.seen.get(key) : undefined;
|
|
359
|
+
if (hash !== undefined) {
|
|
360
|
+
hashes[key] = hash;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
for (const key of files.changed) {
|
|
364
|
+
changed.add(key);
|
|
365
|
+
}
|
|
366
|
+
// the hashes the caller gave win over the ones read here
|
|
367
|
+
const merged = { ...hashes, ...op.ifHash };
|
|
368
|
+
return Object.keys(merged).length > 0 ? { ...op, ifHash: merged } : op;
|
|
350
369
|
}
|
|
351
370
|
const key = fileKey(op.path);
|
|
352
371
|
if (key === undefined) {
|
|
353
372
|
return op;
|
|
354
373
|
}
|
|
355
|
-
const hash = !
|
|
374
|
+
const hash = !unknown && !changed.has(key) ? this.seen.get(key) : undefined;
|
|
356
375
|
changed.add(key);
|
|
357
376
|
const to = op.op === 'move' ? fileKey(op.to) : undefined;
|
|
358
377
|
if (to !== undefined) {
|
|
@@ -390,6 +409,33 @@ function fileKey(path) {
|
|
|
390
409
|
return undefined;
|
|
391
410
|
}
|
|
392
411
|
}
|
|
412
|
+
// The keys of the files a patch reads and of the files it changes; undefined when the patch does
|
|
413
|
+
// not parse. A copy leaves its source as it was, so the source is read but not changed.
|
|
414
|
+
function patchFiles(text) {
|
|
415
|
+
let files;
|
|
416
|
+
try {
|
|
417
|
+
files = (0, sandbox_patch_1.parsePatch)(text);
|
|
418
|
+
}
|
|
419
|
+
catch {
|
|
420
|
+
return undefined;
|
|
421
|
+
}
|
|
422
|
+
const read = [];
|
|
423
|
+
const changed = [];
|
|
424
|
+
for (const file of files) {
|
|
425
|
+
const from = file.from === undefined ? undefined : fileKey(file.from);
|
|
426
|
+
const to = file.to === undefined ? undefined : fileKey(file.to);
|
|
427
|
+
if (from !== undefined) {
|
|
428
|
+
read.push(from);
|
|
429
|
+
if (!file.copy) {
|
|
430
|
+
changed.push(from);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
if (to !== undefined) {
|
|
434
|
+
changed.push(to);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
return { read, changed };
|
|
438
|
+
}
|
|
393
439
|
const SHA256 = /^[0-9a-f]{64}$/;
|
|
394
440
|
function sha256Of(content) {
|
|
395
441
|
return (0, crypto_1.createHash)('sha256').update(content).digest('hex');
|
|
@@ -118,6 +118,13 @@ exports.getRunCommandsDirectory = getRunCommandsDirectory;
|
|
|
118
118
|
const RUNNER_TOOLS = { busybox: BUSYBOX, sandbox: exports.RUNNER_SANDBOX_PATH };
|
|
119
119
|
// How long a command waits for one of its run that still runs before it starts (s)
|
|
120
120
|
const RUN_COMMAND_WAIT = 3600;
|
|
121
|
+
// Time limits of the execs of a runner, which a cancel or a stalled connection must not outlast:
|
|
122
|
+
// an exec that does not connect in EXEC_CONNECT_MS is given up; a start may wait for the commands
|
|
123
|
+
// of its run as long as RUN_COMMAND_WAIT (and a little more); a follow session is opened again
|
|
124
|
+
// after FOLLOW_SESSION_MS, its command may run on (not a failure, see execInRunner)
|
|
125
|
+
const EXEC_CONNECT_MS = 30 * 1000;
|
|
126
|
+
const START_SESSION_MS = (RUN_COMMAND_WAIT + 600) * 1000;
|
|
127
|
+
const FOLLOW_SESSION_MS = 10 * 60 * 1000;
|
|
121
128
|
/**
|
|
122
129
|
* The scripts that start a command in the runner and follow, stop, find and remove the
|
|
123
130
|
* commands of a run, each run as `sh -c <script> hammerkit <args>`. `cleanUp` is what kills
|
|
@@ -766,10 +773,8 @@ root, cwd, command, scripts, where, task, abort) {
|
|
|
766
773
|
...(done ? { done: true } : {}),
|
|
767
774
|
...(cutSaid ? { cut: true } : {}),
|
|
768
775
|
});
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
current = socket;
|
|
772
|
-
};
|
|
776
|
+
// On abort every exec of this command ends with it: start and follow get the signal (runScript),
|
|
777
|
+
// so one that is still connecting, or stalled, is not waited for. The cancel is what kills it.
|
|
773
778
|
const cancel = () => runScript(instance, namespace, pod, scripts.cancel, [directory], { timeout: KILL_TIMEOUT_MS });
|
|
774
779
|
const kill = async () => {
|
|
775
780
|
const killed = await cancel();
|
|
@@ -777,7 +782,6 @@ root, cwd, command, scripts, where, task, abort) {
|
|
|
777
782
|
task.status.write('debug', `the command could not be stopped in the runner, it goes: ${killed.message ?? 'the kill did not end'}`);
|
|
778
783
|
await deletePod(instance, namespace, pod).catch(() => undefined);
|
|
779
784
|
}
|
|
780
|
-
current?.close();
|
|
781
785
|
};
|
|
782
786
|
let killing;
|
|
783
787
|
const aborted = () => {
|
|
@@ -792,7 +796,7 @@ root, cwd, command, scripts, where, task, abort) {
|
|
|
792
796
|
try {
|
|
793
797
|
// a start again after its connection broke takes the command it started, by its nonce
|
|
794
798
|
const nonce = (0, crypto_1.randomBytes)(12).toString('hex');
|
|
795
|
-
const start = (mode) => runScript(instance, namespace, pod, scripts.start, [directory, mode, resumed ? '' : nonce, root, cwd, ...command], {
|
|
799
|
+
const start = (mode) => runScript(instance, namespace, pod, scripts.start, [directory, mode, resumed ? '' : nonce, root, cwd, ...command], { signal: abort, timeout: START_SESSION_MS });
|
|
796
800
|
let started = await start(resumed ? 'adopt' : 'fresh');
|
|
797
801
|
for (let attempt = 0; started.exitCode === undefined && attempt < RECONNECTS && !abort.aborted; attempt++) {
|
|
798
802
|
await (0, sleep_1.sleep)(RUNNER_POLL_MS * 2 ** attempt);
|
|
@@ -876,7 +880,7 @@ root, cwd, command, scripts, where, task, abort) {
|
|
|
876
880
|
const before = offsets.stdout + offsets.stderr;
|
|
877
881
|
const stdout = lines('stdout');
|
|
878
882
|
const stderr = lines('stderr');
|
|
879
|
-
const followed = await runScript(instance, namespace, pod, scripts.follow, [directory, String(offsets.stdout), String(offsets.stderr)], { stdout: stdout.writable, stderr: stderr.writable,
|
|
883
|
+
const followed = await runScript(instance, namespace, pod, scripts.follow, [directory, String(offsets.stdout), String(offsets.stderr)], { stdout: stdout.writable, stderr: stderr.writable, signal: abort, timeout: FOLLOW_SESSION_MS });
|
|
880
884
|
if (abort.aborted) {
|
|
881
885
|
return await stopped();
|
|
882
886
|
}
|
|
@@ -885,8 +889,9 @@ root, cwd, command, scripts, where, task, abort) {
|
|
|
885
889
|
}
|
|
886
890
|
// 0: all of it was said. Else what followed it ended before: the end of the command killed
|
|
887
891
|
// it (137), its connection broke, it failed. It is followed again, a few times in a row
|
|
888
|
-
// without getting further at most: a command that keeps killing what follows it too
|
|
889
|
-
|
|
892
|
+
// without getting further at most: a command that keeps killing what follows it too. A
|
|
893
|
+
// session that ran its time limit is opened again, as a command that runs on is followed.
|
|
894
|
+
if (followed.exitCode !== 0 && !followed.timedOut) {
|
|
890
895
|
failures = offsets.stdout + offsets.stderr > before ? 1 : failures + 1;
|
|
891
896
|
if (failures > RECONNECTS) {
|
|
892
897
|
throw new Error(`the command in the runner of the sandbox could not be followed: ${followed.message ?? `exit code ${followed.exitCode}`}`);
|
|
@@ -940,6 +945,31 @@ async function reconnecting(abort, fn) {
|
|
|
940
945
|
}
|
|
941
946
|
return result;
|
|
942
947
|
}
|
|
948
|
+
// The value of `connecting` once it connects, or undefined when `ms` passed or `signal` aborted
|
|
949
|
+
// first. An exec that connects after that is closed, as nothing waits for it any more.
|
|
950
|
+
function connectWithin(connecting, ms, signal) {
|
|
951
|
+
return new Promise((resolve, reject) => {
|
|
952
|
+
let over = false;
|
|
953
|
+
const onAbort = () => end(() => resolve(undefined));
|
|
954
|
+
const end = (answer) => {
|
|
955
|
+
if (over) {
|
|
956
|
+
return;
|
|
957
|
+
}
|
|
958
|
+
over = true;
|
|
959
|
+
clearTimeout(timer);
|
|
960
|
+
signal?.removeEventListener('abort', onAbort);
|
|
961
|
+
answer();
|
|
962
|
+
};
|
|
963
|
+
const timer = setTimeout(() => end(() => resolve(undefined)), ms);
|
|
964
|
+
if (signal?.aborted) {
|
|
965
|
+
onAbort();
|
|
966
|
+
}
|
|
967
|
+
else {
|
|
968
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
969
|
+
}
|
|
970
|
+
connecting.then((socket) => (over ? socket.close() : end(() => resolve(socket))), (e) => end(() => reject(e)));
|
|
971
|
+
});
|
|
972
|
+
}
|
|
943
973
|
// Runs a script of the runner's busybox with `args` as `$1`… in the runner
|
|
944
974
|
async function runScript(instance, namespace, pod, script, args, options = {}) {
|
|
945
975
|
let out = '';
|
|
@@ -952,34 +982,48 @@ async function runScript(instance, namespace, pod, script, args, options = {}) {
|
|
|
952
982
|
});
|
|
953
983
|
let status;
|
|
954
984
|
let broken;
|
|
985
|
+
let timedOut = false;
|
|
955
986
|
try {
|
|
956
|
-
const
|
|
987
|
+
const connecting = instance.exec.exec(namespace, pod, RUNNER_CONTAINER, [BUSYBOX, 'sh', '-c', script, 'hammerkit', ...args], stdout, options.stderr ?? null, null, false, (received) => {
|
|
957
988
|
status = received;
|
|
958
989
|
});
|
|
959
|
-
options.
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
990
|
+
const socket = await connectWithin(connecting, EXEC_CONNECT_MS, options.signal);
|
|
991
|
+
if (socket) {
|
|
992
|
+
// the end of the exec: its close, an error, the abort or the time limit, whichever comes first
|
|
993
|
+
// (a close that never comes is not waited for)
|
|
994
|
+
// resolves the wait for the exec: at its close, its error, the abort or the time limit
|
|
995
|
+
let resolveClosed = () => undefined;
|
|
996
|
+
const closed = new Promise((resolve) => {
|
|
997
|
+
resolveClosed = resolve;
|
|
998
|
+
socket.on('close', () => resolve());
|
|
999
|
+
socket.on('error', (e) => {
|
|
1000
|
+
broken = e;
|
|
1001
|
+
resolve();
|
|
1002
|
+
});
|
|
965
1003
|
});
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
1004
|
+
const onAbort = () => {
|
|
1005
|
+
socket.close();
|
|
1006
|
+
resolveClosed();
|
|
1007
|
+
};
|
|
1008
|
+
if (options.signal?.aborted) {
|
|
1009
|
+
onAbort();
|
|
1010
|
+
}
|
|
1011
|
+
else {
|
|
1012
|
+
options.signal?.addEventListener('abort', onAbort, { once: true });
|
|
1013
|
+
}
|
|
1014
|
+
const limit = options.timeout && !options.signal?.aborted
|
|
1015
|
+
? setTimeout(() => {
|
|
1016
|
+
timedOut = true;
|
|
1017
|
+
broken ?? (broken = new Error('it did not answer'));
|
|
1018
|
+
onAbort();
|
|
1019
|
+
}, options.timeout)
|
|
1020
|
+
: undefined;
|
|
1021
|
+
await closed;
|
|
1022
|
+
clearTimeout(limit);
|
|
1023
|
+
options.signal?.removeEventListener('abort', onAbort);
|
|
980
1024
|
}
|
|
981
1025
|
else {
|
|
982
|
-
|
|
1026
|
+
broken = new Error(options.signal?.aborted ? 'the run was cancelled' : 'it did not connect');
|
|
983
1027
|
}
|
|
984
1028
|
}
|
|
985
1029
|
catch (e) {
|
|
@@ -992,6 +1036,7 @@ async function runScript(instance, namespace, pod, script, args, options = {}) {
|
|
|
992
1036
|
...(exitCode === undefined
|
|
993
1037
|
? { message: status?.message ?? (broken ? (0, log_1.getErrorMessage)(broken) : 'the connection closed') }
|
|
994
1038
|
: {}),
|
|
1039
|
+
...(timedOut ? { timedOut } : {}),
|
|
995
1040
|
};
|
|
996
1041
|
}
|
|
997
1042
|
//# sourceMappingURL=sandbox-runner.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.restartPods = exports.syncChangedFiles = exports.podFolderOf = exports.SYNC_CHANGES = exports.APPLY_PATHS = exports.getChangeTarget = exports.CHANGES_STAGING_DIR = void 0;
|
|
3
|
+
exports.restartPods = exports.syncChangedFiles = exports.readArchive = exports.podFolderOf = exports.SYNC_CHANGES = exports.APPLY_PATHS = exports.getChangeTarget = exports.CHANGES_STAGING_DIR = void 0;
|
|
4
4
|
const fs_1 = require("fs");
|
|
5
5
|
const promises_1 = require("fs/promises");
|
|
6
6
|
const os_1 = require("os");
|
|
@@ -196,7 +196,13 @@ async function readArchive(archive) {
|
|
|
196
196
|
await new Promise((resolve, reject) => {
|
|
197
197
|
const parser = new tar_1.Parser({
|
|
198
198
|
onReadEntry: (entry) => {
|
|
199
|
-
|
|
199
|
+
// the mtime is kept, so the files are packed again with the times the sandbox gave them
|
|
200
|
+
const file = {
|
|
201
|
+
path: entry.path,
|
|
202
|
+
mode: entry.mode ?? 0o644,
|
|
203
|
+
content: Buffer.alloc(0),
|
|
204
|
+
mtime: entry.mtime,
|
|
205
|
+
};
|
|
200
206
|
files.push(file);
|
|
201
207
|
const chunks = [];
|
|
202
208
|
entry.on('data', (chunk) => chunks.push(chunk));
|
|
@@ -209,6 +215,7 @@ async function readArchive(archive) {
|
|
|
209
215
|
});
|
|
210
216
|
return files;
|
|
211
217
|
}
|
|
218
|
+
exports.readArchive = readArchive;
|
|
212
219
|
// `data` as a stream of pieces of PIECE_BYTES: an exec's standard input takes them as they come
|
|
213
220
|
function piecesOf(data) {
|
|
214
221
|
return stream_1.Readable.from((function* () {
|
package/dist/server/executor.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.HostExecutor = exports.relayWorkerLine = exports.removeServiceRunVolumes = exports.serviceRunScopes = exports.volumeScope = exports.pushCacheNamespace = exports.cacheNamespace = exports.defaultWorker = void 0;
|
|
3
|
+
exports.HostExecutor = exports.killGroup = exports.relayWorkerLine = exports.removeServiceRunVolumes = exports.serviceRunScopes = exports.volumeScope = exports.pushCacheNamespace = exports.cacheNamespace = exports.defaultWorker = void 0;
|
|
4
4
|
const child_process_1 = require("child_process");
|
|
5
5
|
const crypto_1 = require("crypto");
|
|
6
6
|
const checks_1 = require("./checks");
|
|
@@ -12,6 +12,7 @@ const resolve_git_source_1 = require("../includes/resolve-git-source");
|
|
|
12
12
|
const git_checkout_1 = require("./git-checkout");
|
|
13
13
|
const runs_1 = require("./runs");
|
|
14
14
|
const run_plan_1 = require("./run-plan");
|
|
15
|
+
const run_worker_1 = require("./run-worker");
|
|
15
16
|
const work_network_1 = require("../planner/work-network");
|
|
16
17
|
const execute_docker_1 = require("../executer/execute-docker");
|
|
17
18
|
const run_source_environment_1 = require("./run-source-environment");
|
|
@@ -29,6 +30,11 @@ const STOP_GRACE_MS = 15000;
|
|
|
29
30
|
// A run the server leaves to the next one gets this long to stop its tasks on this machine: the
|
|
30
31
|
// rest of what CLOSE_TIMEOUT gives it is for its execution to end (its directory, its volumes)
|
|
31
32
|
const DETACH_GRACE_MS = runs_1.CLOSE_TIMEOUT - 5000;
|
|
33
|
+
// The worker's output is read until its stdio closes. After its exit that comes at once, unless a
|
|
34
|
+
// process of the run keeps the stdio open: it gets this long, then the wait ends with what the
|
|
35
|
+
// worker said. A worker that said its result and does not exit gets killed after RESULT_EXIT_MS.
|
|
36
|
+
const STDIO_CLOSE_MS = 2000;
|
|
37
|
+
const RESULT_EXIT_MS = 10000;
|
|
32
38
|
// what is kept of the error output of a process that died without saying why
|
|
33
39
|
const MAX_STDERR = 2 * 1024;
|
|
34
40
|
/**
|
|
@@ -160,6 +166,24 @@ function relayWorkerLine(line, runId, relay) {
|
|
|
160
166
|
}
|
|
161
167
|
}
|
|
162
168
|
exports.relayWorkerLine = relayWorkerLine;
|
|
169
|
+
// Signals the process group of a worker, which is started as one (`detached` on POSIX): what the
|
|
170
|
+
// worker started, and what it left running, is signalled with it. On Windows, the process alone.
|
|
171
|
+
function killGroup(child, signal) {
|
|
172
|
+
if (child.pid === undefined || process.platform === 'win32') {
|
|
173
|
+
child.kill(signal);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
process.kill(-child.pid, signal);
|
|
178
|
+
}
|
|
179
|
+
catch (e) {
|
|
180
|
+
// the group is gone already, or the process is not its leader any more: the process itself goes
|
|
181
|
+
if (e.code !== 'ESRCH') {
|
|
182
|
+
child.kill(signal);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
exports.killGroup = killGroup;
|
|
163
187
|
class HostExecutor {
|
|
164
188
|
constructor(options) {
|
|
165
189
|
this.options = options;
|
|
@@ -422,6 +446,8 @@ class HostExecutor {
|
|
|
422
446
|
options: run.options,
|
|
423
447
|
...(push ? { cachePush: push } : {}),
|
|
424
448
|
cacheRegistries: this.options.cacheRegistries ?? [],
|
|
449
|
+
// how long a cancel's cleanup of the run's commands may take, from the server's environment
|
|
450
|
+
cleanupTimeoutMs: (0, run_worker_1.cleanupTimeoutMs)(process.env.HAMMERKIT_CLEANUP_TIMEOUT_MS),
|
|
425
451
|
accounts: run.accounts,
|
|
426
452
|
volumeScope: volumeScope(run, this.options.directory),
|
|
427
453
|
...((0, checks_1.isCheckRun)(run) ? { check: true } : {}),
|
|
@@ -533,6 +559,8 @@ class HostExecutor {
|
|
|
533
559
|
env,
|
|
534
560
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
535
561
|
windowsHide: true,
|
|
562
|
+
// its own process group on POSIX, so a kill reaches the children of the worker too
|
|
563
|
+
detached: process.platform !== 'win32',
|
|
536
564
|
});
|
|
537
565
|
child.stdin.on('error', () => undefined);
|
|
538
566
|
// the run first, so a cancel comes after it; kept open, it is how a cancel reaches the process
|
|
@@ -541,10 +569,13 @@ class HostExecutor {
|
|
|
541
569
|
let result;
|
|
542
570
|
let stderr = '';
|
|
543
571
|
let killTimer;
|
|
572
|
+
let resultTimer;
|
|
573
|
+
let stdioTimer;
|
|
574
|
+
let finished = false;
|
|
544
575
|
const stop = () => {
|
|
545
576
|
const detaching = (0, runs_1.isDetached)(context);
|
|
546
577
|
if (detaching && onCluster) {
|
|
547
|
-
child
|
|
578
|
+
killGroup(child, 'SIGKILL');
|
|
548
579
|
return;
|
|
549
580
|
}
|
|
550
581
|
child.stdin.write('cancel\n', (e) => {
|
|
@@ -553,7 +584,7 @@ class HostExecutor {
|
|
|
553
584
|
}
|
|
554
585
|
});
|
|
555
586
|
const grace = this.options.stopGraceMs ?? STOP_GRACE_MS;
|
|
556
|
-
killTimer = setTimeout(() => child
|
|
587
|
+
killTimer = setTimeout(() => killGroup(child, 'SIGKILL'), detaching ? Math.min(grace, DETACH_GRACE_MS) : grace);
|
|
557
588
|
killTimer.unref();
|
|
558
589
|
};
|
|
559
590
|
if (signal.aborted) {
|
|
@@ -562,17 +593,27 @@ class HostExecutor {
|
|
|
562
593
|
else {
|
|
563
594
|
signal.addEventListener('abort', stop, { once: true });
|
|
564
595
|
}
|
|
565
|
-
(0, readline_1.createInterface)({ input: child.stdout })
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
596
|
+
const lines = (0, readline_1.createInterface)({ input: child.stdout });
|
|
597
|
+
lines.on('line', (line) => {
|
|
598
|
+
// nothing is emitted for a run that has settled
|
|
599
|
+
if (finished) {
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
relayWorkerLine(line, runId, {
|
|
603
|
+
emit: (event) => context.emit(event),
|
|
604
|
+
up: (targets) => context.up?.(targets),
|
|
605
|
+
syncFailed: (id) => this.options.sandboxes?.syncFailed?.(id),
|
|
606
|
+
result: (message) => {
|
|
607
|
+
result = message;
|
|
608
|
+
// nothing left to tell the process
|
|
609
|
+
this.children.delete(runId);
|
|
610
|
+
child.stdin.end();
|
|
611
|
+
// the worker says nothing more: it should exit now, and its group is killed if it does not
|
|
612
|
+
resultTimer = setTimeout(() => killGroup(child, 'SIGKILL'), RESULT_EXIT_MS);
|
|
613
|
+
resultTimer.unref();
|
|
614
|
+
},
|
|
615
|
+
});
|
|
616
|
+
});
|
|
576
617
|
child.stderr.on('data', (chunk) => {
|
|
577
618
|
stderr = (stderr + chunk.toString('utf8')).slice(-MAX_STDERR);
|
|
578
619
|
});
|
|
@@ -581,9 +622,18 @@ class HostExecutor {
|
|
|
581
622
|
clearTimeout(killTimer);
|
|
582
623
|
reject(new Error(`the process of the run could not start: ${e.message}`));
|
|
583
624
|
});
|
|
584
|
-
|
|
625
|
+
// The wait ends on the worker's exit. Its stdio may stay open after it (a process of the run
|
|
626
|
+
// the cluster or the worker left holds it), so after the exit the wait ends at the close, or
|
|
627
|
+
// when STDIO_CLOSE_MS passed, with what the worker said.
|
|
628
|
+
const finish = (code, killed) => {
|
|
629
|
+
if (finished) {
|
|
630
|
+
return;
|
|
631
|
+
}
|
|
632
|
+
finished = true;
|
|
585
633
|
signal.removeEventListener('abort', stop);
|
|
586
634
|
clearTimeout(killTimer);
|
|
635
|
+
clearTimeout(resultTimer);
|
|
636
|
+
clearTimeout(stdioTimer);
|
|
587
637
|
if (this.children.get(runId) === child) {
|
|
588
638
|
this.children.delete(runId);
|
|
589
639
|
}
|
|
@@ -600,7 +650,25 @@ class HostExecutor {
|
|
|
600
650
|
const reason = stderr.trim().split('\n').pop() ?? '';
|
|
601
651
|
reject(new Error(`the process of the run stopped (${killed ? `signal ${killed}` : `code ${code}`})${reason ? `: ${reason}` : ''}`));
|
|
602
652
|
}
|
|
653
|
+
};
|
|
654
|
+
// After the worker's exit the stdio may stay open, a process of the run holds it. Then the
|
|
655
|
+
// group is killed, the pipes are closed, and the wait ends with what the worker said.
|
|
656
|
+
const settleOpen = (code, killed) => {
|
|
657
|
+
if (finished) {
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
killGroup(child, 'SIGKILL');
|
|
661
|
+
lines.close();
|
|
662
|
+
child.stdout.destroy();
|
|
663
|
+
child.stderr.destroy();
|
|
664
|
+
child.stdin.destroy();
|
|
665
|
+
finish(code, killed);
|
|
666
|
+
};
|
|
667
|
+
child.on('exit', (code, killed) => {
|
|
668
|
+
stdioTimer = setTimeout(() => settleOpen(code, killed), STDIO_CLOSE_MS);
|
|
669
|
+
stdioTimer.unref();
|
|
603
670
|
});
|
|
671
|
+
child.on('close', (code, killed) => finish(code, killed));
|
|
604
672
|
});
|
|
605
673
|
}
|
|
606
674
|
// The published files go over the checkout; nothing may land outside of it or in
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.git = exports.remoteBranch = exports.isValidBranch = exports.assertBranchName = exports.resolveRef = exports.GitOutputTooLarge = exports.RefError = exports.checkoutRef = exports.isValidRef = void 0;
|
|
3
|
+
exports.git = exports.commitOnBranch = exports.remoteBranch = exports.isValidBranch = exports.assertBranchName = exports.resolveRef = exports.GitOutputTooLarge = exports.RefError = exports.checkoutRef = exports.isValidRef = void 0;
|
|
4
4
|
const child_process_1 = require("child_process");
|
|
5
5
|
const promises_1 = require("fs/promises");
|
|
6
|
+
const os_1 = require("os");
|
|
7
|
+
const path_1 = require("path");
|
|
6
8
|
const util_1 = require("util");
|
|
7
9
|
const execFileAsync = (0, util_1.promisify)(child_process_1.execFile);
|
|
8
10
|
// Anything but plain network and local transports is refused: `ext::` runs a command.
|
|
@@ -130,6 +132,76 @@ async function remoteBranch(repository, branch, env, signal) {
|
|
|
130
132
|
return undefined;
|
|
131
133
|
}
|
|
132
134
|
exports.remoteBranch = remoteBranch;
|
|
135
|
+
// What git says when a commit is not in the repository (its exit code is 128)
|
|
136
|
+
const MISSING_COMMIT = /Not a valid (object|commit) name/;
|
|
137
|
+
// A failed git command: its exit code and the last line git printed
|
|
138
|
+
class GitFailure extends Error {
|
|
139
|
+
constructor(message, exitCode, reason) {
|
|
140
|
+
super(message);
|
|
141
|
+
this.exitCode = exitCode;
|
|
142
|
+
this.reason = reason;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
// Runs git for the answer in its exit code. `answer` says which exit codes, with git's last
|
|
146
|
+
// line, are answers; any other failure throws as `git` does.
|
|
147
|
+
async function gitCode(args, env, signal, what, answer) {
|
|
148
|
+
try {
|
|
149
|
+
await git(args, env, signal, what, 'check');
|
|
150
|
+
return { code: 0, reason: '' };
|
|
151
|
+
}
|
|
152
|
+
catch (e) {
|
|
153
|
+
if (e instanceof GitFailure && e.exitCode !== undefined && answer(e.exitCode, e.reason)) {
|
|
154
|
+
return { code: e.exitCode, reason: e.reason };
|
|
155
|
+
}
|
|
156
|
+
throw e;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Whether `commit` is in the history of `branch` of a repository. The history of the branch is
|
|
161
|
+
* fetched once, without trees or blobs, into a scratch repository. A commit that is not there
|
|
162
|
+
* after that fetch is not on the branch. A branch that is missing, or a fetch that fails,
|
|
163
|
+
* throws: the caller refuses then, it never reads that as "not on the branch".
|
|
164
|
+
*/
|
|
165
|
+
async function commitOnBranch(repository, commit, branch, env, signal) {
|
|
166
|
+
assertBranchName(branch);
|
|
167
|
+
if (!COMMIT.test(commit)) {
|
|
168
|
+
throw new RefError(`${JSON.stringify(commit.slice(0, 80))} is not a commit hash`);
|
|
169
|
+
}
|
|
170
|
+
// a commit the scratch repository lacks must not make git fetch it from a promisor remote
|
|
171
|
+
const gitEnv = { ...env, GIT_NO_LAZY_FETCH: '1' };
|
|
172
|
+
const directory = await (0, promises_1.mkdtemp)((0, path_1.join)((0, os_1.tmpdir)(), 'hammerkit-commit-on-'));
|
|
173
|
+
const what = `the history of ${repository} at ${branch}`;
|
|
174
|
+
try {
|
|
175
|
+
await git(['init', '--quiet', '--bare', directory], gitEnv, signal, 'a scratch repository', 'prepare');
|
|
176
|
+
await git([
|
|
177
|
+
'-C',
|
|
178
|
+
directory,
|
|
179
|
+
'fetch',
|
|
180
|
+
'--quiet',
|
|
181
|
+
'--no-tags',
|
|
182
|
+
// commits only: the history is enough to tell whether one is in it
|
|
183
|
+
'--filter=tree:0',
|
|
184
|
+
'--',
|
|
185
|
+
repository,
|
|
186
|
+
`refs/heads/${branch}:refs/hammerkit/branch`,
|
|
187
|
+
], gitEnv, signal, `${repository} at ${branch}`);
|
|
188
|
+
// exit 0: an ancestor, exit 1: not one. Exit 128 with git saying the commit is not there
|
|
189
|
+
// is not on the branch, once cat-file says the same; any other failure throws
|
|
190
|
+
const ancestor = await gitCode(['-C', directory, 'merge-base', '--is-ancestor', commit, 'refs/hammerkit/branch'], gitEnv, signal, what, (code, reason) => code === 0 || code === 1 || (code === 128 && MISSING_COMMIT.test(reason)));
|
|
191
|
+
if (ancestor.code !== 128) {
|
|
192
|
+
return ancestor.code === 0;
|
|
193
|
+
}
|
|
194
|
+
const present = await gitCode(['-C', directory, 'cat-file', '-e', `${commit}^{commit}`], gitEnv, signal, what, (code, reason) => code === 0 || (code === 128 && MISSING_COMMIT.test(reason)));
|
|
195
|
+
if (present.code === 0) {
|
|
196
|
+
throw new Error(`unable to check ${what}: git could not compare ${commit} with the branch`);
|
|
197
|
+
}
|
|
198
|
+
return false;
|
|
199
|
+
}
|
|
200
|
+
finally {
|
|
201
|
+
await (0, promises_1.rm)(directory, { recursive: true, force: true });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
exports.commitOnBranch = commitOnBranch;
|
|
133
205
|
// Runs git without a prompt and with the network transports only. Errors say what could
|
|
134
206
|
// not be done (`unable to <action> <what>`) with the last line git printed.
|
|
135
207
|
async function git(args, baseEnv, signal, what, action = 'fetch',
|
|
@@ -172,7 +244,7 @@ options = {}) {
|
|
|
172
244
|
.map((line) => line.trim())
|
|
173
245
|
.filter((line) => line.length > 0)
|
|
174
246
|
.pop() ?? error.message;
|
|
175
|
-
throw new
|
|
247
|
+
throw new GitFailure(`unable to ${action} ${what}: ${reason}`, typeof error.code === 'number' ? error.code : undefined, reason);
|
|
176
248
|
}
|
|
177
249
|
}
|
|
178
250
|
exports.git = git;
|
package/dist/server/policy.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.decideRun = exports.sandboxRepos = exports.decideSandbox = exports.sandboxPushBranches = exports.sandboxBranchType = exports.endpointLevel = exports.getGrant = exports.usedAccounts = exports.mayYank = exports.accountLevel = exports.canUse = exports.maySeeDefinitions = exports.mayPublish = exports.mayPropose = exports.mayReadChecks = exports.mayRun = exports.matches = exports.subjectName = void 0;
|
|
3
|
+
exports.decideRun = exports.commitOnBranches = exports.sandboxRepos = exports.decideSandbox = exports.sandboxPushBranches = exports.sandboxBranchType = exports.endpointLevel = exports.getGrant = exports.usedAccounts = exports.mayYank = exports.accountLevel = exports.canUse = exports.maySeeDefinitions = exports.mayPublish = exports.mayPropose = exports.mayReadChecks = exports.mayRun = exports.matches = exports.subjectName = void 0;
|
|
4
4
|
const repo_1 = require("./repo");
|
|
5
5
|
const BUILDS_ORDER = ['run', 'propose', 'publish'];
|
|
6
6
|
// The name an entitlement gives a subject, for the pages to name its runs by when its tokens
|
|
@@ -214,6 +214,44 @@ function checkRepo(repos, repo, readable, what) {
|
|
|
214
214
|
return null;
|
|
215
215
|
}
|
|
216
216
|
const COMMIT = /^[0-9a-f]{40}([0-9a-f]{24})?$/i;
|
|
217
|
+
// The branches a run from a ref must have its commit on: the `commitOn` of the accounts it uses.
|
|
218
|
+
// Its gates mirror decideRun's, so the server reads no repository for a run it refuses. Empty
|
|
219
|
+
// when no account names branches.
|
|
220
|
+
function commitOnBranches(input) {
|
|
221
|
+
const { grant, accounts, catalog, source, readable } = input;
|
|
222
|
+
if (source.type !== 'ref' || !(0, exports.mayRun)(grant) || !(0, repo_1.matchesAnyRepo)(grant.repos, source.repo) || !readable(source.repo)) {
|
|
223
|
+
return [];
|
|
224
|
+
}
|
|
225
|
+
const branches = new Set();
|
|
226
|
+
for (const account of accounts) {
|
|
227
|
+
const rules = Object.prototype.hasOwnProperty.call(catalog, account) ? catalog[account] : undefined;
|
|
228
|
+
if (accountLevel(grant, account) !== undefined && rules?.commitOn) {
|
|
229
|
+
rules.commitOn.forEach((branch) => branches.add(branch));
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return [...branches];
|
|
233
|
+
}
|
|
234
|
+
exports.commitOnBranches = commitOnBranches;
|
|
235
|
+
// An account with `commitOn` takes a run only when the commit is on one of its branches. A check
|
|
236
|
+
// that failed or was not made refuses too: it never passes for want of an answer.
|
|
237
|
+
function commitOnProblem(account, branches, onBranches) {
|
|
238
|
+
const checks = branches.map((branch) => onBranches?.[branch]);
|
|
239
|
+
if (checks.includes(true)) {
|
|
240
|
+
return undefined;
|
|
241
|
+
}
|
|
242
|
+
const reason = checks.find((check) => typeof check === 'string');
|
|
243
|
+
if (reason !== undefined || checks.includes(undefined)) {
|
|
244
|
+
const why = reason ?? 'the server could not check the branch';
|
|
245
|
+
return {
|
|
246
|
+
status: 409,
|
|
247
|
+
error: `the commit of the run could not be checked to be on ${branches.join(', ')} for the account ${account}: ${why}`,
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
return {
|
|
251
|
+
status: 403,
|
|
252
|
+
error: `the account ${account} is only used by runs from commits on ${branches.join(', ')}, this commit is on none of them`,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
217
255
|
// The single place that decides what happens to a run that was submitted: it
|
|
218
256
|
// starts, waits for an approval, or is refused with the reason.
|
|
219
257
|
function decideRun(input) {
|
|
@@ -259,6 +297,13 @@ function decideRun(input) {
|
|
|
259
297
|
};
|
|
260
298
|
}
|
|
261
299
|
}
|
|
300
|
+
// the config takes `commitOn` only with `source: [ref]`, so this run is from a ref and has a commit
|
|
301
|
+
if (rules?.commitOn && !input.commitPinned) {
|
|
302
|
+
const problem = commitOnProblem(account, rules.commitOn, input.onBranches);
|
|
303
|
+
if (problem) {
|
|
304
|
+
return { type: 'refuse', ...problem };
|
|
305
|
+
}
|
|
306
|
+
}
|
|
262
307
|
if (level === 'request') {
|
|
263
308
|
if (!approvable(account)) {
|
|
264
309
|
return { type: 'refuse', status: 409, error: `nobody can approve ${account}, no entitlement uses it` };
|
|
@@ -1,17 +1,25 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.RepoAccess = void 0;
|
|
3
|
+
exports.RepoAccess = exports.BRANCH_CHECK_FAILED = void 0;
|
|
4
|
+
const limit_1 = require("../utils/limit");
|
|
4
5
|
const redact_1 = require("../utils/redact");
|
|
5
6
|
const provider_values_1 = require("../secrets/provider-values");
|
|
6
7
|
const secret_catalog_1 = require("../secrets/secret-catalog");
|
|
7
8
|
const git_checkout_1 = require("./git-checkout");
|
|
8
9
|
const repo_1 = require("./repo");
|
|
10
|
+
function errorText(error) {
|
|
11
|
+
return error instanceof Error ? error.message : String(error);
|
|
12
|
+
}
|
|
9
13
|
// A token is read again after this long, so a short-lived one (a GitHub App
|
|
10
14
|
// installation token minted by the provider command) is not used up and a revoked one
|
|
11
15
|
// stops working soon.
|
|
12
16
|
const TOKEN_TTL_MS = 60 * 1000;
|
|
13
17
|
// A run waits for the repository at submit, not forever
|
|
14
18
|
const RESOLVE_TIMEOUT_MS = 30 * 1000;
|
|
19
|
+
exports.BRANCH_CHECK_FAILED = 'the branch check failed';
|
|
20
|
+
// Branch checks that run at once on the server: each fetches a branch's history
|
|
21
|
+
const BRANCH_CHECKS_AT_ONCE = 2;
|
|
22
|
+
const branchChecks = (0, limit_1.createLimit)(BRANCH_CHECKS_AT_ONCE);
|
|
15
23
|
/**
|
|
16
24
|
* The repositories a server can run code from. What may be read is the operator's
|
|
17
25
|
* `sources` list; who may name which of them is the entitlement's `repos`. The read
|
|
@@ -57,6 +65,45 @@ class RepoAccess {
|
|
|
57
65
|
throw this.scrub(e, credentials.values);
|
|
58
66
|
}
|
|
59
67
|
}
|
|
68
|
+
/**
|
|
69
|
+
* The commit a ref points to now, and for each of `branches` whether that commit is on it. A
|
|
70
|
+
* check that fails is `BRANCH_CHECK_FAILED`, with its detail in `errors` for the log. Each
|
|
71
|
+
* branch gets its own timeout, and the checks of the server run a few at once.
|
|
72
|
+
*/
|
|
73
|
+
async commitBranches(repo, ref, branches, signal) {
|
|
74
|
+
const commit = await this.resolve(repo, ref, signal);
|
|
75
|
+
const on = Object.create(null);
|
|
76
|
+
const errors = Object.create(null);
|
|
77
|
+
for (const branch of branches) {
|
|
78
|
+
const checked = await this.checkBranch(repo, commit, branch, signal);
|
|
79
|
+
if ('error' in checked) {
|
|
80
|
+
on[branch] = exports.BRANCH_CHECK_FAILED;
|
|
81
|
+
errors[branch] = checked.error;
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
on[branch] = checked.on;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return { commit, on, errors };
|
|
88
|
+
}
|
|
89
|
+
checkBranch(repo, commit, branch, signal) {
|
|
90
|
+
return branchChecks(async () => {
|
|
91
|
+
const timeout = AbortSignal.timeout(RESOLVE_TIMEOUT_MS);
|
|
92
|
+
const abort = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
93
|
+
if (this.options.onBranch) {
|
|
94
|
+
return this.options.onBranch(repo, commit, branch, abort).then((on) => ({ on }), (e) => ({ error: errorText(e) }));
|
|
95
|
+
}
|
|
96
|
+
let values = [];
|
|
97
|
+
try {
|
|
98
|
+
const credentials = await this.credentials(repo);
|
|
99
|
+
values = credentials.values;
|
|
100
|
+
return { on: await (0, git_checkout_1.commitOnBranch)(this.url(repo), commit, branch, credentials.env, abort) };
|
|
101
|
+
}
|
|
102
|
+
catch (e) {
|
|
103
|
+
return { error: errorText(this.scrub(e, values)) };
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
}
|
|
60
107
|
/**
|
|
61
108
|
* The environment a git process needs to read the repository: the allowlisted
|
|
62
109
|
* variables of the server, and the token as a header of requests to that host. The
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.workerMain = exports.readInput = exports.ChangeQueue = exports.applyChanges = exports.parseChanges = exports.syncLine = exports.syncServices = exports.taskCommands = exports.taskCauses = exports.describeFailures = exports.failedTasks = exports.runTasks = exports.relayStatus = exports.getRunHosted = exports.createRunSecrets = exports.removeCommandsOfRun = exports.getRunnerCommands = exports.getLogEvent = exports.getEndpointTargets = exports.publishEndpoints = exports.getRunNetwork = exports.workerInputSchema = void 0;
|
|
3
|
+
exports.workerMain = exports.readInput = exports.ChangeQueue = exports.applyChanges = exports.parseChanges = exports.syncLine = exports.syncServices = exports.taskCommands = exports.taskCauses = exports.describeFailures = exports.failedTasks = exports.runTasks = exports.relayStatus = exports.getRunHosted = exports.createRunSecrets = exports.removeCommandsOfRun = exports.getRunnerCommands = exports.getLogEvent = exports.getEndpointTargets = exports.publishEndpoints = exports.getRunNetwork = exports.workerInputSchema = exports.cleanupTimeoutMs = void 0;
|
|
4
4
|
const readline_1 = require("readline");
|
|
5
5
|
const zod_1 = require("zod");
|
|
6
6
|
const cli_1 = require("../cli");
|
|
@@ -40,6 +40,18 @@ const MAX_LOG_TEXT = 8 * 1024;
|
|
|
40
40
|
* engine reads of its process (the home directory, the docker host, the cache directory)
|
|
41
41
|
* is the run's and not the server's.
|
|
42
42
|
*/
|
|
43
|
+
// The cleanup of the commands of a run after a cancel, bounded (ms): HAMMERKIT_CLEANUP_TIMEOUT_MS
|
|
44
|
+
// sets it when it is a plain integer in this range, else the default
|
|
45
|
+
const REMOVE_COMMANDS_MS = 60000;
|
|
46
|
+
const CLEANUP_LIMITS_MS = { min: 1000, max: 600000 };
|
|
47
|
+
function cleanupTimeoutMs(value) {
|
|
48
|
+
if (value === undefined || !/^\d+$/.test(value.trim())) {
|
|
49
|
+
return REMOVE_COMMANDS_MS;
|
|
50
|
+
}
|
|
51
|
+
const ms = Number(value.trim());
|
|
52
|
+
return ms >= CLEANUP_LIMITS_MS.min && ms <= CLEANUP_LIMITS_MS.max ? ms : REMOVE_COMMANDS_MS;
|
|
53
|
+
}
|
|
54
|
+
exports.cleanupTimeoutMs = cleanupTimeoutMs;
|
|
43
55
|
exports.workerInputSchema = zod_1.z
|
|
44
56
|
.object({
|
|
45
57
|
// the build file to start from, in the checkout
|
|
@@ -63,6 +75,8 @@ exports.workerInputSchema = zod_1.z
|
|
|
63
75
|
// on the server's docker host, the runtime a container that adds capabilities runs in
|
|
64
76
|
// (`backend.capabilities.runtime`)
|
|
65
77
|
capabilityRuntime: zod_1.z.string().min(1).optional(),
|
|
78
|
+
// how long the cleanup of the commands of a run after a cancel may take (ms), see cleanupTimeoutMs
|
|
79
|
+
cleanupTimeoutMs: zod_1.z.number().int().min(CLEANUP_LIMITS_MS.min).max(CLEANUP_LIMITS_MS.max).optional(),
|
|
66
80
|
// the server's credential to write a registry cache with, for a trusted run only (`cache.push`,
|
|
67
81
|
// see cache-push.ts); left out for any other run, which may only read the caches
|
|
68
82
|
cachePush: zod_1.z
|
|
@@ -227,10 +241,28 @@ async function removeCommandsOfRun(input, commands, emit) {
|
|
|
227
241
|
if (!kubernetes || !workspace?.runner || commands.executions.size === 0) {
|
|
228
242
|
return;
|
|
229
243
|
}
|
|
244
|
+
// The cluster may not answer: the cleanup ends after its limit, so the result is not held up by a
|
|
245
|
+
// removal that never settles. The command directories of the run may then stay in the runner; the
|
|
246
|
+
// cancel has killed their processes already.
|
|
247
|
+
const limit = input.cleanupTimeoutMs ?? REMOVE_COMMANDS_MS;
|
|
248
|
+
let timer;
|
|
249
|
+
const expired = new Promise((resolve) => {
|
|
250
|
+
timer = setTimeout(() => resolve('expired'), limit);
|
|
251
|
+
});
|
|
230
252
|
try {
|
|
231
|
-
|
|
253
|
+
// inside the try: a synchronous throw of the removal is logged like any other failure
|
|
254
|
+
const removal = Promise.resolve().then(() => (0, sandbox_runner_1.removeRunCommands)((0, kubernetes_instance_1.createKubernetesInstances)(kubernetes), kubernetes.namespace, workspace.label, kubernetes.server.run, {
|
|
232
255
|
clean: true,
|
|
233
|
-
});
|
|
256
|
+
}));
|
|
257
|
+
const outcome = await Promise.race([removal.then(() => 'removed'), expired]);
|
|
258
|
+
if (outcome === 'expired') {
|
|
259
|
+
emit({
|
|
260
|
+
type: 'log',
|
|
261
|
+
task: 'hammerkit',
|
|
262
|
+
stream: 'stderr',
|
|
263
|
+
text: `what the commands of the run left in the sandbox could not be removed: the cluster did not answer in ${limit} ms`,
|
|
264
|
+
});
|
|
265
|
+
}
|
|
234
266
|
}
|
|
235
267
|
catch (e) {
|
|
236
268
|
emit({
|
|
@@ -240,6 +272,9 @@ async function removeCommandsOfRun(input, commands, emit) {
|
|
|
240
272
|
text: `what the commands of the run left in the sandbox could not be removed: ${(0, log_1.getErrorMessage)(e)}`,
|
|
241
273
|
});
|
|
242
274
|
}
|
|
275
|
+
finally {
|
|
276
|
+
clearTimeout(timer);
|
|
277
|
+
}
|
|
243
278
|
}
|
|
244
279
|
exports.removeCommandsOfRun = removeCommandsOfRun;
|
|
245
280
|
// The secrets of a run, masked in what it logs: the password of its cache push, as a secret of a
|
|
@@ -8,6 +8,8 @@ const sandbox_files_1 = require("./sandbox-files");
|
|
|
8
8
|
const sandboxes_1 = require("./sandboxes");
|
|
9
9
|
// a batch of edits carries the content it writes
|
|
10
10
|
exports.MAX_EDITS_BODY_BYTES = 16 * 1024 * 1024;
|
|
11
|
+
// the files one patch may name in its ifHash
|
|
12
|
+
const MAX_IF_HASH_FILES = 1000;
|
|
11
13
|
const hashSchema = zod_1.z.string().regex(/^[0-9a-fA-F]{64}$/, 'expected the sha256 of the file, 64 hex digits');
|
|
12
14
|
const opSchema = zod_1.z.discriminatedUnion('op', [
|
|
13
15
|
zod_1.z
|
|
@@ -31,7 +33,19 @@ const opSchema = zod_1.z.discriminatedUnion('op', [
|
|
|
31
33
|
.strict(),
|
|
32
34
|
zod_1.z.object({ op: zod_1.z.literal('delete'), path: zod_1.z.string(), ifHash: hashSchema.optional() }).strict(),
|
|
33
35
|
zod_1.z.object({ op: zod_1.z.literal('move'), path: zod_1.z.string(), to: zod_1.z.string(), ifHash: hashSchema.optional() }).strict(),
|
|
34
|
-
zod_1.z
|
|
36
|
+
zod_1.z
|
|
37
|
+
.object({
|
|
38
|
+
op: zod_1.z.literal('patch'),
|
|
39
|
+
patch: zod_1.z.string().min(1),
|
|
40
|
+
// the files a patch reads, at most this many, each at most a path of checkPath
|
|
41
|
+
ifHash: zod_1.z
|
|
42
|
+
.record(zod_1.z.string().max(sandbox_files_1.MAX_PATH_LENGTH), hashSchema)
|
|
43
|
+
.refine((map) => Object.keys(map).length <= MAX_IF_HASH_FILES, {
|
|
44
|
+
message: `at most ${MAX_IF_HASH_FILES} files`,
|
|
45
|
+
})
|
|
46
|
+
.optional(),
|
|
47
|
+
})
|
|
48
|
+
.strict(),
|
|
35
49
|
]);
|
|
36
50
|
const editsSchema = zod_1.z.object({ dryRun: zod_1.z.boolean().optional(), ops: zod_1.z.array(opSchema).min(1).max(1000) }).strict();
|
|
37
51
|
// grep tools name the flags `-i`, `-A`: both spellings are taken
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.HostSandboxFiles = exports.isRunState = exports.RUN_STATE_DIRECTORY = exports.deniedPath = exports.checkPath = exports.SandboxFileError = exports.MAX_EDIT_SERVER_BYTES = exports.MAX_EDIT_BATCH_WORK = exports.MAX_EDIT_BATCH_BYTES = exports.MAX_CHANGES_BYTES = exports.READ_LINES = exports.MAX_FILE_BYTES = void 0;
|
|
3
|
+
exports.HostSandboxFiles = exports.isRunState = exports.RUN_STATE_DIRECTORY = exports.deniedPath = exports.checkPath = exports.MAX_PATH_LENGTH = exports.SandboxFileError = exports.MAX_EDIT_SERVER_BYTES = exports.MAX_EDIT_BATCH_WORK = exports.MAX_EDIT_BATCH_BYTES = exports.MAX_CHANGES_BYTES = exports.READ_LINES = exports.MAX_FILE_BYTES = void 0;
|
|
4
4
|
const child_process_1 = require("child_process");
|
|
5
5
|
const crypto_1 = require("crypto");
|
|
6
6
|
const fs_1 = require("fs");
|
|
@@ -51,12 +51,14 @@ class SandboxFileError extends Error {
|
|
|
51
51
|
}
|
|
52
52
|
}
|
|
53
53
|
exports.SandboxFileError = SandboxFileError;
|
|
54
|
+
// the longest path of a file the API takes
|
|
55
|
+
exports.MAX_PATH_LENGTH = 4096;
|
|
54
56
|
/**
|
|
55
57
|
* A path as the API takes it: relative, `/` between names, no `.` or `..`, and nothing the
|
|
56
58
|
* deny list of uploads names (`.git/`, `.env`, keys).
|
|
57
59
|
*/
|
|
58
60
|
function checkPath(path) {
|
|
59
|
-
if (!(0, project_path_1.isRelativePath)(path,
|
|
61
|
+
if (!(0, project_path_1.isRelativePath)(path, exports.MAX_PATH_LENGTH)) {
|
|
60
62
|
throw new SandboxFileError(400, `${JSON.stringify(path.slice(0, 200))} is not a path in the sandbox: relative, / between names, no . or ..`);
|
|
61
63
|
}
|
|
62
64
|
const denied = deniedPath(path);
|
|
@@ -1156,9 +1158,7 @@ class EditBatch {
|
|
|
1156
1158
|
const state = await this.current(path);
|
|
1157
1159
|
const actual = state.kind === 'file' ? sha256(await this.content(path, state)) : undefined;
|
|
1158
1160
|
if (actual !== ifHash.toLowerCase()) {
|
|
1159
|
-
throw new SandboxFileError(412, actual
|
|
1160
|
-
? `${path} changed since you read it (sha256 ${actual}), read it again`
|
|
1161
|
-
: `${path} does not exist any more, read it again`);
|
|
1161
|
+
throw new SandboxFileError(412, actual ? `${path} changed since you read it, read it again` : `${path} does not exist any more, read it again`);
|
|
1162
1162
|
}
|
|
1163
1163
|
}
|
|
1164
1164
|
// A path a file may be written to: nothing but directories above it, no directory there.
|
|
@@ -1192,7 +1192,7 @@ class EditBatch {
|
|
|
1192
1192
|
}
|
|
1193
1193
|
async apply(op) {
|
|
1194
1194
|
if (op.op === 'patch') {
|
|
1195
|
-
return this.patch(op.patch);
|
|
1195
|
+
return this.patch(op.patch, op.ifHash);
|
|
1196
1196
|
}
|
|
1197
1197
|
const path = checkPath(op.path);
|
|
1198
1198
|
await this.checkHash(path, op.ifHash);
|
|
@@ -1261,8 +1261,21 @@ class EditBatch {
|
|
|
1261
1261
|
this.set(to, content, state.exec);
|
|
1262
1262
|
}
|
|
1263
1263
|
}
|
|
1264
|
-
async patch(text) {
|
|
1265
|
-
|
|
1264
|
+
async patch(text, ifHash) {
|
|
1265
|
+
const files = (0, sandbox_patch_1.parsePatch)(text);
|
|
1266
|
+
// the files the patch reads: a hash is only for one of them
|
|
1267
|
+
const read = new Set(files.flatMap((file) => (file.from === undefined ? [] : [checkPath(file.from)])));
|
|
1268
|
+
const hashes = Object.entries(ifHash ?? {}).map(([path, hash]) => [checkPath(path), hash]);
|
|
1269
|
+
for (const [path] of hashes) {
|
|
1270
|
+
if (!read.has(path)) {
|
|
1271
|
+
throw new sandbox_patch_1.PatchError(`${path} is in ifHash, but the patch does not read it`);
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
// all the hashes are checked before the first file changes, so a refused patch changes none
|
|
1275
|
+
for (const [path, hash] of hashes) {
|
|
1276
|
+
await this.checkHash(path, hash);
|
|
1277
|
+
}
|
|
1278
|
+
for (const file of files) {
|
|
1266
1279
|
await this.patchFile(file);
|
|
1267
1280
|
}
|
|
1268
1281
|
}
|
|
@@ -95,6 +95,15 @@ exports.accountSchema = zod_1.z
|
|
|
95
95
|
// the refs (branches or tags, `release/*` for a level) a run using this account
|
|
96
96
|
// may be started from; a commit is not accepted then, it names no branch
|
|
97
97
|
refs: zod_1.z.array(zod_1.z.string().min(1).max(200)).min(1).optional(),
|
|
98
|
+
// the branches a run from a ref is taken only when its commit is in the history of one of
|
|
99
|
+
// them: a tag or a commit that was never reviewed on these is refused. A name, not a pattern.
|
|
100
|
+
commitOn: zod_1.z
|
|
101
|
+
.array(zod_1.z
|
|
102
|
+
.string()
|
|
103
|
+
.regex(/^[A-Za-z0-9][A-Za-z0-9._/-]*$/, 'a branch name, not a pattern')
|
|
104
|
+
.max(200))
|
|
105
|
+
.min(1)
|
|
106
|
+
.optional(),
|
|
98
107
|
// On a Kubernetes backend: the credential the commands of the account's secrets
|
|
99
108
|
// get in the Job of a task, under /var/run/hammerkit/account. The server holds
|
|
100
109
|
// none of the secret manager's credentials.
|
|
@@ -123,6 +132,13 @@ exports.accountSchema = zod_1.z
|
|
|
123
132
|
message: 'refs only restricts runs from a git ref, set source: [ref] too, an upload names no ref',
|
|
124
133
|
});
|
|
125
134
|
}
|
|
135
|
+
if (account.commitOn && (account.source?.length !== 1 || account.source[0] !== 'ref')) {
|
|
136
|
+
ctx.addIssue({
|
|
137
|
+
code: zod_1.z.ZodIssueCode.custom,
|
|
138
|
+
path: ['commitOn'],
|
|
139
|
+
message: 'commitOn only restricts runs from a git ref, set source: [ref] too, a sandbox or an upload names no commit',
|
|
140
|
+
});
|
|
141
|
+
}
|
|
126
142
|
});
|
|
127
143
|
// The capabilities (`capAdd`) a task of a run may add, and the sandboxed runtime its
|
|
128
144
|
// container then runs in, so they hold in the sandbox's own kernel and never in the host's
|
package/dist/server/server.js
CHANGED
|
@@ -348,6 +348,8 @@ function refuseWake(config, repos, run) {
|
|
|
348
348
|
// an account it may only request is refused, the wake has nobody to approve it
|
|
349
349
|
approvable: () => true,
|
|
350
350
|
readable: (repo) => repos.readable(repo),
|
|
351
|
+
// a run with a commit was checked at submit and stays pinned to it: no second check here
|
|
352
|
+
commitPinned: run.source.commit !== undefined,
|
|
351
353
|
});
|
|
352
354
|
if (decision.type === 'refuse') {
|
|
353
355
|
return `its owner ${run.owner.sub} may no longer run it: ${decision.error.replace(/^you /, 'they ')}`;
|
|
@@ -611,17 +613,52 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
|
|
|
611
613
|
(0, http_2.send)(res, 403, { error });
|
|
612
614
|
return;
|
|
613
615
|
}
|
|
616
|
+
const submitted = request.source.type === 'ref'
|
|
617
|
+
? { type: 'ref', repo: request.source.repo, ref: request.source.ref }
|
|
618
|
+
: sandbox
|
|
619
|
+
? { type: 'sandbox', repo: sandbox.repo, branch: sandbox.ref }
|
|
620
|
+
: { type: 'upload' };
|
|
621
|
+
// the commit of a run from a ref is looked for on the branches its accounts name in `commitOn`,
|
|
622
|
+
// here where the repository is, and the run pins that same commit below
|
|
623
|
+
const commitOn = (0, policy_1.commitOnBranches)({
|
|
624
|
+
grant,
|
|
625
|
+
accounts: planned.accounts,
|
|
626
|
+
catalog: config.accounts,
|
|
627
|
+
source: submitted,
|
|
628
|
+
readable: (repo) => repos.readable(repo),
|
|
629
|
+
});
|
|
630
|
+
let checkedCommit;
|
|
631
|
+
let onBranches;
|
|
632
|
+
if (commitOn.length > 0 && request.source.type === 'ref') {
|
|
633
|
+
// a caller that hangs up frees its place in the queue of the branch checks
|
|
634
|
+
const hungUp = new AbortController();
|
|
635
|
+
res.on('close', () => hungUp.abort());
|
|
636
|
+
try {
|
|
637
|
+
const checked = await repos.commitBranches(request.source.repo, request.source.ref, commitOn, hungUp.signal);
|
|
638
|
+
checkedCommit = checked.commit;
|
|
639
|
+
onBranches = checked.on;
|
|
640
|
+
// the detail of a failed check, for the log: the run is refused with the fixed text only
|
|
641
|
+
for (const [branch, detail] of Object.entries(checked.errors)) {
|
|
642
|
+
log(`commitOn check of ${request.source.repo} at ${checked.commit} on ${branch} failed: ${detail}`);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
catch (e) {
|
|
646
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
647
|
+
log(`refuse run iss=${principal.iss} sub=${principal.sub}: ${message}`);
|
|
648
|
+
(0, http_2.send)(res, e instanceof git_checkout_1.RefError ? 400 : 502, {
|
|
649
|
+
error: e instanceof git_checkout_1.RefError ? message : `could not resolve ${request.source.ref}: ${message}`,
|
|
650
|
+
});
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
614
654
|
const decision = (0, policy_1.decideRun)({
|
|
615
655
|
grant,
|
|
616
656
|
accounts: planned.accounts,
|
|
617
657
|
catalog: config.accounts,
|
|
618
|
-
source:
|
|
619
|
-
? { type: 'ref', repo: request.source.repo, ref: request.source.ref }
|
|
620
|
-
: sandbox
|
|
621
|
-
? { type: 'sandbox', repo: sandbox.repo, branch: sandbox.ref }
|
|
622
|
-
: { type: 'upload' },
|
|
658
|
+
source: submitted,
|
|
623
659
|
approvable: (account) => config.entitlements.some((entitlement) => entitlement.accounts[account] === 'use'),
|
|
624
660
|
readable: (repo) => repos.readable(repo),
|
|
661
|
+
onBranches,
|
|
625
662
|
});
|
|
626
663
|
if (decision.type === 'refuse') {
|
|
627
664
|
log(`refuse run iss=${principal.iss} sub=${principal.sub}: ${decision.error}`);
|
|
@@ -633,7 +670,7 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
|
|
|
633
670
|
let source;
|
|
634
671
|
if (request.source.type === 'ref') {
|
|
635
672
|
try {
|
|
636
|
-
const commit = await repos.resolve(request.source.repo, request.source.ref);
|
|
673
|
+
const commit = checkedCommit ?? (await repos.resolve(request.source.repo, request.source.ref));
|
|
637
674
|
if (request.source.commit && commit !== request.source.commit) {
|
|
638
675
|
const error = retryOf
|
|
639
676
|
? `${request.source.ref} moved to ${commit} since ${retryOf.id} ran ${request.source.commit}, start a new run from ${request.source.ref}`
|
package/package.json
CHANGED