hammerkit 2.0.0-next.15 → 2.0.0-next.17

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.
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getNetworkGateContainer = exports.HELPER_SECURITY_CONTEXT = exports.NETWORK_GATE_SCRIPT = exports.NETWORK_GATE_CONTAINER = exports.NETWORK_GATE_TIMEOUT_MS = void 0;
3
+ exports.getOpenNetworkGate = exports.OPEN_NETWORK_GATE_SETTING = exports.METADATA_ADDRESS = exports.getNetworkGateContainer = exports.HELPER_SECURITY_CONTEXT = exports.NETWORK_GATE_SCRIPT = exports.NETWORK_GATE_CONTAINER = exports.NETWORK_GATE_TIMEOUT_MS = void 0;
4
+ const net_1 = require("net");
4
5
  const egress_proxy_1 = require("../network/egress-proxy");
5
6
  // Some network plugins (kind's kindnet among them) enforce a NetworkPolicy a
6
7
  // moment after a pod started, so a limited pod's first connections could
@@ -8,6 +9,9 @@ const egress_proxy_1 = require("../network/egress-proxy");
8
9
  // the pod no longer reaches the cluster DNS, which the policy of every limited
9
10
  // item denies, so the item's own containers start only once the policy holds.
10
11
  // A policy that never takes hold fails the pod instead of running it open.
12
+ // A pod with an open network on a server is limited too, by the policy of its
13
+ // namespace, which denies it the cloud's metadata address among others: its gate
14
+ // waits until that address is out of reach instead (see getOpenNetworkGate).
11
15
  // A script for `node -e` in the proxy's image, like the proxy.
12
16
  exports.NETWORK_GATE_TIMEOUT_MS = 60000;
13
17
  // the name of the gate's init container
@@ -20,23 +24,30 @@ const resolvConf = process.env.HAMMERKIT_GATE_RESOLV_CONF || '/etc/resolv.conf'
20
24
  const port = parseInt(process.env.HAMMERKIT_GATE_PORT || '53', 10)
21
25
  const deadline = Date.now() + parseInt(process.env.HAMMERKIT_GATE_TIMEOUT_MS || '${exports.NETWORK_GATE_TIMEOUT_MS}', 10)
22
26
  function fail(message) {
27
+ if (process.env.HAMMERKIT_GATE_HINT) {
28
+ message += ' (' + process.env.HAMMERKIT_GATE_HINT + ')'
29
+ }
23
30
  process.stderr.write('hammerkit: ' + message + '\\n')
24
31
  try {
25
32
  fs.writeFileSync('/dev/termination-log', 'hammerkit: ' + message)
26
33
  } catch (e) {}
27
34
  process.exit(1)
28
35
  }
