@zereight/mcp-gitlab 2.1.64 → 2.1.65

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.
@@ -30,6 +30,7 @@ const RFC_FORWARDED_HEADERS = {
30
30
  // Minimal 1x1 transparent PNG
31
31
  const MINIMAL_PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', 'base64');
32
32
  const LARGE_FILE_TOKEN = 'glpat-largefile-test-token';
33
+ const ATTACHMENT_TOKEN = 'glpat-attachment-test-token';
33
34
  const FAKE_ZIP = Buffer.from('PK\x03\x04fake-zip-content-for-testing');
34
35
  const MOCK_UPLOAD_RESPONSE = {
35
36
  id: 99,
@@ -52,7 +53,7 @@ describe('Remote Downloads - Download Proxy Endpoint', { timeout: 30_000 }, () =
52
53
  const mockPort = await findMockServerPort();
53
54
  mockGitLab = new MockGitLabServer({
54
55
  port: mockPort,
55
- validTokens: [MOCK_TOKEN, LARGE_FILE_TOKEN],
56
+ validTokens: [MOCK_TOKEN, LARGE_FILE_TOKEN, ATTACHMENT_TOKEN],
56
57
  });
57
58
  // Mock artifact download
58
59
  mockGitLab.addMockHandler('get', `/projects/${TEST_PROJECT_ID}/jobs/${TEST_JOB_ID}/artifacts`, (_req, res) => {
@@ -70,6 +71,13 @@ describe('Remote Downloads - Download Proxy Endpoint', { timeout: 30_000 }, () =
70
71
  res.set('Content-Type', 'text/plain');
71
72
  res.send('hello document content');
72
73
  });
74
+ // Mock attachment whose name contains a slash. The uploads route takes one filename
75
+ // segment, so the proxy has to request it as `nested%2Fdocument.txt`; a handler on
76
+ // `nested/document.txt` would match the wrong route shape and must not be hit.
77
+ mockGitLab.addMockHandler('get', `/projects/${TEST_PROJECT_ID}/uploads/${TEST_SECRET}/nested%2Fdocument.txt`, (_req, res) => {
78
+ res.set('Content-Type', 'text/plain');
79
+ res.send('nested document content');
80
+ });
73
81
  // Mock large artifact (2MB) to verify streaming works for big files
74
82
  mockGitLab.addMockHandler('get', `/projects/${TEST_PROJECT_ID}/jobs/999/artifacts`, (_req, res) => {
75
83
  res.set('Content-Type', 'application/zip');
@@ -143,6 +151,11 @@ describe('Remote Downloads - Download Proxy Endpoint', { timeout: 30_000 }, () =
143
151
  const expectedSize = 2 * 1024 * 1024;
144
152
  assert.strictEqual(buf.length, expectedSize, `Should receive full 2MB (got ${buf.length} bytes)`);
145
153
  });
154
+ test('keeps a slash-bearing attachment filename inside one path segment', async () => {
155
+ const res = await fetch(`http://${HOST}:${serverPort}/downloads/attachment?project_id=${TEST_PROJECT_ID}&secret=${TEST_SECRET}&filename=${encodeURIComponent('nested/document.txt')}`, { headers: { 'Private-Token': ATTACHMENT_TOKEN } });
156
+ assert.strictEqual(res.status, 200, 'attachment proxy should route to one encoded segment');
157
+ assert.strictEqual(await res.text(), 'nested document content');
158
+ });
146
159
  test('returns 429 after exceeding rate limit', async () => {
147
160
  // Use a different token to get a fresh rate limit counter
148
161
  const rateLimitToken = 'glpat-ratelimit-test-token';
@@ -89,8 +89,80 @@ describe("When graphqlQueryContainsDeleteOperation runs", () => {
89
89
  test("should detect delete mutations with variable definitions", () => {
90
90
  assert.equal(graphqlQueryContainsDeleteOperation("mutation DeleteIssue($id: IssueID!) { issueDelete(input: { id: $id }) { errors } }"), true);
91
91
  });
92
+ test("should detect comma-prefixed delete mutations", () => {
93
+ assert.equal(graphqlQueryContainsDeleteOperation(', mutation M { issueDelete(input: { iid: "1" }) { id } }'), true);
94
+ });
95
+ test("should detect comma-prefixed delete mutations without whitespace", () => {
96
+ assert.equal(graphqlQueryContainsDeleteOperation(',mutation{issueDelete(input:{iid:"1"}){id}}'), true);
97
+ });
98
+ test("should detect delete mutations after a comma-separated query", () => {
99
+ assert.equal(graphqlQueryContainsDeleteOperation("query HealthCheck { x }, mutation M { issueDelete(input: {}) { id } }"), true);
100
+ });
101
+ test("should allow comma-separated queries", () => {
102
+ assert.equal(graphqlQueryContainsDeleteOperation("query A { a }, query B { b }"), false);
103
+ });
92
104
  test("should conservatively block top-level fragment spreads in mutations", () => {
93
105
  assert.equal(graphqlQueryContainsDeleteOperation("mutation { ...f } fragment f on Mutation { issueDelete(input: {}) { errors } }"), true);
94
106
  });
95
107
  });
108
+ describe("with destructive mutations that are not named delete", () => {
109
+ test("should detect environmentStop", () => {
110
+ assert.equal(graphqlQueryContainsDeleteOperation('mutation { environmentStop(input: { environmentId: "gid://gitlab/Environment/1" }) { errors } }'), true);
111
+ });
112
+ test("should detect pipelineCancel", () => {
113
+ assert.equal(graphqlQueryContainsDeleteOperation("mutation { pipelineCancel(input: {}) { errors } }"), true);
114
+ });
115
+ test("should detect clusterAgentTokenRevoke", () => {
116
+ assert.equal(graphqlQueryContainsDeleteOperation("mutation { clusterAgentTokenRevoke(input: {}) { errors } }"), true);
117
+ });
118
+ test("should detect jobUnschedule", () => {
119
+ // GitLab moves the scheduled job to manual and clears its scheduled state, so it
120
+ // is a teardown action even though no teardown verb is part of its name.
121
+ assert.equal(graphqlQueryContainsDeleteOperation("mutation { jobUnschedule(input: {}) { errors } }"), true);
122
+ });
123
+ test("should detect aliased destructive mutations", () => {
124
+ assert.equal(graphqlQueryContainsDeleteOperation("mutation { s: environmentStop(input: {}) { errors } }"), true);
125
+ });
126
+ test("should not treat an alias as a destructive mutation field", () => {
127
+ for (const query of [
128
+ "mutation { stop: issueSetSeverity(input: {}) { errors } }",
129
+ "mutation { revoke: issueSetSeverity(input: {}) { errors } }",
130
+ "mutation { terminate: updateIssue(input: {}) { issue { id } } }",
131
+ ]) {
132
+ assert.equal(graphqlQueryContainsDeleteOperation(query), false, query);
133
+ }
134
+ });
135
+ test("should not treat a spaced or comma-separated alias as a destructive field", () => {
136
+ for (const query of [
137
+ "mutation { stop : issueSetSeverity(input: {}) { errors } }",
138
+ "mutation { revoke,: issueSetSeverity(input: {}) { errors } }",
139
+ "mutation { terminate\n: updateIssue(input: {}) { issue { id } } }",
140
+ ]) {
141
+ assert.equal(graphqlQueryContainsDeleteOperation(query), false, query);
142
+ }
143
+ });
144
+ test("should still detect a destructive field after a spaced alias", () => {
145
+ assert.equal(graphqlQueryContainsDeleteOperation("mutation { harmless : environmentStop(input: {}) { errors } }"), true);
146
+ });
147
+ test("should still detect a destructive field hidden behind a harmless alias", () => {
148
+ for (const query of [
149
+ "mutation { harmless: environmentStop(input: {}) { errors } }",
150
+ "mutation { step: pipelineCancel(input: {}) { errors } }",
151
+ ]) {
152
+ assert.equal(graphqlQueryContainsDeleteOperation(query), true, query);
153
+ }
154
+ });
155
+ test("should detect destructive mutations in multi-operation documents", () => {
156
+ assert.equal(graphqlQueryContainsDeleteOperation("query A { project { id } } mutation B { environmentStop(input: {}) { errors } }"), true);
157
+ });
158
+ test("should still allow mutations without a destructive verb", () => {
159
+ for (const query of [
160
+ "mutation { issueMove(input: {}) { errors } }",
161
+ "mutation { mergeRequestMerge(input: {}) { errors } }",
162
+ "mutation { todoMarkDone(input: {}) { errors } }",
163
+ ]) {
164
+ assert.equal(graphqlQueryContainsDeleteOperation(query), false, query);
165
+ }
166
+ });
167
+ });
96
168
  });
@@ -0,0 +1,463 @@
1
+ import assert from "node:assert/strict";
2
+ import http from "node:http";
3
+ import { after, before, describe, test } from "node:test";
4
+ import { Agent, MockAgent } from "undici";
5
+ import { fetchWithValidatedRedirects, isNonPublicAddress, UnsafeRedirectError, } from "../../utils/safe-redirect-fetch.js";
6
+ const dispatcher = new Agent();
7
+ /** A public IPv4 literal, so hop checks never depend on DNS resolution. */
8
+ const PUBLIC_HOST = "93.184.216.34";
9
+ let server;
10
+ let origin;
11
+ let serverPort;
12
+ let secondServer;
13
+ let secondOrigin;
14
+ let secondPort;
15
+ let lastSecondHeaders = {};
16
+ /** Hosts the trusted-host predicate has been called with. */
17
+ const trustedHostArguments = [];
18
+ function listen(target) {
19
+ return new Promise(resolve => {
20
+ target.listen(0, "127.0.0.1", () => {
21
+ const address = target.address();
22
+ if (!address || typeof address === "string")
23
+ throw new Error("no port");
24
+ resolve(address.port);
25
+ });
26
+ });
27
+ }
28
+ /**
29
+ * A fetch stub that answers the first request with a redirect and every later one
30
+ * with a body, recording the headers used on each hop. Injected so hop policy can
31
+ * be asserted without reaching the network.
32
+ */
33
+ function stubRedirectFetch(location, calls) {
34
+ const impl = async (input, init) => {
35
+ calls.push({ url: String(input), headers: { ...(init?.headers ?? {}) } });
36
+ if (calls.length === 1 && location) {
37
+ return new Response(null, { status: 302, headers: { location } });
38
+ }
39
+ return new Response("payload", { status: 200 });
40
+ };
41
+ return impl;
42
+ }
43
+ /**
44
+ * A fetch stub that walks a list of redirect locations: call N answers with
45
+ * `locations[N - 1]` and the call after the last location returns a body. Used to
46
+ * assert the header policy on chains longer than one hop.
47
+ */
48
+ function stubRedirectChain(locations, calls) {
49
+ const impl = async (input, init) => {
50
+ calls.push({ url: String(input), headers: { ...(init?.headers ?? {}) } });
51
+ const location = locations[calls.length - 1];
52
+ if (location) {
53
+ return new Response(null, { status: 302, headers: { location } });
54
+ }
55
+ return new Response("payload", { status: 200 });
56
+ };
57
+ return impl;
58
+ }
59
+ /**
60
+ * Pass one injected client for both the hops that carry the credentials and the ones the
61
+ * helper strips. The stripped hops default to plain `undici`, so injecting only
62
+ * `fetchImpl` in a test would send the hop it wants to inspect to the network.
63
+ */
64
+ function sameClientForEveryHop(stub) {
65
+ return { fetchImpl: stub, unauthenticatedFetchImpl: stub };
66
+ }
67
+ describe("safe redirect fetch", () => {
68
+ before(async () => {
69
+ server = http.createServer((req, res) => {
70
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
71
+ switch (url.pathname) {
72
+ case "/file":
73
+ res.writeHead(200, { "content-type": "application/octet-stream" });
74
+ res.end("payload");
75
+ return;
76
+ case "/same-origin-redirect":
77
+ res.writeHead(302, { location: "/file" });
78
+ res.end();
79
+ return;
80
+ case "/cross-origin-redirect":
81
+ res.writeHead(302, { location: `${secondOrigin}/file` });
82
+ res.end();
83
+ return;
84
+ case "/loopback-redirect":
85
+ res.writeHead(302, { location: "http://127.0.0.1:1/file" });
86
+ res.end();
87
+ return;
88
+ case "/metadata-redirect":
89
+ res.writeHead(302, { location: "http://169.254.169.254/latest/meta-data/" });
90
+ res.end();
91
+ return;
92
+ case "/mapped-metadata-redirect":
93
+ res.writeHead(302, { location: "http://[::ffff:169.254.169.254]/latest/meta-data/" });
94
+ res.end();
95
+ return;
96
+ case "/mapped-loopback-redirect":
97
+ res.writeHead(302, { location: "http://[::ffff:7f00:1]:1/file" });
98
+ res.end();
99
+ return;
100
+ case "/dotted-mapped-loopback-redirect":
101
+ res.writeHead(302, { location: "http://[::ffff:127.0.0.1]:1/file" });
102
+ res.end();
103
+ return;
104
+ case "/nat64-metadata-redirect":
105
+ res.writeHead(302, { location: "http://[64:ff9b::a9fe:a9fe]/latest/meta-data/" });
106
+ res.end();
107
+ return;
108
+ case "/file-protocol-redirect":
109
+ res.writeHead(302, { location: "file:///etc/passwd" });
110
+ res.end();
111
+ return;
112
+ case "/loop":
113
+ res.writeHead(302, { location: "/loop" });
114
+ res.end();
115
+ return;
116
+ default:
117
+ res.writeHead(404);
118
+ res.end();
119
+ }
120
+ });
121
+ secondServer = http.createServer((req, res) => {
122
+ lastSecondHeaders = req.headers;
123
+ res.writeHead(200).end("second");
124
+ });
125
+ serverPort = await listen(server);
126
+ secondPort = await listen(secondServer);
127
+ origin = `http://127.0.0.1:${serverPort}`;
128
+ secondOrigin = `http://127.0.0.1:${secondPort}`;
129
+ });
130
+ after(async () => {
131
+ await Promise.all([
132
+ new Promise(resolve => server.close(resolve)),
133
+ new Promise(resolve => secondServer.close(resolve)),
134
+ dispatcher.close(),
135
+ ]);
136
+ });
137
+ const rejectsWith = (promise, fragment) => assert.rejects(promise, (error) => error instanceof UnsafeRedirectError && error.message.includes(fragment));
138
+ test("follows a same-origin redirect", async () => {
139
+ const response = await fetchWithValidatedRedirects(`${origin}/same-origin-redirect`, {
140
+ headers: {},
141
+ dispatcher,
142
+ });
143
+ assert.equal(response.status, 200);
144
+ assert.equal(await response.text(), "payload");
145
+ });
146
+ test("refuses a redirect to a loopback address on another origin", async () => {
147
+ await rejectsWith(() => fetchWithValidatedRedirects(`${origin}/loopback-redirect`, { headers: {}, dispatcher }), "non-public address");
148
+ });
149
+ test("refuses a redirect to the cloud instance metadata address", async () => {
150
+ await rejectsWith(() => fetchWithValidatedRedirects(`${origin}/metadata-redirect`, { headers: {}, dispatcher }), "169.254.169.254");
151
+ });
152
+ // The URL parser canonicalizes IPv4-mapped hosts to hex (`::ffff:169.254.169.254`
153
+ // becomes `::ffff:a9fe:a9fe`), so the check has to classify parsed bits. These
154
+ // routes exercise the production path: `new URL(location, currentUrl)`.
155
+ for (const [route, address] of [
156
+ ["/mapped-metadata-redirect", "::ffff:a9fe:a9fe"],
157
+ ["/mapped-loopback-redirect", "::ffff:7f00:1"],
158
+ ["/dotted-mapped-loopback-redirect", "::ffff:7f00:1"],
159
+ ["/nat64-metadata-redirect", "64:ff9b::a9fe:a9fe"],
160
+ ]) {
161
+ test(`refuses a redirect to the IPv6 form ${route} (${address})`, async () => {
162
+ await rejectsWith(() => fetchWithValidatedRedirects(`${origin}${route}`, { headers: {}, dispatcher }), "non-public address");
163
+ });
164
+ }
165
+ test("refuses a redirect to a non-http protocol", async () => {
166
+ await rejectsWith(() => fetchWithValidatedRedirects(`${origin}/file-protocol-redirect`, {
167
+ headers: {},
168
+ dispatcher,
169
+ }), "unsupported protocol");
170
+ });
171
+ test("refuses to follow more redirects than the limit allows", async () => {
172
+ await rejectsWith(() => fetchWithValidatedRedirects(`${origin}/loop`, {
173
+ headers: {},
174
+ dispatcher,
175
+ maxRedirects: 2,
176
+ }), "Too many redirects");
177
+ });
178
+ test("follows a non-public redirect target when the host:port is trusted", async () => {
179
+ trustedHostArguments.length = 0;
180
+ const response = await fetchWithValidatedRedirects(`${origin}/cross-origin-redirect`, {
181
+ headers: {},
182
+ dispatcher,
183
+ isTrustedRedirectHost: host => {
184
+ trustedHostArguments.push(host);
185
+ return host === `127.0.0.1:${secondPort}`;
186
+ },
187
+ });
188
+ assert.equal(response.status, 200);
189
+ assert.equal(await response.text(), "second");
190
+ // The allowlist is keyed by `URL.host`, so the predicate must receive the port
191
+ // with the host: matching on a bare hostname would never find `:8443` entries.
192
+ assert.deepEqual(trustedHostArguments, [`127.0.0.1:${secondPort}`]);
193
+ });
194
+ test("the URL parser canonicalizes IPv4-mapped literals before the check runs", () => {
195
+ assert.equal(new URL("http://[::ffff:169.254.169.254]/").hostname, "[::ffff:a9fe:a9fe]");
196
+ assert.equal(new URL("http://[::ffff:7f00:1]/").hostname, "[::ffff:7f00:1]");
197
+ assert.equal(new URL("http://[::ffff:127.0.0.1]:1/").hostname, "[::ffff:7f00:1]");
198
+ assert.equal(new URL("http://[64:ff9b::a9fe:a9fe]/").hostname, "[64:ff9b::a9fe:a9fe]");
199
+ });
200
+ test("classifies address ranges", () => {
201
+ for (const address of [
202
+ // IPv4
203
+ "127.0.0.1",
204
+ "10.1.2.3",
205
+ "172.16.0.1",
206
+ "192.168.1.1",
207
+ "169.254.169.254",
208
+ "100.64.0.1",
209
+ "0.0.0.0",
210
+ // IPv6
211
+ "::",
212
+ "::1",
213
+ "fd00::1",
214
+ "fe80::1",
215
+ "fea0::1",
216
+ "febf::1",
217
+ "fec0::1",
218
+ // IPv6 carrying a non-public IPv4 address
219
+ "::ffff:127.0.0.1",
220
+ "::ffff:a9fe:a9fe",
221
+ "::ffff:7f00:1",
222
+ "::ffff:0:127.0.0.1",
223
+ "::7f00:1",
224
+ "64:ff9b::a9fe:a9fe",
225
+ "64:ff9b:1::a9fe:a9fe",
226
+ "2002:a9fe:a9fe::",
227
+ // Not a literal address this helper understands — fail closed
228
+ "[::ffff:a9fe:a9fe]",
229
+ "not-an-address",
230
+ ]) {
231
+ assert.equal(isNonPublicAddress(address), true, `${address} should be non-public`);
232
+ }
233
+ for (const address of [
234
+ "8.8.8.8",
235
+ "1.1.1.1",
236
+ "2606:4700::1111",
237
+ // IPv6 carrying a public IPv4 address
238
+ "::ffff:8.8.8.8",
239
+ "::ffff:808:808",
240
+ "64:ff9b::808:808",
241
+ "2002:0808:0808::",
242
+ ]) {
243
+ assert.equal(isNonPublicAddress(address), false, `${address} should be public`);
244
+ }
245
+ });
246
+ });
247
+ describe("credential headers across redirect hops", () => {
248
+ const credentials = {
249
+ Accept: "application/octet-stream",
250
+ Authorization: "Bearer secret",
251
+ "Private-Token": "secret",
252
+ };
253
+ test("keeps credentials on a same-origin hop", async () => {
254
+ const calls = [];
255
+ const response = await fetchWithValidatedRedirects("http://127.0.0.1:1/start", {
256
+ headers: credentials,
257
+ fetchImpl: stubRedirectFetch("/file", calls),
258
+ });
259
+ assert.equal(response.status, 200);
260
+ assert.deepEqual(calls.map(call => call.url), ["http://127.0.0.1:1/start", "http://127.0.0.1:1/file"]);
261
+ assert.equal(calls[1].headers.Authorization, "Bearer secret");
262
+ assert.equal(calls[1].headers["Private-Token"], "secret");
263
+ });
264
+ test("drops credential headers on a cross-origin hop to a public host", async () => {
265
+ const calls = [];
266
+ const response = await fetchWithValidatedRedirects("http://127.0.0.1:1/start", {
267
+ headers: credentials,
268
+ ...sameClientForEveryHop(stubRedirectFetch(`http://${PUBLIC_HOST}/file`, calls)),
269
+ });
270
+ assert.equal(response.status, 200);
271
+ assert.equal(calls[0].headers["Private-Token"], "secret");
272
+ assert.equal(calls[1].headers.Authorization, undefined);
273
+ assert.equal(calls[1].headers["Private-Token"], undefined);
274
+ // Non-credential headers still travel with the request.
275
+ assert.equal(calls[1].headers.Accept, "application/octet-stream");
276
+ });
277
+ test("drops additional header names passed as credentialHeaders", async () => {
278
+ const calls = [];
279
+ await fetchWithValidatedRedirects("http://127.0.0.1:1/start", {
280
+ headers: { ...credentials, "X-Gitlab-Session": "secret" },
281
+ credentialHeaders: ["authorization", "private-token", "x-gitlab-session"],
282
+ ...sameClientForEveryHop(stubRedirectFetch(`http://${PUBLIC_HOST}/file`, calls)),
283
+ });
284
+ assert.equal(calls[1].headers["X-Gitlab-Session"], undefined);
285
+ assert.equal(calls[1].headers.Accept, "application/octet-stream");
286
+ });
287
+ test("keeps credentials on a hop to a trusted host", async () => {
288
+ const calls = [];
289
+ const seen = [];
290
+ await fetchWithValidatedRedirects("http://127.0.0.1:1/start", {
291
+ headers: credentials,
292
+ isTrustedRedirectHost: host => {
293
+ seen.push(host);
294
+ return host === PUBLIC_HOST;
295
+ },
296
+ fetchImpl: stubRedirectFetch(`http://${PUBLIC_HOST}/file`, calls),
297
+ });
298
+ assert.deepEqual(seen, [PUBLIC_HOST]);
299
+ assert.equal(calls[1].headers.Authorization, "Bearer secret");
300
+ assert.equal(calls[1].headers["Private-Token"], "secret");
301
+ });
302
+ test("still refuses an untrusted non-public target even without credentials", async () => {
303
+ const calls = [];
304
+ await assert.rejects(() => fetchWithValidatedRedirects("http://127.0.0.1:1/start", {
305
+ headers: credentials,
306
+ fetchImpl: stubRedirectFetch("http://169.254.169.254/latest/meta-data/", calls),
307
+ }), (error) => error instanceof UnsafeRedirectError && error.message.includes("non-public address"));
308
+ assert.equal(calls.length, 1);
309
+ });
310
+ const rejectsWithCleartext = (promise) => assert.rejects(promise, (error) => error instanceof UnsafeRedirectError && error.message.includes("cleartext"));
311
+ test("refuses an https-to-http downgrade even for a trusted host", async () => {
312
+ const calls = [];
313
+ await rejectsWithCleartext(() => fetchWithValidatedRedirects(`https://${PUBLIC_HOST}/start`, {
314
+ headers: credentials,
315
+ // Trust must not re-enable the credentials on a cleartext hop.
316
+ isTrustedRedirectHost: () => true,
317
+ fetchImpl: stubRedirectFetch(`http://${PUBLIC_HOST}/file`, calls),
318
+ }));
319
+ assert.deepEqual(calls.map(call => call.url), [`https://${PUBLIC_HOST}/start`]);
320
+ });
321
+ test("refuses a downgrade that happens after an earlier https hop", async () => {
322
+ const calls = [];
323
+ await rejectsWithCleartext(() => fetchWithValidatedRedirects(`https://${PUBLIC_HOST}/start`, {
324
+ headers: credentials,
325
+ fetchImpl: stubRedirectChain([`https://${PUBLIC_HOST}/mid`, `http://${PUBLIC_HOST}/file`], calls),
326
+ }));
327
+ assert.deepEqual(calls.map(call => call.url), [`https://${PUBLIC_HOST}/start`, `https://${PUBLIC_HOST}/mid`]);
328
+ });
329
+ test("follows an http-to-https upgrade and keeps credentials on a trusted host", async () => {
330
+ const calls = [];
331
+ const response = await fetchWithValidatedRedirects(`http://${PUBLIC_HOST}/start`, {
332
+ headers: credentials,
333
+ isTrustedRedirectHost: host => host === PUBLIC_HOST,
334
+ fetchImpl: stubRedirectFetch(`https://${PUBLIC_HOST}/file`, calls),
335
+ });
336
+ assert.equal(response.status, 200);
337
+ assert.equal(calls[1].headers.Authorization, "Bearer secret");
338
+ assert.equal(calls[1].headers["Private-Token"], "secret");
339
+ });
340
+ test("treats a scheme change to an untrusted host as cross-origin", async () => {
341
+ const calls = [];
342
+ await fetchWithValidatedRedirects(`http://${PUBLIC_HOST}/start`, {
343
+ headers: credentials,
344
+ ...sameClientForEveryHop(stubRedirectFetch(`https://${PUBLIC_HOST}/file`, calls)),
345
+ });
346
+ assert.equal(calls[1].headers.Authorization, undefined);
347
+ assert.equal(calls[1].headers["Private-Token"], undefined);
348
+ assert.equal(calls[1].headers.Accept, "application/octet-stream");
349
+ });
350
+ test("keeps the credentials off a hop that returns to the initial origin", async () => {
351
+ const calls = [];
352
+ const response = await fetchWithValidatedRedirects("http://127.0.0.1:1/start", {
353
+ headers: credentials,
354
+ ...sameClientForEveryHop(stubRedirectChain([`http://${PUBLIC_HOST}/mid`, "http://127.0.0.1:1/file"], calls)),
355
+ });
356
+ assert.equal(response.status, 200);
357
+ assert.deepEqual(calls.map(call => call.url), ["http://127.0.0.1:1/start", `http://${PUBLIC_HOST}/mid`, "http://127.0.0.1:1/file"]);
358
+ // The untrusted hop keeps the token out of the request...
359
+ assert.equal(calls[1].headers["Private-Token"], undefined);
360
+ // ...and a target cannot get it back by bouncing the request to the origin, whose
361
+ // response the caller of this helper reads as the downloaded body.
362
+ assert.equal(calls[2].headers.Authorization, undefined);
363
+ assert.equal(calls[2].headers["Private-Token"], undefined);
364
+ });
365
+ test("restores credentials on a return to the origin only after a trusted hop", async () => {
366
+ const calls = [];
367
+ await fetchWithValidatedRedirects("http://127.0.0.1:1/start", {
368
+ headers: credentials,
369
+ isTrustedRedirectHost: host => host === PUBLIC_HOST,
370
+ fetchImpl: stubRedirectChain([`http://${PUBLIC_HOST}/mid`, "http://127.0.0.1:1/file"], calls),
371
+ });
372
+ // The trusted hop already received the token, so the return hop may carry it too.
373
+ assert.equal(calls[1].headers["Private-Token"], "secret");
374
+ assert.equal(calls[2].headers["Private-Token"], "secret");
375
+ });
376
+ test("stays without credentials across untrusted hops and returns without them", async () => {
377
+ const calls = [];
378
+ await fetchWithValidatedRedirects("http://127.0.0.1:1/start", {
379
+ headers: credentials,
380
+ ...sameClientForEveryHop(stubRedirectChain([`http://${PUBLIC_HOST}/mid`, `http://${PUBLIC_HOST}/other`, "http://127.0.0.1:1/file"], calls)),
381
+ });
382
+ assert.equal(calls[1].headers["Private-Token"], undefined);
383
+ assert.equal(calls[2].headers["Private-Token"], undefined);
384
+ assert.equal(calls[3].headers["Private-Token"], undefined);
385
+ });
386
+ test("a trusted hop after an untrusted one stays without credentials", async () => {
387
+ const calls = [];
388
+ await fetchWithValidatedRedirects("http://127.0.0.1:1/start", {
389
+ headers: credentials,
390
+ isTrustedRedirectHost: host => host === "93.184.216.35",
391
+ ...sameClientForEveryHop(stubRedirectChain([`http://${PUBLIC_HOST}/mid`, "http://93.184.216.35/storage", "http://127.0.0.1:1/file"], calls)),
392
+ });
393
+ // The untrusted hop chose the trusted URL, so trust must not re-attach the token.
394
+ assert.equal(calls[1].headers["Private-Token"], undefined);
395
+ assert.equal(calls[2].headers.Authorization, undefined);
396
+ assert.equal(calls[2].headers["Private-Token"], undefined);
397
+ assert.equal(calls[3].headers["Private-Token"], undefined);
398
+ });
399
+ test("an untrusted hop cannot re-attach credentials via a second trusted host", async () => {
400
+ const calls = [];
401
+ await fetchWithValidatedRedirects("https://gitlab.a/start", {
402
+ headers: credentials,
403
+ isTrustedRedirectHost: host => host === "gitlab.a" || host === "gitlab.b",
404
+ ...sameClientForEveryHop(stubRedirectChain([`https://${PUBLIC_HOST}/evil`, "https://gitlab.b/api/v4/user"], calls)),
405
+ });
406
+ assert.equal(calls[0].headers["Private-Token"], "secret");
407
+ assert.equal(calls[1].headers["Private-Token"], undefined);
408
+ assert.equal(calls[2].headers.Authorization, undefined);
409
+ assert.equal(calls[2].headers["Private-Token"], undefined);
410
+ });
411
+ test("an untrusted hop cannot re-attach credentials via a scheme change on the origin host", async () => {
412
+ const calls = [];
413
+ await fetchWithValidatedRedirects("http://gitlab.a/start", {
414
+ headers: credentials,
415
+ isTrustedRedirectHost: host => host === "gitlab.a",
416
+ ...sameClientForEveryHop(stubRedirectChain([`http://${PUBLIC_HOST}/evil`, "https://gitlab.a/api/v4/user"], calls)),
417
+ });
418
+ assert.equal(calls[1].headers["Private-Token"], undefined);
419
+ assert.equal(calls[2].headers.Authorization, undefined);
420
+ assert.equal(calls[2].headers["Private-Token"], undefined);
421
+ });
422
+ test("uses the unauthenticated client once the credentials are withheld", async () => {
423
+ const authenticatedCalls = [];
424
+ const unauthenticatedCalls = [];
425
+ await fetchWithValidatedRedirects("http://127.0.0.1:1/start", {
426
+ headers: credentials,
427
+ // A client that can add credentials by itself (cookie jar, OAuth 401 retry) must
428
+ // not see a hop the helper stripped.
429
+ fetchImpl: stubRedirectChain([`http://${PUBLIC_HOST}/mid`, "http://127.0.0.1:1/file"], authenticatedCalls),
430
+ // This stub answers from its own first call on, which is the untrusted hop.
431
+ unauthenticatedFetchImpl: stubRedirectChain(["http://127.0.0.1:1/file"], unauthenticatedCalls),
432
+ });
433
+ assert.deepEqual(authenticatedCalls.map(call => call.url), ["http://127.0.0.1:1/start"]);
434
+ assert.deepEqual(unauthenticatedCalls.map(call => call.url), [`http://${PUBLIC_HOST}/mid`, "http://127.0.0.1:1/file"]);
435
+ assert.equal(unauthenticatedCalls[0].headers["Private-Token"], undefined);
436
+ // ...including the hop back to the origin, which the caller reads as the download.
437
+ assert.equal(unauthenticatedCalls[1].headers["Private-Token"], undefined);
438
+ });
439
+ test("falls back to the plain client for stripped hops when only fetchImpl is given", async () => {
440
+ const calls = [];
441
+ // `undici`'s own client is observable through the dispatcher, so this asserts the
442
+ // default rather than trusting it: were the stripped hop routed to `fetchImpl`, the
443
+ // stub would answer and the mock pool would stay untouched.
444
+ const mockAgent = new MockAgent();
445
+ mockAgent.disableNetConnect();
446
+ mockAgent
447
+ .get(`http://${PUBLIC_HOST}`)
448
+ .intercept({ path: "/file", method: "GET" })
449
+ .reply(200, "from-plain-undici");
450
+ try {
451
+ const response = await fetchWithValidatedRedirects("http://127.0.0.1:1/start", {
452
+ headers: credentials,
453
+ dispatcher: mockAgent,
454
+ fetchImpl: stubRedirectFetch(`http://${PUBLIC_HOST}/file`, calls),
455
+ });
456
+ assert.equal(await response.text(), "from-plain-undici");
457
+ assert.deepEqual(calls.map(call => call.url), ["http://127.0.0.1:1/start"]);
458
+ }
459
+ finally {
460
+ await mockAgent.close();
461
+ }
462
+ });
463
+ });
@@ -107,6 +107,38 @@ describe("When cleanMutuallyExclusiveIdUsernameOptions runs", () => {
107
107
  assignee_username: [],
108
108
  });
109
109
  });
110
+ test("should keep assignee_id when assignee_username holds only blank entries", () => {
111
+ // The blank entries are dropped when the query is built, so counting them as a
112
+ // value here would delete the id filter and leave the request unfiltered.
113
+ const result = cleanMutuallyExclusiveIdUsernameOptions({
114
+ assignee_id: "7",
115
+ assignee_username: ["", " "],
116
+ });
117
+ assert.deepEqual(result, {
118
+ assignee_id: "7",
119
+ assignee_username: ["", " "],
120
+ });
121
+ });
122
+ test("should drop assignee_id when a username survives the blank entries", () => {
123
+ const result = cleanMutuallyExclusiveIdUsernameOptions({
124
+ assignee_id: "7",
125
+ assignee_username: ["", "bob"],
126
+ });
127
+ assert.deepEqual(result, {
128
+ assignee_username: ["", "bob"],
129
+ });
130
+ });
131
+ test("should keep assignee_id when assignee_username is a blank scalar", () => {
132
+ // Boolean(" ") is true, so a whitespace-only scalar used to delete the id and then
133
+ // be dropped by the blank guard, leaving the request with no filter at all.
134
+ for (const blank of ["", " ", " \t "]) {
135
+ const result = cleanMutuallyExclusiveIdUsernameOptions({
136
+ assignee_id: "7",
137
+ assignee_username: blank,
138
+ });
139
+ assert.deepEqual(result, { assignee_id: "7", assignee_username: blank }, `blank scalar ${JSON.stringify(blank)} must not drop the id`);
140
+ }
141
+ });
110
142
  });
111
143
  describe("with list_merge_requests reviewer filters", () => {
112
144
  test("should drop reviewer_id when reviewer_username is also set", () => {