/
common.ts
297 lines (278 loc) · 9.21 KB
/
common.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import is from '@sindresorhus/is';
import { parse } from 'auth-header';
import hasha from 'hasha';
import {
HOST_DISABLED,
PAGE_NOT_FOUND_ERROR,
} from '../../../constants/error-messages';
import { logger } from '../../../logger';
import type { HostRule } from '../../../types';
import { ExternalHostError } from '../../../types/errors/external-host-error';
import * as hostRules from '../../../util/host-rules';
import type { Http } from '../../../util/http';
import type {
HttpOptions,
HttpResponse,
OutgoingHttpHeaders,
} from '../../../util/http/types';
import { regEx } from '../../../util/regex';
import { addSecretForSanitizing } from '../../../util/sanitize';
import {
ensureTrailingSlash,
parseUrl,
trimTrailingSlash,
} from '../../../util/url';
import { api as dockerVersioning } from '../../versioning/docker';
import { ecrRegex, getECRAuthToken } from './ecr';
import type { RegistryRepository } from './types';
export const dockerDatasourceId = 'docker' as const;
export const sourceLabels: string[] = [
'org.opencontainers.image.source',
'org.label-schema.vcs-url',
];
export const gitRefLabel = 'org.opencontainers.image.revision';
export const DOCKER_HUB = 'https://index.docker.io';
export function isDockerHost(host: string): boolean {
const regex = regEx(/(?:^|\.)docker\.io$/);
return regex.test(host);
}
export async function getAuthHeaders(
http: Http,
registryHost: string,
dockerRepository: string,
apiCheckUrl = `${registryHost}/v2/`
): Promise<OutgoingHttpHeaders | null> {
try {
const options = {
throwHttpErrors: false,
noAuth: true,
};
const apiCheckResponse = apiCheckUrl.endsWith('/v2/')
? await http.get(apiCheckUrl, options)
: // use json request, as this will be cached for tags, so it returns json
// TODO: add cache test
await http.getJson(apiCheckUrl, options);
if (apiCheckResponse.statusCode === 200) {
logger.debug(`No registry auth required for ${apiCheckUrl}`);
return {};
}
if (apiCheckResponse.statusCode === 404) {
logger.debug(`Page Not Found ${apiCheckUrl}`);
// throw error up to be caught and potentially retried with library/ prefix
throw new Error(PAGE_NOT_FOUND_ERROR);
}
if (
apiCheckResponse.statusCode !== 401 ||
!is.nonEmptyString(apiCheckResponse.headers['www-authenticate'])
) {
logger.warn(
{ apiCheckUrl, res: apiCheckResponse },
'Invalid registry response'
);
return null;
}
const authenticateHeader = parse(
apiCheckResponse.headers['www-authenticate']
);
const opts: HostRule & HttpOptions = hostRules.find({
hostType: dockerDatasourceId,
url: apiCheckUrl,
});
if (ecrRegex.test(registryHost)) {
logger.trace(
{ registryHost, dockerRepository },
`Using ecr auth for Docker registry`
);
const [, region] = ecrRegex.exec(registryHost) ?? [];
const auth = await getECRAuthToken(region, opts);
if (auth) {
opts.headers = { authorization: `Basic ${auth}` };
}
} else if (opts.username && opts.password) {
logger.trace(
{ registryHost, dockerRepository },
`Using basic auth for Docker registry`
);
const auth = Buffer.from(`${opts.username}:${opts.password}`).toString(
'base64'
);
opts.headers = { authorization: `Basic ${auth}` };
} else if (opts.token) {
const authType = opts.authType ?? 'Bearer';
logger.trace(
{ registryHost, dockerRepository },
`Using ${authType} token for Docker registry`
);
opts.headers = { authorization: `${authType} ${opts.token}` };
}
delete opts.username;
delete opts.password;
delete opts.token;
// If realm isn't an url, we should directly use auth header
// Can happen when we get a Basic auth or some other auth type
// * WWW-Authenticate: Basic realm="Artifactory Realm"
// * Www-Authenticate: Basic realm="https://123456789.dkr.ecr.eu-central-1.amazonaws.com/",service="ecr.amazonaws.com"
// * www-authenticate: Bearer realm="https://ghcr.io/token",service="ghcr.io",scope="repository:user/image:pull"
// * www-authenticate: Bearer realm="https://auth.docker.io/token",service="registry.docker.io"
if (
authenticateHeader.scheme.toUpperCase() !== 'BEARER' ||
!is.string(authenticateHeader.params.realm) ||
parseUrl(authenticateHeader.params.realm) === null
) {
logger.trace(
{ registryHost, dockerRepository, authenticateHeader },
`Invalid realm, testing direct auth`
);
return opts.headers ?? null;
}
const authUrl = new URL(`${authenticateHeader.params.realm}`);
// repo isn't known to server yet, so causing wrong scope `repository:user/image:pull`
if (
is.string(authenticateHeader.params.scope) &&
!apiCheckUrl.endsWith('/v2/')
) {
authUrl.searchParams.append('scope', authenticateHeader.params.scope);
} else {
authUrl.searchParams.append(
'scope',
`repository:${dockerRepository}:pull`
);
}
if (is.string(authenticateHeader.params.service)) {
authUrl.searchParams.append('service', authenticateHeader.params.service);
}
logger.trace(
{ registryHost, dockerRepository, authUrl: authUrl.href },
`Obtaining docker registry token`
);
opts.noAuth = true;
const authResponse = (
await http.getJson<{ token?: string; access_token?: string }>(
authUrl.href,
opts
)
).body;
const token = authResponse.token ?? authResponse.access_token;
// istanbul ignore if
if (!token) {
logger.warn('Failed to obtain docker registry token');
return null;
}
// sanitize token
addSecretForSanitizing(token);
return {
authorization: `Bearer ${token}`,
};
} catch (err) /* istanbul ignore next */ {
if (err.host === 'quay.io') {
// TODO: debug why quay throws errors (#9604)
return null;
}
if (err.statusCode === 401) {
logger.debug(
{ registryHost, dockerRepository },
'Unauthorized docker lookup'
);
logger.debug({ err });
return null;
}
if (err.statusCode === 403) {
logger.debug(
{ registryHost, dockerRepository },
'Not allowed to access docker registry'
);
logger.debug({ err });
return null;
}
if (err.name === 'RequestError' && isDockerHost(registryHost)) {
throw new ExternalHostError(err);
}
if (err.statusCode === 429 && isDockerHost(registryHost)) {
throw new ExternalHostError(err);
}
if (err.statusCode >= 500 && err.statusCode < 600) {
throw new ExternalHostError(err);
}
if (err.message === PAGE_NOT_FOUND_ERROR) {
throw err;
}
if (err.message === HOST_DISABLED) {
logger.trace({ registryHost, dockerRepository, err }, 'Host disabled');
return null;
}
logger.warn(
{ registryHost, dockerRepository, err },
'Error obtaining docker token'
);
return null;
}
}
export function getRegistryRepository(
packageName: string,
registryUrl: string
): RegistryRepository {
if (registryUrl !== DOCKER_HUB) {
const registryEndingWithSlash = ensureTrailingSlash(
registryUrl.replace(regEx(/^https?:\/\//), '')
);
if (packageName.startsWith(registryEndingWithSlash)) {
let registryHost = trimTrailingSlash(registryUrl);
if (!regEx(/^https?:\/\//).test(registryHost)) {
registryHost = `https://${registryHost}`;
}
let dockerRepository = packageName.replace(registryEndingWithSlash, '');
const fullUrl = `${registryHost}/${dockerRepository}`;
const { origin, pathname } = parseUrl(fullUrl)!;
registryHost = origin;
dockerRepository = pathname.substring(1);
return {
registryHost,
dockerRepository,
};
}
}
let registryHost: string | undefined;
const split = packageName.split('/');
if (split.length > 1 && (split[0].includes('.') || split[0].includes(':'))) {
[registryHost] = split;
split.shift();
}
let dockerRepository = split.join('/');
if (!registryHost) {
registryHost = registryUrl.replace(
'https://docker.io',
'https://index.docker.io'
);
}
if (registryHost === 'docker.io') {
registryHost = 'index.docker.io';
}
if (!regEx(/^https?:\/\//).exec(registryHost)) {
registryHost = `https://${registryHost}`;
}
const opts = hostRules.find({
hostType: dockerDatasourceId,
url: registryHost,
});
if (opts?.insecureRegistry) {
registryHost = registryHost.replace('https', 'http');
}
if (registryHost.endsWith('.docker.io') && !dockerRepository.includes('/')) {
dockerRepository = 'library/' + dockerRepository;
}
return {
registryHost,
dockerRepository,
};
}
export function extractDigestFromResponseBody(
manifestResponse: HttpResponse
): string {
return 'sha256:' + hasha(manifestResponse.body, { algorithm: 'sha256' });
}
export function findLatestStable(tags: string[]): string | null {
const versions = tags
.filter((v) => dockerVersioning.isValid(v) && dockerVersioning.isStable(v))
.sort((a, b) => dockerVersioning.sortVersions(a, b));
return versions.pop() ?? tags.slice(-1).pop() ?? null;
}