-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathutil.ts
529 lines (457 loc) · 15.8 KB
/
util.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
import { Readable } from 'node:stream';
import { GetObjectCommand } from '@aws-sdk/client-s3';
import { XmlDocument } from 'xmldoc';
import { HOST_DISABLED } from '../../../constants/error-messages';
import { logger } from '../../../logger';
import { ExternalHostError } from '../../../types/errors/external-host-error';
import { type Http, HttpError } from '../../../util/http';
import { PackageHttpCacheProvider } from '../../../util/http/cache/package-http-cache-provider';
import type { HttpOptions, HttpResponse } from '../../../util/http/types';
import { regEx } from '../../../util/regex';
import { Result } from '../../../util/result';
import { getS3Client, parseS3Url } from '../../../util/s3';
import { streamToString } from '../../../util/streams';
import { asTimestamp } from '../../../util/timestamp';
import { ensureTrailingSlash, isHttpUrl, parseUrl } from '../../../util/url';
import { getGoogleAuthToken } from '../util';
import { MAVEN_REPO } from './common';
import type {
DependencyInfo,
MavenDependency,
MavenFetchResult,
MavenFetchSuccess,
} from './types';
function getHost(url: string): string | undefined {
return parseUrl(url)?.host;
}
function isTemporaryError(err: HttpError): boolean {
if (err.code === 'ECONNRESET') {
return true;
}
if (err.response) {
const status = err.response.statusCode;
return status === 429 || (status >= 500 && status < 600);
}
return false;
}
function isHostError(err: HttpError): boolean {
return err.code === 'ETIMEDOUT';
}
function isNotFoundError(err: HttpError): boolean {
return err.code === 'ENOTFOUND' || err.response?.statusCode === 404;
}
function isPermissionsIssue(err: HttpError): boolean {
const status = err.response?.statusCode;
return status === 401 || status === 403;
}
function isConnectionError(err: HttpError): boolean {
return (
err.code === 'EAI_AGAIN' ||
err.code === 'ERR_TLS_CERT_ALTNAME_INVALID' ||
err.code === 'ECONNREFUSED'
);
}
function isUnsupportedHostError(err: HttpError): boolean {
return err.name === 'UnsupportedProtocolError';
}
const cacheProvider = new PackageHttpCacheProvider({
namespace: 'datasource-maven:cache-provider',
ttlMinutes: 7 * 24 * 60,
checkCacheControlHeader: false, // Maven doesn't respond with `cache-control` headers
});
export async function downloadHttpProtocol(
http: Http,
pkgUrl: URL | string,
opts: HttpOptions = {},
): Promise<MavenFetchResult> {
const url = pkgUrl.toString();
const fetchResult = await Result.wrap<HttpResponse, Error>(
http.getText(url, { ...opts, cacheProvider }),
)
.transform((res): MavenFetchSuccess => {
const result: MavenFetchSuccess = { data: res.body };
if (!res.authorization) {
result.isCacheable = true;
}
const lastModified = asTimestamp(res?.headers?.['last-modified']);
if (lastModified) {
result.lastModified = lastModified;
}
return result;
})
.catch((err): MavenFetchResult => {
/* v8 ignore start: never happens, needs for type narrowing */
if (!(err instanceof HttpError)) {
return Result.err({ type: 'unknown', err });
} /* v8 ignore stop */
const failedUrl = url;
if (err.message === HOST_DISABLED) {
logger.trace({ failedUrl }, 'Host disabled');
return Result.err({ type: 'host-disabled' });
}
if (isNotFoundError(err)) {
logger.trace({ failedUrl }, `Url not found`);
return Result.err({ type: 'not-found' });
}
if (isHostError(err)) {
logger.debug(`Cannot connect to host ${failedUrl}`);
return Result.err({ type: 'host-error' });
}
if (isPermissionsIssue(err)) {
logger.debug(
`Dependency lookup unauthorized. Please add authentication with a hostRule for ${failedUrl}`,
);
return Result.err({ type: 'permission-issue' });
}
if (isTemporaryError(err)) {
logger.debug({ failedUrl, err }, 'Temporary error');
if (getHost(url) === getHost(MAVEN_REPO)) {
return Result.err({ type: 'maven-central-temporary-error', err });
} else {
return Result.err({ type: 'temporary-error' });
}
}
if (isConnectionError(err)) {
logger.debug(`Connection refused to maven registry ${failedUrl}`);
return Result.err({ type: 'connection-error' });
}
if (isUnsupportedHostError(err)) {
logger.debug(`Unsupported host ${failedUrl}`);
return Result.err({ type: 'unsupported-host' });
}
logger.info({ failedUrl, err }, 'Unknown HTTP download error');
return Result.err({ type: 'unknown', err });
});
const { err } = fetchResult.unwrap();
if (err?.type === 'maven-central-temporary-error') {
throw new ExternalHostError(err.err);
}
return fetchResult;
}
export async function downloadHttpContent(
http: Http,
pkgUrl: URL | string,
opts: HttpOptions = {},
): Promise<string | null> {
const fetchResult = await downloadHttpProtocol(http, pkgUrl, opts);
return fetchResult.transform(({ data }) => data).unwrapOrNull();
}
function isS3NotFound(err: Error): boolean {
return err.message === 'NotFound' || err.message === 'NoSuchKey';
}
export async function downloadS3Protocol(
pkgUrl: URL,
): Promise<MavenFetchResult> {
logger.trace({ url: pkgUrl.toString() }, `Attempting to load S3 dependency`);
const s3Url = parseS3Url(pkgUrl);
if (!s3Url) {
return Result.err({ type: 'invalid-url' });
}
return await Result.wrap(() => {
const command = new GetObjectCommand(s3Url);
const client = getS3Client();
return client.send(command);
})
.transform(
async ({
Body,
LastModified,
DeleteMarker,
}): Promise<MavenFetchResult> => {
if (DeleteMarker) {
logger.trace(
{ failedUrl: pkgUrl.toString() },
'Maven S3 lookup error: DeleteMarker encountered',
);
return Result.err({ type: 'not-found' });
}
if (!(Body instanceof Readable)) {
logger.debug(
{ failedUrl: pkgUrl.toString() },
'Maven S3 lookup error: unsupported Body type',
);
return Result.err({ type: 'unsupported-format' });
}
const data = await streamToString(Body);
const result: MavenFetchSuccess = { data };
const lastModified = asTimestamp(LastModified);
if (lastModified) {
result.lastModified = lastModified;
}
return Result.ok(result);
},
)
.catch((err): MavenFetchResult => {
if (!(err instanceof Error)) {
return Result.err(err);
}
const failedUrl = pkgUrl.toString();
if (err.name === 'CredentialsProviderError') {
logger.debug(
{ failedUrl },
'Maven S3 lookup error: credentials provider error, check "AWS_ACCESS_KEY_ID" and "AWS_SECRET_ACCESS_KEY" variables',
);
return Result.err({ type: 'credentials-error' });
}
if (err.message === 'Region is missing') {
logger.debug(
{ failedUrl },
'Maven S3 lookup error: missing region, check "AWS_REGION" variable',
);
return Result.err({ type: 'missing-aws-region' });
}
if (isS3NotFound(err)) {
logger.trace({ failedUrl }, 'Maven S3 lookup error: object not found');
return Result.err({ type: 'not-found' });
}
logger.debug({ failedUrl, err }, 'Maven S3 lookup error: unknown error');
return Result.err({ type: 'unknown', err });
});
}
export async function downloadArtifactRegistryProtocol(
http: Http,
pkgUrl: URL,
): Promise<MavenFetchResult> {
const opts: HttpOptions = {};
const host = pkgUrl.host;
const path = pkgUrl.pathname;
logger.trace({ host, path }, `Using google auth for Maven repository`);
const auth = await getGoogleAuthToken();
if (auth) {
opts.headers = { authorization: `Basic ${auth}` };
} else {
logger.once.debug(
{ host, path },
'Could not get Google access token, using no auth',
);
}
const url = pkgUrl.toString().replace('artifactregistry:', 'https:');
return downloadHttpProtocol(http, url, opts);
}
function containsPlaceholder(str: string): boolean {
return regEx(/\${.*?}/g).test(str);
}
export function getMavenUrl(
dependency: MavenDependency,
repoUrl: string,
path: string,
): URL {
return new URL(
`${dependency.dependencyUrl}/${path}`,
ensureTrailingSlash(repoUrl),
);
}
export async function downloadMaven(
http: Http,
url: URL,
): Promise<MavenFetchResult> {
const protocol = url.protocol;
let result: MavenFetchResult = Result.err({ type: 'unsupported-protocol' });
if (isHttpUrl(url)) {
result = await downloadHttpProtocol(http, url);
}
if (protocol === 'artifactregistry:') {
result = await downloadArtifactRegistryProtocol(http, url);
}
if (protocol === 's3:') {
result = await downloadS3Protocol(url);
}
return result.onError((err) => {
if (err.type === 'unsupported-protocol') {
logger.debug(
{ url: url.toString() },
`Maven lookup error: unsupported protocol (${protocol})`,
);
}
});
}
export async function downloadMavenXml(
http: Http,
url: URL,
): Promise<MavenFetchResult<XmlDocument>> {
const rawResult = await downloadMaven(http, url);
return rawResult.transform((result): MavenFetchResult<XmlDocument> => {
try {
return Result.ok({
...result,
data: new XmlDocument(result.data),
});
} catch (err) {
return Result.err({ type: 'xml-parse-error', err });
}
});
}
export function getDependencyParts(packageName: string): MavenDependency {
const [group, name] = packageName.split(':');
const dependencyUrl = `${group.replace(regEx(/\./g), '/')}/${name}`;
return {
display: packageName,
group,
name,
dependencyUrl,
};
}
function extractSnapshotVersion(metadata: XmlDocument): string | null {
// Parse the maven-metadata.xml for the snapshot version and determine
// the fixed version of the latest deployed snapshot.
// The metadata descriptor can be found at
// https://maven.apache.org/ref/3.3.3/maven-repository-metadata/repository-metadata.html
//
// Basically, we need to replace -SNAPSHOT with the artifact timestanp & build number,
// so for example 1.0.0-SNAPSHOT will become 1.0.0-<timestamp>-<buildNumber>
const version = metadata
.descendantWithPath('version')
?.val?.replace('-SNAPSHOT', '');
const snapshot = metadata.descendantWithPath('versioning.snapshot');
const timestamp = snapshot?.childNamed('timestamp')?.val;
const build = snapshot?.childNamed('buildNumber')?.val;
// If we weren't able to parse out the required 3 version elements,
// return null because we can't determine the fixed version of the latest snapshot.
if (!version || !timestamp || !build) {
return null;
}
return `${version}-${timestamp}-${build}`;
}
async function getSnapshotFullVersion(
http: Http,
version: string,
dependency: MavenDependency,
repoUrl: string,
): Promise<string | null> {
// To determine what actual files are available for the snapshot, first we have to fetch and parse
// the metadata located at http://<repo>/<group>/<artifact>/<version-SNAPSHOT>/maven-metadata.xml
const metadataUrl = getMavenUrl(
dependency,
repoUrl,
`${version}/maven-metadata.xml`,
);
const metadataXmlResult = await downloadMavenXml(http, metadataUrl);
return metadataXmlResult
.transform(({ data }) =>
Result.wrapNullable(extractSnapshotVersion(data), {
type: 'snapshot-extract-error',
}),
)
.unwrapOrNull();
}
function isSnapshotVersion(version: string): boolean {
if (version.endsWith('-SNAPSHOT')) {
return true;
}
return false;
}
export async function createUrlForDependencyPom(
http: Http,
version: string,
dependency: MavenDependency,
repoUrl: string,
): Promise<string> {
if (isSnapshotVersion(version)) {
// By default, Maven snapshots are deployed to the repository with fixed file names.
// Resolve the full, actual pom file name for the version.
const fullVersion = await getSnapshotFullVersion(
http,
version,
dependency,
repoUrl,
);
// If we were able to resolve the version, use that, otherwise fall back to using -SNAPSHOT
if (fullVersion !== null) {
// TODO: types (#22198)
return `${version}/${dependency.name}-${fullVersion}.pom`;
}
}
// TODO: types (#22198)
return `${version}/${dependency.name}-${version}.pom`;
}
export async function getDependencyInfo(
http: Http,
dependency: MavenDependency,
repoUrl: string,
version: string,
recursionLimit = 5,
): Promise<DependencyInfo> {
const path = await createUrlForDependencyPom(
http,
version,
dependency,
repoUrl,
);
const pomUrl = getMavenUrl(dependency, repoUrl, path);
const pomXmlResult = await downloadMavenXml(http, pomUrl);
const dependencyInfoResult = await pomXmlResult.transform(
async ({ data: pomContent }) => {
const result: DependencyInfo = {};
const homepage = pomContent.valueWithPath('url');
if (homepage && !containsPlaceholder(homepage)) {
result.homepage = homepage;
}
const sourceUrl = pomContent.valueWithPath('scm.url');
if (sourceUrl && !containsPlaceholder(sourceUrl)) {
result.sourceUrl = sourceUrl
.replace(regEx(/^scm:/), '')
.replace(regEx(/^git:/), '')
.replace(regEx(/^[email protected]:/), 'https://github.com/')
.replace(regEx(/^[email protected]\//), 'https://github.com/');
if (result.sourceUrl.startsWith('//')) {
// most likely the result of us stripping scm:, git: etc
// going with prepending https: here which should result in potential information retrival
result.sourceUrl = `https:${result.sourceUrl}`;
}
}
const relocation = pomContent.descendantWithPath(
'distributionManagement.relocation',
);
if (relocation) {
const relocationGroup =
relocation.valueWithPath('groupId') ?? dependency.group;
const relocationName =
relocation.valueWithPath('artifactId') ?? dependency.name;
result.replacementName = `${relocationGroup}:${relocationName}`;
const relocationVersion = relocation.valueWithPath('version');
result.replacementVersion = relocationVersion ?? version;
const relocationMessage = relocation.valueWithPath('message');
if (relocationMessage) {
result.deprecationMessage = relocationMessage;
}
}
const groupId = pomContent.valueWithPath('groupId');
if (groupId) {
result.packageScope = groupId;
}
const parent = pomContent.childNamed('parent');
if (
recursionLimit > 0 &&
parent &&
(!result.sourceUrl || !result.homepage)
) {
// if we found a parent and are missing some information
// trying to get the scm/homepage information from it
const [parentGroupId, parentArtifactId, parentVersion] = [
'groupId',
'artifactId',
'version',
].map((k) => parent.valueWithPath(k)?.replace(/\s+/g, ''));
if (parentGroupId && parentArtifactId && parentVersion) {
const parentDisplayId = `${parentGroupId}:${parentArtifactId}`;
const parentDependency = getDependencyParts(parentDisplayId);
const parentInformation = await getDependencyInfo(
http,
parentDependency,
repoUrl,
parentVersion,
recursionLimit - 1,
);
if (!result.sourceUrl && parentInformation.sourceUrl) {
result.sourceUrl = parentInformation.sourceUrl;
}
if (!result.homepage && parentInformation.homepage) {
result.homepage = parentInformation.homepage;
}
}
}
return result;
},
);
return dependencyInfoResult.unwrapOr({});
}