@zereight/mcp-gitlab 2.1.41 → 2.1.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/schemas.js CHANGED
@@ -2547,26 +2547,31 @@ export const MergeRequestThreadPositionSchema = z.object({
2547
2547
  });
2548
2548
  const optionalMergeRequestThreadPosition = z.preprocess(omitIncompleteMergeRequestPosition, MergeRequestThreadPositionSchema.optional());
2549
2549
  // Draft Notes API schemas
2550
+ // Response shape follows Draft Notes API (not Notes API): note, author_id,
2551
+ // line_code, merge_request_id, commit_id — no created_at/updated_at.
2550
2552
  export const GitLabDraftNoteSchema = z
2551
2553
  .object({
2552
2554
  id: z.coerce.string(),
2555
+ author_id: z.coerce.number().nullable().optional(),
2553
2556
  author: GitLabUserSchema.optional(),
2554
2557
  body: z.string().optional(),
2555
- note: z.string().optional(), // Some APIs might use 'note' instead of 'body'
2556
- created_at: z.string().optional(),
2557
- updated_at: z.string().optional(),
2558
+ note: z.string().optional(), // Draft Notes API uses 'note'; keep 'body' for callers
2559
+ line_code: z.string().nullable().optional(),
2560
+ merge_request_id: z.coerce.number().nullable().optional(),
2561
+ commit_id: z.string().nullable().optional(),
2558
2562
  discussion_id: z.string().nullable().optional(),
2559
2563
  position: z.record(z.unknown()).nullable().optional(),
2560
2564
  resolve_discussion: z.coerce.boolean().optional(),
2561
2565
  })
2562
2566
  .transform(data => ({
2563
- // Normalize the response to always have consistent field names
2564
2567
  id: data.id,
2568
+ author_id: data.author_id ?? null,
2565
2569
  author: data.author,
2566
2570
  body: data.body || data.note || "",
2567
- created_at: data.created_at || "",
2568
- updated_at: data.updated_at || "",
2569
- discussion_id: data.discussion_id || null,
2571
+ line_code: data.line_code ?? null,
2572
+ merge_request_id: data.merge_request_id ?? null,
2573
+ commit_id: data.commit_id ?? null,
2574
+ discussion_id: data.discussion_id ?? null,
2570
2575
  position: data.position,
2571
2576
  resolve_discussion: data.resolve_discussion,
2572
2577
  }));
