@zereight/mcp-gitlab 2.1.62 → 2.1.64

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.
@@ -0,0 +1,145 @@
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 = "123";
7
+ const TEST_GROUP_ID = "my-group";
8
+ // Milestone tools live in the non-default "milestones" toolset
9
+ const TOOLSET_ENV = { GITLAB_TOOLSETS: "milestones" };
10
+ // Helper to run an MCP tool through the stdio server
11
+ async function callTool(toolName, args, env) {
12
+ return new Promise((resolve, reject) => {
13
+ const proc = spawn("node", ["build/index.js"], {
14
+ stdio: ["pipe", "pipe", "pipe"],
15
+ env: {
16
+ ...process.env,
17
+ ...TOOLSET_ENV,
18
+ ...env,
19
+ GITLAB_READ_ONLY_MODE: "true",
20
+ },
21
+ });
22
+ let output = "";
23
+ let errorOutput = "";
24
+ proc.stdout?.on("data", d => (output += d));
25
+ proc.stderr?.on("data", d => (errorOutput += d));
26
+ proc.on("close", code => {
27
+ if (code !== 0)
28
+ return reject(new Error(`Process exited with code ${code}: ${errorOutput}`));
29
+ const line = output.split("\n").find(l => l.startsWith("{"));
30
+ if (!line)
31
+ return reject(new Error("No JSON output found"));
32
+ try {
33
+ const response = JSON.parse(line);
34
+ if (response.error) {
35
+ reject(new Error(JSON.stringify(response.error)));
36
+ return;
37
+ }
38
+ const content = response.result?.content?.[0]?.text;
39
+ if (content) {
40
+ try {
41
+ resolve(JSON.parse(content));
42
+ }
43
+ catch {
44
+ reject(new Error(`Failed to parse tool output JSON: ${content}`));
45
+ }
46
+ }
47
+ else {
48
+ resolve(response.result);
49
+ }
50
+ }
51
+ catch (e) {
52
+ reject(e);
53
+ }
54
+ });
55
+ proc.stdin?.end(JSON.stringify({
56
+ jsonrpc: "2.0",
57
+ id: 1,
58
+ method: "tools/call",
59
+ params: { name: toolName, arguments: args },
60
+ }) + "\n");
61
+ });
62
+ }
63
+ describe("milestone list iids filters", () => {
64
+ let mockGitLab;
65
+ let mockGitLabUrl;
66
+ before(async () => {
67
+ const mockPort = await findMockServerPort();
68
+ mockGitLab = new MockGitLabServer({ port: mockPort, validTokens: [MOCK_TOKEN] });
69
+ await mockGitLab.start();
70
+ mockGitLabUrl = mockGitLab.getUrl();
71
+ });
72
+ after(async () => {
73
+ await mockGitLab.stop();
74
+ });
75
+ const env = () => ({
76
+ GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
77
+ GITLAB_PERSONAL_ACCESS_TOKEN: MOCK_TOKEN,
78
+ });
79
+ test("omits an empty iids filter for list_milestones", async () => {
80
+ let capturedUrl;
81
+ mockGitLab.addMockHandler("get", `/projects/${TEST_PROJECT_ID}/milestones`, (req, res) => {
82
+ capturedUrl = req.originalUrl;
83
+ res.json([]);
84
+ });
85
+ try {
86
+ const milestones = await callTool("list_milestones", { project_id: TEST_PROJECT_ID, iids: [] }, env());
87
+ assert.deepStrictEqual(milestones, []);
88
+ assert.ok(capturedUrl, "Mock handler should have received a request");
89
+ assert.strictEqual(new URL(capturedUrl, "http://localhost").search, "", "An empty iids array should not be serialized as `iids=`");
90
+ }
91
+ finally {
92
+ mockGitLab.clearCustomHandlers();
93
+ }
94
+ });
95
+ test("forwards non-empty iids in bracket-array form", async () => {
96
+ let capturedUrl;
97
+ mockGitLab.addMockHandler("get", `/projects/${TEST_PROJECT_ID}/milestones`, (req, res) => {
98
+ capturedUrl = req.originalUrl;
99
+ res.json([]);
100
+ });
101
+ try {
102
+ await callTool("list_milestones", { project_id: TEST_PROJECT_ID, iids: [1, 2] }, env());
103
+ assert.ok(capturedUrl, "Mock handler should have received a request");
104
+ const params = new URL(capturedUrl, "http://localhost").searchParams;
105
+ assert.deepStrictEqual(params.getAll("iids[]"), ["1", "2"]);
106
+ }
107
+ finally {
108
+ mockGitLab.clearCustomHandlers();
109
+ }
110
+ });
111
+ test("omits blank milestone filters", async () => {
112
+ let capturedUrl;
113
+ mockGitLab.addMockHandler("get", `/projects/${TEST_PROJECT_ID}/milestones`, (req, res) => {
114
+ capturedUrl = req.originalUrl;
115
+ res.json([]);
116
+ });
117
+ try {
118
+ await callTool("list_milestones", { project_id: TEST_PROJECT_ID, iids: [], title: " ", search: "" }, env());
119
+ assert.ok(capturedUrl, "Mock handler should have received a request");
120
+ assert.strictEqual(new URL(capturedUrl, "http://localhost").search, "", "Blank milestone filters should not be serialized");
121
+ }
122
+ finally {
123
+ mockGitLab.clearCustomHandlers();
124
+ }
125
+ });
126
+ test("omits an empty iids filter for list_group_milestones", async () => {
127
+ let capturedUrl;
128
+ mockGitLab.addMockHandler("get", `/groups/${TEST_GROUP_ID}/milestones`, (req, res) => {
129
+ capturedUrl = req.originalUrl;
130
+ res.json([]);
131
+ });
132
+ try {
133
+ const milestones = await callTool("list_group_milestones", { group_id: TEST_GROUP_ID, iids: [], state: "active" }, env());
134
+ assert.deepStrictEqual(milestones, []);
135
+ assert.ok(capturedUrl, "Mock handler should have received a request");
136
+ const params = new URL(capturedUrl, "http://localhost").searchParams;
137
+ assert.equal(params.has("iids"), false, "An empty iids array should not be serialized as `iids=`");
138
+ assert.deepStrictEqual(params.getAll("iids[]"), []);
139
+ assert.deepStrictEqual(params.getAll("state"), ["active"]);
140
+ }
141
+ finally {
142
+ mockGitLab.clearCustomHandlers();
143
+ }
144
+ });
145
+ });
@@ -16,7 +16,7 @@ const MOCK_PORT_BASE = 9200;
16
16
  const MCP_PORT_BASE = 3200;
