-
Notifications
You must be signed in to change notification settings - Fork 228
Expand file tree
/
Copy pathdatabase-fetcher.ts
More file actions
632 lines (572 loc) · 18.3 KB
/
database-fetcher.ts
File metadata and controls
632 lines (572 loc) · 18.3 KB
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
import type { InputBoxOptions } from "vscode";
import { Uri, window } from "vscode";
import type { CodeQLCliServer } from "../codeql-cli/cli";
import {
ensureDir,
realpath as fs_realpath,
createWriteStream,
remove,
readdir,
copy,
} from "fs-extra";
import { basename, join } from "path";
import type { Octokit } from "@octokit/rest";
import { nanoid } from "nanoid";
import type { DatabaseManager, DatabaseItem } from "./local-databases";
import { tmpDir } from "../tmp-dir";
import type { ProgressCallback } from "../common/vscode/progress";
import { reportStreamProgress } from "../common/vscode/progress";
import { extLogger } from "../common/logging/vscode";
import { getErrorMessage } from "../common/helpers-pure";
import {
getNwoFromGitHubUrl,
isValidGitHubNwo,
} from "../common/github-url-identifier-helper";
import {
addDatabaseSourceToWorkspace,
allowHttp,
downloadTimeout,
getGitHubInstanceUrl,
} from "../config";
import { showAndLogInformationMessage } from "../common/logging";
import type { DatabaseOrigin } from "./local-databases/database-origin";
import { createTimeoutSignal } from "../common/fetch-stream";
import type { App } from "../common/app";
import { createFilenameFromString } from "../common/filenames";
import { findDirWithFile } from "../common/files";
import { convertGithubNwoToDatabaseUrl } from "./github-databases/api";
import { ensureZippedSourceLocation } from "./local-databases/database-contents";
// The number of tries to use when generating a unique filename before
// giving up and using a nanoid.
const DUPLICATE_FILENAMES_TRIES = 10_000;
export class DatabaseFetcher {
/**
* @param app the App
* @param databaseManager the DatabaseManager
* @param storagePath where to store the unzipped database.
* @param cli the CodeQL CLI server
**/
constructor(
private readonly app: App,
private readonly databaseManager: DatabaseManager,
private readonly storagePath: string,
private readonly cli: CodeQLCliServer,
) {}
/**
* Prompts a user to fetch a database from a remote location. Database is assumed to be an archive file.
*/
public async promptImportInternetDatabase(
progress: ProgressCallback,
): Promise<DatabaseItem | undefined> {
const databaseUrl = await window.showInputBox({
prompt: "Enter URL of zipfile of database to download",
});
if (!databaseUrl) {
return;
}
this.validateUrl(databaseUrl);
const item = await this.fetchDatabaseToWorkspaceStorage(
databaseUrl,
{},
undefined,
{
type: "url",
url: databaseUrl,
},
progress,
);
if (item) {
await this.app.commands.execute("codeQLDatabases.focus");
void showAndLogInformationMessage(
extLogger,
"Database downloaded and imported successfully.",
);
}
return item;
}
/**
* Prompts a user to fetch a database from GitHub.
* User enters a GitHub repository and then the user is asked which language
* to download (if there is more than one)
*
* @param progress the progress callback
* @param language the language to download. If undefined, the user will be prompted to choose a language.
* @param suggestedRepoNwo the suggested value to use when prompting for a github repo
* @param makeSelected make the new database selected in the databases panel (default: true)
* @param addSourceArchiveFolder whether to add a workspace folder containing the source archive to the workspace
*/
public async promptImportGithubDatabase(
progress: ProgressCallback,
language?: string,
suggestedRepoNwo?: string,
makeSelected = true,
addSourceArchiveFolder = addDatabaseSourceToWorkspace(),
): Promise<DatabaseItem | undefined> {
const githubRepo = await this.askForGitHubRepo(progress, suggestedRepoNwo);
if (!githubRepo) {
return;
}
const databaseItem = await this.downloadGitHubDatabase(
githubRepo,
progress,
language,
makeSelected,
addSourceArchiveFolder,
);
if (databaseItem) {
if (makeSelected) {
await this.app.commands.execute("codeQLDatabases.focus");
}
void showAndLogInformationMessage(
extLogger,
"Database downloaded and imported successfully.",
);
return databaseItem;
}
return;
}
private async askForGitHubRepo(
progress?: ProgressCallback,
suggestedValue?: string,
): Promise<string | undefined> {
progress?.({
message: "Choose repository",
step: 1,
maxStep: 2,
});
const instanceUrl = getGitHubInstanceUrl();
const options: InputBoxOptions = {
title: `Enter a GitHub repository URL or "name with owner" (e.g. ${new URL("/github/codeql", instanceUrl).toString()} or github/codeql)`,
placeHolder: `${new URL("/", instanceUrl).toString()}<owner>/<repo> or <owner>/<repo>`,
ignoreFocusOut: true,
};
if (suggestedValue) {
options.value = suggestedValue;
}
return await window.showInputBox(options);
}
/**
* Downloads a database from GitHub
*
* @param githubRepo the GitHub repository to download the database from
* @param progress the progress callback
* @param language the language to download. If undefined, the user will be prompted to choose a language.
* @param makeSelected make the new database selected in the databases panel (default: true)
* @param addSourceArchiveFolder whether to add a workspace folder containing the source archive to the workspace
**/
private async downloadGitHubDatabase(
githubRepo: string,
progress: ProgressCallback,
language?: string,
makeSelected = true,
addSourceArchiveFolder = addDatabaseSourceToWorkspace(),
): Promise<DatabaseItem | undefined> {
const nwo =
getNwoFromGitHubUrl(githubRepo, getGitHubInstanceUrl()) || githubRepo;
if (!isValidGitHubNwo(nwo)) {
throw new Error(`Invalid GitHub repository: ${githubRepo}`);
}
const octokit = await this.app.credentials.getOctokit();
const result = await convertGithubNwoToDatabaseUrl(
nwo,
octokit,
progress,
language,
);
if (!result) {
return;
}
const {
databaseUrl,
name,
owner,
databaseId,
databaseCreatedAt,
commitOid,
} = result;
return this.downloadGitHubDatabaseFromUrl(
databaseUrl,
databaseId,
databaseCreatedAt,
commitOid,
owner,
name,
octokit,
progress,
makeSelected,
addSourceArchiveFolder,
);
}
public async downloadGitHubDatabaseFromUrl(
databaseUrl: string,
databaseId: number,
databaseCreatedAt: string,
commitOid: string | null,
owner: string,
name: string,
octokit: Octokit,
progress: ProgressCallback,
makeSelected = true,
addSourceArchiveFolder = true,
): Promise<DatabaseItem | undefined> {
/**
* The 'token' property of the token object returned by `octokit.auth()`.
* The object is undocumented, but looks something like this:
* {
* token: 'xxxx',
* tokenType: 'oauth',
* type: 'token',
* }
* We only need the actual token string.
*/
const octokitToken = ((await octokit.auth()) as { token: string })?.token;
return await this.fetchDatabaseToWorkspaceStorage(
databaseUrl,
{
Accept: "application/zip",
Authorization: octokitToken ? `Bearer ${octokitToken}` : "",
},
`${owner}/${name}`,
{
type: "github",
repository: `${owner}/${name}`,
databaseId,
databaseCreatedAt,
commitOid,
},
progress,
makeSelected,
addSourceArchiveFolder,
);
}
/**
* Imports a database from a local archive or a test database that is in a folder
* ending with `.testproj`.
*
* @param databaseUrl the file url of the archive or directory to import
* @param progress the progress callback
*/
public async importLocalDatabase(
databaseUrl: string,
progress: ProgressCallback,
): Promise<DatabaseItem | undefined> {
try {
const origin: DatabaseOrigin = {
type: databaseUrl.endsWith(".testproj") ? "testproj" : "archive",
path: Uri.parse(databaseUrl).fsPath,
};
const item = await this.fetchDatabaseToWorkspaceStorage(
databaseUrl,
{},
undefined,
origin,
progress,
);
if (item) {
await this.app.commands.execute("codeQLDatabases.focus");
void showAndLogInformationMessage(
extLogger,
origin.type === "testproj"
? "Test database imported successfully."
: "Database unzipped and imported successfully.",
);
}
return item;
} catch (e) {
if (getErrorMessage(e).includes("unexpected end of file")) {
throw new Error(
"Database is corrupt or too large. Try unzipping outside of VS Code and importing the unzipped folder instead.",
);
} else {
// delegate
throw e;
}
}
}
/**
* Fetches a database into workspace storage. The database might be on the internet
* or in the local filesystem.
*
* @param databaseUrl URL from which to grab the database. This could be a local archive file, a local directory, or a remote URL.
* @param requestHeaders Headers to send with the request
* @param nameOverride a name for the database that overrides the default
* @param origin the origin of the database
* @param progress callback to send progress messages to
* @param makeSelected make the new database selected in the databases panel (default: true)
* @param addSourceArchiveFolder whether to add a workspace folder containing the source archive to the workspace
*/
private async fetchDatabaseToWorkspaceStorage(
databaseUrl: string,
requestHeaders: { [key: string]: string },
nameOverride: string | undefined,
origin: DatabaseOrigin,
progress: ProgressCallback,
makeSelected = true,
addSourceArchiveFolder = addDatabaseSourceToWorkspace(),
): Promise<DatabaseItem> {
progress({
message: "Getting database",
step: 1,
maxStep: 4,
});
if (!this.storagePath) {
throw new Error("No storage path specified.");
}
await ensureDir(this.storagePath);
const unzipPath = await this.getStorageFolder(databaseUrl, nameOverride);
if (Uri.parse(databaseUrl).scheme === "file") {
if (origin.type === "testproj") {
await this.copyDatabase(databaseUrl, unzipPath, progress);
} else {
await this.readAndUnzip(databaseUrl, unzipPath, progress);
}
} else {
await this.fetchAndUnzip(
databaseUrl,
requestHeaders,
unzipPath,
progress,
);
}
progress({
message: "Opening database",
step: 3,
maxStep: 4,
});
// find the path to the database. The actual database might be in a sub-folder
const dbPath = await findDirWithFile(
unzipPath,
".dbinfo",
"codeql-database.yml",
);
if (dbPath) {
progress({
message: "Validating and fixing source location",
step: 4,
maxStep: 4,
});
await ensureZippedSourceLocation(dbPath);
const item = await this.databaseManager.openDatabase(
Uri.file(dbPath),
origin,
makeSelected,
nameOverride,
{
addSourceArchiveFolder,
extensionManagedLocation: unzipPath,
},
);
return item;
} else {
throw new Error("Database not found in archive.");
}
}
private async getStorageFolder(urlStr: string, nameOverrride?: string) {
let lastName: string;
if (nameOverrride) {
lastName = createFilenameFromString(nameOverrride);
} else {
// we need to generate a folder name for the unzipped archive,
// this needs to be human readable since we may use this name as the initial
// name for the database
const url = Uri.parse(urlStr);
// MacOS has a max filename length of 255
// and remove a few extra chars in case we need to add a counter at the end.
lastName = basename(url.path).substring(0, 250);
if (lastName.endsWith(".zip")) {
lastName = lastName.substring(0, lastName.length - 4);
} else if (lastName.endsWith(".testproj")) {
lastName = lastName.substring(0, lastName.length - 9);
}
}
const realpath = await fs_realpath(this.storagePath);
let folderName = lastName;
// get all existing files instead of calling pathExists on every
// single combination of realpath and folderName
const existingFiles = await readdir(realpath);
// avoid overwriting existing folders
let counter = 0;
while (existingFiles.includes(basename(folderName))) {
counter++;
if (counter <= DUPLICATE_FILENAMES_TRIES) {
// First try to use a counter to make the name unique.
folderName = `${lastName}-${counter}`;
} else if (counter <= DUPLICATE_FILENAMES_TRIES + 5) {
// If there are more than 10,000 similarly named databases,
// give up on using a counter and use a random string instead.
folderName = `${lastName}-${nanoid()}`;
} else {
// This should almost never happen, but just in case, we don't want to
// get stuck in an infinite loop.
throw new Error(
"Could not find a unique name for downloaded database. Please remove some databases and try again.",
);
}
}
return join(realpath, folderName);
}
private validateUrl(databaseUrl: string) {
let uri;
try {
uri = Uri.parse(databaseUrl, true);
} catch {
throw new Error(`Invalid url: ${databaseUrl}`);
}
if (!allowHttp() && uri.scheme !== "https") {
throw new Error("Must use https for downloading a database.");
}
}
/**
* Copies a database folder from the file system into the workspace storage.
* @param scrDirURL the original location of the database as a URL string
* @param destDir the location to copy the database to. This should be a folder in the workspace storage.
* @param progress callback to send progress messages to
*/
private async copyDatabase(
srcDirURL: string,
destDir: string,
progress?: ProgressCallback,
) {
progress?.({
maxStep: 10,
step: 9,
message: `Copying database ${basename(destDir)} into the workspace`,
});
await ensureDir(destDir);
await copy(Uri.parse(srcDirURL).fsPath, destDir);
}
private async readAndUnzip(
zipUrl: string,
unzipPath: string,
progress?: ProgressCallback,
) {
const zipFile = Uri.parse(zipUrl).fsPath;
progress?.({
maxStep: 10,
step: 9,
message: `Unzipping into ${basename(unzipPath)}`,
});
await this.cli.databaseUnbundle(zipFile, unzipPath);
}
private async fetchAndUnzip(
databaseUrl: string,
requestHeaders: { [key: string]: string },
unzipPath: string,
progress?: ProgressCallback,
) {
// Although it is possible to download and stream directly to an unzipped directory,
// we need to avoid this for two reasons. The central directory is located at the
// end of the zip file. It is the source of truth of the content locations. Individual
// file headers may be incorrect. Additionally, saving to file first will reduce memory
// pressure compared with unzipping while downloading the archive.
const archivePath = join(tmpDir.name, `archive-${Date.now()}.zip`);
progress?.({
maxStep: 3,
message: "Downloading database",
step: 1,
});
const {
signal,
onData,
dispose: disposeTimeout,
} = createTimeoutSignal(downloadTimeout());
let response: Response;
try {
response = await this.checkForFailingResponse(
await fetch(databaseUrl, {
headers: requestHeaders,
signal,
}),
"Error downloading database",
);
} catch (e) {
disposeTimeout();
if (e instanceof DOMException && e.name === "AbortError") {
const thrownError = new Error("The request timed out.");
thrownError.stack = e.stack;
throw thrownError;
}
throw e;
}
const body = response.body;
if (!body) {
throw new Error("No response body found");
}
const archiveFileStream = createWriteStream(archivePath);
const contentLength = response.headers.get("content-length");
const totalNumBytes = contentLength
? parseInt(contentLength, 10)
: undefined;
const reportProgress = reportStreamProgress(
"Downloading database",
totalNumBytes,
progress,
);
try {
const reader = body.getReader();
for (;;) {
const { done, value } = await reader.read();
if (done) {
break;
}
onData();
reportProgress(value?.length ?? 0);
await new Promise((resolve, reject) => {
archiveFileStream.write(value, (err) => {
if (err) {
reject(err);
}
resolve(undefined);
});
});
}
await new Promise((resolve, reject) => {
archiveFileStream.close((err) => {
if (err) {
reject(err);
}
resolve(undefined);
});
});
} catch (e) {
// Close and remove the file if an error occurs
archiveFileStream.close(() => {
void remove(archivePath);
});
if (e instanceof DOMException && e.name === "AbortError") {
const thrownError = new Error("The download timed out.");
thrownError.stack = e.stack;
throw thrownError;
}
throw e;
} finally {
disposeTimeout();
}
await this.readAndUnzip(
Uri.file(archivePath).toString(true),
unzipPath,
progress,
);
// remove archivePath eagerly since these archives can be large.
await remove(archivePath);
}
private async checkForFailingResponse(
response: Response,
errorMessage: string,
): Promise<Response | never> {
if (response.ok) {
return response;
}
// An error downloading the database. Attempt to extract the reason behind it.
const text = await response.text();
let msg: string;
try {
const obj = JSON.parse(text);
msg =
obj.error || obj.message || obj.reason || JSON.stringify(obj, null, 2);
} catch {
msg = text;
}
throw new Error(`${errorMessage}.\n\nReason: ${msg}`);
}
}