-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgithubService.ts
More file actions
798 lines (711 loc) · 21.9 KB
/
githubService.ts
File metadata and controls
798 lines (711 loc) · 21.9 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
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
import { Octokit } from "@octokit/rest";
import * as vscode from "vscode";
import { LoggerService } from "./loggerService";
import { CodeQLService } from "./codeqlService";
export interface RepositoryInfo {
owner: string;
repo: string;
instance: string; // GitHub instance URL (e.g., github.com, github.enterprise.com)
defaultBranch: string;
languages: string[];
isPrivate: boolean;
codeqlEnabled: boolean;
}
export interface CodeQLAnalysis {
id: number;
ref: string;
status: string;
createdAt: string;
completedAt?: string;
resultsCount?: number;
url: string;
}
export class GitHubService {
private octokit: Octokit | null = null;
private logger: LoggerService;
constructor() {
this.logger = LoggerService.getInstance();
this.initialize();
}
private initialize() {
const config = vscode.workspace.getConfiguration("codeql-scanner");
const token = config.get<string>("github.token");
const baseUrl = config.get<string>(
"github.baseUrl",
"https://api.github.com"
);
if (token) {
config.update("github.token", token, vscode.ConfigurationTarget.Global);
this.octokit = new Octokit({
auth: token,
baseUrl: baseUrl,
});
this.logger.info(
"GitHubService",
"GitHub token configured successfully",
{ baseUrl }
);
} else if (process.env.GITHUB_TOKEN || process.env.GH_TOKEN) {
var envToken = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
this.octokit = new Octokit({
auth: envToken,
baseUrl: baseUrl,
});
this.logger.info(
"GitHubService",
"GitHub token configured from environment variable",
{ baseUrl }
);
config.update(
"github.token",
envToken,
vscode.ConfigurationTarget.Global
);
} else {
this.logger.warn(
"GitHubService",
"GitHub token not configured. Some features may not work."
);
}
this.getRepositoryInfo()
.then((repoInfo) => {
this.logger.info(
"GitHubService",
"Repository info fetched successfully",
repoInfo
);
config.update(
"github.owner",
repoInfo.owner,
vscode.ConfigurationTarget.Workspace
)
config.update(
"github.repo",
repoInfo.repo,
vscode.ConfigurationTarget.Workspace
)
if (repoInfo.codeqlEnabled === false) {
// Send error to the users
vscode.window
.showErrorMessage(
`CodeQL is not enabled for the repository ${repoInfo.owner}/${repoInfo.repo}. Please enable CodeQL analysis in your repository settings.`,
"Learn More"
)
.then((selection) => {
if (selection === "Learn More") {
vscode.env.openExternal(
vscode.Uri.parse(
"https://docs.github.com/en/code-security/secure-coding/using-codeql-code-scanning-in-your-repository"
)
);
}
});
}
})
.catch((error) => {
this.logger.error(
"GitHubService",
"Failed to fetch repository info",
error
);
});
}
/**
* Update the GitHub token used for authentication.
* @param token GitHub token to use for authentication
*/
public updateToken(token: string) {
this.octokit = new Octokit({
auth: token,
});
this.logger.info("GitHubService", "GitHub token updated");
vscode.workspace
.getConfiguration("codeql-scanner")
.update("github.token", token, vscode.ConfigurationTarget.Global);
}
public async getRepositoryInfo(): Promise<RepositoryInfo> {
this.logger.logServiceCall("GitHubService", "getRepositoryInfo", "started");
if (!this.octokit) {
const error = new Error("GitHub token not configured");
this.logger.logServiceCall(
"GitHubService",
"getRepositoryInfo",
"failed",
error
);
throw error;
}
const config = vscode.workspace.getConfiguration("codeql-scanner");
const owner = config.get<string>("github.owner");
const repo = config.get<string>("github.repo");
if (!owner || !repo) {
// Try to get from workspace git remote
const gitInfo = await this.getGitInfo();
if (gitInfo) {
this.logger.info(
"GitHubService",
"Using git remote info for repository details",
gitInfo
);
return await this.fetchRepositoryInfo(gitInfo.owner, gitInfo.repo);
}
const error = new Error("Repository owner and name must be configured");
this.logger.logServiceCall(
"GitHubService",
"getRepositoryInfo",
"failed",
error
);
throw error;
}
const result = await this.fetchRepositoryInfo(owner, repo);
this.logger.logServiceCall(
"GitHubService",
"getRepositoryInfo",
"completed",
{ owner, repo }
);
return result;
}
private async fetchRepositoryInfo(
owner: string,
repo: string
): Promise<RepositoryInfo> {
if (!this.octokit) {
throw new Error("GitHub token not configured");
}
try {
this.logger.logGitHubAPI(`repos/${owner}/${repo}`, "request");
const [repoResponse, languagesResponse, codeqlResponse] =
await Promise.all([
this.octokit.repos.get({ owner, repo }),
this.octokit.repos.listLanguages({ owner, repo }),
this.getCodeQLStatus(owner, repo),
]);
this.logger.logGitHubAPI(`repos/${owner}/${repo}`, "response", {
languages: Object.keys(languagesResponse.data),
isPrivate: repoResponse.data.private,
codeqlEnabled: codeqlResponse,
});
// Determine the instance from the base URL
const config = vscode.workspace.getConfiguration("codeql-scanner");
const baseUrl = config.get<string>(
"github.baseUrl",
"https://api.github.com"
);
const instance = this.extractInstanceFromBaseUrl(baseUrl);
const repoLanguages = Object.keys(languagesResponse.data);
config.update(
"github.languages",
repoLanguages,
vscode.ConfigurationTarget.WorkspaceFolder
);
this.logger.info(
"GitHubService",
`GitHub Languages for ${owner}/${repo}: ${repoLanguages.join(", ")}`
);
return {
owner,
repo,
instance,
defaultBranch: repoResponse.data.default_branch,
languages: repoLanguages,
isPrivate: repoResponse.data.private,
codeqlEnabled: codeqlResponse,
};
} catch (error) {
this.logger.logGitHubAPI(`repos/${owner}/${repo}`, "error", error);
throw new Error(`Failed to fetch repository info: ${error}`);
}
}
private async getCodeQLStatus(owner: string, repo: string): Promise<boolean> {
if (!this.octokit) {
return false;
}
try {
this.logger.logGitHubAPI(
`repos/${owner}/${repo}/code-scanning/alerts`,
"request"
);
await this.octokit.codeScanning.listAlertsForRepo({ owner, repo });
this.logger.debug(
"GitHubService",
`CodeQL is enabled for ${owner}/${repo}`
);
return true;
} catch (error) {
// CodeQL might not be enabled or we don't have permission
this.logger.debug(
"GitHubService",
`CodeQL status check failed for ${owner}/${repo}`,
error
);
return false;
}
}
public async triggerCodeQLScan(
owner: string,
repo: string,
ref?: string
): Promise<void> {
this.logger.logServiceCall(
"GitHubService",
"triggerCodeQLScan",
"started",
{ owner, repo, ref }
);
if (!this.octokit) {
const error = new Error("GitHub token not configured");
this.logger.logServiceCall(
"GitHubService",
"triggerCodeQLScan",
"failed",
error
);
throw error;
}
const config = vscode.workspace.getConfiguration("codeql-scanner");
const languages = config.get<string[]>("languages", [
"javascript",
"typescript",
]);
try {
// Try to trigger CodeQL analysis via workflow dispatch
try {
this.logger.logGitHubAPI(
`repos/${owner}/${repo}/actions/workflows/codeql-analysis.yml/dispatches`,
"request"
);
await this.octokit.actions.createWorkflowDispatch({
owner,
repo,
workflow_id: "codeql-analysis.yml",
ref: ref || "main",
inputs: {
languages: languages.join(","),
},
});
this.logger.logServiceCall(
"GitHubService",
"triggerCodeQLScan",
"completed"
);
} catch (workflowError) {
// If workflow doesn't exist, suggest creating it
const error = new Error(
`CodeQL workflow not found. Run 'CodeQL: Initialize Repository' first. Error: ${workflowError}`
);
this.logger.logServiceCall(
"GitHubService",
"triggerCodeQLScan",
"failed",
error
);
throw error;
}
} catch (error) {
this.logger.logServiceCall(
"GitHubService",
"triggerCodeQLScan",
"failed",
error
);
throw new Error(`Failed to trigger CodeQL scan: ${error}`);
}
}
public async getCodeQLAnalyses(
owner: string,
repo: string
): Promise<CodeQLAnalysis[]> {
this.logger.logServiceCall(
"GitHubService",
"getCodeQLAnalyses",
"started",
{ owner, repo }
);
if (!this.octokit) {
const error = new Error("GitHub token not configured");
this.logger.logServiceCall(
"GitHubService",
"getCodeQLAnalyses",
"failed",
error
);
throw error;
}
try {
this.logger.logGitHubAPI(
`repos/${owner}/${repo}/code-scanning/alerts`,
"request"
);
const response = await this.octokit.codeScanning.listAlertsForRepo({
owner,
repo,
per_page: 50,
state: "open",
});
const analyses = response.data.map((analysis: any) => ({
id: analysis.number || analysis.id,
ref: analysis.ref || "main",
status: analysis.state || "unknown",
createdAt: analysis.created_at,
completedAt: analysis.updated_at || undefined,
resultsCount: 1,
url: analysis.html_url,
}));
this.logger.logServiceCall(
"GitHubService",
"getCodeQLAnalyses",
"completed",
{ count: analyses.length }
);
return analyses;
} catch (error) {
this.logger.logServiceCall(
"GitHubService",
"getCodeQLAnalyses",
"failed",
error
);
throw new Error(`Failed to get CodeQL analyses: ${error}`);
}
}
public async getCodeQLAlerts(owner: string, repo: string) {
this.logger.logServiceCall("GitHubService", "getCodeQLAlerts", "started", {
owner,
repo,
});
if (!this.octokit) {
const error = new Error("GitHub token not configured");
this.logger.logServiceCall(
"GitHubService",
"getCodeQLAlerts",
"failed",
error
);
throw error;
}
try {
this.logger.logGitHubAPI(
`repos/${owner}/${repo}/code-scanning/alerts`,
"request"
);
const allAlerts: any[] = [];
let page = 1;
let hasNextPage = true;
// Use pagination to fetch all alerts
while (hasNextPage) {
this.logger.debug(
"GitHubService",
`Fetching code scanning alerts page ${page}`,
{ owner, repo }
);
const response = await this.octokit.codeScanning.listAlertsForRepo({
owner,
repo,
state: "open",
per_page: 100,
page: page,
});
if (response.data.length === 0) {
hasNextPage = false;
} else {
allAlerts.push(...response.data);
page++;
// Check if we've reached the end of pagination
// by looking at the headers
const linkHeader = response.headers.link;
if (!linkHeader || !linkHeader.includes('rel="next"')) {
hasNextPage = false;
}
}
}
// Filter for CodeQL alerts only
const codeqlAlerts = allAlerts.filter(
(alert: any) =>
alert.tool &&
(alert.tool.name === "CodeQL" || alert.tool.name.startsWith("CodeQL"))
);
this.logger.logServiceCall(
"GitHubService",
"getCodeQLAlerts",
"completed",
{
totalPages: page,
totalAlerts: allAlerts.length,
codeqlAlerts: codeqlAlerts.length,
}
);
return codeqlAlerts;
} catch (error) {
this.logger.logServiceCall(
"GitHubService",
"getCodeQLAlerts",
"failed",
error
);
throw new Error(`Failed to get CodeQL alerts: ${error}`);
}
}
public async getGitInfo(): Promise<{ owner: string; repo: string } | null> {
this.logger.logServiceCall("GitHubService", "getGitInfo", "started");
try {
// First try to get info from VS Code Git extension
const vscodeGitInfo = await this.getGitInfoFromVSCode();
if (vscodeGitInfo) {
this.logger.logServiceCall("GitHubService", "getGitInfo", "completed", {
source: "vscode",
...vscodeGitInfo,
});
return vscodeGitInfo;
}
// Fallback to git CLI
const gitCliInfo = await this.getGitInfoFromCLI();
if (gitCliInfo) {
this.logger.logServiceCall("GitHubService", "getGitInfo", "completed", {
source: "cli",
...gitCliInfo,
});
return gitCliInfo;
}
this.logger.warn(
"GitHubService",
"Could not retrieve git information from VS Code extension or CLI"
);
return null;
} catch (error) {
this.logger.logServiceCall(
"GitHubService",
"getGitInfo",
"failed",
error
);
return null;
}
}
private async getGitInfoFromVSCode(): Promise<{
owner: string;
repo: string;
} | null> {
try {
const gitExtension = vscode.extensions.getExtension("vscode.git");
if (!gitExtension) {
this.logger.debug("GitHubService", "VS Code Git extension not found");
return null;
}
if (!gitExtension.isActive) {
await gitExtension.activate();
}
const git = gitExtension.exports.getAPI(1);
if (!git || git.repositories.length === 0) {
this.logger.debug(
"GitHubService",
"No git repositories found in VS Code"
);
return null;
}
const repository = git.repositories[0];
if (!repository.state.remotes || repository.state.remotes.length === 0) {
this.logger.debug(
"GitHubService",
"No git remotes found in VS Code repository"
);
return null;
}
// Look for origin remote first, then any remote
let remote = repository.state.remotes.find(
(r: any) => r.name === "origin"
);
if (!remote) {
remote = repository.state.remotes[0];
}
const fetchUrl = remote.fetchUrl || remote.pushUrl;
if (!fetchUrl) {
this.logger.debug(
"GitHubService",
"No remote URL found in VS Code repository"
);
return null;
}
const gitInfo = this.parseGitRemoteUrl(fetchUrl);
if (gitInfo) {
this.logger.debug(
"GitHubService",
"Successfully parsed git info from VS Code",
{ url: fetchUrl, ...gitInfo }
);
}
return gitInfo;
} catch (error) {
this.logger.debug(
"GitHubService",
"Failed to get git info from VS Code extension",
error
);
return null;
}
}
private async getGitInfoFromCLI(): Promise<{
owner: string;
repo: string;
} | null> {
try {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (!workspaceFolders || workspaceFolders.length === 0) {
this.logger.debug(
"GitHubService",
"No workspace folders found for git CLI"
);
return null;
}
const workspaceRoot = workspaceFolders[0].uri.fsPath;
// Import child_process and util for exec
const { exec } = require("child_process");
const { promisify } = require("util");
const execAsync = promisify(exec);
// Get the remote URL using git CLI
const { stdout } = await execAsync("git remote get-url origin", {
cwd: workspaceRoot,
timeout: 5000,
});
const remoteUrl = stdout.trim();
if (!remoteUrl) {
this.logger.debug("GitHubService", "No git remote URL found via CLI");
return null;
}
const gitInfo = this.parseGitRemoteUrl(remoteUrl);
if (gitInfo) {
this.logger.debug(
"GitHubService",
"Successfully parsed git info from CLI",
{ url: remoteUrl, ...gitInfo }
);
}
return gitInfo;
} catch (error) {
this.logger.debug(
"GitHubService",
"Failed to get git info from CLI",
error
);
return null;
}
}
private parseGitRemoteUrl(
url: string
): { owner: string; repo: string } | null {
try {
// Remove .git suffix if present
const cleanUrl = url.replace(/\.git$/, "");
// Handle different URL formats
let match;
// SSH format: git@github.com:owner/repo or git@enterprise.com:owner/repo
match = cleanUrl.match(/git@([^:]+):([^/]+)\/(.+)$/);
if (match) {
return { owner: match[2], repo: match[3] };
}
// HTTPS format: https://github.com/owner/repo or https://enterprise.com/owner/repo
match = cleanUrl.match(/https:\/\/([^/]+)\/([^/]+)\/(.+)$/);
if (match) {
return { owner: match[2], repo: match[3] };
}
// HTTP format: http://github.com/owner/repo or http://enterprise.com/owner/repo
match = cleanUrl.match(/http:\/\/([^/]+)\/([^/]+)\/(.+)$/);
if (match) {
return { owner: match[2], repo: match[3] };
}
this.logger.debug("GitHubService", "Could not parse git remote URL", {
url,
});
return null;
} catch (error) {
this.logger.debug("GitHubService", "Error parsing git remote URL", {
url,
error,
});
return null;
}
}
private extractInstanceFromBaseUrl(baseUrl: string): string {
try {
// Extract the hostname from the base URL
const url = new URL(baseUrl);
let hostname = url.hostname;
// Handle common GitHub instances
if (hostname === "api.github.com") {
return "github.com";
}
// For GitHub Enterprise Server, the API URL is typically:
// https://your-github-instance.com/api/v3
// We want to extract just the main domain
if (hostname.includes("github")) {
// Remove 'api.' prefix if present
hostname = hostname.replace(/^api\./, "");
return hostname;
}
return hostname;
} catch (error) {
this.logger.warn(
"GitHubService",
"Failed to parse base URL, using default",
{ baseUrl, error }
);
return "github.com";
}
}
/**
* Authenticate with GitHub using VS Code's built-in GitHub authentication provider.
* This method will prompt the user to sign in with GitHub and return the authentication session.
* @param scopes The GitHub OAuth scopes to request
* @returns A promise that resolves to the authentication session, or null if authentication failed
*/
public async authenticateWithGitHub(scopes: string[] = ['repo', 'read:org', 'security_events']): Promise<boolean> {
this.logger.logServiceCall("GitHubService", "authenticateWithGitHub", "started");
try {
// Use VS Code's built-in GitHub authentication provider
const session = await vscode.authentication.getSession('github', scopes, { createIfNone: true });
if (session) {
// Got a valid session, update the token and Octokit instance
this.updateToken(session.accessToken);
this.logger.logServiceCall("GitHubService", "authenticateWithGitHub", "completed", {
scopes: session.scopes,
account: session.account.label
});
// Show confirmation to user
vscode.window.showInformationMessage(`Signed in to GitHub as ${session.account.label}`);
return true;
}
return false;
} catch (error) {
this.logger.logServiceCall("GitHubService", "authenticateWithGitHub", "failed", error);
vscode.window.showErrorMessage(`GitHub authentication failed: ${error instanceof Error ? error.message : String(error)}`);
return false;
}
}
/**
* Check if there's an existing GitHub authentication session through VS Code authentication API
* @returns A promise that resolves to information about the current session or null if none exists
*/
public async checkGitHubAuth(): Promise<{ isAuthenticated: boolean; displayName?: string }> {
this.logger.logServiceCall("GitHubService", "checkGitHubAuth", "started");
try {
// Check for existing sessions without prompting the user
const sessions = await vscode.authentication.getAccounts('github');
if (sessions && sessions.length > 0) {
// We have an existing session, use it
this.logger.logServiceCall("GitHubService", "checkGitHubAuth", "completed", {
isAuthenticated: true,
account: sessions[0].label
});
return {
isAuthenticated: true,
displayName: sessions[0].label
};
}
return { isAuthenticated: false };
} catch (error) {
this.logger.logServiceCall("GitHubService", "checkGitHubAuth", "failed", error);
return { isAuthenticated: false };
}
}
}