17
17
  // Known tool counts per toolset (from TOOLSET_DEFINITIONS)
18
18
  const TOOLSET_TOOL_COUNTS = {
19
- merge_requests: 42,
19
+ merge_requests: 43,
20
20
  issues: 24,
21
21
  repositories: 7,
22
22
  branches: 15,
@@ -0,0 +1,384 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { describe, test } from "node:test";
6
+ import { createMaskingEngine, createMaskingPolicyResolver } from "../../masking/engine.js";
7
+ import { getManagedMaskingProjectIds } from "../../masking/project-scope.js";
8
+ import { allTools } from "../../tools/registry.js";
9
+ describe("response masking", () => {
10
+ test("is a no-op and does not read a config when disabled", () => {
11
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "gitlab-mask-"));
12
+ const engine = createMaskingEngine({
13
+ enabled: false,
14
+ workspaceDir: workspace,
15
+ configPath: "missing.json",
16
+ });
17
+ assert.equal(engine, undefined);
18
+ });
19
+ test("applies built-in rules and literal keyword rules", () => {
20
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "gitlab-mask-"));
21
+ fs.writeFileSync(path.join(workspace, ".gitlab-mcp-mask.json"), JSON.stringify({
22
+ version: 1,
23
+ builtins: { ipv4: { replacement: "[Address]" } },
24
+ rules: [
25
+ {
26
+ id: "company",
27
+ type: "keyword",
28
+ match: "Example Corp",
29
+ replacement: "Our organization",
30
+ },
31
+ { id: "token", type: "regex", pattern: "TOKEN-[0-9]+", replacement: "[Token]" },
32
+ ],
33
+ }));
34
+ const engine = createMaskingEngine({ enabled: true, workspaceDir: workspace });
35
+ assert.ok(engine);
36
+ assert.equal(engine.maskText("Example Corp 10.20.30.40 TOKEN-123"), "Our organization [Address] [Token]");
37
+ });
38
+ test("masks nested tool text without recursively masking replacements", () => {
39
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "gitlab-mask-"));
40
+ fs.writeFileSync(path.join(workspace, "rules.json"), JSON.stringify({
41
+ version: 1,
42
+ rules: [
43
+ { id: "a", type: "keyword", match: "Example Corp", replacement: "Customer Corp" },
44
+ {
45
+ id: "b",
46
+ type: "keyword",
47
+ match: "Customer Corp",
48
+ replacement: "Customer organization",
49
+ },
50
+ ],
51
+ }));
52
+ const engine = createMaskingEngine({
53
+ enabled: true,
54
+ workspaceDir: workspace,
55
+ configPath: "rules.json",
56
+ });
57
+ assert.ok(engine);
58
+ const result = engine.maskToolResult({
59
+ content: [{ type: "text", text: JSON.stringify({ description: "Example Corp" }) }],
60
+ structuredContent: { nested: "Example Corp" },
61
+ });
62
+ assert.equal(result.content[0].text, '{"description":"Customer Corp"}');
63
+ assert.deepEqual(result.structuredContent, { nested: "Customer Corp" });
64
+ });
65
+ test("masks plain text blocks and returned error messages", () => {
66
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "gitlab-mask-"));
67
+ const engine = createMaskingEngine({ enabled: true, workspaceDir: workspace });
68
+ assert.ok(engine);
69
+ const result = engine.maskToolResult({
70
+ content: [{ type: "text", text: "Connect to 10.20.30.40 with glpat-abcdefghijklmnopqrst" }],
71
+ });
72
+ assert.equal(result.content[0].text, "Connect to [IP address] with [Token masked]");
73
+ const error = engine.maskError(new Error("Failed at 10.20.30.40"));
74
+ assert.equal(error instanceof Error && error.message, "Failed at [IP address]");
75
+ });
76
+ test("masks every documented GitLab token prefix", () => {
77
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "gitlab-mask-"));
78
+ const engine = createMaskingEngine({ enabled: true, workspaceDir: workspace });
79
+ assert.ok(engine);
80
+ const suffix = "abcdefghijklmnopqrst";
81
+ const prefixes = [
82
+ "glpat",
83
+ "glrt",
84
+ "glptt",
85
+ "gldt",
86
+ "glcbt",
87
+ "glsoat",
88
+ "gloas",
89
+ "glagent",
90
+ "glft",
91
+ "glimt",
92
+ ];
93
+ assert.equal(engine.maskText(prefixes.map(prefix => `${prefix}-${suffix}`).join(" ")), prefixes.map(() => "[Token masked]").join(" "));
94
+ });
95
+ test("covers the full union of overlapping secrets without merging adjacent matches", t => {
96
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "gitlab-mask-"));
97
+ const configPath = path.join(workspace, "rules.json");
98
+ t.after(() => {
99
+ fs.unlinkSync(configPath);
100
+ fs.rmdirSync(workspace);
101
+ });
102
+ fs.writeFileSync(configPath, JSON.stringify({
103
+ rules: [
104
+ { id: "label", type: "keyword", match: "token=glpat-", replacement: "[label]" },
105
+ { id: "first", type: "keyword", match: "abc", replacement: "[first]" },
106
+ { id: "second", type: "keyword", match: "cde", replacement: "[second]" },
107
+ { id: "third", type: "keyword", match: "efg", replacement: "[third]" },
108
+ ],
109
+ }));
110
+ const engine = createMaskingEngine({ enabled: true, configPath });
111
+ assert.ok(engine);
112
+ assert.equal(engine.maskText("token=glpat-ABCDEFGHIJKLMNOPQRST"), "[label]");
113
+ assert.equal(engine.maskText("abcdefg"), "[first]");
114
+ assert.equal(engine.maskText("abccde"), "[first][second]");
115
+ });
116
+ test("preserves plain text primitives and applies numeric keyword rules", t => {
117
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "gitlab-mask-"));
118
+ const configPath = path.join(workspace, "rules.json");
119
+ t.after(() => {
120
+ fs.unlinkSync(configPath);
121
+ fs.rmdirSync(workspace);
122
+ });
123
+ fs.writeFileSync(configPath, JSON.stringify({
124
+ rules: [{ id: "number", type: "keyword", match: "123456", replacement: "[number]" }],
125
+ }));
126
+ const engine = createMaskingEngine({ enabled: true, configPath });
127
+ assert.ok(engine);
128
+ const texts = ["9007199254740993\n", "123456\n", "true\n", '"ordinary text"\n'];
129
+ const result = engine.maskToolResult({ content: texts.map(text => ({ type: "text", text })) });
130
+ assert.deepEqual(result.content.map(block => block.text), ["9007199254740993\n", "[number]\n", "true\n", '"ordinary text"\n']);
131
+ assert.equal(engine.maskToolResult({
132
+ content: [{ type: "text", text: '{"123456":9007199254740993}\n' }],
133
+ }, { textFormat: "plain" }).content[0].text, '{"[number]":9007199254740993}\n');
134
+ });
135
+ test("preserves JSON numbers and formatting while masking escaped string values", t => {
136
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "gitlab-mask-"));
137
+ t.after(() => fs.rmdirSync(workspace));
138
+ const engine = createMaskingEngine({ enabled: true, workspaceDir: workspace });
139
+ assert.ok(engine);
140
+ const text = '{\n "id": 9007199254740993, "host": "10.20.30.\\u0034\\u0030",\n' +
141
+ ' "download_url": "http://10.20.30.40/file", "nested": ["10.20.30.40"]\n}\n';
142
+ assert.equal(engine.maskToolResult({ content: [{ type: "text", text }] }).content[0].text, '{\n "id": 9007199254740993, "host": "[IP address]",\n' +
143
+ ' "download_url": "[Download URL masked]", "nested": ["[IP address]"]\n}\n');
144
+ const unchanged = '{ "id": 9007199254740993, "value": "ordinary" }\n';
145
+ assert.equal(engine.maskToolResult({ content: [{ type: "text", text: unchanged }] }).content[0].text, unchanged);
146
+ });
147
+ test("masks compressed IPv6 addresses", () => {
148
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "gitlab-mask-"));
149
+ const engine = createMaskingEngine({ enabled: true, workspaceDir: workspace });
150
+ assert.ok(engine);
151
+ assert.equal(engine.maskText("Hosts: 2001:db8::1, fe80::1234, ::1, and 2001:db8:0:0:0:0:0:1"), "Hosts: [IP address], [IP address], [IP address], and [IP address]");
152
+ assert.equal(engine.maskText("Version 1:2:3 is not an IPv6 address"), "Version 1:2:3 is not an IPv6 address");
153
+ });
154
+ test("rejects invalid and empty-match regex rules", () => {
155
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "gitlab-mask-"));
156
+ const configPath = path.join(workspace, "bad.json");
157
+ fs.writeFileSync(configPath, JSON.stringify({ rules: [{ id: "bad", type: "regex", pattern: "", replacement: "x" }] }));
158
+ assert.throws(() => createMaskingEngine({ enabled: true, workspaceDir: workspace, configPath: "bad.json" }), /must not be empty/);
159
+ });
160
+ test("fails closed when an explicitly configured file is missing", () => {
161
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "gitlab-mask-"));
162
+ assert.throws(() => createMaskingEngine({ enabled: true, workspaceDir: workspace, configPath: "missing.json" }), /Configured masking config does not exist/);
163
+ assert.throws(() => createMaskingPolicyResolver({
164
+ enabled: true,
165
+ workspaceDir: workspace,
166
+ configPath: "missing.json",
167
+ }), /Configured masking config does not exist/);
168
+ });
169
+ test("selects a server-owned policy by normalized GitLab instance and project", () => {
170
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "gitlab-mask-"));
171
+ const policyPath = path.join(workspace, "managed-policies.json");
172
+ fs.writeFileSync(policyPath, JSON.stringify({
173
+ version: 1,
174
+ policyGroups: {
175
+ customer: {
176
+ rules: [
177
+ {
178
+ id: "customer",
179
+ type: "keyword",
180
+ match: "Customer Corp",
181
+ replacement: "[customer]",
182
+ },
183
+ ],
184
+ },
185
+ },
186
+ bindings: [
187
+ {
188
+ gitlabInstance: "https://gitlab.example.test",
189
+ projectIds: [12, 13],
190
+ policyGroup: "customer",
191
+ },
192
+ ],
193
+ }));
194
+ const resolver = createMaskingPolicyResolver({
195
+ enabled: true,
196
+ workspaceDir: workspace,
197
+ policyFilePath: "managed-policies.json",
198
+ });
199
+ assert.ok(resolver);
200
+ assert.equal(resolver
201
+ .select({ gitlabInstance: "https://gitlab.example.test/api/v4", projectIds: ["12"] })
202
+ .maskText("Customer Corp"), "[customer]");
203
+ assert.throws(() => resolver.select({
204
+ gitlabInstance: "https://another.example.test/api/v4",
205
+ projectIds: [12],
206
+ }), /No managed masking policy/);
207
+ assert.throws(() => resolver.select({ gitlabInstance: "https://gitlab.example.test", projectIds: [14] }), /No managed masking policy/);
208
+ assert.throws(() => resolver.select({ gitlabInstance: "https://gitlab.example.test", hasProjectScope: false }), /project-less tool/);
209
+ });
210
+ test("rejects a workspace group that conflicts with the server binding", () => {
211
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "gitlab-mask-"));
212
+ fs.writeFileSync(path.join(workspace, ".gitlab-mcp-mask.json"), JSON.stringify({ version: 2, mode: "managed", policyGroup: "one" }));
213
+ fs.writeFileSync(path.join(workspace, "managed-policies.json"), JSON.stringify({
214
+ version: 1,
215
+ policyGroups: { one: {}, two: {} },
216
+ bindings: [
217
+ { gitlabInstance: "https://gitlab.example.test", projectIds: [12], policyGroup: "two" },
218
+ ],
219
+ }));
220
+ const resolver = createMaskingPolicyResolver({
221
+ enabled: true,
222
+ workspaceDir: workspace,
223
+ policyFilePath: "managed-policies.json",
224
+ });
225
+ assert.ok(resolver);
226
+ assert.throws(() => resolver.select({ gitlabInstance: "https://gitlab.example.test", projectIds: [12] }), /does not match/);
227
+ });
228
+ test("rejects project paths and calls spanning managed policy groups", () => {
229
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "gitlab-mask-"));
230
+ const policyPath = path.join(workspace, "managed-policies.json");
231
+ fs.writeFileSync(policyPath, JSON.stringify({
232
+ version: 1,
233
+ policyGroups: { one: {}, two: {} },
234
+ bindings: [
235
+ { gitlabInstance: "https://gitlab.example.test", projectIds: [12], policyGroup: "one" },
236
+ { gitlabInstance: "https://gitlab.example.test", projectIds: [13], policyGroup: "two" },
237
+ ],
238
+ }));
239
+ const resolver = createMaskingPolicyResolver({
240
+ enabled: true,
241
+ workspaceDir: workspace,
242
+ policyFilePath: "managed-policies.json",
243
+ });
244
+ assert.ok(resolver);
245
+ assert.throws(() => resolver.select({
246
+ gitlabInstance: "https://gitlab.example.test",
247
+ projectIds: ["group/project"],
248
+ }), /numeric project IDs/);
249
+ assert.throws(() => resolver.select({ gitlabInstance: "https://gitlab.example.test", projectIds: [12, 13] }), /span policy groups/);
250
+ });
251
+ test("derives managed scope only from project fields declared by the tool", () => {
252
+ const globalTool = { properties: { search: { type: "string" } } };
253
+ assert.deepEqual(getManagedMaskingProjectIds(globalTool, { project_id: "12", search: "example" }), { hasProjectScope: false, projectIds: [] });
254
+ const projectTool = {
255
+ properties: { project_id: { type: "string" }, target_project_id: { type: "string" } },
256
+ };
257
+ assert.deepEqual(getManagedMaskingProjectIds(projectTool, { project_id: "12", target_project_id: "13" }), { hasProjectScope: true, projectIds: ["12", "13"] });
258
+ assert.deepEqual(getManagedMaskingProjectIds(projectTool, {}, () => "12"), { hasProjectScope: true, projectIds: ["12"] });
259
+ });
260
+ test("includes the default primary project alongside explicit and nested references", () => {
261
+ const createMergeRequest = allTools.find(tool => tool.name === "create_merge_request");
262
+ const updateWorkItem = allTools.find(tool => tool.name === "update_work_item");
263
+ assert.ok(createMergeRequest);
264
+ assert.ok(updateWorkItem);
265
+ assert.deepEqual(getManagedMaskingProjectIds(createMergeRequest.inputSchema, {
266
+ project_id: "",
267
+ target_project_id: "13",
268
+ }, () => "12"), { hasProjectScope: true, projectIds: ["12", "13"] });
269
+ assert.deepEqual(getManagedMaskingProjectIds(updateWorkItem.inputSchema, {
270
+ project_id: "",
271
+ children_to_add: [{ project_id: "13", iid: 1 }],
272
+ }, () => "12"), { hasProjectScope: true, projectIds: ["12", "13"] });
273
+ });
274
+ test("treats absent optional filters as unscoped and absent required projects as scoped", () => {
275
+ for (const name of ["list_issues", "list_merge_requests", "list_todos"]) {
276
+ const tool = allTools.find(tool => tool.name === name);
277
+ assert.ok(tool, name);
278
+ assert.deepEqual(getManagedMaskingProjectIds(tool.inputSchema, {}), {
279
+ hasProjectScope: false,
280
+ projectIds: [],
281
+ });
282
+ }
283
+ const getIssue = allTools.find(tool => tool.name === "get_issue");
284
+ assert.ok(getIssue);
285
+ assert.deepEqual(getManagedMaskingProjectIds(getIssue.inputSchema, {}), {
286
+ hasProjectScope: true,
287
+ projectIds: [],
288
+ });
289
+ const groupMergeRequests = allTools.find(tool => tool.name === "list_group_merge_requests");
290
+ assert.ok(groupMergeRequests);
291
+ assert.deepEqual(getManagedMaskingProjectIds(groupMergeRequests.inputSchema, {
292
+ group_id: "99",
293
+ source_project_id: "12",
294
+ }, () => "12"), { hasProjectScope: false, projectIds: [] });
295
+ });
296
+ test("does not use a default project for a selected group scope", () => {
297
+ const webhookTool = {
298
+ properties: {
299
+ project_id: { type: "string" },
300
+ group_id: { type: "string" },
301
+ },
302
+ };
303
+ assert.deepEqual(getManagedMaskingProjectIds(webhookTool, { group_id: "99" }, () => "12"), { hasProjectScope: false, projectIds: [] });
304
+ });
305
+ test("collects nested declared project references", () => {
306
+ const workItemTool = {
307
+ properties: {
308
+ project_id: { type: "string" },
309
+ children_to_add: {
310
+ type: "array",
311
+ items: {
312
+ type: "object",
313
+ properties: { project_id: { type: "string" }, iid: { type: "number" } },
314
+ },
315
+ },
316
+ linked_items_to_remove: {
317
+ type: "array",
318
+ items: {
319
+ type: "object",
320
+ properties: { project_id: { type: "string" }, iid: { type: "number" } },
321
+ },
322
+ },
323
+ },
324
+ };
325
+ assert.deepEqual(getManagedMaskingProjectIds(workItemTool, {
326
+ project_id: "12",
327
+ children_to_add: [{ project_id: "13", iid: 1 }],
328
+ linked_items_to_remove: [{ project_id: "14", iid: 2 }],
329
+ }), { hasProjectScope: true, projectIds: ["12", "13", "14"] });
330
+ });
331
+ test("uses the registered work item schema to reject cross-project actions", () => {
332
+ const updateWorkItem = allTools.find(tool => tool.name === "update_work_item");
333
+ assert.ok(updateWorkItem);
334
+ assert.deepEqual(getManagedMaskingProjectIds(updateWorkItem.inputSchema, {
335
+ project_id: "12",
336
+ children_to_add: [{ project_id: "13", iid: 1 }],
337
+ linked_items_to_add: [{ project_id: "14", iid: 2 }],
338
+ }), { hasProjectScope: true, projectIds: ["12", "13", "14"] });
339
+ });
340
+ test("uses the registered webhook schema without selecting a default project for a group", () => {
341
+ const listWebhooks = allTools.find(tool => tool.name === "list_webhooks");
342
+ assert.ok(listWebhooks);
343
+ assert.deepEqual(getManagedMaskingProjectIds(listWebhooks.inputSchema, { group_id: "99" }, () => "12"), { hasProjectScope: false, projectIds: [] });
344
+ });
345
+ test("allows project-less tools only with the explicit built-in fallback", () => {
346
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "gitlab-mask-"));
347
+ const policyPath = path.join(workspace, "managed-policies.json");
348
+ fs.writeFileSync(policyPath, JSON.stringify({
349
+ version: 1,
350
+ policyGroups: {},
351
+ bindings: [],
352
+ unboundProjectBehavior: "builtin",
353
+ }));
354
+ const resolver = createMaskingPolicyResolver({
355
+ enabled: true,
356
+ workspaceDir: workspace,
357
+ policyFilePath: "managed-policies.json",
358
+ });
359
+ assert.ok(resolver);
360
+ assert.equal(resolver
361
+ .select({ gitlabInstance: "https://gitlab.example.test", hasProjectScope: false })
362
+ .maskText("10.20.30.40"), "[IP address]");
363
+ assert.throws(() => resolver.select({ gitlabInstance: "https://gitlab.example.test", hasProjectScope: true }), /requires a project ID/);
364
+ });
365
+ test("allows only explicitly designated unscoped tools to use built-in masking", () => {
366
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "gitlab-mask-"));
367
+ const policyPath = path.join(workspace, "managed-policies.json");
368
+ fs.writeFileSync(policyPath, JSON.stringify({ version: 1, policyGroups: {}, bindings: [] }));
369
+ const resolver = createMaskingPolicyResolver({
370
+ enabled: true,
371
+ workspaceDir: workspace,
372
+ policyFilePath: "managed-policies.json",
373
+ });
374
+ assert.ok(resolver);
375
+ assert.equal(resolver
376
+ .select({
377
+ gitlabInstance: "https://gitlab.example.test",
378
+ hasProjectScope: false,
379
+ allowBuiltinForUnscoped: true,
380
+ })
381
+ .maskText("10.20.30.40"), "[IP address]");
382
+ assert.throws(() => resolver.select({ gitlabInstance: "https://gitlab.example.test", hasProjectScope: false }), /project-less tool/);
383
+ });
384
+ });
@@ -1,6 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { describe, test } from "node:test";
3
- import { cleanMutuallyExclusiveIdUsernameOptions, LIST_MERGE_REQUESTS_ID_USERNAME_PAIRS, sanitizeToolArguments, } from "../../utils/tool-args.js";
3
+ import { appendFilterParam, appendFilterParams, cleanMutuallyExclusiveIdUsernameOptions, dropBlankArrayEntries, isBlankFilterValue, LIST_MERGE_REQUESTS_ID_USERNAME_PAIRS, sanitizeToolArguments, } from "../../utils/tool-args.js";
4
4
  describe("When sanitizeToolArguments runs", () => {
5
5
  describe("with top-level null optionals", () => {
6
6
  test("should omit null and undefined keys for generic tools", () => {
@@ -120,3 +120,59 @@ describe("When cleanMutuallyExclusiveIdUsernameOptions runs", () => {
120
120
  });
121
121
  });
122
122
  });
123
+ describe("When dropBlankArrayEntries runs", () => {
124
+ test("should drop blank string entries and keep meaningful ones", () => {
125
+ assert.deepEqual(dropBlankArrayEntries(["", " ", "bug"]), ["bug"]);
126
+ assert.deepEqual(dropBlankArrayEntries(["\t", "alice", ""]), ["alice"]);
127
+ });
128
+ test("should leave non-array values untouched", () => {
129
+ assert.equal(dropBlankArrayEntries("bug"), "bug");
130
+ assert.equal(dropBlankArrayEntries(" "), " ");
131
+ assert.equal(dropBlankArrayEntries(undefined), undefined);
132
+ assert.equal(dropBlankArrayEntries(false), false);
133
+ });
134
+ test("should keep non-string array entries", () => {
135
+ assert.deepEqual(dropBlankArrayEntries([0, "bug", false]), [0, "bug", false]);
136
+ });
137
+ });
138
+ describe("When isBlankFilterValue runs", () => {
139
+ test("should treat undefined, blank strings and empty arrays as blank", () => {
140
+ assert.equal(isBlankFilterValue(undefined), true);
141
+ assert.equal(isBlankFilterValue(""), true);
142
+ assert.equal(isBlankFilterValue(" \t\n"), true);
143
+ assert.equal(isBlankFilterValue([]), true);
144
+ });
145
+ test("should keep meaningful values, including false and zero", () => {
146
+ assert.equal(isBlankFilterValue("bug"), false);
147
+ assert.equal(isBlankFilterValue(["bug"]), false);
148
+ assert.equal(isBlankFilterValue(0), false);
149
+ assert.equal(isBlankFilterValue(false), false);
150
+ });
151
+ });
152
+ describe("When appendFilterParams runs", () => {
153
+ test("should omit blank scalars, blank array entries and empty arrays", () => {
154
+ const searchParams = new URLSearchParams();
155
+ appendFilterParams(searchParams, {
156
+ search: "",
157
+ ref: " ",
158
+ labels: ["", "bug"],
159
+ iids: [],
160
+ omitted: undefined,
161
+ });
162
+ assert.deepEqual([...searchParams.entries()], [["labels", "bug"]]);
163
+ });
164
+ test("should keep booleans, zero and non-blank values", () => {
165
+ const searchParams = new URLSearchParams();
166
+ appendFilterParams(searchParams, { with_labels_details: false, page: 0, search: "bug" });
167
+ assert.deepEqual([...searchParams.entries()], [
168
+ ["with_labels_details", "false"],
169
+ ["page", "0"],
170
+ ["search", "bug"],
171
+ ]);
172
+ });
173
+ test("should append a single parameter without dropping a meaningful value", () => {
174
+ const searchParams = new URLSearchParams();
175
+ appendFilterParam(searchParams, "filter[environment_scope]", "production");
176
+ assert.deepEqual([...searchParams.entries()], [["filter[environment_scope]", "production"]]);
177
+ });
178
+ });