hammerkit 2.2.0-next.1 → 2.2.0-next.2

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.
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertMayRead = exports.assertMayWrite = exports.CacheWriteRefusedError = exports.pushCredentialFor = exports.isSameRepository = void 0;
4
+ const registry_reference_1 = require("./registry-reference");
5
+ // The same registry and repository, however a build file or the configuration writes them: as
6
+ // docker reads them, so `https://ghcr.io/o/c/` and `ghcr.io/o/c` are one. False for a reference
7
+ // it can not read.
8
+ function isSameRepository(a, b) {
9
+ try {
10
+ const left = (0, registry_reference_1.parseRegistryReference)(a);
11
+ const right = (0, registry_reference_1.parseRegistryReference)(b);
12
+ return left.host === right.host && left.repository === right.repository;
13
+ }
14
+ catch {
15
+ return false;
16
+ }
17
+ }
18
+ exports.isSameRepository = isSameRepository;
19
+ // The credential to write `repository` with: the server's, and only for the repository it is
20
+ // configured for. Null for any other repository, so a build file can not point it elsewhere.
21
+ function pushCredentialFor(environment, repository) {
22
+ const push = environment.hosted?.cachePush;
23
+ return push && isSameRepository(push.repository, repository)
24
+ ? { username: push.username, password: push.password }
25
+ : null;
26
+ }
27
+ exports.pushCredentialFor = pushCredentialFor;
28
+ // A write a server run may not make: the run reads the registry and keeps its results to itself.
29
+ class CacheWriteRefusedError extends Error {
30
+ }
31
+ exports.CacheWriteRefusedError = CacheWriteRefusedError;
32
+ // A run on a server writes a registry only with the server's credential for it. Outside of a
33
+ // server (a developer's machine, a CI job of its own) hosted is not set and the registry's own
34
+ // logins are used, as before.
35
+ function assertMayWrite(environment, repository) {
36
+ if (environment.hosted && !pushCredentialFor(environment, repository)) {
37
+ throw new CacheWriteRefusedError(`this server writes ${repository} only as a trusted run of its cache.push configuration, this run may not`);
38
+ }
39
+ }
40
+ exports.assertMayWrite = assertMayWrite;
41
+ // A server run reads only the registries its operator allows: `cache.registries`, and the
42
+ // registry of each `cache.push` rule. Outside of a server nothing is refused.
43
+ function assertMayRead(environment, host) {
44
+ const hosted = environment.hosted;
45
+ if (hosted && !(hosted.cacheRegistries ?? []).includes(host)) {
46
+ throw new Error(`registry ${host} is not one of the registries this server reads (cache.registries)`);
47
+ }
48
+ }
49
+ exports.assertMayRead = assertMayRead;
50
+ //# sourceMappingURL=push-credentials.js.map
@@ -57,9 +57,12 @@ function basicHeader(credentials) {
57
57
  // mainstream registry (Docker Hub, GHCR, ECR, GAR, Artifactory, registry:2)
58
58
  // uses. Talks HTTP directly so no docker daemon or extra binary is involved.
59
59
  class RegistryClient {
60
- constructor(reference, environment) {
60
+ constructor(reference, environment,
61
+ // the server's own credential for this repository, when the run has one (push-credentials.ts)
62
+ serverCredentials = null) {
61
63
  this.reference = reference;
62
64
  this.environment = environment;
65
+ this.serverCredentials = serverCredentials;
63
66
  this.authorization = null;
64
67
  this.credentials = undefined;
65
68
  }
@@ -67,12 +70,29 @@ class RegistryClient {
67
70
  const scheme = this.reference.insecure ? 'http' : 'https';
68
71
  return `${scheme}://${this.reference.host}/v2/${this.reference.repository}/${path}`;
69
72
  }
73
+ // A request is the registry's own only on its origin: an upload location, a blob on a CDN or a
74
+ // redirect elsewhere gets no credential and no token (fetch drops the header on a redirect too).
75
+ isOwnOrigin(url) {
76
+ return new URL(url).origin === new URL(this.url('')).origin;
77
+ }
78
+ // On a server run the server's credential is the only one: the docker login of the run's home
79
+ // is never read, so a build file can not reach it (ADR-0010).
70
80
  async getCredentials() {
71
81
  if (this.credentials === undefined) {
72
- this.credentials = await (0, registry_credentials_1.resolveRegistryCredentials)(this.reference.credentialHost, this.environment);
82
+ this.credentials = this.environment.hosted
83
+ ? this.serverCredentials
84
+ : this.serverCredentials ?? (await (0, registry_credentials_1.resolveRegistryCredentials)(this.reference.credentialHost, this.environment));
73
85
  }
74
86
  return this.credentials;
75
87
  }
88
+ // On a server run a token is requested only from https, and from the registry or an allowed host.
89
+ mayAskForToken(tokenUrl) {
90
+ if (!this.environment.hosted) {
91
+ return true;
92
+ }
93
+ const allowed = [this.reference.host, ...(this.environment.hosted.cacheRegistries ?? [])];
94
+ return tokenUrl.protocol === 'https:' && allowed.includes(tokenUrl.host);
95
+ }
76
96
  async authenticate(challengeHeader) {
77
97
  if (!challengeHeader) {
78
98
  return false;
@@ -90,6 +110,9 @@ class RegistryClient {
90
110
  return false;
91
111
  }
92
112
  const tokenUrl = new URL(challenge.params.realm);
113
+ if (!this.mayAskForToken(tokenUrl)) {
114
+ throw new RegistryError(`the registry names a token service this server does not trust: ${tokenUrl.host}`);
115
+ }
93
116
  if (challenge.params.service) {
94
117
  tokenUrl.searchParams.set('service', challenge.params.service);
95
118
  }
@@ -114,27 +137,35 @@ class RegistryClient {
114
137
  // on some Node versions.
115
138
  async request(method, urlOrPath, init = {}) {
116
139
  const url = urlOrPath.startsWith('http') ? urlOrPath : this.url(urlOrPath);
117
- // the credentials are the registry's: an upload location or a next page elsewhere (another
118
- // host, another port, or http in place of https) gets none, as fetch does on a redirect
119
- const own = new URL(url).origin === new URL(this.url('')).origin;
120
- const send = () => fetch(url, {
140
+ const send = (target) => fetch(target, {
121
141
  method,
122
142
  headers: {
123
143
  ...(init.headers ?? {}),
124
- ...(own && this.authorization ? { authorization: this.authorization } : {}),
144
+ // the credentials are the registry's only: see isOwnOrigin
145
+ ...(this.authorization && this.isOwnOrigin(target) ? { authorization: this.authorization } : {}),
125
146
  },
126
147
  // BodyInit of Node's fetch, also when the dashboard checks these types with the DOM's
127
148
  body: init.body?.(),
128
149
  redirect: init.redirect ?? 'follow',
129
150
  });
130
- let response = await send();
131
- if (own && response.status === 401 && (await this.authenticate(response.headers.get('www-authenticate')))) {
151
+ let response = await send(url);
152
+ // the origin the answer came from, after any redirect: a 401 of another origin is not the
153
+ // registry's to answer for, so it gets no token and the credential stays here
154
+ const reached = response.url || url;
155
+ if (this.isOwnOrigin(reached) &&
156
+ response.status === 401 &&
157
+ (await this.authenticate(response.headers.get('www-authenticate')))) {
132
158
  await response.body?.cancel();
133
- response = await send();
159
+ response = await send(url);
134
160
  }
135
161
  return response;
136
162
  }
137
163
  async fail(response, what) {
164
+ if (this.environment.hosted) {
165
+ // the body of a registry is its own text: a server run says the status and no more
166
+ await response.body?.cancel().catch(() => undefined);
167
+ throw new RegistryError(`${what} failed with ${response.status}`, response.status);
168
+ }
138
169
  const text = await response.text().catch(() => '');
139
170
  const hint = response.status === 401 || response.status === 403 ? ' (check `docker login` for this registry)' : '';
140
171
  throw new RegistryError(`${what} failed with ${response.status} ${text.substring(0, 200)}${hint}`.trim(), response.status);
@@ -7,6 +7,7 @@ const path_1 = require("path");
7
7
  const tar_1 = require("tar");
8
8
  const tar_2 = require("../../utils/tar");
9
9
  const registry_reference_1 = require("./registry/registry-reference");
10
+ const push_credentials_1 = require("./registry/push-credentials");
10
11
  const registry_client_1 = require("./registry/registry-client");
11
12
  const MAX_TAG_LENGTH = 128;
12
13
  // The deterministic tag for one entry. A task id (sha1) plus a state key (md5)
@@ -38,9 +39,10 @@ function createRegistryCacheBackend(spec) {
38
39
  const reference = (0, registry_reference_1.parseRegistryReference)(spec.repository, spec.insecure);
39
40
  const clients = new WeakMap();
40
41
  const client = (environment) => {
42
+ (0, push_credentials_1.assertMayRead)(environment, reference.host);
41
43
  let instance = clients.get(environment);
42
44
  if (!instance) {
43
- instance = new registry_client_1.RegistryClient(reference, environment);
45
+ instance = new registry_client_1.RegistryClient(reference, environment, (0, push_credentials_1.pushCredentialFor)(environment, spec.repository));
44
46
  clients.set(environment, instance);
45
47
  }
46
48
  return instance;
@@ -70,6 +72,7 @@ function createRegistryCacheBackend(spec) {
70
72
  });
71
73
  },
72
74
  async push(taskId, stateKey, from, environment) {
75
+ (0, push_credentials_1.assertMayWrite)(environment, spec.repository);
73
76
  const registry = client(environment);
74
77
  await withTempDir(environment, async (dir) => {
75
78
  const layerFile = (0, path_1.join)(dir, 'layer.tar');
@@ -97,6 +100,7 @@ function createRegistryCacheBackend(spec) {
97
100
  });
98
101
  },
99
102
  async clear(taskId, environment) {
103
+ (0, push_credentials_1.assertMayWrite)(environment, spec.repository);
100
104
  const registry = client(environment);
101
105
  const tags = (await registry.listTags()).filter((tag) => tag.startsWith(`${taskId}-`));
102
106
  for (const tag of tags) {
@@ -133,6 +137,7 @@ function createRegistryCacheBackend(spec) {
133
137
  return entries;
134
138
  },
135
139
  async remove(taskId, stateKey, environment) {
140
+ (0, push_credentials_1.assertMayWrite)(environment, spec.repository);
136
141
  const registry = client(environment);
137
142
  const digest = await registry.manifestDigest(entryTag(taskId, stateKey));
138
143
  if (digest) {
@@ -61,6 +61,9 @@ async function pruneCache(workTree, cacheName, policy, options, environment) {
61
61
  return plan;
62
62
  }
63
63
  exports.pruneCache = pruneCache;
64
+ // `cache prune` is a command of the CLI, which a server never runs: a server's worker runs `exec`
65
+ // and `up`, and autoPrune below only touches machine-local caches. So a registry's
66
+ // CacheWriteRefusedError (push-credentials.ts) can't reach a server run from here.
64
67
  // After a successful run: prune every machine-local cache the run used that
65
68
  // declares a retention policy. Remote caches are never pruned implicitly.
66
69
  async function autoPrune(workTree, environment) {
@@ -98,6 +98,8 @@ async function storeCache(environment, path, workTree) {
98
98
  }
99
99
  }
100
100
  exports.storeCache = storeCache;
101
+ // `clean` is a command of the CLI: a server runs `exec` and `up` only, so no run of it removes the
102
+ // entries of a registry (CacheWriteRefusedError, see push-credentials.ts)
101
103
  async function cleanCache(workTree, environment, options) {
102
104
  for (const task of (0, plan_work_tasks_1.iterateWorkTasks)(workTree)) {
103
105
  await task.runtime.remove(environment);
@@ -14,6 +14,7 @@ const archive_task_entry_1 = require("./archive-task-entry");
14
14
  const units_1 = require("../utils/units");
15
15
  const deferred_restore_1 = require("./deferred-restore");
16
16
  const task_priority_1 = require("./task-priority");
17
+ const push_credentials_1 = require("../cache/backends/registry/push-credentials");
17
18
  async function pushToBackend(work, environment, cacheState, options) {
18
19
  const { resolved, stateKey, provable } = cacheState;
19
20
  // an aggregate has nothing to store, see checkCacheState
@@ -30,6 +31,13 @@ async function pushToBackend(work, environment, cacheState, options) {
30
31
  work.status.write('info', `${work.name} pushed to cache "${resolved.name}" (${resolved.backend.type})`);
31
32
  }
32
33
  catch (e) {
34
+ // a run that may only read a registry is not a failure of its task; a trusted run that could
35
+ // not write its cache is, as the cache then holds nothing it pushed
36
+ if (e instanceof push_credentials_1.CacheWriteRefusedError) {
37
+ const level = environment.hosted?.cachePush ? 'warn' : 'debug';
38
+ work.status.write(level, `${work.name} not pushed to cache "${resolved.name}" (${(0, log_1.getErrorMessage)(e)})`);
39
+ return;
40
+ }
33
41
  work.status.write('warn', `${work.name} failed to push to cache "${resolved.name}": ${(0, log_1.getErrorMessage)(e)}`);
34
42
  }
35
43
  }
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cacheRegistriesOf = exports.cachePushOf = void 0;
4
+ const registry_reference_1 = require("../cache/backends/registry/registry-reference");
5
+ const policy_1 = require("./policy");
6
+ const repo_1 = require("./repo");
7
+ // a ref may name a commit, which is no branch of the repository (see git-checkout.ts)
8
+ const COMMIT = /^[0-9a-f]{40}([0-9a-f]{24})?$/i;
9
+ // Whether a run writes a registry cache, and with which credential (ADR-0010). Every run reads
10
+ // the caches of its build file; only a trusted run writes one, and the answer is null for all
11
+ // others, which fails closed:
12
+ // - a run from a git ref that resolved as a branch when the server pinned it (`branch`, so a tag
13
+ // that matches a branch pattern is not one), of a repository and branch `cache.push` lists
14
+ // - by a caller who may publish build files, who is trusted with what the cache then holds; a
15
+ // caller whose grant is gone is no longer one
16
+ // - with a password the server's environment holds for the rule's registry
17
+ //
18
+ // The build file takes no part in it: a run writes the registry of its own configuration only.
19
+ // `envs` is the server's own environment, not the one of a run, which holds the allowlist.
20
+ function cachePushOf(run, config, envs) {
21
+ const source = run.source;
22
+ if (source.type !== 'ref' || source.branch !== true || COMMIT.test(source.ref)) {
23
+ return null;
24
+ }
25
+ const grant = (0, policy_1.getGrant)(config.entitlements, {
26
+ iss: run.owner.iss,
27
+ sub: run.owner.sub,
28
+ groups: run.owner.groups ?? [],
29
+ claims: run.owner.claims ?? {},
30
+ });
31
+ if (!(0, policy_1.mayPublish)(grant)) {
32
+ return null;
33
+ }
34
+ // the first rule that covers the run decides, even when its password is missing
35
+ const rule = config.cache.push.find((entry) => (0, repo_1.matchesRepo)(entry.repo, source.repo) && (0, repo_1.matchesRef)(entry.refs, source.ref));
36
+ const password = rule ? envs[rule.registry.passwordEnv] : undefined;
37
+ if (!rule || !password) {
38
+ return null;
39
+ }
40
+ return { repository: rule.registry.repository, username: rule.registry.username, password };
41
+ }
42
+ exports.cachePushOf = cachePushOf;
43
+ // The registry hosts a server run may read its caches from: `cache.registries`, and the host of
44
+ // each `cache.push` rule, which the operator named already.
45
+ function cacheRegistriesOf(config) {
46
+ const hosts = config.cache.push.map((rule) => (0, registry_reference_1.parseRegistryReference)(rule.registry.repository).host);
47
+ return [...new Set([...config.cache.registries, ...hosts])];
48
+ }
49
+ exports.cacheRegistriesOf = cacheRegistriesOf;
50
+ //# sourceMappingURL=cache-push.js.map
@@ -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.cacheNamespace = exports.defaultWorker = void 0;
3
+ exports.HostExecutor = 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");
@@ -67,6 +67,14 @@ function cacheNamespace(run) {
67
67
  return `${kind}-${(0, crypto_1.createHash)('sha256').update(key).digest('hex').slice(0, 24)}`;
68
68
  }
69
69
  exports.cacheNamespace = cacheNamespace;
70
+ // The local cache of a run that pushes to a registry (ADR-0010). Only the runs that push write it,
71
+ // and a pushing run restores from it and from the registry, never from the cache the other runs of
72
+ // the repository share: what an untrusted run left there is no result to push.
73
+ function pushCacheNamespace(run) {
74
+ const key = `push\0${run.source.repo}`;
75
+ return `push-${(0, crypto_1.createHash)('sha256').update(key).digest('hex').slice(0, 24)}`;
76
+ }
77
+ exports.pushCacheNamespace = pushCacheNamespace;
70
78
  // The docker volumes of a run's services are its caller's, within the cache's source trust:
71
79
  // two callers of one repository share a cache, a task is keyed by what it reads, but not the
72
80
  // data their services keep. A service run's are its own: they stay while it sleeps and go
@@ -396,7 +404,10 @@ class HostExecutor {
396
404
  emitPhase(context, 'source', sourceStarted);
397
405
  const home = (0, path_1.join)(root, 'home');
398
406
  await (0, promises_1.mkdir)(home, { recursive: true });
399
- const cache = (0, path_1.join)(this.options.cache, cacheNamespace(run));
407
+ // a run writes a registry cache only with the server's credential for it (ADR-0010); a run
408
+ // that does has a local cache of its own, which no other run writes
409
+ const push = this.options.cachePush?.(run) ?? null;
410
+ const cache = (0, path_1.join)(this.options.cache, push ? pushCacheNamespace(run) : cacheNamespace(run));
400
411
  await (0, promises_1.mkdir)(cache, { recursive: true });
401
412
  const placement = this.options.placement;
402
413
  const namespaceStarted = new Date();
@@ -409,6 +420,8 @@ class HostExecutor {
409
420
  ...input,
410
421
  tasks: run.tasks,
411
422
  options: run.options,
423
+ ...(push ? { cachePush: push } : {}),
424
+ cacheRegistries: this.options.cacheRegistries ?? [],
412
425
  accounts: run.accounts,
413
426
  volumeScope: volumeScope(run, this.options.directory),
414
427
  ...((0, checks_1.isCheckRun)(run) ? { check: true } : {}),
@@ -20,6 +20,7 @@ const task_arguments_1 = require("../planner/utils/task-arguments");
20
20
  const work_network_1 = require("../planner/work-network");
21
21
  const run_source_envs_1 = require("../environment/run-source-envs");
22
22
  const prefetch_secrets_1 = require("../secrets/prefetch-secrets");
23
+ const registry_reference_1 = require("../cache/backends/registry/registry-reference");
23
24
  class DefinitionError extends Error {
24
25
  }
25
26
  exports.DefinitionError = DefinitionError;
@@ -72,12 +73,31 @@ function checkGitSource(path, where, source, noRemote) {
72
73
  }
73
74
  }
74
75
  // What a build file may not name on a server: the places it would run or store things
75
- // are the operator's. The docker host, a Kubernetes cluster and a remote cache are
76
- // credentials of the machine, not of the build file, and a project file that could carry
77
- // them could send runs, or the cache, anywhere.
76
+ // are the operator's. The docker host and a Kubernetes cluster are credentials of the machine,
77
+ // not of the build file, and a project file that could carry them could send runs anywhere. A
78
+ // remote cache is named by the build file only as a registry, which the server reads, and writes
79
+ // with its own credential for it (cache.push, ADR-0010).
78
80
  // A file a server leaves out (`publish: false`) is not checked, and neither is a service
79
81
  // with `publish: false`: what is left out is never run there.
80
- function findHostProblems(files) {
82
+ // What a registry cache a build file names needs to be on a server: a reference that parses, over
83
+ // https (a localhost registry is http, so refused), on a host the operator allows. Null when it is.
84
+ function checkRegistry(repository, allowed) {
85
+ let reference;
86
+ try {
87
+ reference = (0, registry_reference_1.parseRegistryReference)(repository);
88
+ }
89
+ catch (e) {
90
+ return (0, log_1.getErrorMessage)(e);
91
+ }
92
+ if (reference.insecure) {
93
+ return 'a server keeps its own cache, a build file names no path, s3 bucket or insecure registry (localhost is http)';
94
+ }
95
+ if (!allowed.includes(reference.host)) {
96
+ return `registry ${reference.host} is not one of the registries this server reads (cache.registries: ${allowed.join(', ') || 'none'})`;
97
+ }
98
+ return null;
99
+ }
100
+ function findHostProblems(files, allowed) {
81
101
  const problems = [];
82
102
  for (const [path, content] of Object.entries(files)) {
83
103
  let document;
@@ -94,9 +114,20 @@ function findHostProblems(files) {
94
114
  problems.push(`${path}: environments pick a docker host or a Kubernetes cluster, which are the server's to choose, remove them`);
95
115
  }
96
116
  for (const [name, cache] of Object.entries(document.caches ?? {})) {
97
- if (cache?.backend?.type !== 'local' || cache.backend.path !== undefined) {
98
- problems.push(`${path}: caches.${name}: a server keeps its own cache, a build file names no backend or path`);
117
+ const backend = cache?.backend;
118
+ if (backend?.type === 'local' && backend.path === undefined) {
119
+ continue;
120
+ }
121
+ // a registry is read over https from a host the operator allows; the server writes it only
122
+ // as a trusted run (cache.push), so the build file names no credential
123
+ if (backend?.type === 'registry' && typeof backend.repository === 'string' && !backend.insecure) {
124
+ const problem = checkRegistry(backend.repository, allowed);
125
+ if (problem) {
126
+ problems.push(`${path}: caches.${name}: ${problem}`);
127
+ }
128
+ continue;
99
129
  }
130
+ problems.push(`${path}: caches.${name}: a server keeps its own cache, a build file names no path, s3 bucket or insecure registry`);
100
131
  }
101
132
  for (const [name, service] of Object.entries(document.services ?? {})) {
102
133
  if (service &&
@@ -427,7 +458,7 @@ async function planBundle(bundle, environment, options = {}) {
427
458
  : (0, path_1.relative)(directory, from.fileName), `${block}.${name}`, source, options.noRemote),
428
459
  });
429
460
  if (options.policy) {
430
- const problems = findHostProblems(publishedBundleFiles(bundle, directory, scope));
461
+ const problems = findHostProblems(publishedBundleFiles(bundle, directory, scope), options.policy.cacheRegistries ?? []);
431
462
  if (problems.length > 0) {
432
463
  throw new DefinitionError(problems.join('\n'));
433
464
  }
@@ -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.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 = void 0;
4
4
  const readline_1 = require("readline");
5
5
  const zod_1 = require("zod");
6
6
  const cli_1 = require("../cli");
@@ -63,6 +63,19 @@ exports.workerInputSchema = zod_1.z
63
63
  // on the server's docker host, the runtime a container that adds capabilities runs in
64
64
  // (`backend.capabilities.runtime`)
65
65
  capabilityRuntime: zod_1.z.string().min(1).optional(),
66
+ // the server's credential to write a registry cache with, for a trusted run only (`cache.push`,
67
+ // see cache-push.ts); left out for any other run, which may only read the caches
68
+ cachePush: zod_1.z
69
+ .object({
70
+ repository: zod_1.z.string().min(1),
71
+ username: zod_1.z.string().min(1),
72
+ password: zod_1.z.string().min(1),
73
+ })
74
+ .strict()
75
+ .optional(),
76
+ // the registry hosts the run may read its caches from (`cache.registries`, and each `cache.push`
77
+ // rule's registry): a build file's cache of any other is refused
78
+ cacheRegistries: zod_1.z.array(zod_1.z.string().min(1)).optional(),
66
79
  // the most any task or service reaches besides its needs, as `--network`: `runs.network`
67
80
  network: network_schema_1.networkSchema.optional(),
68
81
  // for a run on a sandbox, `sandboxes.network`: the run gets the lower of the two
@@ -229,6 +242,30 @@ async function removeCommandsOfRun(input, commands, emit) {
229
242
  }
230
243
  }
231
244
  exports.removeCommandsOfRun = removeCommandsOfRun;
245
+ // The secrets of a run, masked in what it logs: the password of its cache push, as a secret of a
246
+ // task is (ADR-0010).
247
+ function createRunSecrets(input) {
248
+ const secrets = (0, redact_1.createSecretRegistry)();
249
+ if (input.cachePush) {
250
+ secrets.register(input.cachePush.password);
251
+ }
252
+ return secrets;
253
+ }
254
+ exports.createRunSecrets = createRunSecrets;
255
+ // What the engine of a run knows of its server: the credential to write a cache with, and the
256
+ // registries it may read, which only a server run has (see HostedPolicy).
257
+ function getRunHosted(input, commands) {
258
+ return {
259
+ catalog: input.catalog,
260
+ accounts: input.accounts,
261
+ kubernetes: input.kubernetes,
262
+ capabilityRuntime: input.capabilityRuntime,
263
+ runnerCommands: commands,
264
+ cacheRegistries: input.cacheRegistries ?? [],
265
+ ...(input.cachePush ? { cachePush: input.cachePush } : {}),
266
+ };
267
+ }
268
+ exports.getRunHosted = getRunHosted;
232
269
  // What a task says in the process of a run, as events: the lines it prints (with where the log
233
270
  // of its pod got to) and its warnings and errors, in the order they come. The `output` events
234
271
  // of the commands in a runner are emitted after the lines they count, on the same way (see
@@ -257,7 +294,7 @@ commands = getRunnerCommands(input, emit),
257
294
  // a service run: hands the changed files of its sandbox to the services that are up while
258
295
  // they are up (undefined once they are not)
259
296
  register) {
260
- const secrets = (0, redact_1.createSecretRegistry)();
297
+ const secrets = createRunSecrets(input);
261
298
  const status = (0, work_item_status_1.statusConsole)((0, empty_writable_1.emptyWritable)(), secrets);
262
299
  // the process starts in a directory of the server, the tasks work on the run's files
263
300
  const work = input.directory?.work ?? cwd;
@@ -265,13 +302,7 @@ register) {
265
302
  // is what is streamed: it is redacted with the secrets of this run
266
303
  const environment = {
267
304
  processEnvs,
268
- hosted: {
269
- catalog: input.catalog,
270
- accounts: input.accounts,
271
- kubernetes: input.kubernetes,
272
- capabilityRuntime: input.capabilityRuntime,
273
- runnerCommands: commands,
274
- },
305
+ hosted: getRunHosted(input, commands),
275
306
  abortCtrl,
276
307
  cwd: work,
277
308
  file: (0, get_file_context_1.getFileContext)(work),
@@ -14,6 +14,7 @@ const capabilities_schema_1 = require("../schema/capabilities-schema");
14
14
  const build_file_secret_provider_schema_1 = require("../schema/build-file-secret-provider-schema");
15
15
  const repo_1 = require("./repo");
16
16
  const work_network_1 = require("../planner/work-network");
17
+ const registry_reference_1 = require("../cache/backends/registry/registry-reference");
17
18
  const LOOPBACK_HOSTS = ['127.0.0.1', 'localhost', '::1'];
18
19
  exports.serverPlatformSchema = zod_1.z
19
20
  .object({
@@ -427,6 +428,41 @@ exports.sourceSchema = zod_1.z
427
428
  .optional(),
428
429
  })
429
430
  .strict();
431
+ // A trusted run of these repositories and branches writes a registry cache, with the credential
432
+ // of its registry. A build file can name the registry it reads from, never the credential; a run
433
+ // writes only the registry of the first rule that covers it, and only with that credential.
434
+ const cachePushSchema = zod_1.z
435
+ .object({
436
+ // the repositories, as a pattern of `host/path`, such as github.com/corp/*
437
+ repo: repoPatternSchema,
438
+ // the branches a trusted run is from: the default branch, such as `main` or `release/*`. A
439
+ // commit is never one, nor a tag, so a sandbox and an upload never are.
440
+ refs: zod_1.z.array(branchPatternSchema).min(1),
441
+ registry: zod_1.z
442
+ .object({
443
+ // the repository of the build file's `backend.repository`, written the same way; a password
444
+ // goes over https only, so a registry on localhost is refused here
445
+ repository: zod_1.z
446
+ .string()
447
+ .min(1)
448
+ .superRefine((value, ctx) => {
449
+ try {
450
+ if ((0, registry_reference_1.parseRegistryReference)(value).insecure) {
451
+ ctx.addIssue({ code: zod_1.z.ZodIssueCode.custom, message: 'a push credential goes over https only' });
452
+ }
453
+ }
454
+ catch (e) {
455
+ ctx.addIssue({ code: zod_1.z.ZodIssueCode.custom, message: (0, log_1.getErrorMessage)(e) });
456
+ }
457
+ }),
458
+ username: zod_1.z.string().min(1),
459
+ // the variable of the server's environment that holds its password or token; it is read
460
+ // by the server and passed to the one run that pushes, never to a task
461
+ passwordEnv: zod_1.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),
462
+ })
463
+ .strict(),
464
+ })
465
+ .strict();
430
466
  // The server config is written by an operator and reviewed like code, so a typo
431
467
  // is an error and not a silently ignored key.
432
468
  exports.serverConfigSchema = zod_1.z
@@ -479,6 +515,19 @@ exports.serverConfigSchema = zod_1.z
479
515
  .array(zod_1.z.enum(['docker', 'local']))
480
516
  .min(1)
481
517
  .default(['docker']),
518
+ // the registry caches of the build files a server runs: the hosts a run may read from
519
+ // (`registries`, besides those of the `push` rules, which are allowed already), and the rules
520
+ // by which a trusted run writes one (see cachePushSchema). A registry is read anonymously
521
+ // unless a rule of `push` writes it; nothing is read from a host not listed here.
522
+ cache: zod_1.z
523
+ .object({
524
+ registries: zod_1.z
525
+ .array(zod_1.z.string().regex(/^[A-Za-z0-9.-]+(:[0-9]{1,5})?$/, 'a registry host, such as ghcr.io'))
526
+ .default([]),
527
+ push: zod_1.z.array(cachePushSchema).default([]),
528
+ })
529
+ .strict()
530
+ .default({}),
482
531
  // where the server keeps what must survive a restart: the published build files
483
532
  storage: zod_1.z
484
533
  .object({ directory: zod_1.z.string().min(1).optional() })
@@ -693,6 +742,17 @@ exports.serverConfigSchema = zod_1.z
693
742
  })
694
743
  .strict()
695
744
  .superRefine((config, ctx) => {
745
+ // the password of a cache push is the server's alone: a variable a run sees would reach its tasks
746
+ config.cache.push.forEach((rule, index) => {
747
+ const name = rule.registry.passwordEnv;
748
+ if (config.runs.env.allow.includes(name) || Object.prototype.hasOwnProperty.call(config.runs.env.set, name)) {
749
+ ctx.addIssue({
750
+ code: zod_1.z.ZodIssueCode.custom,
751
+ path: ['cache', 'push', index, 'registry', 'passwordEnv'],
752
+ message: `${name} is seen by the runs (runs.env), the password of a cache push may not be`,
753
+ });
754
+ }
755
+ });
696
756
  const issuers = config.issuers.map((i) => i.issuer);
697
757
  config.entitlements.forEach((entitlement, index) => {
698
758
  const iss = (entitlement.subject ?? entitlement.group ?? entitlement.claims)?.iss;
@@ -10,6 +10,7 @@ const server_config_1 = require("./server-config");
10
10
  const discovery_1 = require("./discovery");
11
11
  const oauth_1 = require("./oauth");
12
12
  const policy_1 = require("./policy");
13
+ const cache_push_1 = require("./cache-push");
13
14
  const repo_1 = require("./repo");
14
15
  const run_store_1 = require("./run-store");
15
16
  const runs_1 = require("./runs");
@@ -398,6 +399,8 @@ function listRun(registry, definitions, viewer, run) {
398
399
  }
399
400
  // where in its repository the build file of a version is
400
401
  const entryOf = (definitions) => (definition) => definitions.find(definition)?.entry;
402
+ // a full commit hash, 40 or 64 hex digits: the ref of a run that names its commit
403
+ const FULL_COMMIT = /^[0-9a-f]{40}([0-9a-f]{24})?$/i;
401
404
  async function submitRun(config, registry, definitions, sources, sandboxes, planning, repos, endpointUrl, log, principal, req, res) {
402
405
  const parsed = run_request_1.runRequestSchema.safeParse(await (0, http_2.readJson)(req));
403
406
  if (!parsed.success) {
@@ -636,7 +639,18 @@ async function startRun(config, registry, definitions, sources, sandboxes, plann
636
639
  (0, http_2.send)(res, 409, { error });
637
640
  return;
638
641
  }
639
- source = { type: 'ref', repo: request.source.repo, ref: request.source.ref, commit };
642
+ // a branch at that commit, or a tag or a commit: only a branch's run may write a cache. A
643
+ // full commit names no branch, whatever the repository says of it.
644
+ const branch = FULL_COMMIT.test(request.source.ref)
645
+ ? false
646
+ : await repos.resolve(request.source.repo, request.source.ref, undefined, 'branch').then((found) => found === commit, () => false);
647
+ source = {
648
+ type: 'ref',
649
+ repo: request.source.repo,
650
+ ref: request.source.ref,
651
+ commit,
652
+ ...(branch ? { branch: true } : {}),
653
+ };
640
654
  }
641
655
  catch (e) {
642
656
  const message = e instanceof Error ? e.message : String(e);
@@ -950,6 +964,8 @@ async function startServer(config, environment, options = {}) {
950
964
  },
951
965
  policy: {
952
966
  envs: config.runs.env.allow,
967
+ // the registries a build file's cache may name: the operator's, see cache-push.ts
968
+ cacheRegistries: (0, cache_push_1.cacheRegistriesOf)(config),
953
969
  reserved: (0, server_config_1.getServerAccounts)(config),
954
970
  runtimes: config.runtimes,
955
971
  backend: config.backend.type,
@@ -1044,6 +1060,9 @@ async function startServer(config, environment, options = {}) {
1044
1060
  syncFailed: (runId) => sandboxSync.failed(runId),
1045
1061
  },
1046
1062
  localTasksOnHost,
1063
+ // the registry a trusted run writes its cache to, with the password of this server's environment
1064
+ cachePush: (run) => (0, cache_push_1.cachePushOf)(run, config, environment.processEnvs),
1065
+ cacheRegistries: (0, cache_push_1.cacheRegistriesOf)(config),
1047
1066
  ...(config.backend.type === 'host' && config.backend.capabilities
1048
1067
  ? { capabilityRuntime: config.backend.capabilities.runtime }
1049
1068
  : {}),
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "hammerkit",
3
3
  "description": "Containerized build tool with incremental caching that runs the same build file locally, in Docker and on Kubernetes.",
4
- "version": "2.2.0-next.1",
4
+ "version": "2.2.0-next.2",
5
5
  "keywords": [
6
6
  "build",
7
7
  "build-tool",