@@ -2617,6 +2622,18 @@ export const PublishDraftNoteSchema = ProjectParamsSchema.extend({
2617
2622
  // Bulk publish draft notes schema
2618
2623
  export const BulkPublishDraftNotesSchema = ProjectParamsSchema.extend({
2619
2624
  merge_request_iid: z.coerce.string().describe("The IID of a merge request"),
2625
+ reviewer_state: z
2626
+ .enum(["requested_changes", "reviewed"])
2627
+ .optional()
2628
+ .describe("Set reviewer review state after publishing (GitLab 19.2+). Does not record a formal approval. Works even with no draft notes."),
2629
+ note: z
2630
+ .string()
2631
+ .optional()
2632
+ .describe("Summary note body to post on the merge request (GitLab 19.2+)"),
2633
+ internal: z.coerce
2634
+ .boolean()
2635
+ .optional()
2636
+ .describe("If true, the summary note is internal (GitLab 19.2+, default false)"),
2620
2637
  });
2621
2638
  // Schema for creating a new merge request thread
2622
2639
  export const CreateMergeRequestThreadSchema = ProjectParamsSchema.extend({
@@ -4006,3 +4023,70 @@ export const ListDependencyProxyBlobsSchema = z.object({
4006
4023
  export const PurgeDependencyProxyCacheSchema = z.object({
4007
4024
  group_id: z.coerce.string().describe("Group ID or URL-encoded path"),
4008
4025
  });
4026
+ // --- Vulnerability schemas ---
4027
+ // Schema for listing project vulnerabilities with optional filters (GraphQL-backed)
4028
+ export const ListProjectVulnerabilitiesSchema = z.object({
4029
+ project_id: z.coerce.string().describe("Project ID or URL-encoded path"),
4030
+ state: z
4031
+ .enum(["detected", "confirmed", "resolved", "dismissed"])
4032
+ .optional()
4033
+ .describe("Filter by vulnerability state"),
4034
+ severity: z
4035
+ .enum(["critical", "high", "medium", "low", "info", "unknown"])
4036
+ .optional()
4037
+ .describe("Filter by severity level"),
4038
+ report_type: z
4039
+ .enum([
4040
+ "sast",
4041
+ "dast",
4042
+ "dependency_scanning",
4043
+ "container_scanning",
4044
+ "secret_detection",
4045
+ "coverage_fuzzing",
4046
+ "api_fuzzing",
4047
+ "cluster_image_scanning",
4048
+ "generic",
4049
+ ])
4050
+ .optional()
4051
+ .describe("Filter by scan/report type (e.g. secret_detection, sast, dast)"),
4052
+ first: z.coerce
4053
+ .number()
4054
+ .int()
4055
+ .min(1)
4056
+ .max(100)
4057
+ .optional()
4058
+ .describe("Number of vulnerabilities to return (max: 100, default: 20)"),
4059
+ after: z
4060
+ .string()
4061
+ .optional()
4062
+ .describe("Cursor for pagination; use the endCursor from a previous response"),
4063
+ });
4064
+ // Schema for getting a single vulnerability by ID
4065
+ export const GetVulnerabilitySchema = z.object({
4066
+ vulnerability_id: z.coerce
4067
+ .string()
4068
+ .describe("The vulnerability ID (numeric or GraphQL global ID)"),
4069
+ });
4070
+ // Schema for dismissing a vulnerability with required reason and optional comment
4071
+ export const DismissVulnerabilitySchema = z.object({
4072
+ vulnerability_id: z.coerce
4073
+ .string()
4074
+ .describe("The ID of the vulnerability to dismiss (numeric or GraphQL global ID)"),
4075
+ reason: z
4076
+ .enum([
4077
+ "acceptable_risk",
4078
+ "false_positive",
4079
+ "used_in_tests",
4080
+ "mitigating_control",
4081
+ "not_applicable",
4082
+ ])
4083
+ .describe("Reason for dismissal"),
4084
+ comment: z.string().optional().describe("Optional comment explaining the dismissal"),
4085
+ });
4086
+ // Schema for confirming a vulnerability with optional comment
4087
+ export const ConfirmVulnerabilitySchema = z.object({
4088
+ vulnerability_id: z.coerce
4089
+ .string()
4090
+ .describe("The ID of the vulnerability to confirm (numeric or GraphQL global ID)"),
4091
+ comment: z.string().optional().describe("Optional comment explaining the confirmation"),
4092
+ });
@@ -14,6 +14,7 @@ const SKILL_PATH = join(REPO_ROOT, "skills", "gitlab-mcp", "SKILL.md");
14
14
  const REF_DIR = join(REPO_ROOT, "skills", "gitlab-mcp", "reference");
15
15
  // Response field names in reference docs — not MCP tools.
16
16
  const REFERENCE_FIELD_ALLOWLIST = new Set([
17
+ "after",
17
18
  "allow_multiple",
18
19
  "deleted_file",
19
20
  "excluded_file_patterns",
@@ -115,6 +115,10 @@ const GROUP_META = {
115
115
  title: "Dependency Proxy",
116
116
  blurb: "Inspect and manage the GitLab dependency proxy cache settings, blob storage, and purge operations.",
117
117
  },
118
+ vulnerabilities: {
119
+ title: "Vulnerabilities",
120
+ blurb: "AI-assisted vulnerability triage — list findings, inspect details, dismiss with reason, or confirm for remediation. Backed by the GitLab GraphQL API; requires GitLab Ultimate.",
121
+ },
118
122
  };
119
123
  const GROUP_ORDER = [
120
124
  "projects",
@@ -136,6 +140,7 @@ const GROUP_ORDER = [
136
140
  "webhooks",
137
141
  "search",
138
142
  "dependency_proxy",
143
+ "vulnerabilities",
139
144
  ];
140
145
  // Authoritative classification — uses the `readOnlyTools` set from
141
146
  // tools/registry.ts. That set is what the server itself consults to decide
@@ -210,7 +215,7 @@ function buildGroupPage(id, toolNames) {
210
215
  lines.push("## Tools in this group");
211
216
  lines.push("");
212
217
  for (const name of toolNames) {
213
- lines.push(`- [\`${name}\`](#${name.replace(/_/g, "_")}) — ${rwBadge(name)}`);
218
+ lines.push(`- [\`${name}\`](#${name}) — ${rwBadge(name)}`);
214
219
  }
215
220
  lines.push("");
216
221
  lines.push("---");
@@ -0,0 +1,44 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { GitLabDraftNoteSchema } from "../schemas.js";
4
+ test("draft note schema keeps Draft Notes API fields and drops fake timestamps", () => {
5
+ const parsed = GitLabDraftNoteSchema.parse({
6
+ id: 42,
7
+ author_id: 7,
8
+ note: "looks wrong on this line",
9
+ line_code: "a1b2c3d4e5f6_12_17",
10
+ merge_request_id: 99,
11
+ commit_id: "abc123",
12
+ discussion_id: null,
13
+ position: { new_path: "src/app.ts", new_line: 17 },
14
+ resolve_discussion: false,
15
+ // Notes-API leftovers that Draft Notes API never returns — must be stripped
16
+ created_at: "2024-01-01T00:00:00Z",
17
+ updated_at: "2024-01-02T00:00:00Z",
18
+ });
19
+ assert.equal(parsed.id, "42");
20
+ assert.equal(parsed.author_id, 7);
21
+ assert.equal(parsed.body, "looks wrong on this line");
22
+ assert.equal(parsed.line_code, "a1b2c3d4e5f6_12_17");
23
+ assert.equal(parsed.merge_request_id, 99);
24
+ assert.equal(parsed.commit_id, "abc123");
25
+ assert.equal(parsed.discussion_id, null);
26
+ assert.equal(parsed.resolve_discussion, false);
27
+ assert.equal("created_at" in parsed, false);
28
+ assert.equal("updated_at" in parsed, false);
29
+ });
30
+ test("draft note schema preserves null line_code for unresolved positions", () => {
31
+ const parsed = GitLabDraftNoteSchema.parse({
32
+ id: "43",
33
+ author_id: 7,
34
+ note: "orphan draft",
35
+ line_code: null,
36
+ merge_request_id: 99,
37
+ commit_id: null,
38
+ discussion_id: null,
39
+ position: null,
40
+ resolve_discussion: false,
41
+ });
42
+ assert.equal(parsed.line_code, null);
43
+ assert.equal(parsed.commit_id, null);
44
+ });
@@ -26,6 +26,7 @@ describe("Dynamic API URL allowlist", () => {
26
26
  let secondaryGitLab;
27
27
  let attackerServer;
28
28
  let mcpServer;
29
+ let mcpPort;
29
30
  let mcpUrl;
30
31
  let secondaryHit = false;
31
32
  let getAttackerHits = () => 0;
@@ -44,7 +45,7 @@ describe("Dynamic API URL allowlist", () => {
44
45
  const attacker = await startAttackerServer(attackerPort);
45
46
  attackerServer = attacker.server;
46
47
  getAttackerHits = attacker.getHits;
47
- const mcpPort = await findAvailablePort(3100);
48
+ mcpPort = await findAvailablePort(3100);
48
49
  mcpServer = await launchServer({
49
50
  mode: TransportMode.STREAMABLE_HTTP,
50
51
  port: mcpPort,
@@ -101,4 +102,20 @@ describe("Dynamic API URL allowlist", () => {
101
102
  assert.strictEqual(connected, false, "untrusted dynamic host should not initialize a session");
102
103
  assert.strictEqual(getAttackerHits(), 0, "token-bearing requests must not reach untrusted hosts");
103
104
  });
105
+ test("returns remediation text when download proxy rejects untrusted dynamic hosts", async () => {
106
+ const server = attackerServer;
107
+ assert.ok(server, "attacker server should be running");
108
+ const attackerUrl = `http://${HOST}:${server.address().port}/api/v4`;
109
+ const response = await fetch(`http://${HOST}:${mcpPort}/downloads/job-artifacts?project_id=1&job_id=1`, {
110
+ headers: {
111
+ "Private-Token": MOCK_TOKEN,
112
+ "x-gitlab-api-url": attackerUrl,
113
+ },
114
+ });
115
+ assert.strictEqual(response.status, 400);
116
+ const body = (await response.json());
117
+ assert.match(body.error, /not allowed/);
118
+ assert.match(body.error, /GITLAB_ALLOWED_HOSTS/);
119
+ assert.strictEqual(getAttackerHits(), 0, "download proxy must not forward to untrusted hosts");
120
+ });
104
121
  });
@@ -35,6 +35,7 @@ const TOOLSET_TOOL_COUNTS = {
35
35
  groups: 1,
36
36
  variables: 10,
37
37
  dependency_proxy: 4,
38
+ vulnerabilities: 4,
38
39
  };
39
40
  const LEGACY_PIPELINE_CI_TOOL_COUNT = 2;
40
41
  const LEGACY_PIPELINE_TOOL_COUNT = TOOLSET_TOOL_COUNTS.pipelines + LEGACY_PIPELINE_CI_TOOL_COUNT;
@@ -60,6 +61,7 @@ const NON_DEFAULT_TOOLSETS = [
60
61
  "search",
61
62
  "variables",
62
63
  "dependency_proxy",
64
+ "vulnerabilities",
63
65
  ];
64
66
  // discover_tools meta-tool is always force-injected (Step 5.5)
65
67
  const DISCOVER_TOOLS_COUNT = 1;
@@ -0,0 +1,399 @@
1
+ import { describe, test, before, after } from "node:test";
2
+ import assert from "node:assert";
3
+ import { spawn } from "child_process";
4
+ import { MockGitLabServer, findMockServerPort } from "./utils/mock-gitlab-server.js";
5
+ const MOCK_TOKEN = "glpat-mock-token-12345";
6
+ const TEST_PROJECT_ID = "456";
7
+ const TEST_PROJECT_FULL_PATH = "test-group/test-project";
8
+ const TEST_VULNERABILITY_ID = "789";
9
+ const TEST_VULNERABILITY_GID = `gid://gitlab/Vulnerability/${TEST_VULNERABILITY_ID}`;
10
+ const mockVulnerability = {
11
+ id: TEST_VULNERABILITY_GID,
12
+ title: "Hard-coded credential detected",
13
+ description: "A hard-coded credential was found in source code",
14
+ state: "DETECTED",
15
+ severity: "CRITICAL",
16
+ reportType: "SECRET_DETECTION",
17
+ detectedAt: "2024-06-01T10:00:00Z",
18
+ confirmedAt: null,
19
+ resolvedAt: null,
20
+ dismissedAt: null,
21
+ dismissalReason: null,
22
+ webUrl: "https://gitlab.mock/test-group/test-project/-/security/vulnerabilities/789",
23
+ scanner: { name: "GitLeaks", externalId: "gitleaks", vendor: "GitLab" },
24
+ identifiers: [
25
+ { externalType: "cve", externalId: "CVE-2024-0001", name: "CVE-2024-0001", url: null },
26
+ ],
27
+ links: [{ name: "More info", url: "https://example.com/vuln/789" }],
28
+ location: { file: "config/secrets.yml", startLine: 42, endLine: 42 },
29
+ };
30
+ const mockVulnerabilityList = [
31
+ mockVulnerability,
32
+ {
33
+ ...mockVulnerability,
34
+ id: "gid://gitlab/Vulnerability/790",
35
+ title: "SQL Injection in login form",
36
+ state: "CONFIRMED",
37
+ severity: "HIGH",
38
+ reportType: "SAST",
39
+ confirmedAt: "2024-06-03T09:00:00Z",
40
+ location: { file: "src/auth/login.ts", startLine: 18, endLine: 22 },
41
+ },
42
+ {
43
+ ...mockVulnerability,
44
+ id: "gid://gitlab/Vulnerability/791",
45
+ title: "Outdated dependency with known CVE",
46
+ state: "DISMISSED",
47
+ severity: "MEDIUM",
48
+ reportType: "DEPENDENCY_SCANNING",
49
+ dismissedAt: "2024-05-20T14:00:00Z",
50
+ dismissalReason: "ACCEPTABLE_RISK",
51
+ location: { file: "package.json", dependency: { package: { name: "foo" }, version: "1.2.3" } },
52
+ },
53
+ ];
54
+ async function callTool(toolName, args, env) {
55
+ return new Promise((resolve, reject) => {
56
+ const proc = spawn("node", ["build/index.js"], {
57
+ stdio: ["pipe", "pipe", "pipe"],
58
+ env: {
59
+ ...process.env,
60
+ ...env,
61
+ USE_PIPELINE: "true",
62
+ },
63
+ });
64
+ let output = "";
65
+ let errorOutput = "";
66
+ proc.stdout?.on("data", (d) => (output += d));
67
+ proc.stderr?.on("data", (d) => (errorOutput += d));
68
+ proc.on("close", code => {
69
+ if (code !== 0) {
70
+ return reject(new Error(`Process exited with code ${code}: ${errorOutput}`));
71
+ }
72
+ const line = output.split("\n").find(l => l.startsWith("{"));
73
+ if (!line) {
74
+ return reject(new Error("No JSON output found"));
75
+ }
76
+ try {
77
+ const response = JSON.parse(line);
78
+ if (response.error) {
79
+ reject(response.error);
80
+ }
81
+ else {
82
+ const content = response.result?.content?.[0]?.text;
83
+ if (content) {
84
+ try {
85
+ resolve(JSON.parse(content));
86
+ }
87
+ catch {
88
+ resolve(content);
89
+ }
90
+ }
91
+ else {
92
+ resolve(response.result);
93
+ }
94
+ }
95
+ }
96
+ catch (e) {
97
+ reject(e);
98
+ }
99
+ });
100
+ proc.stdin?.end(JSON.stringify({
101
+ jsonrpc: "2.0",
102
+ id: 1,
103
+ method: "tools/call",
104
+ params: { name: toolName, arguments: args },
105
+ }) + "\n");
106
+ });
107
+ }
108
+ describe("vulnerability tools", () => {
109
+ let mockGitLab;
110
+ let mockGitLabUrl;
111
+ // Capture variables for verifying GraphQL payloads
112
+ let lastListVariables = null;
113
+ let lastDismissInput = null;
114
+ let lastConfirmInput = null;
115
+ let lastGetId = null;
116
+ const baseEnv = () => ({
117
+ GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
118
+ GITLAB_PERSONAL_ACCESS_TOKEN: MOCK_TOKEN,
119
+ GITLAB_TOOLSETS: "vulnerabilities",
120
+ });
121
+ before(async () => {
122
+ const mockPort = await findMockServerPort();
123
+ mockGitLab = new MockGitLabServer({
124
+ port: mockPort,
125
+ validTokens: [MOCK_TOKEN],
126
+ });
127
+ // All four tools go through POST /api/graphql; dispatch on operation name
128
+ mockGitLab.addRootHandler("post", "/api/graphql", (req, res) => {
129
+ const query = req.body.query || "";
130
+ const variables = req.body.variables || {};
131
+ if (query.includes("vulnerabilityDismiss")) {
132
+ lastDismissInput = variables.input;
133
+ res.json({
134
+ data: {
135
+ vulnerabilityDismiss: {
136
+ vulnerability: {
137
+ id: TEST_VULNERABILITY_GID,
138
+ state: "DISMISSED",
139
+ dismissedAt: "2024-06-10T12:00:00Z",
140
+ dismissalReason: variables.input?.dismissalReason || null,
141
+ },
142
+ errors: [],
143
+ },
144
+ },
145
+ });
146
+ return;
147
+ }
148
+ if (query.includes("vulnerabilityConfirm")) {
149
+ lastConfirmInput = variables.input;
150
+ res.json({
151
+ data: {
152
+ vulnerabilityConfirm: {
153
+ vulnerability: {
154
+ id: TEST_VULNERABILITY_GID,
155
+ state: "CONFIRMED",
156
+ confirmedAt: "2024-06-10T12:00:00Z",
157
+ },
158
+ errors: [],
159
+ },
160
+ },
161
+ });
162
+ return;
163
+ }
164
+ if (query.includes("listProjectVulnerabilities")) {
165
+ lastListVariables = variables;
166
+ let nodes = mockVulnerabilityList;
167
+ if (variables.state) {
168
+ nodes = nodes.filter(v => variables.state.includes(v.state));
169
+ }
170
+ if (variables.severity) {
171
+ nodes = nodes.filter(v => variables.severity.includes(v.severity));
172
+ }
173
+ if (variables.reportType) {
174
+ nodes = nodes.filter(v => variables.reportType.includes(v.reportType));
175
+ }
176
+ res.json({
177
+ data: {
178
+ project: {
179
+ vulnerabilities: {
180
+ nodes,
181
+ pageInfo: { endCursor: "cursor-abc", hasNextPage: false },
182
+ },
183
+ },
184
+ },
185
+ });
186
+ return;
187
+ }
188
+ if (query.includes("getVulnerability")) {
189
+ lastGetId = variables.id;
190
+ res.json({
191
+ data: {
192
+ vulnerability: {
193
+ ...mockVulnerability,
194
+ project: {
195
+ id: "gid://gitlab/Project/456",
196
+ name: "Test Project",
197
+ fullPath: TEST_PROJECT_FULL_PATH,
198
+ },
199
+ },
200
+ },
201
+ });
202
+ return;
203
+ }
204
+ res
205
+ .status(400)
206
+ .json({ errors: [{ message: `Unexpected GraphQL query: ${query.slice(0, 80)}` }] });
207
+ });
208
+ await mockGitLab.start();
209
+ mockGitLabUrl = mockGitLab.getUrl();
210
+ });
211
+ after(async () => {
212
+ await mockGitLab.stop();
213
+ });
214
+ test("list_project_vulnerabilities returns vulnerabilities with pageInfo", async () => {
215
+ const result = await callTool("list_project_vulnerabilities", { project_id: TEST_PROJECT_ID }, baseEnv());
216
+ assert.ok(Array.isArray(result.vulnerabilities), "Response should contain vulnerabilities array");
217
+ assert.strictEqual(result.vulnerabilities.length, 3, "Should return 3 vulnerabilities");
218
+ assert.strictEqual(result.vulnerabilities[0].id, TEST_VULNERABILITY_GID);
219
+ assert.strictEqual(result.vulnerabilities[0].title, "Hard-coded credential detected");
220
+ assert.ok(result.pageInfo, "Response should include pageInfo for cursor pagination");
221
+ assert.strictEqual(result.pageInfo.hasNextPage, false);
222
+ });
223
+ test("list_project_vulnerabilities resolves numeric project ID to full path", async () => {
224
+ lastListVariables = null;
225
+ await callTool("list_project_vulnerabilities", { project_id: TEST_PROJECT_ID }, baseEnv());
226
+ assert.ok(lastListVariables, "GraphQL variables should have been captured");
227
+ assert.strictEqual(lastListVariables.fullPath, TEST_PROJECT_FULL_PATH, "Numeric project ID should be resolved to the project full path");
228
+ });
229
+ test("list_project_vulnerabilities passes state filter as GraphQL enum", async () => {
230
+ lastListVariables = null;
231
+ const result = await callTool("list_project_vulnerabilities", { project_id: TEST_PROJECT_ID, state: "detected" }, baseEnv());
232
+ assert.ok(lastListVariables, "GraphQL variables should have been captured");
233
+ assert.deepStrictEqual(lastListVariables.state, ["DETECTED"], "state should be uppercased enum array");
234
+ assert.strictEqual(result.vulnerabilities.length, 1, "Mock should filter to only DETECTED");
235
+ });
236
+ test("list_project_vulnerabilities passes severity filter as GraphQL enum", async () => {
237
+ lastListVariables = null;
238
+ const result = await callTool("list_project_vulnerabilities", { project_id: TEST_PROJECT_ID, severity: "critical" }, baseEnv());
239
+ assert.ok(lastListVariables, "GraphQL variables should have been captured");
240
+ assert.deepStrictEqual(lastListVariables.severity, ["CRITICAL"]);
241
+ assert.strictEqual(result.vulnerabilities.length, 1, "Mock should filter to only CRITICAL");
242
+ });
243
+ test("list_project_vulnerabilities passes report_type filter as GraphQL enum", async () => {
244
+ lastListVariables = null;
245
+ const result = await callTool("list_project_vulnerabilities", { project_id: TEST_PROJECT_ID, report_type: "secret_detection" }, baseEnv());
246
+ assert.ok(lastListVariables, "GraphQL variables should have been captured");
247
+ assert.deepStrictEqual(lastListVariables.reportType, ["SECRET_DETECTION"]);
248
+ assert.strictEqual(result.vulnerabilities.length, 1, "Mock should filter to only SECRET_DETECTION");
249
+ });
250
+ test("list_project_vulnerabilities forwards cursor pagination", async () => {
251
+ lastListVariables = null;
252
+ await callTool("list_project_vulnerabilities", { project_id: TEST_PROJECT_ID, first: 50, after: "cursor-abc" }, baseEnv());
253
+ assert.ok(lastListVariables, "GraphQL variables should have been captured");
254
+ assert.strictEqual(lastListVariables.first, 50);
255
+ assert.strictEqual(lastListVariables.after, "cursor-abc");
256
+ });
257
+ test("get_vulnerability returns full vulnerability object via GID", async () => {
258
+ lastGetId = null;
259
+ const result = await callTool("get_vulnerability", { vulnerability_id: TEST_VULNERABILITY_ID }, baseEnv());
260
+ assert.strictEqual(lastGetId, TEST_VULNERABILITY_GID, "Numeric ID should be converted to a GraphQL global ID");
261
+ assert.strictEqual(result.id, TEST_VULNERABILITY_GID);
262
+ assert.strictEqual(result.title, "Hard-coded credential detected");
263
+ assert.strictEqual(result.description, "A hard-coded credential was found in source code");
264
+ assert.strictEqual(result.state, "DETECTED");
265
+ assert.strictEqual(result.severity, "CRITICAL");
266
+ assert.strictEqual(result.reportType, "SECRET_DETECTION");
267
+ assert.strictEqual(result.location.file, "config/secrets.yml");
268
+ assert.strictEqual(result.location.startLine, 42);
269
+ assert.strictEqual(result.identifiers[0].name, "CVE-2024-0001");
270
+ assert.strictEqual(result.links[0].url, "https://example.com/vuln/789");
271
+ assert.strictEqual(result.project.fullPath, TEST_PROJECT_FULL_PATH);
272
+ });
273
+ test("dismiss_vulnerability sends dismissalReason in mutation input", async () => {
274
+ lastDismissInput = null;
275
+ const result = await callTool("dismiss_vulnerability", { vulnerability_id: TEST_VULNERABILITY_ID, reason: "false_positive" }, baseEnv());
276
+ assert.ok(lastDismissInput, "Mutation input should have been captured");
277
+ assert.strictEqual(lastDismissInput.id, TEST_VULNERABILITY_GID);
278
+ assert.strictEqual(lastDismissInput.dismissalReason, "FALSE_POSITIVE", "Reason should be mapped to the GraphQL enum");
279
+ assert.strictEqual(result.state, "DISMISSED");
280
+ assert.strictEqual(result.dismissalReason, "FALSE_POSITIVE");
281
+ });
282
+ test("dismiss_vulnerability includes comment when provided", async () => {
283
+ lastDismissInput = null;
284
+ await callTool("dismiss_vulnerability", {
285
+ vulnerability_id: TEST_VULNERABILITY_ID,
286
+ reason: "acceptable_risk",
287
+ comment: "Reviewed by security team, risk accepted",
288
+ }, baseEnv());
289
+ assert.ok(lastDismissInput, "Mutation input should have been captured");
290
+ assert.strictEqual(lastDismissInput.dismissalReason, "ACCEPTABLE_RISK");
291
+ assert.strictEqual(lastDismissInput.comment, "Reviewed by security team, risk accepted");
292
+ });
293
+ test("dismiss_vulnerability accepts mitigating_control and not_applicable reasons", async () => {
294
+ lastDismissInput = null;
295
+ await callTool("dismiss_vulnerability", { vulnerability_id: TEST_VULNERABILITY_ID, reason: "mitigating_control" }, baseEnv());
296
+ assert.strictEqual(lastDismissInput.dismissalReason, "MITIGATING_CONTROL");
297
+ lastDismissInput = null;
298
+ await callTool("dismiss_vulnerability", { vulnerability_id: TEST_VULNERABILITY_ID, reason: "not_applicable" }, baseEnv());
299
+ assert.strictEqual(lastDismissInput.dismissalReason, "NOT_APPLICABLE");
300
+ });
301
+ test("confirm_vulnerability sends mutation with GID", async () => {
302
+ lastConfirmInput = null;
303
+ const result = await callTool("confirm_vulnerability", { vulnerability_id: TEST_VULNERABILITY_ID }, baseEnv());
304
+ assert.ok(lastConfirmInput, "Mutation input should have been captured");
305
+ assert.strictEqual(lastConfirmInput.id, TEST_VULNERABILITY_GID);
306
+ assert.strictEqual(result.state, "CONFIRMED");
307
+ assert.strictEqual(result.confirmedAt, "2024-06-10T12:00:00Z");
308
+ });
309
+ test("confirm_vulnerability includes comment when provided", async () => {
310
+ lastConfirmInput = null;
311
+ await callTool("confirm_vulnerability", {
312
+ vulnerability_id: TEST_VULNERABILITY_ID,
313
+ comment: "Confirmed after manual verification",
314
+ }, baseEnv());
315
+ assert.ok(lastConfirmInput, "Mutation input should have been captured");
316
+ assert.strictEqual(lastConfirmInput.comment, "Confirmed after manual verification");
317
+ });
318
+ // Read-only mode tests
319
+ test("read-only mode: list_project_vulnerabilities succeeds", async () => {
320
+ const result = await callTool("list_project_vulnerabilities", { project_id: TEST_PROJECT_ID }, { ...baseEnv(), GITLAB_PERMISSION_MODE: "readonly" });
321
+ assert.ok(Array.isArray(result.vulnerabilities), "Should return vulnerabilities in readonly mode");
322
+ assert.strictEqual(result.vulnerabilities.length, 3);
323
+ });
324
+ test("read-only mode: get_vulnerability succeeds", async () => {
325
+ const result = await callTool("get_vulnerability", { vulnerability_id: TEST_VULNERABILITY_ID }, { ...baseEnv(), GITLAB_PERMISSION_MODE: "readonly" });
326
+ assert.strictEqual(result.id, TEST_VULNERABILITY_GID);
327
+ assert.strictEqual(result.title, "Hard-coded credential detected");
328
+ });
329
+ test("read-only mode: dismiss_vulnerability is rejected", async () => {
330
+ await assert.rejects(() => callTool("dismiss_vulnerability", { vulnerability_id: TEST_VULNERABILITY_ID, reason: "false_positive" }, { ...baseEnv(), GITLAB_PERMISSION_MODE: "readonly" }), (err) => {
331
+ const msg = typeof err === "string" ? err : err?.message || JSON.stringify(err);
332
+ assert.ok(msg.toLowerCase().includes("not allowed") ||
333
+ msg.toLowerCase().includes("read-only") ||
334
+ msg.toLowerCase().includes("readonly") ||
335
+ msg.toLowerCase().includes("not available"), `Expected read-only rejection, got: ${msg}`);
336
+ return true;
337
+ });
338
+ });
339
+ test("read-only mode: confirm_vulnerability is rejected", async () => {
340
+ await assert.rejects(() => callTool("confirm_vulnerability", { vulnerability_id: TEST_VULNERABILITY_ID }, { ...baseEnv(), GITLAB_PERMISSION_MODE: "readonly" }), (err) => {
341
+ const msg = typeof err === "string" ? err : err?.message || JSON.stringify(err);
342
+ assert.ok(msg.toLowerCase().includes("not allowed") ||
343
+ msg.toLowerCase().includes("read-only") ||
344
+ msg.toLowerCase().includes("readonly") ||
345
+ msg.toLowerCase().includes("not available"), `Expected read-only rejection, got: ${msg}`);
346
+ return true;
347
+ });
348
+ });
349
+ // GITLAB_ALLOWED_PROJECT_IDS tests: the mock vulnerability belongs to
350
+ // project 456 (test-group/test-project), so an allowlist of "999" must
351
+ // deny all id-only vulnerability tools.
352
+ const assertAccessDenied = (err) => {
353
+ const msg = typeof err === "string" ? err : err?.message || JSON.stringify(err);
354
+ assert.ok(msg.includes("Access denied"), `Expected allowlist rejection, got: ${msg}`);
355
+ return true;
356
+ };
357
+ test("allowlist: get_vulnerability is rejected for a vulnerability outside allowed projects", async () => {
358
+ await assert.rejects(() => callTool("get_vulnerability", { vulnerability_id: TEST_VULNERABILITY_ID }, { ...baseEnv(), GITLAB_ALLOWED_PROJECT_IDS: "999" }), assertAccessDenied);
359
+ });
360
+ test("allowlist: get_vulnerability succeeds when project is allowed by numeric ID", async () => {
361
+ const result = await callTool("get_vulnerability", { vulnerability_id: TEST_VULNERABILITY_ID }, { ...baseEnv(), GITLAB_ALLOWED_PROJECT_IDS: TEST_PROJECT_ID });
362
+ assert.strictEqual(result.id, TEST_VULNERABILITY_GID);
363
+ });
364
+ test("allowlist: get_vulnerability succeeds when project is allowed by full path", async () => {
365
+ const result = await callTool("get_vulnerability", { vulnerability_id: TEST_VULNERABILITY_ID }, { ...baseEnv(), GITLAB_ALLOWED_PROJECT_IDS: `999,${TEST_PROJECT_FULL_PATH}` });
366
+ assert.strictEqual(result.id, TEST_VULNERABILITY_GID);
367
+ });
368
+ test("allowlist: dismiss_vulnerability is rejected before the mutation is sent", async () => {
369
+ lastDismissInput = null;
370
+ await assert.rejects(() => callTool("dismiss_vulnerability", { vulnerability_id: TEST_VULNERABILITY_ID, reason: "false_positive" }, { ...baseEnv(), GITLAB_ALLOWED_PROJECT_IDS: "999" }), assertAccessDenied);
371
+ assert.strictEqual(lastDismissInput, null, "vulnerabilityDismiss mutation must not be sent for a denied project");
372
+ });
373
+ test("allowlist: confirm_vulnerability is rejected before the mutation is sent", async () => {
374
+ lastConfirmInput = null;
375
+ await assert.rejects(() => callTool("confirm_vulnerability", { vulnerability_id: TEST_VULNERABILITY_ID }, { ...baseEnv(), GITLAB_ALLOWED_PROJECT_IDS: "999" }), assertAccessDenied);
376
+ assert.strictEqual(lastConfirmInput, null, "vulnerabilityConfirm mutation must not be sent for a denied project");
377
+ });
378
+ test("allowlist: dismiss_vulnerability succeeds when the vulnerability's project is allowed", async () => {
379
+ lastDismissInput = null;
380
+ const result = await callTool("dismiss_vulnerability", { vulnerability_id: TEST_VULNERABILITY_ID, reason: "false_positive" }, { ...baseEnv(), GITLAB_ALLOWED_PROJECT_IDS: TEST_PROJECT_ID });
381
+ assert.ok(lastDismissInput, "Mutation should be sent after the allowlist check passes");
382
+ assert.strictEqual(lastDismissInput.id, TEST_VULNERABILITY_GID);
383
+ assert.strictEqual(result.state, "DISMISSED");
384
+ });
385
+ // GID validation tests: only numeric IDs and Vulnerability GIDs are accepted
386
+ const assertInvalidVulnerabilityId = (err) => {
387
+ const msg = typeof err === "string" ? err : err?.message || JSON.stringify(err);
388
+ assert.ok(msg.includes("Invalid vulnerability ID"), `Expected invalid-ID rejection, got: ${msg}`);
389
+ return true;
390
+ };
391
+ test("gid validation: get_vulnerability rejects non-Vulnerability GIDs", async () => {
392
+ await assert.rejects(() => callTool("get_vulnerability", { vulnerability_id: "gid://gitlab/Project/456" }, baseEnv()), assertInvalidVulnerabilityId);
393
+ });
394
+ test("gid validation: dismiss_vulnerability rejects a non-numeric ID before any request", async () => {
395
+ lastDismissInput = null;
396
+ await assert.rejects(() => callTool("dismiss_vulnerability", { vulnerability_id: "not-a-vuln-id", reason: "false_positive" }, baseEnv()), assertInvalidVulnerabilityId);
397
+ assert.strictEqual(lastDismissInput, null, "vulnerabilityDismiss mutation must not be sent for an invalid ID");
398
+ });
399
+ });