hammerkit 2.2.0-next.1 → 2.2.0-next.3

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) {