/
index.ts
951 lines (907 loc) · 27.4 KB
/
index.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
import URL from 'url';
import { ECR } from '@aws-sdk/client-ecr';
import type { ECRClientConfig } from '@aws-sdk/client-ecr';
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 { cache } from '../../../util/cache/package/decorator';
import * as hostRules from '../../../util/host-rules';
import { Http, HttpError } from '../../../util/http';
import type {
HttpOptions,
HttpResponse,
OutgoingHttpHeaders,
} from '../../../util/http/types';
import { hasKey } from '../../../util/object';
import { regEx } from '../../../util/regex';
import {
ensurePathPrefix,
ensureTrailingSlash,
parseLinkHeader,
parseUrl,
trimTrailingSlash,
} from '../../../util/url';
import {
api as dockerVersioning,
id as dockerVersioningId,
} from '../../versioning/docker';
import { Datasource } from '../datasource';
import type { GetReleasesConfig, ReleaseResult } from '../types';
import { gitRefLabel, sourceLabels } from './common';
import {
Image,
ImageList,
MediaType,
OciImage,
OciImageList,
RegistryRepository,
} from './types';
export const DOCKER_HUB = 'https://index.docker.io';
export const ecrRegex = regEx(/\d+\.dkr\.ecr\.([-a-z0-9]+)\.amazonaws\.com/);
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({ apiCheckUrl }, 'No registry auth required');
return {};
}
if (apiCheckResponse.statusCode === 404) {
logger.debug({ apiCheckUrl }, 'Page Not Found');
// 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: DockerDatasource.id,
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) ||
!is.string(authenticateHeader.params.service) ||
parseUrl(authenticateHeader.params.realm) === null
) {
logger.trace(
{ registryHost, dockerRepository, authenticateHeader },
`Invalid realm, testing direct auth`
);
return opts.headers ?? null;
}
let scope = `repository:${dockerRepository}:pull`;
// repo isn't known to server yet, so causing wrong scope `repository:user/image:pull`
if (
is.string(authenticateHeader.params.scope) &&
!apiCheckUrl.endsWith('/v2/')
) {
scope = authenticateHeader.params.scope;
}
const authUrl = `${authenticateHeader.params.realm}?service=${authenticateHeader.params.service}&scope=${scope}`;
logger.trace(
{ registryHost, dockerRepository, authUrl },
`Obtaining docker registry token`
);
opts.noAuth = true;
const authResponse = (
await http.getJson<{ token?: string; access_token?: string }>(
authUrl,
opts
)
).body;
const token = authResponse.token ?? authResponse.access_token;
// istanbul ignore if
if (!token) {
logger.warn('Failed to obtain docker registry token');
return null;
}
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;
}
}
async function getECRAuthToken(
region: string | undefined,
opts: HostRule
): Promise<string | null> {
const config: ECRClientConfig = { region };
if (opts.username && opts.password) {
config.credentials = {
accessKeyId: opts.username,
secretAccessKey: opts.password,
...(opts.token && { sessionToken: opts.token }),
};
}
const ecr = new ECR(config);
try {
const data = await ecr.getAuthorizationToken({});
const authorizationToken = data?.authorizationData?.[0]?.authorizationToken;
if (authorizationToken) {
return authorizationToken;
}
logger.warn(
'Could not extract authorizationToken from ECR getAuthorizationToken response'
);
} catch (err) {
logger.trace({ err }, 'err');
logger.debug('ECR getAuthorizationToken error');
}
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: DockerDatasource.id,
url: registryHost,
});
if (opts?.insecureRegistry) {
registryHost = registryHost.replace('https', 'http');
}
if (registryHost.endsWith('.docker.io') && !dockerRepository.includes('/')) {
dockerRepository = 'library/' + dockerRepository;
}
return {
registryHost,
dockerRepository,
};
}
function digestFromManifestStr(str: hasha.HashaInput): string {
return 'sha256:' + hasha(str, { algorithm: 'sha256' });
}
export function extractDigestFromResponseBody(
manifestResponse: HttpResponse
): string {
return digestFromManifestStr(manifestResponse.body);
}
export function isECRMaxResultsError(err: HttpError): boolean {
const resp = err.response as HttpResponse<any> | undefined;
return !!(
resp?.statusCode === 405 &&
resp.headers?.['docker-distribution-api-version'] &&
// https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_DescribeRepositories.html#ECR-DescribeRepositories-request-maxResults
resp.body?.['errors']?.[0]?.message?.includes(
'Member must have value less than or equal to 1000'
)
);
}
export const defaultConfig = {
commitMessageTopic: '{{{depName}}} Docker tag',
commitMessageExtra:
'to {{#if isMajor}}{{{prettyNewMajor}}}{{else}}{{{prettyNewVersion}}}{{/if}}',
digest: {
branchTopic: '{{{depNameSanitized}}}-{{{currentValue}}}',
commitMessageExtra: 'to {{newDigestShort}}',
commitMessageTopic:
'{{{depName}}}{{#if currentValue}}:{{{currentValue}}}{{/if}} Docker digest',
group: {
commitMessageTopic: '{{{groupName}}}',
commitMessageExtra: '',
},
},
pin: {
commitMessageExtra: '',
groupName: 'Docker digests',
group: {
commitMessageTopic: '{{{groupName}}}',
branchTopic: 'digests-pin',
},
},
group: {
commitMessageTopic: '{{{groupName}}} Docker tags',
},
};
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;
}
export class DockerDatasource extends Datasource {
static readonly id = 'docker';
override readonly defaultVersioning = dockerVersioningId;
override readonly defaultRegistryUrls = [DOCKER_HUB];
constructor() {
super(DockerDatasource.id);
}
// TODO: debug why quay throws errors (#9612)
private async getManifestResponse(
registryHost: string,
dockerRepository: string,
tag: string,
mode: 'head' | 'get' = 'get'
): Promise<HttpResponse | null> {
logger.debug(
`getManifestResponse(${registryHost}, ${dockerRepository}, ${tag})`
);
try {
const headers = await getAuthHeaders(
this.http,
registryHost,
dockerRepository
);
if (!headers) {
logger.debug('No docker auth found - returning');
return null;
}
headers.accept = [
MediaType.manifestListV2,
MediaType.manifestV2,
MediaType.ociManifestV1,
MediaType.ociManifestIndexV1,
].join(', ');
const url = `${registryHost}/v2/${dockerRepository}/manifests/${tag}`;
const manifestResponse = await this.http[mode](url, {
headers,
noAuth: true,
});
return manifestResponse;
} catch (err) /* istanbul ignore next */ {
if (err instanceof ExternalHostError) {
throw err;
}
if (err.statusCode === 401) {
logger.debug(
{ registryHost, dockerRepository },
'Unauthorized docker lookup'
);
logger.debug({ err });
return null;
}
if (err.statusCode === 404) {
logger.debug(
{
err,
registryHost,
dockerRepository,
tag,
},
'Docker Manifest is unknown'
);
return null;
}
if (err.statusCode === 429 && isDockerHost(registryHost)) {
throw new ExternalHostError(err);
}
if (err.statusCode >= 500 && err.statusCode < 600) {
throw new ExternalHostError(err);
}
if (err.code === 'ETIMEDOUT') {
logger.debug(
{ registryHost },
'Timeout when attempting to connect to docker registry'
);
logger.debug({ err });
return null;
}
logger.debug(
{
err,
registryHost,
dockerRepository,
tag,
},
'Unknown Error looking up docker manifest'
);
return null;
}
}
private async getConfigDigest(
registry: string,
dockerRepository: string,
tag: string
): Promise<string | null> {
const manifestResponse = await this.getManifestResponse(
registry,
dockerRepository,
tag
);
// If getting the manifest fails here, then abort
// This means that the latest tag doesn't have a manifest, which shouldn't
// be possible
// istanbul ignore if
if (!manifestResponse) {
return null;
}
const manifest = JSON.parse(manifestResponse.body) as
| ImageList
| Image
| OciImageList
| OciImage;
if (manifest.schemaVersion !== 2) {
logger.debug(
{ registry, dockerRepository, tag },
'Manifest schema version is not 2'
);
return null;
}
if (manifest.mediaType === MediaType.manifestListV2) {
if (manifest.manifests.length) {
logger.trace(
{ registry, dockerRepository, tag },
'Found manifest list, using first image'
);
return this.getConfigDigest(
registry,
dockerRepository,
manifest.manifests[0].digest
);
} else {
logger.debug(
{ manifest },
'Invalid manifest list with no manifests - returning'
);
return null;
}
}
if (
manifest.mediaType === MediaType.manifestV2 &&
is.string(manifest.config?.digest)
) {
return manifest.config?.digest;
}
// OCI image lists are not required to specify a mediaType
if (
manifest.mediaType === MediaType.ociManifestIndexV1 ||
(!manifest.mediaType && hasKey('manifests', manifest))
) {
if (manifest.manifests.length) {
logger.trace(
{ registry, dockerRepository, tag },
'Found manifest index, using first image'
);
return this.getConfigDigest(
registry,
dockerRepository,
manifest.manifests[0].digest
);
} else {
logger.debug(
{ manifest },
'Invalid manifest index with no manifests - returning'
);
return null;
}
}
// OCI manifests are not required to specify a mediaType
if (
(manifest.mediaType === MediaType.ociManifestV1 ||
(!manifest.mediaType && hasKey('config', manifest))) &&
is.string(manifest.config?.digest)
) {
return manifest.config?.digest;
}
logger.debug({ manifest }, 'Invalid manifest - returning');
return null;
}
/*
* docker.getLabels
*
* This function will:
* - Return the labels for the requested image
*/
@cache({
namespace: 'datasource-docker-labels',
key: (registryHost: string, dockerRepository: string, tag: string) =>
`${registryHost}:${dockerRepository}:${tag}`,
ttlMinutes: 60,
})
public async getLabels(
registryHost: string,
dockerRepository: string,
tag: string
): Promise<Record<string, string>> {
logger.debug(`getLabels(${registryHost}, ${dockerRepository}, ${tag})`);
try {
let labels: Record<string, string> = {};
const configDigest = await this.getConfigDigest(
registryHost,
dockerRepository,
tag
);
if (!configDigest) {
return {};
}
const headers = await getAuthHeaders(
this.http,
registryHost,
dockerRepository
);
// istanbul ignore if: Should never be happen
if (!headers) {
logger.debug('No docker auth found - returning');
return {};
}
const url = `${registryHost}/v2/${dockerRepository}/blobs/${configDigest}`;
const configResponse = await this.http.get(url, {
headers,
noAuth: true,
});
labels = JSON.parse(configResponse.body).config.Labels;
if (labels) {
logger.debug(
{
labels,
},
'found labels in manifest'
);
}
return labels;
} catch (err) /* istanbul ignore next: should be tested in future */ {
if (err instanceof ExternalHostError) {
throw err;
}
if (err.statusCode === 400 || err.statusCode === 401) {
logger.debug(
{ registryHost, dockerRepository, err },
'Unauthorized docker lookup'
);
} else if (err.statusCode === 404) {
logger.warn(
{
err,
registryHost,
dockerRepository,
tag,
},
'Config Manifest is unknown'
);
} else if (err.statusCode === 429 && isDockerHost(registryHost)) {
logger.warn({ err }, 'docker registry failure: too many requests');
} else if (err.statusCode >= 500 && err.statusCode < 600) {
logger.debug(
{
err,
registryHost,
dockerRepository,
tag,
},
'docker registry failure: internal error'
);
} else if (
err.code === 'ERR_TLS_CERT_ALTNAME_INVALID' ||
err.code === 'ETIMEDOUT'
) {
logger.debug(
{ registryHost, err },
'Error connecting to docker registry'
);
} else if (registryHost === 'https://quay.io') {
// istanbul ignore next
logger.debug(
'Ignoring quay.io errors until they fully support v2 schema'
);
} else {
logger.info(
{ registryHost, dockerRepository, tag, err },
'Unknown error getting Docker labels'
);
}
return {};
}
}
private async getTagsQuayRegistry(
registry: string,
repository: string
): Promise<string[]> {
let tags: string[] = [];
const limit = 100;
const pageUrl = (page: number): string =>
`${registry}/api/v1/repository/${repository}/tag/?limit=${limit}&page=${page}&onlyActiveTags=true`;
let page = 1;
let url: string | null = pageUrl(page);
while (url && page <= 20) {
interface QuayRestDockerTags {
tags: {
name: string;
}[];
has_additional: boolean;
}
// typescript issue :-/
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const res = (await this.http.getJson<QuayRestDockerTags>(
url
)) as HttpResponse<QuayRestDockerTags>;
const pageTags = res.body.tags.map((tag) => tag.name);
tags = tags.concat(pageTags);
page += 1;
url = res.body.has_additional ? pageUrl(page) : null;
}
return tags;
}
private async getDockerApiTags(
registryHost: string,
dockerRepository: string
): Promise<string[] | null> {
let tags: string[] = [];
// AWS ECR limits the maximum number of results to 1000
// See https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_DescribeRepositories.html#ECR-DescribeRepositories-request-maxResults
const limit = ecrRegex.test(registryHost) ? 1000 : 10000;
let url:
| string
| null = `${registryHost}/${dockerRepository}/tags/list?n=${limit}`;
url = ensurePathPrefix(url, '/v2');
const headers = await getAuthHeaders(
this.http,
registryHost,
dockerRepository,
url
);
if (!headers) {
logger.debug('Failed to get authHeaders for getTags lookup');
return null;
}
let page = 1;
let foundMaxResultsError = false;
do {
let res: HttpResponse<{ tags: string[] }>;
try {
res = await this.http.getJson<{ tags: string[] }>(url, {
headers,
noAuth: true,
});
} catch (err) {
if (
!foundMaxResultsError &&
err instanceof HttpError &&
isECRMaxResultsError(err)
) {
const maxResults = 1000;
url = `${registryHost}/${dockerRepository}/tags/list?n=${maxResults}`;
url = ensurePathPrefix(url, '/v2');
foundMaxResultsError = true;
continue;
}
throw err;
}
tags = tags.concat(res.body.tags);
const linkHeader = parseLinkHeader(res.headers.link);
url = linkHeader?.next ? URL.resolve(url, linkHeader.next.url) : null;
page += 1;
} while (url && page < 20);
return tags;
}
@cache({
namespace: 'datasource-docker-tags',
key: (registryHost: string, dockerRepository: string) =>
`${registryHost}:${dockerRepository}`,
})
public async getTags(
registryHost: string,
dockerRepository: string
): Promise<string[] | null> {
try {
const isQuay = regEx(/^https:\/\/quay\.io(?::[1-9][0-9]{0,4})?$/i).test(
registryHost
);
let tags: string[] | null;
if (isQuay) {
tags = await this.getTagsQuayRegistry(registryHost, dockerRepository);
} else {
tags = await this.getDockerApiTags(registryHost, dockerRepository);
}
return tags;
} catch (err) /* istanbul ignore next */ {
if (err instanceof ExternalHostError) {
throw err;
}
if (
(err.statusCode === 404 || err.message === PAGE_NOT_FOUND_ERROR) &&
!dockerRepository.includes('/')
) {
logger.debug(
`Retrying Tags for ${registryHost}/${dockerRepository} using library/ prefix`
);
return this.getTags(registryHost, 'library/' + dockerRepository);
}
// prettier-ignore
if (err.statusCode === 429 && isDockerHost(registryHost)) {
logger.warn(
{ registryHost, dockerRepository, err },
'docker registry failure: too many requests'
);
throw new ExternalHostError(err);
}
// prettier-ignore
if (err.statusCode === 401 && isDockerHost(registryHost)) {
logger.warn(
{ registryHost, dockerRepository, err },
'docker registry failure: unauthorized'
);
throw new ExternalHostError(err);
}
if (err.statusCode >= 500 && err.statusCode < 600) {
logger.warn(
{ registryHost, dockerRepository, err },
'docker registry failure: internal error'
);
throw new ExternalHostError(err);
}
throw err;
}
}
/**
* docker.getDigest
*
* The `newValue` supplied here should be a valid tag for the docker image.
*
* This function will:
* - Look up a sha256 digest for a tag on its registry
* - Return the digest as a string
*/
@cache({
namespace: 'datasource-docker-digest',
key: (
{ registryUrl, packageName }: GetReleasesConfig,
newValue?: string
) => {
const newTag = newValue ?? 'latest';
const { registryHost, dockerRepository } = getRegistryRepository(
packageName,
registryUrl!
);
return `${registryHost}:${dockerRepository}:${newTag}`;
},
})
override async getDigest(
{ registryUrl, packageName }: GetReleasesConfig,
newValue?: string
): Promise<string | null> {
const { registryHost, dockerRepository } = getRegistryRepository(
packageName,
registryUrl!
);
logger.debug(
// TODO: types (#7154)
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`getDigest(${registryHost}, ${dockerRepository}, ${newValue})`
);
const newTag = newValue ?? 'latest';
let digest: string | null = null;
try {
let manifestResponse = await this.getManifestResponse(
registryHost,
dockerRepository,
newTag,
'head'
);
if (manifestResponse) {
if (hasKey('docker-content-digest', manifestResponse.headers)) {
digest =
(manifestResponse.headers['docker-content-digest'] as string) ||
null;
} else {
logger.debug(
{ registryHost },
'Missing docker content digest header, pulling full manifest'
);
manifestResponse = await this.getManifestResponse(
registryHost,
dockerRepository,
newTag
);
digest = extractDigestFromResponseBody(manifestResponse!);
}
logger.debug({ digest }, 'Got docker digest');
}
} catch (err) /* istanbul ignore next */ {
if (err instanceof ExternalHostError) {
throw err;
}
logger.debug(
{
err,
packageName,
newTag,
},
'Unknown Error looking up docker image digest'
);
}
return digest;
}
/**
* docker.getReleases
*
* A docker image usually looks something like this: somehost.io/owner/repo:8.1.0-alpine
* In the above:
* - 'somehost.io' is the registry
* - 'owner/repo' is the package name
* - '8.1.0-alpine' is the tag
*
* This function will filter only tags that contain a semver version
*/
async getReleases({
packageName,
registryUrl,
}: GetReleasesConfig): Promise<ReleaseResult | null> {
const { registryHost, dockerRepository } = getRegistryRepository(
packageName,
registryUrl!
);
const tags = await this.getTags(registryHost, dockerRepository);
if (!tags) {
return null;
}
const releases = tags.map((version) => ({ version }));
const ret: ReleaseResult = {
registryUrl: registryHost,
releases,
};
const latestTag = tags.includes('latest')
? 'latest'
: findLatestStable(tags);
// istanbul ignore if: needs test
if (!latestTag) {
return ret;
}
const labels = await this.getLabels(
registryHost,
dockerRepository,
latestTag
);
if (labels) {
if (is.nonEmptyString(labels[gitRefLabel])) {
ret.gitRef = labels[gitRefLabel];
}
for (const label of sourceLabels) {
if (is.nonEmptyString(labels[label])) {
ret.sourceUrl = labels[label];
break;
}
}
}
return ret;
}
}