29
- let conf = ''
30
- try {
31
- conf = fs.readFileSync(resolvConf, 'utf8')
32
- } catch (e) {}
33
- const match = /^nameserver\\s+(\\S+)/m.exec(conf)
34
- if (!match) {
35
- fail('the pod has no cluster DNS, so its network policy can not be checked')
36
+ const probeMs = parseInt(process.env.HAMMERKIT_GATE_PROBE_MS || '2000', 10)
37
+ let nameserver = process.env.HAMMERKIT_GATE_HOST
38
+ if (!nameserver) {
39
+ let conf = ''
40
+ try {
41
+ conf = fs.readFileSync(resolvConf, 'utf8')
42
+ } catch (e) {}
43
+ const match = /^nameserver\\s+(\\S+)/m.exec(conf)
44
+ if (!match) {
45
+ fail('the pod has no cluster DNS, so its network policy can not be checked')
46
+ }
47
+ nameserver = match[1]
36
48
  }
37
- const nameserver = match[1]
38
49
  function attempt() {
39
- const socket = net.connect({ host: nameserver, port, timeout: 2000 })
50
+ const socket = net.connect({ host: nameserver, port, timeout: probeMs })
40
51
  socket.once('connect', () => {
41
52
  socket.destroy()
42
53
  if (Date.now() > deadline) {
@@ -58,14 +69,66 @@ exports.HELPER_SECURITY_CONTEXT = {
58
69
  readOnlyRootFilesystem: true,
59
70
  capabilities: { drop: ['ALL'] },
60
71
  };
61
- function getNetworkGateContainer() {
72
+ // how long the gate of an open pod waits for an answer of its target: a link-local
73
+ // address answers at once, when it is reached at all
74
+ const OPEN_GATE_PROBE_MS = 1000;
75
+ // `target`: the address of an open pod's gate (getOpenNetworkGate); without it, the
76
+ // cluster DNS a limited pod is denied
77
+ function getNetworkGateContainer(target) {
62
78
  return {
63
79
  name: exports.NETWORK_GATE_CONTAINER,
64
80
  image: egress_proxy_1.EGRESS_PROXY_IMAGE,
65
81
  command: ['node', '-e', exports.NETWORK_GATE_SCRIPT],
82
+ ...(target
83
+ ? {
84
+ env: [
85
+ { name: 'HAMMERKIT_GATE_HOST', value: target.host },
86
+ { name: 'HAMMERKIT_GATE_PORT', value: `${target.port}` },
87
+ { name: 'HAMMERKIT_GATE_PROBE_MS', value: `${OPEN_GATE_PROBE_MS}` },
88
+ {
89
+ name: 'HAMMERKIT_GATE_HINT',
90
+ value: `the server's ${exports.OPEN_NETWORK_GATE_SETTING} points this wait at another address ` +
91
+ 'the namespace denies, or turns it off with false',
92
+ },
93
+ ],
94
+ }
95
+ : {}),
66
96
  securityContext: exports.HELPER_SECURITY_CONTEXT,
67
97
  resources: { limits: { memory: '64Mi' } },
68
98
  };
69
99
  }
70
100
  exports.getNetworkGateContainer = getNetworkGateContainer;
101
+ // The metadata endpoint of the clouds, which hands out the node's identity
102
+ exports.METADATA_ADDRESS = '169.254.169.254';
103
+ // the setting of the server that turns the gate of open pods off or points it elsewhere
104
+ exports.OPEN_NETWORK_GATE_SETTING = 'backend.openNetworkGate';
105
+ /**
106
+ * The gate of the pods with an open network on a server: they wait until they no longer
107
+ * reach an address the policy of their namespace denies them, by default the metadata
108
+ * endpoint (`backend.deniedEgress` covers it). The operator points it elsewhere, or turns
109
+ * it off with `false` (`backend.openNetworkGate`). None when the operator did not state that
110
+ * the cluster enforces NetworkPolicy, or when the address isn't denied or is allowed: the
111
+ * gate would never open.
112
+ */
113
+ function getOpenNetworkGate(backend) {
114
+ if (backend.networkPolicy !== 'enforced' || backend.openNetworkGate === false) {
115
+ return undefined;
116
+ }
117
+ const target = backend.openNetworkGate ?? { host: exports.METADATA_ADDRESS, port: 80 };
118
+ const covers = (ranges) => {
119
+ const list = new net_1.BlockList();
120
+ for (const range of ranges) {
121
+ const [address, prefix] = range.split('/');
122
+ if ((0, net_1.isIPv4)(address)) {
123
+ list.addSubnet(address, prefix === undefined ? 32 : parseInt(prefix, 10), 'ipv4');
124
+ }
125
+ }
126
+ return list.check(target.host, 'ipv4');
127
+ };
128
+ if (!covers(backend.deniedEgress) || covers(backend.allowedEgress)) {
129
+ return undefined;
130
+ }
131
+ return target;
132
+ }
133
+ exports.getOpenNetworkGate = getOpenNetworkGate;
71
134
  //# sourceMappingURL=network-gate.js.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.removeSandboxProxies = exports.getProxyReadinessScript = exports.removeAllKubernetesItemNetworks = exports.releaseKubernetesItemNetwork = exports.awaitPodsEnded = exports.removeKubernetesItemNetwork = exports.ensureKubernetesItemNetwork = exports.buildProxyPolicy = exports.buildNetworkPolicy = exports.getNetworkPolicyName = exports.getSandboxProxy = exports.getProxyName = exports.getNetworkLabels = exports.NETWORK_PROXY = exports.NETWORK_LIMITED = exports.NETWORK_LABEL = exports.PROXY_OF_SANDBOX_LABEL = exports.RUN_LABEL = void 0;
3
+ exports.removeSandboxProxies = exports.getProxyReadinessScript = exports.removeAllKubernetesItemNetworks = exports.releaseKubernetesItemNetwork = exports.awaitPodsEnded = exports.removeKubernetesItemNetwork = exports.ensureKubernetesItemNetwork = exports.buildProxyPolicy = exports.buildNetworkPolicy = exports.getNetworkPolicyName = exports.getSandboxProxy = exports.getProxyName = exports.getNetworkLabels = exports.getTransferNetworkLabels = exports.TRANSFER_LABEL = exports.NETWORK_PROXY = exports.NETWORK_LIMITED = exports.NETWORK_LABEL = exports.PROXY_OF_SANDBOX_LABEL = exports.RUN_LABEL = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const stream_1 = require("stream");
6
6
  const readline_1 = require("readline");
@@ -35,6 +35,14 @@ const POD_END_POLL_MS = 500;
35
35
  exports.NETWORK_LABEL = 'hammerkit.dev/network';
36
36
  exports.NETWORK_LIMITED = 'limited';
37
37
  exports.NETWORK_PROXY = 'proxy';
38
+ // on the pods that copy files into and out of a claim on a server: they need no network, so
39
+ // the policies of the caller's namespace for open pods leave them out (`limited`), and one
40
+ // of its own lets nothing in or out (see getNamespacePolicies)
41
+ exports.TRANSFER_LABEL = 'hammerkit.dev/transfer';
42
+ function getTransferNetworkLabels() {
43
+ return { [exports.NETWORK_LABEL]: exports.NETWORK_LIMITED, [exports.TRANSFER_LABEL]: 'true' };
44
+ }
45
+ exports.getTransferNetworkLabels = getTransferNetworkLabels;
38
46
  function getNetworkLabels(env, item) {
39
47
  return env.server && (0, work_network_1.getEffectiveNetwork)(item.data).type !== 'open' ? { [exports.NETWORK_LABEL]: exports.NETWORK_LIMITED } : {};
40
48
  }
@@ -88,6 +96,13 @@ exports.getNetworkPolicyName = getNetworkPolicyName;
88
96
  function getItemPodLabels(item, scope) {
89
97
  return { [resources_1.ID_LABEL]: item.id(), ...(scope.run ? { [job_placement_1.RUN_LABEL]: scope.run } : {}) };
90
98
  }
99
+ // The pods of the item, but those that copy files into and out of its claims on a server,
100
+ // which carry its labels too: the policy of their namespace lets nothing in or out of them,
101
+ // and the item's policy doesn't widen it.
102
+ const NOT_TRANSFER = { key: exports.TRANSFER_LABEL, operator: 'DoesNotExist' };
103
+ function withoutTransferPods(labels) {
104
+ return { matchLabels: labels, matchExpressions: [NOT_TRANSFER] };
105
+ }
91
106
  function toSelector(labels) {
92
107
  return Object.entries(labels)
93
108
  .map(([key, value]) => `${key}=${value}`)
@@ -110,7 +125,7 @@ function getIngress(env, item) {
110
125
  // on a server, of this run: the runs of a caller share their namespace
111
126
  const run = (0, job_placement_1.getRunLabels)(env);
112
127
  const from = {
113
- matchExpressions: [{ key: resources_1.ID_LABEL, operator: 'In', values: ids }],
128
+ matchExpressions: [{ key: resources_1.ID_LABEL, operator: 'In', values: ids }, NOT_TRANSFER],
114
129
  ...(Object.keys(run).length > 0 ? { matchLabels: run } : {}),
115
130
  };
116
131
  // the client's name for `from`, a reserved word
@@ -133,12 +148,12 @@ function buildNetworkPolicy(env, item, network, scope, proxy = getRunProxy(item,
133
148
  ...(scope.owners ? { ownerReferences: scope.owners } : {}),
134
149
  },
135
150
  spec: {
136
- podSelector: { matchLabels: getItemPodLabels(item, scope) },
151
+ podSelector: withoutTransferPods(getItemPodLabels(item, scope)),
137
152
  policyTypes: ['Ingress', 'Egress'],
138
153
  ingress: getIngress(env, item),
139
154
  egress: [
140
155
  ...(needs.length > 0
141
- ? [{ to: needs.map((need) => ({ podSelector: { matchLabels: (0, resources_1.getItemLabels)(need.service, env) } })) }]
156
+ ? [{ to: needs.map((need) => ({ podSelector: withoutTransferPods((0, resources_1.getItemLabels)(need.service, env)) })) }]
142
157
  : []),
143
158
  ...(proxied
144
159
  ? [
@@ -172,7 +187,7 @@ function buildProxyPolicy(env, item, network, scope, proxy = getRunProxy(item, s
172
187
  policyTypes: ['Ingress'],
173
188
  ingress: [
174
189
  {
175
- _from: [{ podSelector: { matchLabels: getItemPodLabels(item, scope) } }],
190
+ _from: [{ podSelector: withoutTransferPods(getItemPodLabels(item, scope)) }],
176
191
  ports: (0, egress_proxy_1.getEgressProxyPorts)(network).map((port) => ({ protocol: 'TCP', port })),
177
192
  },
178
193
  ],
@@ -203,7 +218,9 @@ async function ensureKubernetesItemNetwork(instance, env, item, options) {
203
218
  // without the rights to manage NetworkPolicies, hammerkit never made one
204
219
  await removeKubernetesItemNetwork(instance, env, item, { run: null }, { ignoreForbidden: true });
205
220
  }
206
- return { env: [], secretEnv: [], hostAliases, initContainers: [], close() { } };
221
+ // on a server, the policy of its namespace limits it: it starts once that holds
222
+ const gate = env.server?.openGate && env.networkPolicyEnforced ? [(0, network_gate_1.getNetworkGateContainer)(env.server.openGate)] : [];
223
+ return { env: [], secretEnv: [], hostAliases, initContainers: gate, close() { } };
207
224
  }
208
225
  const secretHosts = options.secretHosts ?? [];
209
226
  if (secretHosts.length > 0 && options.sandbox) {
@@ -285,13 +302,18 @@ async function removeKubernetesItemNetwork(instance, env, item, scope, options =
285
302
  }
286
303
  }
287
304
  exports.removeKubernetesItemNetwork = removeKubernetesItemNetwork;
288
- // Waits until no pod with the labels runs or waits to run.
289
- async function awaitPodsEnded(instance, env, labels, timeout = POD_END_TIMEOUT_MS) {
305
+ // Waits until no pod with the labels (or of the label selector) runs or waits to run.
306
+ async function awaitPodsEnded(instance, env, labels, timeout = POD_END_TIMEOUT_MS, pollInterval = POD_END_POLL_MS,
307
+ // stops the wait: they count as not ended
308
+ signal) {
290
309
  const deadline = Date.now() + timeout;
291
310
  for (;;) {
311
+ if (signal?.aborted) {
312
+ return false;
313
+ }
292
314
  const pods = await instance.coreApi.listNamespacedPod({
293
315
  namespace: env.namespace,
294
- labelSelector: toSelector(labels),
316
+ labelSelector: typeof labels === 'string' ? labels : toSelector(labels),
295
317
  });
296
318
  if (pods.items.every((pod) => pod.status?.phase === 'Succeeded' || pod.status?.phase === 'Failed')) {
297
319
  return true;
@@ -299,7 +321,7 @@ async function awaitPodsEnded(instance, env, labels, timeout = POD_END_TIMEOUT_M
299
321
  if (Date.now() >= deadline) {
300
322
  return false;
301
323
  }
302
- await (0, sleep_1.sleep)(POD_END_POLL_MS);
324
+ await (0, sleep_1.sleep)(pollInterval);
303
325
  }
304
326
  }
305
327
  exports.awaitPodsEnded = awaitPodsEnded;
@@ -4,12 +4,18 @@ exports.getStaleItemSelector = exports.removeStaleItems = void 0;
4
4
  const job_placement_1 = require("./job-placement");
5
5
  const resources_1 = require("./resources");
6
6
  const apply_1 = require("./apply");
7
+ const network_policy_1 = require("./network-policy");
7
8
  /**
8
9
  * What a service run made for items it has no more, once it moved to another commit: the
9
10
  * Deployment, Service, Secret, policies and Jobs of a service or task whose id changed (a new
10
- * image, other volumes). Their claims stay, with the namespace of the run.
11
+ * image, other volumes). Their claims stay, with the namespace of the run. The policies go
12
+ * last, once the pods they limit ended: a pod that is still terminating would otherwise run
13
+ * a moment without its limits. When pods outlast the wait, the policies stay, and the next
14
+ * move or the end of the run removes them.
11
15
  */
12
- async function removeStaleItems(instance, env, ids) {
16
+ async function removeStaleItems(instance, env, ids,
17
+ // a run stopped while its old pods end: the policies stay, and go with the run
18
+ options = {}) {
13
19
  if (!env.server) {
14
20
  return;
15
21
  }
@@ -20,6 +26,13 @@ async function removeStaleItems(instance, env, ids) {
20
26
  await instance.batchApi.deleteCollectionNamespacedJob({ ...selector, propagationPolicy: 'Background' });
21
27
  await instance.coreApi.deleteCollectionNamespacedService(selector);
22
28
  await instance.coreApi.deleteCollectionNamespacedSecret(selector);
29
+ const ended = await (0, network_policy_1.awaitPodsEnded)(instance, env, labelSelector, options.podEndTimeout, options.podEndPollInterval, options.signal);
30
+ if (options.signal?.aborted) {
31
+ return;
32
+ }
33
+ if (!ended) {
34
+ throw new Error('pods of the previous commit are still running, so their network policies stay');
35
+ }
23
36
  const policies = await instance.objectApi.list('networking.k8s.io/v1', 'NetworkPolicy', namespace, undefined, undefined, undefined, undefined, labelSelector);
24
37
  for (const policy of policies.items) {
25
38
  const metadata = { name: policy.metadata?.name, namespace };
@@ -6,6 +6,7 @@ const log_1 = require("../log");
6
6
  const volumes_1 = require("./volumes");
7
7
  const ensure_persistent_data_1 = require("./ensure-persistent-data");
8
8
  const claim_layout_1 = require("./claim-layout");
9
+ const transfer_tools_1 = require("./transfer-tools");
9
10
  // Unpacks the archive of an output that is a file to `$1`: by its content, since the name in
10
11
  // the archive is the file's and the one in the claim may carry a hash (see getClaimSubPath)
11
12
  exports.RESTORE_FILE = 'mkdir -p "$(dirname "$1")" && rm -rf "$1" && tar xzf - -O > "$1"';
@@ -49,13 +50,13 @@ options = {}) {
49
50
  // a claim made for this run (a server removes the claims of a run when it
50
51
  // ends) does not have the directory of the output yet
51
52
  let failure = null;
52
- const res = await instance.exec.exec(kubernetes.namespace, name, 'volume', [
53
+ const res = await instance.exec.exec(kubernetes.namespace, name, 'volume', (0, transfer_tools_1.inTransferPod)([
53
54
  'sh',
54
55
  '-c',
55
56
  files.has(generatedArchive.path) ? exports.RESTORE_FILE : 'mkdir -p "$1" && tar xzf - -C "$1"',
56
57
  'sh',
57
58
  targetPath,
58
- ], process.stdout, process.stderr, environment.file.readStream(generatedArchive.filename), false, (status) => {
59
+ ]), process.stdout, process.stderr, environment.file.readStream(generatedArchive.filename), false, (status) => {
59
60
  work.status.write('debug', `upload ${generatedArchive.filename} to ${name}: ${status.status}`);
60
61
  if (status.status !== 'Success') {
61
62
  failure = status.message ?? status.reason ?? 'unknown';
@@ -16,6 +16,7 @@ const container_resources_1 = require("./container-resources");
16
16
  const job_placement_1 = require("./job-placement");
17
17
  const network_policy_1 = require("./network-policy");
18
18
  const resources_1 = require("./resources");
19
+ const transfer_tools_1 = require("./transfer-tools");
19
20
  const volumes_1 = require("./volumes");
20
21
  /**
21
22
  * The runner of a sandbox: one pod that the commands of a run on the sandbox are exec'd
@@ -46,10 +47,8 @@ const TMP_VOLUME = 'hammerkit-runner-tmp';
46
47
  const TOOLS_VOLUME = 'hammerkit-runner-tools';
47
48
  const TOOLS_PATH = '/.hammerkit';
48
49
  const BUSYBOX = `${TOOLS_PATH}/busybox`;
49
- // Pinned, static (it runs in any image), and copied into the runner by an init container.
50
- // To bump it, take the index digest of the tag (`docker buildx imagetools inspect
51
- // busybox:<version>-musl`).
52
- exports.RUNNER_TOOLS_IMAGE = 'busybox:1.37.0-musl@sha256:5cec3fc171c87218698e85a52af7087de727372aae264a787b8112901a5b0092';
50
+ // copied into the runner by an init container
51
+ exports.RUNNER_TOOLS_IMAGE = transfer_tools_1.HELPER_TOOLS_IMAGE;
53
52
  const RUNNER_START_MS = 5 * 60 * 1000;
54
53
  const RUNNER_POLL_MS = 250;
55
54
  const PULL_FAILURES = ['ErrImagePull', 'ImagePullBackOff', 'InvalidImageName'];
@@ -6,6 +6,7 @@ const log_1 = require("../log");
6
6
  const event_cache_1 = require("../executer/event-cache");
7
7
  const volumes_1 = require("./volumes");
8
8
  const ensure_persistent_data_1 = require("./ensure-persistent-data");
9
+ const transfer_tools_1 = require("./transfer-tools");
9
10
  async function storeKubernetesData(work, kubernetes, instance, environment, path,
10
11
  // the state the outputs are of: on a service run, they are in its folder (see
11
12
  // getStateFilesDir)
@@ -22,9 +23,9 @@ stateKey) {
22
23
  await (0, ensure_persistent_data_1.getPodForPersistence)(instance, kubernetes, work, persistence, 'read', signal, async (name) => {
23
24
  for (const generatedArchive of (0, event_cache_1.getArchivePaths)(work.data, path)) {
24
25
  const writerStream = environment.file.createWriteStream(generatedArchive.filename);
25
- const res = await instance.exec.exec(kubernetes.namespace, name, 'volume', files.has(generatedArchive.path)
26
+ const res = await instance.exec.exec(kubernetes.namespace, name, 'volume', (0, transfer_tools_1.inTransferPod)(files.has(generatedArchive.path)
26
27
  ? ['tar', 'zcf', '-', '-C', path_1.posix.dirname(generatedArchive.path), path_1.posix.basename(generatedArchive.path)]
27
- : ['tar', 'zcf', '-', '-C', generatedArchive.path, '.'], writerStream, process.stderr, null, false, (status) => {
28
+ : ['tar', 'zcf', '-', '-C', generatedArchive.path, '.']), writerStream, process.stderr, null, false, (status) => {
28
29
  work.status.write('debug', `archive ${generatedArchive.path} of ${name}: ${status}`);
29
30
  writerStream.close();
30
31
  });
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TRANSFER_TOOLS_ENV = exports.TRANSFER_TOOLS_MOUNT = exports.TRANSFER_TOOLS_VOLUMES = exports.getTransferToolsInitContainer = exports.inTransferPod = exports.isTransferToolsPath = exports.TRANSFER_BUSYBOX = exports.TRANSFER_TOOLS_PATH = exports.HELPER_TOOLS_IMAGE = void 0;
4
+ const path_1 = require("path");
5
+ // Pinned, static (it runs in any image) busybox: the tools of the pods hammerkit runs its own
6
+ // commands in, such as the runner of a sandbox and the pods that copy files into and out of
7
+ // a claim. To bump it, take the index digest of the tag (`docker buildx imagetools inspect
8
+ // busybox:<version>-musl`).
9
+ exports.HELPER_TOOLS_IMAGE = 'busybox:1.37.0-musl@sha256:5cec3fc171c87218698e85a52af7087de727372aae264a787b8112901a5b0092';
10
+ /**
11
+ * The pod that copies files into and out of a claim mounts the outputs of a task at the
12
+ * paths the task wrote them to, which may be any path, /bin included. So what it runs comes
13
+ * from a folder no mount of the task can be: an init container copies the pinned busybox
14
+ * into it and links each of its tools there, and the pod's own container finds them by its
15
+ * PATH, mounted read-only. Every command starts with the busybox itself, so a tool of the
16
+ * same name in a mounted output never runs.
17
+ */
18
+ exports.TRANSFER_TOOLS_PATH = '/.hammerkit';
19
+ const TRANSFER_TOOLS_VOLUME = 'hammerkit-transfer-tools';
20
+ exports.TRANSFER_BUSYBOX = `${exports.TRANSFER_TOOLS_PATH}/busybox`;
21
+ const TRANSFER_BIN = `${exports.TRANSFER_TOOLS_PATH}/bin`;
22
+ // a path in or over the folder of the tools (`/`, `/.hammerkit`, `/.hammerkit/bin`), where a
23
+ // mount would hide them
24
+ function isTransferToolsPath(path) {
25
+ const normalized = path_1.posix.normalize(path).replace(/\/+$/, '') || '/';
26
+ return normalized === '/' || normalized === exports.TRANSFER_TOOLS_PATH || normalized.startsWith(`${exports.TRANSFER_TOOLS_PATH}/`);
27
+ }
28
+ exports.isTransferToolsPath = isTransferToolsPath;
29
+ // `command` (a tool and its arguments) run by the busybox of the transfer pod
30
+ function inTransferPod(command) {
31
+ return [exports.TRANSFER_BUSYBOX, ...command];
32
+ }
33
+ exports.inTransferPod = inTransferPod;
34
+ function getTransferToolsInitContainer() {
35
+ return {
36
+ name: TRANSFER_TOOLS_VOLUME,
37
+ image: exports.HELPER_TOOLS_IMAGE,
38
+ command: [
39
+ '/bin/busybox',
40
+ 'sh',
41
+ '-c',
42
+ `/bin/busybox cp /bin/busybox ${exports.TRANSFER_BUSYBOX} && /bin/busybox mkdir -p ${TRANSFER_BIN} && ${exports.TRANSFER_BUSYBOX} --install -s ${TRANSFER_BIN}`,
43
+ ],
44
+ volumeMounts: [{ name: TRANSFER_TOOLS_VOLUME, mountPath: exports.TRANSFER_TOOLS_PATH }],
45
+ securityContext: {
46
+ runAsNonRoot: true,
47
+ runAsUser: 65534,
48
+ allowPrivilegeEscalation: false,
49
+ readOnlyRootFilesystem: true,
50
+ capabilities: { drop: ['ALL'] },
51
+ },
52
+ // its own requests: the defaults of a namespace are sized for tasks, and a pod's
53
+ // request is the larger of its init containers' and the sum of its containers'
54
+ resources: { requests: { cpu: '10m', memory: '16Mi' }, limits: { memory: '16Mi' } },
55
+ };
56
+ }
57
+ exports.getTransferToolsInitContainer = getTransferToolsInitContainer;
58
+ exports.TRANSFER_TOOLS_VOLUMES = [{ name: TRANSFER_TOOLS_VOLUME, emptyDir: {} }];
59
+ exports.TRANSFER_TOOLS_MOUNT = {
60
+ name: TRANSFER_TOOLS_VOLUME,
61
+ mountPath: exports.TRANSFER_TOOLS_PATH,
62
+ readOnly: true,
63
+ };
64
+ // the tools a script of the transfer pod runs, and nothing else
65
+ exports.TRANSFER_TOOLS_ENV = [{ name: 'PATH', value: TRANSFER_BIN }];
66
+ //# sourceMappingURL=transfer-tools.js.map
@@ -11,14 +11,14 @@ const hosted_volumes_1 = require("./hosted-volumes");
11
11
  * checkout it did not write either: a `src: ../..` or a link in the checkout would
12
12
  * have the server mount or upload its own files (its credentials, other callers'
13
13
  * caches) into a task. Checked when the run is planned and again before each item
14
- * runs, since an earlier task may have left a link behind.
14
+ * runs, since an earlier task may have left a link behind: the sources and outputs it
15
+ * inherits from its dependencies too, which a task after them may have swapped for a link.
15
16
  */
16
17
  async function assertItemPathsWithinRoot(item, root) {
17
18
  const data = item.data;
18
19
  for (const source of 'src' in data ? data.src : []) {
19
- if (!source.inherited) {
20
- await (0, within_root_1.assertWithinRoot)(root, source.absolutePath, `${item.name}: src ${source.source}`);
21
- }
20
+ const of = source.inherited ? ` of ${source.inherited.name}` : '';
21
+ await (0, within_root_1.assertWithinRoot)(root, source.absolutePath, `${item.name}: src ${source.source}${of}`);
22
22
  }
23
23
  if ((0, work_task_1.isContainerWorkTask)(data) || (0, work_service_1.isContainerWorkService)(data)) {
24
24
  for (const mount of data.mounts) {
@@ -34,9 +34,8 @@ async function assertItemPathsWithinRoot(item, root) {
34
34
  }
35
35
  if ((0, work_task_1.isWorkTask)(data)) {
36
36
  for (const generate of data.generates) {
37
- if (!generate.inherited) {
38
- await (0, within_root_1.assertWithinRoot)(root, generate.path, `${item.name}: generates ${generate.path}`);
39
- }
37
+ const of = generate.inherited ? ` of ${generate.inherited.name}` : '';
38
+ await (0, within_root_1.assertWithinRoot)(root, generate.path, `${item.name}: generates ${generate.path}${of}`);
40
39
  }
41
40
  }
42
41
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.dockerServiceRuntime = exports.dockerTaskRuntime = void 0;
3
+ exports.dockerServiceRuntime = exports.getCacheHelperOptions = exports.dockerTaskRuntime = void 0;
4
4
  const run_labels_1 = require("../docker/run-labels");
5
5
  const execute_docker_1 = require("../executer/execute-docker");
6
6
  const remove_container_1 = require("../docker/remove-container");
@@ -11,8 +11,7 @@ const using_container_1 = require("../docker/using-container");
11
11
  const event_cache_1 = require("../executer/event-cache");
12
12
  const get_docker_executor_1 = require("../executer/get-docker-executor");
13
13
  const path_1 = require("path");
14
- const tar_1 = require("tar");
15
- const tar_2 = require("../utils/tar");
14
+ const tar_1 = require("../utils/tar");
16
15
  const plan_work_volume_1 = require("./utils/plan-work-volume");
17
16
  const work_instance_id_1 = require("./work-instance-id");
18
17
  const stream_1 = require("stream");
@@ -117,20 +116,11 @@ exports.dockerTaskRuntime = dockerTaskRuntime;
117
116
  function isOnHost(generate) {
118
117
  return generate.isFile || generate.export;
119
118
  }
120
- async function restoreContainer(docker, environment, item, path) {
121
- await (0, execution_steps_1.refuseHostLinks)(item, environment);
122
- // on a server the volumes the outputs are restored into carry the run's files, so they
123
- // are removed with a sandbox
124
- const root = (0, execution_steps_1.hostedRoot)(environment);
125
- if (root) {
126
- const names = item.data.type === 'container-service'
127
- ? item.data.volumes.filter((v) => !v.inherited).map((v) => v.name)
128
- : item.data.generates.filter((v) => !v.inherited && !v.isFile).map((v) => v.volumeName);
129
- for (const name of names) {
130
- await (0, get_docker_executor_1.ensureVolumeExists)(docker, item.status, name, (0, get_docker_executor_1.volumeLabels)(root));
131
- }
132
- }
133
- await (0, using_container_1.usingContainer)(docker, item, {
119
+ // The container that copies an item's outputs into and out of its volumes for the cache:
120
+ // the item's image with those volumes mounted, kept running while archives go in or out.
121
+ // The image is the item's, so whatever its network, this step has none.
122
+ function getCacheHelperOptions(item, environment) {
123
+ return {
134
124
  abortSignal: environment.abortCtrl.signal,
135
125
  Image: item.data.image,
136
126
  Tty: true,
@@ -145,18 +135,32 @@ async function restoreContainer(docker, environment, item, path) {
145
135
  },
146
136
  HostConfig: {
147
137
  AutoRemove: true,
148
- // mount the same volumes archiveContainer reads from, so the restored
149
- // archives land in the task's output volumes rather than in this
150
- // throwaway container's filesystem
138
+ NetworkMode: 'none',
139
+ // the item's own output volumes, so restored archives land there rather than in
140
+ // this throwaway container's filesystem
151
141
  Binds: item.data.type === 'container-service'
152
- ? item.data.volumes
153
- .filter((v) => !v.inherited)
154
- .map((v) => `${v.name}:${(0, execute_docker_1.convertToPosixPath)(v.containerPath)}`)
142
+ ? item.data.volumes.filter((v) => !v.inherited).map((v) => `${v.name}:${(0, execute_docker_1.convertToPosixPath)(v.containerPath)}`)
155
143
  : item.data.generates
156
144
  .filter((v) => !v.inherited && !v.isFile)
157
145
  .map((v) => `${v.volumeName}:${(0, execute_docker_1.convertToPosixPath)(v.path)}`),
158
146
  },
159
- }, async (container) => {
147
+ };
148
+ }
149
+ exports.getCacheHelperOptions = getCacheHelperOptions;
150
+ async function restoreContainer(docker, environment, item, path) {
151
+ await (0, execution_steps_1.refuseHostLinks)(item, environment);
152
+ // on a server the volumes the outputs are restored into carry the run's files, so they
153
+ // are removed with a sandbox
154
+ const root = (0, execution_steps_1.hostedRoot)(environment);
155
+ if (root) {
156
+ const names = item.data.type === 'container-service'
157
+ ? item.data.volumes.filter((v) => !v.inherited).map((v) => v.name)
158
+ : item.data.generates.filter((v) => !v.inherited && !v.isFile).map((v) => v.volumeName);
159
+ for (const name of names) {
160
+ await (0, get_docker_executor_1.ensureVolumeExists)(docker, item.status, name, (0, get_docker_executor_1.volumeLabels)(root));
161
+ }
162
+ }
163
+ await (0, using_container_1.usingContainer)(docker, item, getCacheHelperOptions(item, environment), async (container) => {
160
164
  for (const generate of (0, event_cache_1.getArchivePaths)(item.data, path)) {
161
165
  if (await environment.file.exists(generate.filename)) {
162
166
  // a cache hit means exactly the stored outputs: whatever a failed or
@@ -174,7 +178,7 @@ async function restoreContainer(docker, environment, item, path) {
174
178
  for (const generate of (0, event_cache_1.getArchivePaths)(item.data, path)) {
175
179
  if (onHost.has(generate.path) && (await environment.file.exists(generate.filename))) {
176
180
  await environment.file.remove(generate.path);
177
- await (0, tar_1.extract)({ file: generate.filename, cwd: (0, path_1.dirname)(generate.path) });
181
+ await (0, tar_1.extractOutput)(generate.filename, (0, path_1.dirname)(generate.path), (0, path_1.basename)(generate.path), !!environment.hosted);
178
182
  }
179
183
  }
180
184
  }
@@ -273,37 +277,14 @@ function dockerServiceRuntime(service, workEnvironment) {
273
277
  exports.dockerServiceRuntime = dockerServiceRuntime;
274
278
  async function archiveContainer(docker, environment, item, path) {
275
279
  await (0, execution_steps_1.refuseHostLinks)(item, environment);
276
- await (0, using_container_1.usingContainer)(docker, item, {
277
- abortSignal: environment.abortCtrl.signal,
278
- Image: item.data.image,
279
- Tty: true,
280
- Entrypoint: ['sh'],
281
- Cmd: ['-c', 'sleep 3600'],
282
- WorkingDir: (0, execute_docker_1.convertToPosixPath)(item.data.cwd),
283
- Labels: {
284
- app: 'hammerkit',
285
- 'hammerkit-id': (0, work_instance_id_1.getWorkInstanceId)(item),
286
- ...(0, run_labels_1.getRunLabels)(),
287
- 'hammerkit-type': 'task',
288
- },
289
- HostConfig: {
290
- AutoRemove: true,
291
- Binds: item.data.type === 'container-service'
292
- ? item.data.volumes
293
- .filter((v) => !v.inherited)
294
- .map((v) => `${v.name}:${(0, execute_docker_1.convertToPosixPath)(v.containerPath)}`)
295
- : item.data.generates
296
- .filter((v) => !v.inherited && !v.isFile)
297
- .map((v) => `${v.volumeName}:${(0, execute_docker_1.convertToPosixPath)(v.path)}`),
298
- },
299
- }, async (container) => {
280
+ await (0, using_container_1.usingContainer)(docker, item, getCacheHelperOptions(item, environment), async (container) => {
300
281
  const hostFiles = new Set(item.data.type === 'container-task'
301
282
  ? item.data.generates.filter((g) => !g.inherited && g.isFile).map((g) => g.path)
302
283
  : []);
303
284
  for (const generatedArchive of (0, event_cache_1.getArchivePaths)(item.data, path)) {
304
285
  // a file output is a bind mount of a host file, so archive it from the host
305
286
  const readable = hostFiles.has(generatedArchive.path)
306
- ? stream_1.Readable.from((0, tar_2.packArchive)({ cwd: (0, path_1.dirname)(generatedArchive.path) }, [(0, path_1.basename)(generatedArchive.path)]))
287
+ ? stream_1.Readable.from((0, tar_1.packArchive)({ cwd: (0, path_1.dirname)(generatedArchive.path) }, [(0, path_1.basename)(generatedArchive.path)]))
307
288
  : await container.getArchive({
308
289
  path: generatedArchive.path,
309
290
  });
@@ -4,8 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getLocalWorkRuntime = exports.getStateFilename = void 0;
7
- const tar_1 = require("tar");
8
- const tar_2 = require("../utils/tar");
7
+ const tar_1 = require("../utils/tar");
9
8
  const path_1 = require("path");
10
9
  const local_task_1 = require("../executer/local-task");
11
10
  const event_cache_1 = require("../executer/event-cache");
@@ -122,7 +121,7 @@ async function archiveLocal(environment, task, path) {
122
121
  for (const generatedArchive of (0, event_cache_1.getArchivePaths)(task.data, path)) {
123
122
  await environment.file.writeStream(generatedArchive.filename,
124
123
  // tar's stream is a Minipass stream; Readable.from adapts it to a Node one
125
- stream_1.Readable.from((0, tar_2.packArchive)({ cwd: task.data.cwd, gzip: true }, [(0, path_1.relative)(task.data.cwd, generatedArchive.path)])));
124
+ stream_1.Readable.from((0, tar_1.packArchive)({ cwd: task.data.cwd, gzip: true }, [(0, path_1.relative)(task.data.cwd, generatedArchive.path)])));
126
125
  }
127
126
  }
128
127
  async function restoreLocal(environment, task, path) {
@@ -131,10 +130,7 @@ async function restoreLocal(environment, task, path) {
131
130
  // a cache hit means exactly the stored outputs: whatever a failed or
132
131
  // older run left in the folder goes first
133
132
  await environment.file.remove(generate.path);
134
- await (0, tar_1.extract)({
135
- file: generate.filename,
136
- cwd: task.cwd,
137
- });
133
+ await (0, tar_1.extractOutput)(generate.filename, task.cwd, (0, path_1.relative)(task.cwd, generate.path), !!environment.hosted);
138
134
  }
139
135
  }
140
136
  }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.collectBundle = void 0;
4
+ const promises_1 = require("node:fs/promises");
4
5
  const path_1 = require("path");
5
6
  const resolve_git_source_1 = require("../includes/resolve-git-source");
6
7
  const schema_parser_1 = require("../schema/schema-parser");
@@ -10,7 +11,10 @@ const bundle_1 = require("./bundle");
10
11
  // The build file is read with the parser of a run, so what it pulls in is what a
11
12
  // run would read. Git includes are not part of it (the server fetches them, at
12
13
  // the commit they are pinned to), and neither is anything outside of the
13
- // directory of the build file, which a server could not reproduce.
14
+ // directory of the build file, which a server could not reproduce. That holds for
15
+ // where a file really is too: a link to a file outside of the directory is refused
16
+ // rather than followed, so publishing a checkout never sends a file of this machine
17
+ // that the checkout only points to.
14
18
  async function collectBundle(fileName, environment) {
15
19
  if (!(await environment.file.exists(fileName))) {
16
20
  throw new Error(`there is no build file at ${fileName}`);
@@ -24,11 +28,15 @@ async function collectBundle(fileName, environment) {
24
28
  paths.add((0, path_1.resolve)(scope.fileName));
25
29
  }
26
30
  }
31
+ const realRoot = await (0, promises_1.realpath)(root);
27
32
  const files = {};
28
33
  for (const path of [...paths].sort()) {
29
34
  if (!(0, resolve_git_source_1.isWithin)(root, path)) {
30
35
  throw new Error(`${path} is outside of ${root}: a published build file can only include files below its own directory`);
31
36
  }
37
+ if (!(0, resolve_git_source_1.isWithin)(realRoot, await (0, promises_1.realpath)(path))) {
38
+ throw new Error(`${path} links to a file outside of ${root}: a published build file can only include files below its own directory`);
39
+ }
32
40
  files[(0, path_1.relative)(root, path).split(path_1.sep).join('/')] = await environment.file.read(path);
33
41
  }
34
42
  const result = bundle_1.bundleSchema.safeParse({ entry: (0, path_1.relative)(root, entryPath).split(path_1.sep).join('/'), files });