@zereight/mcp-gitlab 2.1.50 → 2.1.52
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/README.ko.md +34 -10
- package/README.md +34 -10
- package/README.zh-CN.md +35 -10
- package/build/auth-cli.js +95 -0
- package/build/cli-command.js +33 -0
- package/build/index.js +40 -20
- package/build/oauth-device-flow.js +158 -0
- package/build/oauth.js +20 -0
- package/build/schemas.js +53 -10
- package/build/scripts/generate-tool-docs.js +1 -1
- package/build/test/create-commit-actions.test.js +102 -0
- package/build/test/gitlab-artifact-entry-schema.test.js +44 -0
- package/build/test/oauth-device-flow-tests.js +440 -0
- package/build/test/schema-tests.js +117 -3
- package/build/test/test-job-artifacts.js +35 -1
- package/build/test/test-permission-mode.js +28 -0
- package/build/tools/tool-descriptions.js +2 -2
- package/build/utils/gitlab-commit-actions.js +42 -0
- package/package.json +4 -3
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { describe, it } from "node:test";
|
|
3
|
+
import * as fs from "node:fs";
|
|
4
|
+
import * as os from "node:os";
|
|
5
|
+
import * as path from "node:path";
|
|
6
|
+
import { getPositionalCliCommand } from "../cli-command.js";
|
|
7
|
+
import { gitlabOriginFromApiUrl, runAuthCommandAsync } from "../auth-cli.js";
|
|
8
|
+
import { runDeviceAuthorizationGrantAsync } from "../oauth-device-flow.js";
|
|
9
|
+
import { GitLabOAuth } from "../oauth.js";
|
|
10
|
+
const GITLAB_URL = "https://gitlab.example";
|
|
11
|
+
const CLIENT_ID = "test-client-id";
|
|
12
|
+
const DEVICE_CODE = "device-code-not-for-stdout";
|
|
13
|
+
const USER_CODE = "0A44L90H";
|
|
14
|
+
const ACCESS_TOKEN = "oauth-device-flow-access-token";
|
|
15
|
+
const REFRESH_TOKEN = "refresh-token-device-flow";
|
|
16
|
+
function requestUrl(input) {
|
|
17
|
+
if (typeof input === "string") {
|
|
18
|
+
return input;
|
|
19
|
+
}
|
|
20
|
+
if (input instanceof URL) {
|
|
21
|
+
return input.href;
|
|
22
|
+
}
|
|
23
|
+
return input.url;
|
|
24
|
+
}
|
|
25
|
+
function jsonResponse(status, body) {
|
|
26
|
+
return new Response(JSON.stringify(body), {
|
|
27
|
+
status,
|
|
28
|
+
headers: { "Content-Type": "application/json" },
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
function createFetchStub(plan, capture) {
|
|
32
|
+
const remainingTokens = [...plan.tokens];
|
|
33
|
+
return async (input, init) => {
|
|
34
|
+
const url = requestUrl(input);
|
|
35
|
+
if (url.includes("/oauth/authorize_device")) {
|
|
36
|
+
if (typeof init?.body === "string") {
|
|
37
|
+
capture?.authorizeBodies.push(init.body);
|
|
38
|
+
}
|
|
39
|
+
return jsonResponse(plan.authorize.status, plan.authorize.body);
|
|
40
|
+
}
|
|
41
|
+
if (url.includes("/oauth/token")) {
|
|
42
|
+
const next = remainingTokens.shift();
|
|
43
|
+
if (!next) {
|
|
44
|
+
throw new Error(`Unexpected token poll: ${url}`);
|
|
45
|
+
}
|
|
46
|
+
return jsonResponse(next.status, next.body);
|
|
47
|
+
}
|
|
48
|
+
throw new Error(`Unexpected fetch URL: ${url}`);
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function deviceAuthorizationBody(interval = 5) {
|
|
52
|
+
return {
|
|
53
|
+
device_code: DEVICE_CODE,
|
|
54
|
+
user_code: USER_CODE,
|
|
55
|
+
verification_uri: `${GITLAB_URL}/oauth/device`,
|
|
56
|
+
verification_uri_complete: `${GITLAB_URL}/oauth/device?user_code=${USER_CODE}`,
|
|
57
|
+
expires_in: 300,
|
|
58
|
+
interval,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function successTokenBody() {
|
|
62
|
+
return {
|
|
63
|
+
access_token: ACCESS_TOKEN,
|
|
64
|
+
refresh_token: REFRESH_TOKEN,
|
|
65
|
+
expires_in: 7200,
|
|
66
|
+
token_type: "Bearer",
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function pendingBody() {
|
|
70
|
+
return { error: "authorization_pending" };
|
|
71
|
+
}
|
|
72
|
+
function createTempTokenPath() {
|
|
73
|
+
return path.join(os.tmpdir(), `gitlab-mcp-device-flow-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.json`);
|
|
74
|
+
}
|
|
75
|
+
function createOauthClient(tokenStoragePath) {
|
|
76
|
+
return new GitLabOAuth({
|
|
77
|
+
clientId: CLIENT_ID,
|
|
78
|
+
redirectUri: "http://127.0.0.1:8888/callback",
|
|
79
|
+
gitlabUrl: GITLAB_URL,
|
|
80
|
+
scopes: ["api"],
|
|
81
|
+
tokenStoragePath,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
function createAuthorizeCapture() {
|
|
85
|
+
return { authorizeBodies: [] };
|
|
86
|
+
}
|
|
87
|
+
function capturedAuthorizeScope(bodies) {
|
|
88
|
+
if (bodies.length !== 1) {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
const [body] = bodies;
|
|
92
|
+
if (body === undefined) {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
return new URLSearchParams(body).get("scope");
|
|
96
|
+
}
|
|
97
|
+
async function runAuthCapturingScopeAsync(input) {
|
|
98
|
+
const tokenPath = createTempTokenPath();
|
|
99
|
+
const capture = createAuthorizeCapture();
|
|
100
|
+
const fetchImpl = createFetchStub({
|
|
101
|
+
authorize: { status: 200, body: deviceAuthorizationBody() },
|
|
102
|
+
tokens: [{ status: 200, body: successTokenBody() }],
|
|
103
|
+
}, capture);
|
|
104
|
+
try {
|
|
105
|
+
await runAuthCommandAsync({
|
|
106
|
+
argv: [
|
|
107
|
+
"node",
|
|
108
|
+
"index.js",
|
|
109
|
+
"auth",
|
|
110
|
+
`--client-id=${CLIENT_ID}`,
|
|
111
|
+
`--api-url=${GITLAB_URL}`,
|
|
112
|
+
`--token-path=${tokenPath}`,
|
|
113
|
+
...(input.extraArgv ?? []),
|
|
114
|
+
],
|
|
115
|
+
env: input.env ?? {},
|
|
116
|
+
stdout: createStdoutBuffer().stdout,
|
|
117
|
+
fetchImpl,
|
|
118
|
+
sleepAsync: async () => { },
|
|
119
|
+
});
|
|
120
|
+
return capturedAuthorizeScope(capture.authorizeBodies);
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
if (fs.existsSync(tokenPath)) {
|
|
124
|
+
fs.unlinkSync(tokenPath);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function createStdoutBuffer() {
|
|
129
|
+
const chunks = [];
|
|
130
|
+
return {
|
|
131
|
+
stdout: {
|
|
132
|
+
write(chunk) {
|
|
133
|
+
chunks.push(chunk);
|
|
134
|
+
return true;
|
|
135
|
+
},
|
|
136
|
+
},
|
|
137
|
+
text: () => chunks.join(""),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
function createSleepRecorder() {
|
|
141
|
+
const delays = [];
|
|
142
|
+
return {
|
|
143
|
+
delays,
|
|
144
|
+
async sleepAsync(ms) {
|
|
145
|
+
delays.push(ms);
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
function readStoredToken(value) {
|
|
150
|
+
if (typeof value !== "object" || value === null) {
|
|
151
|
+
throw new Error("token file is not an object");
|
|
152
|
+
}
|
|
153
|
+
const accessToken = Reflect.get(value, "access_token");
|
|
154
|
+
const refreshToken = Reflect.get(value, "refresh_token");
|
|
155
|
+
const expiresIn = Reflect.get(value, "expires_in");
|
|
156
|
+
const createdAt = Reflect.get(value, "created_at");
|
|
157
|
+
const tokenType = Reflect.get(value, "token_type");
|
|
158
|
+
if (typeof accessToken !== "string") {
|
|
159
|
+
throw new Error("access_token missing");
|
|
160
|
+
}
|
|
161
|
+
if (typeof createdAt !== "number") {
|
|
162
|
+
throw new Error("created_at missing");
|
|
163
|
+
}
|
|
164
|
+
if (typeof tokenType !== "string") {
|
|
165
|
+
throw new Error("token_type missing");
|
|
166
|
+
}
|
|
167
|
+
return {
|
|
168
|
+
access_token: accessToken,
|
|
169
|
+
refresh_token: typeof refreshToken === "string" ? refreshToken : undefined,
|
|
170
|
+
expires_in: typeof expiresIn === "number" ? expiresIn : undefined,
|
|
171
|
+
created_at: createdAt,
|
|
172
|
+
token_type: tokenType,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
describe("When reading the CLI command", () => {
|
|
176
|
+
describe("with auth as the first positional argument", () => {
|
|
177
|
+
it("should return auth", () => {
|
|
178
|
+
assert.equal(getPositionalCliCommand(["node", "index.js", "auth"]), "auth");
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
describe("with only --token", () => {
|
|
182
|
+
it("should return undefined so MCP startup stays unchanged", () => {
|
|
183
|
+
assert.equal(getPositionalCliCommand(["node", "index.js", "--token=glpat-xxxxxxxx"]), undefined);
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
describe("with flags before auth", () => {
|
|
187
|
+
it("should still return auth", () => {
|
|
188
|
+
assert.equal(getPositionalCliCommand(["node", "index.js", "--api-url=https://gitlab.com", "auth"]), "auth");
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
describe("with tsx index.ts auth", () => {
|
|
192
|
+
it("should skip the script path and return auth", () => {
|
|
193
|
+
assert.equal(getPositionalCliCommand(["node", "/usr/local/bin/tsx", "index.ts", "auth", "--help"]), "auth");
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
describe("with space-separated --api-url before auth", () => {
|
|
197
|
+
it("should skip the URL value and return auth", () => {
|
|
198
|
+
assert.equal(getPositionalCliCommand([
|
|
199
|
+
"node",
|
|
200
|
+
"index.js",
|
|
201
|
+
"--api-url",
|
|
202
|
+
"https://gitlab.example/api/v4",
|
|
203
|
+
"auth",
|
|
204
|
+
]), "auth");
|
|
205
|
+
});
|
|
206
|
+
});
|
|
207
|
+
describe("with space-separated --client-id before auth", () => {
|
|
208
|
+
it("should skip the client id value and return auth", () => {
|
|
209
|
+
assert.equal(getPositionalCliCommand(["node", "index.js", "--client-id", "app-id", "auth"]), "auth");
|
|
210
|
+
});
|
|
211
|
+
});
|
|
212
|
+
describe("with -h before auth", () => {
|
|
213
|
+
it("should not consume auth as a help value", () => {
|
|
214
|
+
assert.equal(getPositionalCliCommand(["node", "index.js", "-h", "auth"]), "auth");
|
|
215
|
+
});
|
|
216
|
+
});
|
|
217
|
+
});
|
|
218
|
+
describe("When converting a GitLab API URL", () => {
|
|
219
|
+
describe("with an /api/v4 suffix", () => {
|
|
220
|
+
it("should strip it the same way initializeOAuthClient does", () => {
|
|
221
|
+
assert.equal(gitlabOriginFromApiUrl("https://gitlab.com/api/v4"), "https://gitlab.com");
|
|
222
|
+
});
|
|
223
|
+
});
|
|
224
|
+
describe("with a trailing slash after /api/v4", () => {
|
|
225
|
+
it("should strip the suffix and trailing slash", () => {
|
|
226
|
+
assert.equal(gitlabOriginFromApiUrl("https://gitlab.example/api/v4/"), "https://gitlab.example");
|
|
227
|
+
});
|
|
228
|
+
});
|
|
229
|
+
});
|
|
230
|
+
describe("When running device authorization grant", () => {
|
|
231
|
+
describe("with authorization_pending then a token", () => {
|
|
232
|
+
it("should return TokenData compatible with the existing OAuth store", async () => {
|
|
233
|
+
const fetchImpl = createFetchStub({
|
|
234
|
+
authorize: { status: 200, body: deviceAuthorizationBody() },
|
|
235
|
+
tokens: [
|
|
236
|
+
{ status: 400, body: pendingBody() },
|
|
237
|
+
{ status: 200, body: successTokenBody() },
|
|
238
|
+
],
|
|
239
|
+
});
|
|
240
|
+
const sleep = createSleepRecorder();
|
|
241
|
+
const token = await runDeviceAuthorizationGrantAsync({
|
|
242
|
+
gitlabUrl: GITLAB_URL,
|
|
243
|
+
clientId: CLIENT_ID,
|
|
244
|
+
scopes: ["api"],
|
|
245
|
+
fetchImpl,
|
|
246
|
+
sleepAsync: sleep.sleepAsync,
|
|
247
|
+
});
|
|
248
|
+
assert.equal(token.access_token, ACCESS_TOKEN);
|
|
249
|
+
assert.equal(token.refresh_token, REFRESH_TOKEN);
|
|
250
|
+
assert.equal(token.expires_in, 7200);
|
|
251
|
+
assert.equal(token.token_type, "Bearer");
|
|
252
|
+
assert.equal(typeof token.created_at, "number");
|
|
253
|
+
assert.deepEqual(sleep.delays, [5000]);
|
|
254
|
+
});
|
|
255
|
+
});
|
|
256
|
+
describe("with slow_down then a token", () => {
|
|
257
|
+
it("should wait the increased interval before the next poll", async () => {
|
|
258
|
+
const fetchImpl = createFetchStub({
|
|
259
|
+
authorize: { status: 200, body: deviceAuthorizationBody(5) },
|
|
260
|
+
tokens: [
|
|
261
|
+
{ status: 400, body: { error: "slow_down" } },
|
|
262
|
+
{ status: 200, body: successTokenBody() },
|
|
263
|
+
],
|
|
264
|
+
});
|
|
265
|
+
const sleep = createSleepRecorder();
|
|
266
|
+
await runDeviceAuthorizationGrantAsync({
|
|
267
|
+
gitlabUrl: GITLAB_URL,
|
|
268
|
+
clientId: CLIENT_ID,
|
|
269
|
+
scopes: ["api"],
|
|
270
|
+
fetchImpl,
|
|
271
|
+
sleepAsync: sleep.sleepAsync,
|
|
272
|
+
});
|
|
273
|
+
assert.deepEqual(sleep.delays, [10000]);
|
|
274
|
+
});
|
|
275
|
+
});
|
|
276
|
+
});
|
|
277
|
+
describe("When the token endpoint returns expired_token", () => {
|
|
278
|
+
describe("with no token file yet", () => {
|
|
279
|
+
it("should throw and not write a token file", async () => {
|
|
280
|
+
const tokenPath = createTempTokenPath();
|
|
281
|
+
const fetchImpl = createFetchStub({
|
|
282
|
+
authorize: { status: 200, body: deviceAuthorizationBody() },
|
|
283
|
+
tokens: [{ status: 400, body: { error: "expired_token" } }],
|
|
284
|
+
});
|
|
285
|
+
const oauth = createOauthClient(tokenPath);
|
|
286
|
+
await assert.rejects(() => oauth.runDeviceFlowAsync({ fetchImpl, sleepAsync: async () => { } }), /Device code expired/);
|
|
287
|
+
assert.equal(fs.existsSync(tokenPath), false);
|
|
288
|
+
});
|
|
289
|
+
});
|
|
290
|
+
});
|
|
291
|
+
describe("When the token endpoint returns access_denied", () => {
|
|
292
|
+
describe("with no token file yet", () => {
|
|
293
|
+
it("should throw and not write a token file", async () => {
|
|
294
|
+
const tokenPath = createTempTokenPath();
|
|
295
|
+
const fetchImpl = createFetchStub({
|
|
296
|
+
authorize: { status: 200, body: deviceAuthorizationBody() },
|
|
297
|
+
tokens: [{ status: 400, body: { error: "access_denied" } }],
|
|
298
|
+
});
|
|
299
|
+
const oauth = createOauthClient(tokenPath);
|
|
300
|
+
await assert.rejects(() => oauth.runDeviceFlowAsync({ fetchImpl, sleepAsync: async () => { } }), /Authorization was denied/);
|
|
301
|
+
assert.equal(fs.existsSync(tokenPath), false);
|
|
302
|
+
});
|
|
303
|
+
});
|
|
304
|
+
});
|
|
305
|
+
describe("When GitLab returns 404 for authorize_device", () => {
|
|
306
|
+
describe("with a self-managed instance", () => {
|
|
307
|
+
it("should tell the user to use a PAT", async () => {
|
|
308
|
+
const fetchImpl = createFetchStub({
|
|
309
|
+
authorize: { status: 404, body: { error: "not_found" } },
|
|
310
|
+
tokens: [],
|
|
311
|
+
});
|
|
312
|
+
await assert.rejects(() => runDeviceAuthorizationGrantAsync({
|
|
313
|
+
gitlabUrl: GITLAB_URL,
|
|
314
|
+
clientId: CLIENT_ID,
|
|
315
|
+
scopes: ["api"],
|
|
316
|
+
fetchImpl,
|
|
317
|
+
sleepAsync: async () => { },
|
|
318
|
+
}), /GITLAB_PERSONAL_ACCESS_TOKEN/);
|
|
319
|
+
});
|
|
320
|
+
});
|
|
321
|
+
});
|
|
322
|
+
describe("When device flow succeeds", () => {
|
|
323
|
+
describe("with GitLabOAuth.saveToken", () => {
|
|
324
|
+
it("should persist the existing token file shape", async () => {
|
|
325
|
+
const tokenPath = createTempTokenPath();
|
|
326
|
+
const fetchImpl = createFetchStub({
|
|
327
|
+
authorize: { status: 200, body: deviceAuthorizationBody() },
|
|
328
|
+
tokens: [{ status: 200, body: successTokenBody() }],
|
|
329
|
+
});
|
|
330
|
+
try {
|
|
331
|
+
await createOauthClient(tokenPath).runDeviceFlowAsync({
|
|
332
|
+
fetchImpl,
|
|
333
|
+
sleepAsync: async () => { },
|
|
334
|
+
});
|
|
335
|
+
const raw = JSON.parse(fs.readFileSync(tokenPath, "utf8"));
|
|
336
|
+
const stored = readStoredToken(raw);
|
|
337
|
+
assert.equal(stored.access_token, ACCESS_TOKEN);
|
|
338
|
+
assert.equal(stored.refresh_token, REFRESH_TOKEN);
|
|
339
|
+
assert.equal(stored.expires_in, 7200);
|
|
340
|
+
assert.equal(stored.token_type, "Bearer");
|
|
341
|
+
assert.equal(typeof stored.created_at, "number");
|
|
342
|
+
assert.equal(fs.statSync(tokenPath).mode & 0o777, 0o600);
|
|
343
|
+
}
|
|
344
|
+
finally {
|
|
345
|
+
if (fs.existsSync(tokenPath)) {
|
|
346
|
+
fs.unlinkSync(tokenPath);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
});
|
|
350
|
+
});
|
|
351
|
+
});
|
|
352
|
+
describe("When running the auth command", () => {
|
|
353
|
+
describe("with --help", () => {
|
|
354
|
+
it("should print usage and not fetch", async () => {
|
|
355
|
+
const out = createStdoutBuffer();
|
|
356
|
+
const fetchImpl = async () => {
|
|
357
|
+
throw new Error("fetch should not run for --help");
|
|
358
|
+
};
|
|
359
|
+
await runAuthCommandAsync({
|
|
360
|
+
argv: ["node", "index.js", "auth", "--help"],
|
|
361
|
+
env: {},
|
|
362
|
+
stdout: out.stdout,
|
|
363
|
+
fetchImpl,
|
|
364
|
+
});
|
|
365
|
+
assert.match(out.text(), /zereight-mcp-gitlab auth/);
|
|
366
|
+
assert.equal(out.text().includes(DEVICE_CODE), false);
|
|
367
|
+
});
|
|
368
|
+
});
|
|
369
|
+
describe("without a client id", () => {
|
|
370
|
+
it("should fail before calling GitLab", async () => {
|
|
371
|
+
await assert.rejects(() => runAuthCommandAsync({
|
|
372
|
+
argv: ["node", "index.js", "auth"],
|
|
373
|
+
env: {},
|
|
374
|
+
stdout: createStdoutBuffer().stdout,
|
|
375
|
+
fetchImpl: async () => {
|
|
376
|
+
throw new Error("fetch should not run without client id");
|
|
377
|
+
},
|
|
378
|
+
}), /GITLAB_OAUTH_CLIENT_ID/);
|
|
379
|
+
});
|
|
380
|
+
});
|
|
381
|
+
describe("with a successful device flow", () => {
|
|
382
|
+
it("should print the user code and not the device code or access token", async () => {
|
|
383
|
+
const tokenPath = createTempTokenPath();
|
|
384
|
+
const out = createStdoutBuffer();
|
|
385
|
+
const fetchImpl = createFetchStub({
|
|
386
|
+
authorize: { status: 200, body: deviceAuthorizationBody() },
|
|
387
|
+
tokens: [{ status: 200, body: successTokenBody() }],
|
|
388
|
+
});
|
|
389
|
+
try {
|
|
390
|
+
await runAuthCommandAsync({
|
|
391
|
+
argv: [
|
|
392
|
+
"node",
|
|
393
|
+
"index.js",
|
|
394
|
+
"auth",
|
|
395
|
+
`--client-id=${CLIENT_ID}`,
|
|
396
|
+
`--api-url=${GITLAB_URL}`,
|
|
397
|
+
`--token-path=${tokenPath}`,
|
|
398
|
+
],
|
|
399
|
+
env: {},
|
|
400
|
+
stdout: out.stdout,
|
|
401
|
+
fetchImpl,
|
|
402
|
+
sleepAsync: async () => { },
|
|
403
|
+
});
|
|
404
|
+
const printed = out.text();
|
|
405
|
+
assert.equal(printed.includes(USER_CODE), true);
|
|
406
|
+
assert.match(printed, /Token saved to/);
|
|
407
|
+
assert.match(printed, /GITLAB_USE_OAUTH=true/);
|
|
408
|
+
assert.match(printed, /GITLAB_OAUTH_TOKEN_PATH/);
|
|
409
|
+
assert.equal(printed.includes(DEVICE_CODE), false);
|
|
410
|
+
assert.equal(printed.includes(ACCESS_TOKEN), false);
|
|
411
|
+
assert.equal(fs.existsSync(tokenPath), true);
|
|
412
|
+
}
|
|
413
|
+
finally {
|
|
414
|
+
if (fs.existsSync(tokenPath)) {
|
|
415
|
+
fs.unlinkSync(tokenPath);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
});
|
|
419
|
+
});
|
|
420
|
+
describe("without a read-only flag", () => {
|
|
421
|
+
it("should request the api scope", async () => {
|
|
422
|
+
assert.equal(await runAuthCapturingScopeAsync({}), "api");
|
|
423
|
+
});
|
|
424
|
+
});
|
|
425
|
+
describe("with --permission-mode=readonly", () => {
|
|
426
|
+
it("should request the read_api scope", async () => {
|
|
427
|
+
assert.equal(await runAuthCapturingScopeAsync({ extraArgv: ["--permission-mode=readonly"] }), "read_api");
|
|
428
|
+
});
|
|
429
|
+
});
|
|
430
|
+
describe("with GITLAB_PERMISSION_MODE=readonly", () => {
|
|
431
|
+
it("should request the read_api scope", async () => {
|
|
432
|
+
assert.equal(await runAuthCapturingScopeAsync({ env: { GITLAB_PERMISSION_MODE: "readonly" } }), "read_api");
|
|
433
|
+
});
|
|
434
|
+
});
|
|
435
|
+
describe("with --read-only=true", () => {
|
|
436
|
+
it("should request the read_api scope", async () => {
|
|
437
|
+
assert.equal(await runAuthCapturingScopeAsync({ extraArgv: ["--read-only=true"] }), "read_api");
|
|
438
|
+
});
|
|
439
|
+
});
|
|
440
|
+
});
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env ts-node
|
|
2
|
-
import { GetFileContentsSchema, GitLabFileContentSchema, GitLabRepositorySchema, CreatePipelineSchema, CreateCommitStatusSchema, ListCommitStatusesSchema, CreateIssueNoteSchema, CreateMergeRequestEmojiReactionSchema, CreateIssueEmojiReactionSchema, DeleteMergeRequestEmojiReactionSchema, DeleteIssueEmojiReactionSchema, CreateWorkItemEmojiReactionSchema, CreateWorkItemNoteEmojiReactionSchema, CreateIssueSchema, ListIssuesSchema, ListMergeRequestsSchema, ListLabelsSchema, GitLabMergeRequestSchema, GitLabTreeItemSchema, GetMergeRequestSchema, ListMergeRequestPipelinesSchema, GetRepositoryTreeSchema, GitLabUserFullSchema, GitLabMarkdownUploadSchema, GitLabDependencyProxySchema, GitLabDependencyProxyBlobSchema, } from '../schemas.js';
|
|
2
|
+
import { GetFileContentsSchema, GitLabFileContentSchema, GitLabRepositorySchema, CreatePipelineSchema, CreateCommitStatusSchema, ListCommitStatusesSchema, CreateIssueNoteSchema, CreateMergeRequestEmojiReactionSchema, CreateIssueEmojiReactionSchema, DeleteMergeRequestEmojiReactionSchema, DeleteIssueEmojiReactionSchema, CreateWorkItemEmojiReactionSchema, CreateWorkItemNoteEmojiReactionSchema, CreateIssueSchema, ListIssuesSchema, ListMergeRequestsSchema, ListLabelsSchema, GitLabMergeRequestSchema, GitLabTreeItemSchema, GetMergeRequestSchema, ListMergeRequestPipelinesSchema, GetRepositoryTreeSchema, GitLabUserFullSchema, GitLabMarkdownUploadSchema, GitLabDependencyProxySchema, GitLabDependencyProxyBlobSchema, PushFilesSchema, CreateOrUpdateFileSchema, } from '../schemas.js';
|
|
3
3
|
function runGetFileContentsSchemaTests() {
|
|
4
4
|
console.log('🧪 Testing GetFileContentsSchema...');
|
|
5
5
|
const cases = [
|
|
@@ -822,6 +822,21 @@ function runGitLabMergeRequestSchemaTests() {
|
|
|
822
822
|
},
|
|
823
823
|
validate: (data) => data.merge_user === undefined && data.merged_by === undefined,
|
|
824
824
|
},
|
|
825
|
+
{
|
|
826
|
+
name: 'schema:gitlab_merge_request:preserves-sha',
|
|
827
|
+
input: {
|
|
828
|
+
...baseMergeRequest,
|
|
829
|
+
sha: 'e82eb4a098e32c796079ca3915e07487fc4db24c',
|
|
830
|
+
},
|
|
831
|
+
validate: (data) => data.sha === 'e82eb4a098e32c796079ca3915e07487fc4db24c',
|
|
832
|
+
},
|
|
833
|
+
{
|
|
834
|
+
name: 'schema:gitlab_merge_request:allows-omitted-sha',
|
|
835
|
+
input: {
|
|
836
|
+
...baseMergeRequest,
|
|
837
|
+
},
|
|
838
|
+
validate: (data) => data.sha === undefined,
|
|
839
|
+
},
|
|
825
840
|
];
|
|
826
841
|
let passed = 0;
|
|
827
842
|
let failed = 0;
|
|
@@ -1536,6 +1551,104 @@ function runGitLabDependencyProxyBlobSchemaTests() {
|
|
|
1536
1551
|
console.log(`\nResults: ${passed} passed, ${failed} failed`);
|
|
1537
1552
|
return { passed, failed };
|
|
1538
1553
|
}
|
|
1554
|
+
function runPushFilesSchemaTests() {
|
|
1555
|
+
console.log('🧪 Testing PushFilesSchema / CreateOrUpdateFileSchema (per-file action + encoding)...');
|
|
1556
|
+
const base = { project_id: '1', branch: 'main', commit_message: 'm' };
|
|
1557
|
+
function record(name, ok, error) {
|
|
1558
|
+
const result = { name, status: ok ? 'passed' : 'failed', error };
|
|
1559
|
+
if (result.status === 'passed') {
|
|
1560
|
+
console.log(`✅ ${result.name}`);
|
|
1561
|
+
}
|
|
1562
|
+
else {
|
|
1563
|
+
console.log(`❌ ${result.name}: ${result.error}`);
|
|
1564
|
+
}
|
|
1565
|
+
return result;
|
|
1566
|
+
}
|
|
1567
|
+
const results = [];
|
|
1568
|
+
{
|
|
1569
|
+
const parsed = PushFilesSchema.safeParse({ ...base, files: [{ file_path: 'a.txt', content: 'hi' }] });
|
|
1570
|
+
results.push(record('schema:push_files:plain-text-default', parsed.success &&
|
|
1571
|
+
parsed.data.files[0]?.action === undefined &&
|
|
1572
|
+
parsed.data.files[0]?.encoding === undefined, parsed.success ? undefined : parsed.error.message));
|
|
1573
|
+
}
|
|
1574
|
+
{
|
|
1575
|
+
const parsed = PushFilesSchema.safeParse({
|
|
1576
|
+
...base,
|
|
1577
|
+
files: [{ file_path: 'logo.png', content: 'aGk=', encoding: 'base64' }],
|
|
1578
|
+
});
|
|
1579
|
+
results.push(record('schema:push_files:binary-base64', parsed.success && parsed.data.files[0]?.encoding === 'base64', parsed.success ? undefined : parsed.error.message));
|
|
1580
|
+
}
|
|
1581
|
+
{
|
|
1582
|
+
const parsed = PushFilesSchema.safeParse({
|
|
1583
|
+
...base,
|
|
1584
|
+
files: [{ file_path: 'a.txt', content: 'new', action: 'update' }],
|
|
1585
|
+
});
|
|
1586
|
+
results.push(record('schema:push_files:action-update', parsed.success && parsed.data.files[0]?.action === 'update', parsed.success ? undefined : parsed.error.message));
|
|
1587
|
+
}
|
|
1588
|
+
{
|
|
1589
|
+
const parsed = PushFilesSchema.safeParse({
|
|
1590
|
+
...base,
|
|
1591
|
+
files: [{ file_path: 'a.txt', action: 'delete' }],
|
|
1592
|
+
});
|
|
1593
|
+
results.push(record('schema:push_files:action-delete-content-optional', parsed.success &&
|
|
1594
|
+
parsed.data.files[0]?.action === 'delete' &&
|
|
1595
|
+
parsed.data.files[0]?.content === undefined, parsed.success ? undefined : parsed.error.message));
|
|
1596
|
+
}
|
|
1597
|
+
{
|
|
1598
|
+
const parsed = PushFilesSchema.safeParse({
|
|
1599
|
+
...base,
|
|
1600
|
+
files: [{ file_path: 'b.txt', action: 'move', previous_path: 'a.txt' }],
|
|
1601
|
+
});
|
|
1602
|
+
results.push(record('schema:push_files:action-move-previous-path', parsed.success &&
|
|
1603
|
+
parsed.data.files[0]?.action === 'move' &&
|
|
1604
|
+
parsed.data.files[0]?.previous_path === 'a.txt', parsed.success ? undefined : parsed.error.message));
|
|
1605
|
+
}
|
|
1606
|
+
{
|
|
1607
|
+
const parsed = PushFilesSchema.safeParse({
|
|
1608
|
+
...base,
|
|
1609
|
+
files: [{ file_path: 'a.txt', content: 'hi', encoding: 'text' }],
|
|
1610
|
+
});
|
|
1611
|
+
results.push(record('schema:push_files:explicit-text-encoding', parsed.success && parsed.data.files[0]?.encoding === 'text', parsed.success ? undefined : parsed.error.message));
|
|
1612
|
+
}
|
|
1613
|
+
results.push(record('schema:push_files:reject-create-without-content', !PushFilesSchema.safeParse({ ...base, files: [{ file_path: 'a.txt' }] }).success, 'Expected schema validation to fail'));
|
|
1614
|
+
results.push(record('schema:push_files:reject-update-without-content', !PushFilesSchema.safeParse({ ...base, files: [{ file_path: 'a.txt', action: 'update' }] }).success, 'Expected schema validation to fail'));
|
|
1615
|
+
results.push(record('schema:push_files:reject-move-without-previous-path', !PushFilesSchema.safeParse({ ...base, files: [{ file_path: 'b.txt', action: 'move' }] }).success, 'Expected schema validation to fail'));
|
|
1616
|
+
results.push(record('schema:push_files:reject-invalid-action', !PushFilesSchema.safeParse({
|
|
1617
|
+
...base,
|
|
1618
|
+
files: [{ file_path: 'a.txt', content: 'hi', action: 'copy' }],
|
|
1619
|
+
}).success, 'Expected schema validation to fail'));
|
|
1620
|
+
results.push(record('schema:push_files:reject-invalid-encoding', !PushFilesSchema.safeParse({
|
|
1621
|
+
...base,
|
|
1622
|
+
files: [{ file_path: 'a.txt', content: 'hi', encoding: 'utf16' }],
|
|
1623
|
+
}).success, 'Expected schema validation to fail'));
|
|
1624
|
+
{
|
|
1625
|
+
const parsed = CreateOrUpdateFileSchema.safeParse({
|
|
1626
|
+
...base,
|
|
1627
|
+
file_path: 'a.txt',
|
|
1628
|
+
content: 'hi',
|
|
1629
|
+
});
|
|
1630
|
+
results.push(record('schema:create_or_update_file:plain-text-default', parsed.success && parsed.data.encoding === undefined, parsed.success ? undefined : parsed.error.message));
|
|
1631
|
+
}
|
|
1632
|
+
{
|
|
1633
|
+
const parsed = CreateOrUpdateFileSchema.safeParse({
|
|
1634
|
+
...base,
|
|
1635
|
+
file_path: 'logo.png',
|
|
1636
|
+
content: 'aGk=',
|
|
1637
|
+
encoding: 'base64',
|
|
1638
|
+
});
|
|
1639
|
+
results.push(record('schema:create_or_update_file:encoding-base64', parsed.success && parsed.data.encoding === 'base64', parsed.success ? undefined : parsed.error.message));
|
|
1640
|
+
}
|
|
1641
|
+
results.push(record('schema:create_or_update_file:reject-invalid-encoding', !CreateOrUpdateFileSchema.safeParse({
|
|
1642
|
+
...base,
|
|
1643
|
+
file_path: 'a.txt',
|
|
1644
|
+
content: 'hi',
|
|
1645
|
+
encoding: 'utf16',
|
|
1646
|
+
}).success, 'Expected schema validation to fail'));
|
|
1647
|
+
const passed = results.filter(result => result.status === 'passed').length;
|
|
1648
|
+
const failed = results.filter(result => result.status === 'failed').length;
|
|
1649
|
+
console.log(`\nResults: ${passed} passed, ${failed} failed`);
|
|
1650
|
+
return { passed, failed };
|
|
1651
|
+
}
|
|
1539
1652
|
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
1540
1653
|
const getFileContentsResult = runGetFileContentsSchemaTests();
|
|
1541
1654
|
const fileContentResult = runGitLabFileContentSchemaTests();
|
|
@@ -1556,8 +1669,9 @@ if (import.meta.url === `file://${process.argv[1]}`) {
|
|
|
1556
1669
|
const gitLabMarkdownUploadResult = runGitLabMarkdownUploadSchemaTests();
|
|
1557
1670
|
const dependencyProxyResult = runGitLabDependencyProxySchemaTests();
|
|
1558
1671
|
const dependencyProxyBlobResult = runGitLabDependencyProxyBlobSchemaTests();
|
|
1559
|
-
const
|
|
1560
|
-
const
|
|
1672
|
+
const pushFilesResult = runPushFilesSchemaTests();
|
|
1673
|
+
const totalPassed = getFileContentsResult.passed + fileContentResult.passed + createPipelineResult.passed + commitStatusResult.passed + createIssueNoteResult.passed + getMergeRequestResult.passed + listMergeRequestPipelinesResult.passed + gitLabMergeRequestResult.passed + emojiReactionResult.passed + repositorySchemaResult.passed + labelsCoercionResult.passed + approvedByUsernamesResult.passed + listLabelsResult.passed + treeItemResult.passed + repositoryTreeResult.passed + gitLabUserFullResult.passed + gitLabMarkdownUploadResult.passed + dependencyProxyResult.passed + dependencyProxyBlobResult.passed + pushFilesResult.passed;
|
|
1674
|
+
const totalFailed = getFileContentsResult.failed + fileContentResult.failed + createPipelineResult.failed + commitStatusResult.failed + createIssueNoteResult.failed + getMergeRequestResult.failed + listMergeRequestPipelinesResult.failed + gitLabMergeRequestResult.failed + emojiReactionResult.failed + repositorySchemaResult.failed + labelsCoercionResult.failed + approvedByUsernamesResult.failed + listLabelsResult.failed + treeItemResult.failed + repositoryTreeResult.failed + gitLabUserFullResult.failed + gitLabMarkdownUploadResult.failed + dependencyProxyResult.failed + dependencyProxyBlobResult.failed + pushFilesResult.failed;
|
|
1561
1675
|
console.log(`\nTotal Results: ${totalPassed} passed, ${totalFailed} failed`);
|
|
1562
1676
|
if (totalFailed > 0) {
|
|
1563
1677
|
process.exit(1);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describe, test, before, after } from 'node:test';
|
|
1
|
+
import { describe, test, it, before, after } from 'node:test';
|
|
2
2
|
import assert from 'node:assert';
|
|
3
3
|
import { spawn } from 'child_process';
|
|
4
4
|
import { MockGitLabServer, findMockServerPort } from './utils/mock-gitlab-server.js';
|
|
@@ -8,6 +8,7 @@ import os from 'node:os';
|
|
|
8
8
|
const MOCK_TOKEN = 'glpat-mock-token-12345';
|
|
9
9
|
const TEST_PROJECT_ID = '123';
|
|
10
10
|
const TEST_JOB_ID = '456';
|
|
11
|
+
const NULL_MODE_JOB_ID = '457';
|
|
11
12
|
const TEST_ENCODED_ARTIFACT_PATH = 'reports/report#1.txt';
|
|
12
13
|
// Helper to run an MCP tool via the built server
|
|
13
14
|
async function callTool(toolName, args, env) {
|
|
@@ -117,6 +118,25 @@ describe('job artifacts tools', () => {
|
|
|
117
118
|
res.set('Content-Type', 'text/plain');
|
|
118
119
|
res.send('encoded artifact content');
|
|
119
120
|
});
|
|
121
|
+
// GitLab.com can return mode/size as null on artifacts/tree entries (#661)
|
|
122
|
+
mockGitLab.addMockHandler('get', `/projects/${TEST_PROJECT_ID}/jobs/${NULL_MODE_JOB_ID}/artifacts/tree`, (req, res) => {
|
|
123
|
+
res.json([
|
|
124
|
+
{
|
|
125
|
+
name: 'report.xml',
|
|
126
|
+
path: 'report.xml',
|
|
127
|
+
type: 'file',
|
|
128
|
+
size: 1024,
|
|
129
|
+
mode: null,
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
name: 'logs',
|
|
133
|
+
path: 'logs',
|
|
134
|
+
type: 'directory',
|
|
135
|
+
size: null,
|
|
136
|
+
mode: '040755',
|
|
137
|
+
},
|
|
138
|
+
]);
|
|
139
|
+
});
|
|
120
140
|
// Add mock handler for 404 on non-existent artifact
|
|
121
141
|
mockGitLab.addMockHandler('get', `/projects/${TEST_PROJECT_ID}/jobs/999/artifacts/tree`, (req, res) => {
|
|
122
142
|
res.status(404).json({ message: 'Not Found' });
|
|
@@ -147,6 +167,20 @@ describe('job artifacts tools', () => {
|
|
|
147
167
|
assert.strictEqual(result[1].name, 'logs');
|
|
148
168
|
assert.strictEqual(result[1].type, 'directory');
|
|
149
169
|
});
|
|
170
|
+
describe('When listing job artifacts', () => {
|
|
171
|
+
describe('with a null mode entry', () => {
|
|
172
|
+
it('should return the entries instead of failing', async () => {
|
|
173
|
+
const result = await callTool('list_job_artifacts', { project_id: TEST_PROJECT_ID, job_id: NULL_MODE_JOB_ID }, {
|
|
174
|
+
GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
|
|
175
|
+
GITLAB_PERSONAL_ACCESS_TOKEN: MOCK_TOKEN,
|
|
176
|
+
});
|
|
177
|
+
assert.ok(Array.isArray(result), 'Response should be an array');
|
|
178
|
+
assert.strictEqual(result.length, 2);
|
|
179
|
+
assert.strictEqual(result[0].mode, null);
|
|
180
|
+
assert.strictEqual(result[1].size, null);
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
});
|
|
150
184
|
test('download_job_artifacts saves archive to disk', async () => {
|
|
151
185
|
const result = await callTool('download_job_artifacts', { project_id: TEST_PROJECT_ID, job_id: TEST_JOB_ID, local_path: tmpDir }, {
|
|
152
186
|
GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
|