@zereight/mcp-gitlab 2.1.70 → 2.2.1

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.
Files changed (158) hide show
  1. package/README.ko.md +9 -5
  2. package/README.md +15 -11
  3. package/README.pt-BR.md +9 -5
  4. package/README.zh-CN.md +9 -5
  5. package/build/config.js +12 -4
  6. package/build/deprecated-env.js +63 -0
  7. package/build/index.js +430 -200
  8. package/build/oauth-device-flow.js +80 -0
  9. package/build/oauth.js +135 -18
  10. package/build/schemas.js +1 -1
  11. package/build/server/remote-http-stack.js +39 -0
  12. package/build/tools/discover-activation.js +38 -0
  13. package/build/tools/exposed-tools.js +35 -0
  14. package/build/tools/listed-tools.js +76 -0
  15. package/build/tools/registry.js +232 -63
  16. package/build/tools/tool-descriptions.js +3 -3
  17. package/build/tools/tool-profile.js +66 -0
  18. package/build/utils/compact-tool-allowlist.js +14 -0
  19. package/build/utils/logger.js +34 -12
  20. package/package.json +3 -3
  21. package/build/scripts/check-skill-sync.js +0 -143
  22. package/build/scripts/generate-server-card.js +0 -39
  23. package/build/scripts/generate-tool-coverage.js +0 -58
  24. package/build/scripts/generate-tool-docs.js +0 -430
  25. package/build/scripts/tool-coverage/coverage.js +0 -341
  26. package/build/scripts/tool-coverage/coverage.test.js +0 -142
  27. package/build/test/callback-proxy-tests.js +0 -321
  28. package/build/test/cli/args.test.js +0 -175
  29. package/build/test/cli/boolean-flags.test.js +0 -106
  30. package/build/test/cli/compact-mcp-result.test.js +0 -93
  31. package/build/test/cli/credentials.test.js +0 -153
  32. package/build/test/cli/exposure.test.js +0 -104
  33. package/build/test/cli/load-config-snapshot.js +0 -5
  34. package/build/test/cli/output.test.js +0 -74
  35. package/build/test/cli/replay-command.test.js +0 -37
  36. package/build/test/cli/router.test.js +0 -183
  37. package/build/test/client-pool-test.js +0 -109
  38. package/build/test/clients/client.js +0 -34
  39. package/build/test/clients/custom-header-client.js +0 -122
  40. package/build/test/clients/sse-client.js +0 -95
  41. package/build/test/clients/stdio-client.js +0 -113
  42. package/build/test/clients/streamable-http-client.js +0 -95
  43. package/build/test/config-allowed-groups.test.js +0 -97
  44. package/build/test/create-commit-actions.test.js +0 -102
  45. package/build/test/draft-note-schema.test.js +0 -44
  46. package/build/test/dynamic-api-url-allowlist.test.js +0 -121
  47. package/build/test/dynamic-api-url-test.js +0 -304
  48. package/build/test/dynamic-routing-tests.js +0 -495
  49. package/build/test/get-merge-request-discussion-schema.test.js +0 -30
  50. package/build/test/gitlab-api-tool-errors.test.js +0 -112
  51. package/build/test/gitlab-artifact-entry-schema.test.js +0 -44
  52. package/build/test/gitlab-diff-schema.test.js +0 -36
  53. package/build/test/gitlab-pipeline-schedule-schema.test.js +0 -32
  54. package/build/test/gitlab-tag-schema.test.js +0 -51
  55. package/build/test/group-milestone-schema.test.js +0 -45
  56. package/build/test/mcp-oauth-tests.js +0 -905
  57. package/build/test/mcp-server-name.test.js +0 -87
  58. package/build/test/merge-merge-request-schema.test.js +0 -75
  59. package/build/test/multi-server-test.js +0 -190
  60. package/build/test/no-proxy-integration-test.js +0 -183
  61. package/build/test/no-proxy-test.js +0 -149
  62. package/build/test/nullable-gitlab-response-fields.test.js +0 -37
  63. package/build/test/nullish-tool-arguments-schema.test.js +0 -118
  64. package/build/test/oauth-device-flow-tests.js +0 -450
  65. package/build/test/oauth-download-url.test.js +0 -157
  66. package/build/test/oauth-startup.test.js +0 -204
  67. package/build/test/oauth-tests.js +0 -428
  68. package/build/test/path-segment-encoding.test.js +0 -98
  69. package/build/test/remote-auth-simple-test.js +0 -277
  70. package/build/test/remote-auth-tests.js +0 -314
  71. package/build/test/response-masking.test.js +0 -445
  72. package/build/test/schema-tests.js +0 -1679
  73. package/build/test/server/metrics.test.js +0 -47
  74. package/build/test/server/request-helpers.test.js +0 -48
  75. package/build/test/server/version.test.js +0 -13
  76. package/build/test/sse-auth-guard.test.js +0 -96
  77. package/build/test/sse-session-limits.test.js +0 -273
  78. package/build/test/stateless/callback-proxy.test.js +0 -510
  79. package/build/test/stateless/client-id.test.js +0 -177
  80. package/build/test/stateless/codec.test.js +0 -328
  81. package/build/test/stateless/config-ttl.test.js +0 -149
  82. package/build/test/stateless/consumed-proxy-code-cache.test.js +0 -150
  83. package/build/test/stateless/session-id-integration.test.js +0 -675
  84. package/build/test/stateless/session-id.test.js +0 -157
  85. package/build/test/streamable-http-concurrent-session.test.js +0 -171
  86. package/build/test/streamable-http-dns-rebinding.test.js +0 -185
  87. package/build/test/streamable-http-sse-stream.test.js +0 -350
  88. package/build/test/streamable-http-static-token-auth.test.js +0 -157
  89. package/build/test/streamable-http-unauthenticated-discovery.test.js +0 -207
  90. package/build/test/test-all-transport-server.js +0 -255
  91. package/build/test/test-auth-retry.js +0 -195
  92. package/build/test/test-blank-filters.js +0 -156
  93. package/build/test/test-ci-catalog.js +0 -177
  94. package/build/test/test-ci-lint.js +0 -191
  95. package/build/test/test-ci-variables.js +0 -309
  96. package/build/test/test-create-repository.js +0 -120
  97. package/build/test/test-dependency-proxy.js +0 -195
  98. package/build/test/test-deployment-tools.js +0 -463
  99. package/build/test/test-download-attachment.js +0 -190
  100. package/build/test/test-dynamic-project-scope.js +0 -524
  101. package/build/test/test-empty-toolsets.js +0 -535
  102. package/build/test/test-get-file-blame.js +0 -145
  103. package/build/test/test-get-file-contents.js +0 -128
  104. package/build/test/test-geteffectiveprojectid.js +0 -804
  105. package/build/test/test-health-check.js +0 -115
  106. package/build/test/test-issue-description-patch.js +0 -256
  107. package/build/test/test-job-artifacts.js +0 -275
  108. package/build/test/test-json-schema.js +0 -166
  109. package/build/test/test-list-group-members.js +0 -150
  110. package/build/test/test-list-group-merge-requests.js +0 -165
  111. package/build/test/test-list-issues.js +0 -170
  112. package/build/test/test-list-merge-requests.js +0 -201
  113. package/build/test/test-list-milestones.js +0 -145
  114. package/build/test/test-list-project-members.js +0 -132
  115. package/build/test/test-merge-request-approval-state-tools.js +0 -213
  116. package/build/test/test-merge-request-approvals.js +0 -187
  117. package/build/test/test-merge-request-pipelines.js +0 -106
  118. package/build/test/test-mr-diffs-filter.js +0 -132
  119. package/build/test/test-mr-file-diffs.js +0 -251
  120. package/build/test/test-oauth-proxy-rate-limit.js +0 -133
  121. package/build/test/test-orbit.js +0 -155
  122. package/build/test/test-permission-mode.js +0 -424
  123. package/build/test/test-pipeline-schedules.js +0 -484
  124. package/build/test/test-protected-branches.js +0 -174
  125. package/build/test/test-remote-downloads.js +0 -510
  126. package/build/test/test-search-code.js +0 -275
  127. package/build/test/test-snippets.js +0 -735
  128. package/build/test/test-tags.js +0 -220
  129. package/build/test/test-todos.js +0 -195
  130. package/build/test/test-token-optimizations.js +0 -691
  131. package/build/test/test-toolset-filtering.js +0 -499
  132. package/build/test/test-update-issue-slim.js +0 -141
  133. package/build/test/test-update-project.js +0 -112
  134. package/build/test/test-upload-markdown.js +0 -206
  135. package/build/test/test-vulnerabilities.js +0 -399
  136. package/build/test/test-webhooks.js +0 -218
  137. package/build/test/tool-description-quality.test.js +0 -50
  138. package/build/test/utils/bulk-publish-options.test.js +0 -32
  139. package/build/test/utils/download-token.test.js +0 -35
  140. package/build/test/utils/forwarded-public-base-url.test.js +0 -46
  141. package/build/test/utils/gitlab-instance-version.test.js +0 -32
  142. package/build/test/utils/gitlab-version-gate.test.js +0 -74
  143. package/build/test/utils/graphql-query.test.js +0 -168
  144. package/build/test/utils/helpers-path.test.js +0 -104
  145. package/build/test/utils/jmespath-tool-result.test.js +0 -91
  146. package/build/test/utils/masking.test.js +0 -384
  147. package/build/test/utils/merge-request-position.test.js +0 -57
  148. package/build/test/utils/mock-gitlab-server.js +0 -614
  149. package/build/test/utils/proxy-client-ip.test.js +0 -28
  150. package/build/test/utils/redact-sensitive.test.js +0 -32
  151. package/build/test/utils/safe-redirect-fetch.test.js +0 -463
  152. package/build/test/utils/server-launcher.js +0 -231
  153. package/build/test/utils/tool-args.test.js +0 -210
  154. package/build/test/utils/url.test.js +0 -141
  155. package/build/test/utils/version-check.test.js +0 -239
  156. package/build/test/utils/wiki-title.test.js +0 -21
  157. package/build/test-note.js +0 -54
  158. package/build/test-resolve-issue-note.js +0 -127
@@ -1,98 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { readFileSync } from "node:fs";
3
- import { test } from "node:test";
4
- import { encodeGitLabPath, encodeGitLabPathSegment } from "../utils/url.js";
5
- const readSource = (relativePath) => readFileSync(new URL(relativePath, import.meta.url), "utf8");
6
- const indexSource = readSource("../index.ts");
7
- const rawPathSegmentPatterns = [
8
- "/issues/${issueIid}",
9
- "/merge_requests/${mergeRequestIid}",
10
- "/discussions/${discussionId}",
11
- "/notes/${noteId}",
12
- "/links/${issueLinkId}",
13
- "/draft_notes/${draftNoteId}",
14
- "/versions/${versionId}",
15
- "/groups/${groupId}",
16
- "/jobs/${jobId}",
17
- "/pipelines/${pipelineId}",
18
- "/milestones/${milestoneId}",
19
- "/merge_requests/${merge_request_iid}/draft_notes/${draft_note_id}",
20
- "/uploads/${secret}/${filename}",
21
- "/downloads/${directAssetPath}",
22
- "/${entity}/${entityIid}",
23
- ];
24
- test("GitLab URL path IDs are encoded before interpolation", () => {
25
- for (const pattern of rawPathSegmentPatterns) {
26
- assert.equal(indexSource.includes(pattern), false, `${pattern} must use encodeGitLabPathSegment`);
27
- }
28
- });
29
- /**
30
- * encodeURIComponent() does not validate what it encodes: "../../user" becomes
31
- * "..%2F..%2Fuser", which a server that decodes the separator turns back into a
32
- * traversal. Every value that lands in a URL path goes through
33
- * encodeGitLabPathSegment()/encodeGitLabPath() instead; plain encoding stays only
34
- * for query-string values, where a "/" is data and not a path separator.
35
- */
36
- const queryStringEncoders = [
37
- "?source_branch=${encodeURIComponent(branchName)}",
38
- "?access_token=${encodeURIComponent(token)}",
39
- ];
40
- const serverSources = [
41
- ["index.ts", "../index.ts"],
42
- ["downloads/proxy.ts", "../downloads/proxy.ts"],
43
- ["oauth-proxy.ts", "../oauth-proxy.ts"],
44
- ];
45
- for (const [name, relativePath] of serverSources) {
46
- test(`${name} validates values before they reach a URL path`, () => {
47
- for (const line of readSource(relativePath).split("\n")) {
48
- if (!line.includes("encodeURIComponent("))
49
- continue;
50
- assert.ok(queryStringEncoders.some(allowed => line.includes(allowed)), `${name} encodes a URL value without validating it: ${line.trim()}`);
51
- }
52
- });
53
- }
54
- test("plain encoding of a project path would leave the traversal visible", () => {
55
- // The payload this guard exists for: the old encoder emits the separators, so a
56
- // server that decodes them routes the request to /api/v4/user.
57
- const payload = "../../user";
58
- const legacy = `https://gitlab.com/api/v4/projects/${encodeURIComponent(payload)}`;
59
- assert.equal(new URL(legacy).pathname, "/api/v4/projects/..%2F..%2Fuser");
60
- });
61
- test("the validated encoder keeps an ordinary project path inside one segment", () => {
62
- const url = new URL(`https://gitlab.com/api/v4/projects/${encodeGitLabPathSegment("group/project")}/issues/${encodeGitLabPathSegment("1")}/notes`);
63
- assert.equal(url.pathname, "/api/v4/projects/group%2Fproject/issues/1/notes");
64
- });
65
- test("path traversal payloads are rejected instead of encoded into one segment", () => {
66
- // GHSA-7c3w-fxgh-frc7 / #587: an unencoded job_id with ../ escaped to /api/v4/user
67
- for (const payload of [
68
- "../../../user",
69
- "1/../../../../admin/ci/variables",
70
- "..%2F..%2Fuser",
71
- "..%252F..%252Fuser",
72
- "/etc/passwd",
73
- ]) {
74
- assert.throws(() => encodeGitLabPathSegment(payload), /Cannot use value as a GitLab URL path segment/, payload);
75
- }
76
- });
77
- test("a slash-separated path cannot start outside its route prefix", () => {
78
- assert.throws(() => encodeGitLabPath("/etc/passwd"), /Cannot use value as a GitLab URL path/);
79
- assert.throws(() => encodeGitLabPath("1/../../../../admin/ci/variables"), /Cannot use value as a GitLab URL path segment/);
80
- });
81
- test("a broken escape next to a valid one is rejected, not passed through", () => {
82
- // A guard cannot inspect a value it fails to decode: "%2E%2E%2F%ZZ" still holds a
83
- // real escape that may hide a separator, so it must not be forwarded unvalidated.
84
- assert.throws(() => encodeGitLabPathSegment("%2E%2E%2F%ZZ"), /Cannot use value as a GitLab URL path segment/);
85
- });
86
- test("the artifact path goes through the shared multi-segment validator", () => {
87
- // getJobArtifactFile() was the last call site that split the path itself. The
88
- // hand-rolled version kept empty segments, so "a//b" reached the URL as an extra
89
- // separator instead of being rejected like every other call site.
90
- assert.ok(indexSource.includes("const encodedArtifactPath = encodeGitLabPath(artifactPath);"), "artifact paths must go through encodeGitLabPath");
91
- assert.equal(indexSource.includes(".map(segment => encodeGitLabPathSegment(segment))"), false, "artifact paths must not be split into segments by hand");
92
- });
93
- test("a percent sign that starts no escape stays a literal character", () => {
94
- // "bad%zz/path" cannot be decoded either, but it holds no escape at all, so the
95
- // guard sees the entire value and the percent sign is encoded as data. Rejecting
96
- // it would break every file or branch name containing "%".
97
- assert.equal(encodeGitLabPathSegment("bad%zz/path"), "bad%25zz%2Fpath");
98
- });
@@ -1,277 +0,0 @@
1
- /**
2
- * Remote Authorization Test Suite
3
- * Tests remote auth functionality with mock GitLab server
4
- */
5
- import { describe, test, after, before } from 'node:test';
6
- import assert from 'node:assert';
7
- import { launchServer, findAvailablePort, cleanupServers, TransportMode, HOST } from './utils/server-launcher.js';
8
- import { MockGitLabServer, findMockServerPort } from './utils/mock-gitlab-server.js';
9
- import { CustomHeaderClient } from './clients/custom-header-client.js';
10
- // Test constants
11
- const MOCK_TOKEN = 'glpat-mock-token-12345';
12
- const MOCK_JOB_TOKEN = 'glcbt-mock-job-token-9876';
13
- // Port ranges to avoid collisions
14
- const MOCK_GITLAB_PORT_BASE = 9000;
15
- const MOCK_GITLAB_PORT_OFFSET = 500; // Offset for timeout test suite
16
- const MCP_SERVER_PORT_BASE = 3000;
17
- const MCP_SERVER_PORT_OFFSET = 500; // Offset for timeout test suite
18
- // Timeout settings
19
- const SESSION_TIMEOUT_SECONDS = 3;
20
- const TIMEOUT_BUFFER_MS = 1000; // Extra time beyond timeout to ensure expiration
21
- const TIMEOUT_TEST_WAIT_MS = SESSION_TIMEOUT_SECONDS * 1000 + TIMEOUT_BUFFER_MS;
22
- const KEEPALIVE_INTERVAL_MS = 2000; // Must be less than SESSION_TIMEOUT_SECONDS
23
- const KEEPALIVE_REQUEST_COUNT = 3; // Number of keepalive requests to test
24
- async function getMetrics(mcpUrl) {
25
- const metricsUrl = mcpUrl.replace(/\/mcp$/, '/metrics.json');
26
- const response = await fetch(metricsUrl);
27
- assert.strictEqual(response.status, 200, 'metrics JSON endpoint should be available');
28
- return (await response.json());
29
- }
30
- async function waitForSessionDecrease(mcpUrl, beforeTimeout, timeoutMs = 3000) {
31
- const startedAt = Date.now();
32
- let last = await getMetrics(mcpUrl);
33
- while (Date.now() - startedAt < timeoutMs) {
34
- if (last.activeSessions < beforeTimeout.activeSessions &&
35
- last.authenticatedSessions < beforeTimeout.authenticatedSessions) {
36
- return;
37
- }
38
- await new Promise(resolve => setTimeout(resolve, 100));
39
- last = await getMetrics(mcpUrl);
40
- }
41
- assert.ok(last.activeSessions < beforeTimeout.activeSessions, `activeSessions should decrease after timeout (${last.activeSessions} !< ${beforeTimeout.activeSessions})`);
42
- assert.ok(last.authenticatedSessions < beforeTimeout.authenticatedSessions, `authenticatedSessions should decrease after timeout (${last.authenticatedSessions} !< ${beforeTimeout.authenticatedSessions})`);
43
- }
44
- console.log('🔐 Remote Authorization Test Suite');
45
- console.log('');
46
- describe('Remote Authorization', { concurrency: 1 }, () => {
47
- describe('Remote Authorization - Basic Functionality', () => {
48
- let mcpUrl;
49
- let mockGitLab;
50
- let servers = [];
51
- before(async () => {
52
- // Start mock GitLab server
53
- const mockPort = await findMockServerPort();
54
- mockGitLab = new MockGitLabServer({
55
- port: mockPort,
56
- validTokens: [MOCK_TOKEN, MOCK_JOB_TOKEN],
57
- });
58
- await mockGitLab.start();
59
- const mockGitLabUrl = mockGitLab.getUrl();
60
- // Start MCP server with remote auth
61
- const mcpPort = await findAvailablePort(MCP_SERVER_PORT_BASE);
62
- const server = await launchServer({
63
- mode: TransportMode.STREAMABLE_HTTP,
64
- port: mcpPort,
65
- timeout: 5000,
66
- env: {
67
- STREAMABLE_HTTP: 'true',
68
- REMOTE_AUTHORIZATION: 'true',
69
- GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
70
- GITLAB_READ_ONLY_MODE: 'true',
71
- }
72
- });
73
- servers.push(server);
74
- mcpUrl = `http://${HOST}:${mcpPort}/mcp`;
75
- console.log(`Mock GitLab: ${mockGitLabUrl}`);
76
- console.log(`MCP Server: ${mcpUrl}`);
77
- });
78
- after(async () => {
79
- cleanupServers(servers);
80
- if (mockGitLab) {
81
- await mockGitLab.stop();
82
- }
83
- });
84
- test('should reject invalid tokens before creating a session', async () => {
85
- const before = await getMetrics(mcpUrl);
86
- const response = await fetch(mcpUrl, {
87
- method: 'POST',
88
- headers: {
89
- 'Content-Type': 'application/json',
90
- Accept: 'application/json, text/event-stream',
91
- 'Private-Token': 'aaaaaaaaaaaaaaaaaaaaaaaa',
92
- },
93
- body: JSON.stringify({
94
- jsonrpc: '2.0',
95
- id: 1,
96
- method: 'initialize',
97
- params: {
98
- protocolVersion: '2025-03-26',
99
- capabilities: {},
100
- clientInfo: { name: 'invalid-token-test', version: '1.0.0' },
101
- },
102
- }),
103
- });
104
- assert.strictEqual(response.status, 401);
105
- const after = await getMetrics(mcpUrl);
106
- assert.strictEqual(after.activeSessions, before.activeSessions);
107
- assert.strictEqual(after.authenticatedSessions, before.authenticatedSessions);
108
- });
109
- test('should connect with Authorization Bearer header', async () => {
110
- const client = new CustomHeaderClient({
111
- 'authorization': `Bearer ${MOCK_TOKEN}`
112
- });
113
- await client.connect(mcpUrl);
114
- const tools = await client.listTools();
115
- assert.ok(tools.tools.length > 0, 'Should have tools');
116
- console.log(` ✓ Connected successfully, got ${tools.tools.length} tools`);
117
- await client.disconnect();
118
- });
119
- test('should connect with Private-Token header', async () => {
120
- const client = new CustomHeaderClient({
121
- 'private-token': MOCK_TOKEN
122
- });
123
- await client.connect(mcpUrl);
124
- const tools = await client.listTools();
125
- assert.ok(tools.tools.length > 0, 'Should have tools');
126
- console.log(` ✓ Connected with Private-Token, got ${tools.tools.length} tools`);
127
- await client.disconnect();
128
- });
129
- test('should connect with JOB-TOKEN header', async () => {
130
- const client = new CustomHeaderClient({
131
- 'job-token': MOCK_JOB_TOKEN,
132
- });
133
- await client.connect(mcpUrl);
134
- const tools = await client.listTools();
135
- assert.ok(tools.tools.length > 0, 'Should have tools');
136
- console.log(` ✓ Connected with JOB-TOKEN, got ${tools.tools.length} tools`);
137
- await client.disconnect();
138
- });
139
- test('should successfully call listTools with auth', async () => {
140
- const client = new CustomHeaderClient({
141
- 'authorization': `Bearer ${MOCK_TOKEN}`
142
- });
143
- await client.connect(mcpUrl);
144
- // List tools multiple times to verify auth persists
145
- const tools1 = await client.listTools();
146
- const tools2 = await client.listTools();
147
- const tools3 = await client.listTools();
148
- assert.ok(tools1.tools.length > 0, 'Should have tools');
149
- assert.strictEqual(tools1.tools.length, tools2.tools.length, 'Tool count should be consistent');
150
- assert.strictEqual(tools2.tools.length, tools3.tools.length, 'Tool count should be consistent');
151
- console.log(' ✓ Multiple tool list calls successful with persistent auth');
152
- await client.disconnect();
153
- });
154
- test('should expose Prometheus metrics at /metrics', async () => {
155
- const metricsUrl = mcpUrl.replace(/\/mcp$/, '/metrics');
156
- const response = await fetch(metricsUrl);
157
- assert.strictEqual(response.status, 200, 'metrics endpoint should be available');
158
- assert.match(response.headers.get('content-type') || '', /^text\/plain/);
159
- const body = await response.text();
160
- assert.match(body, /# HELP gitlab_mcp_requests_processed_total/);
161
- assert.match(body, /# TYPE gitlab_mcp_active_sessions gauge/);
162
- assert.match(body, /gitlab_mcp_config_info\{[^}]*remote_auth_enabled="true"/);
163
- console.log(' ✓ Prometheus metrics available');
164
- });
165
- test('should reject connection without auth header', async () => {
166
- const client = new CustomHeaderClient({});
167
- try {
168
- await client.connect(mcpUrl);
169
- await client.listTools();
170
- await client.disconnect();
171
- assert.fail('Should have rejected connection without auth');
172
- }
173
- catch (error) {
174
- assert.ok(error instanceof Error);
175
- console.log(' ✓ Correctly rejected connection without auth');
176
- }
177
- });
178
- });
179
- describe('Remote Authorization - Session Timeout', () => {
180
- let mcpUrl;
181
- let mockGitLab;
182
- let servers = [];
183
- before(async () => {
184
- // Use different port ranges to avoid collisions with basic tests
185
- const mockPort = await findMockServerPort();
186
- mockGitLab = new MockGitLabServer({
187
- port: mockPort,
188
- validTokens: [MOCK_TOKEN]
189
- });
190
- await mockGitLab.start();
191
- const mockGitLabUrl = mockGitLab.getUrl();
192
- const mcpPort = await findAvailablePort(MCP_SERVER_PORT_BASE + MCP_SERVER_PORT_OFFSET);
193
- const server = await launchServer({
194
- mode: TransportMode.STREAMABLE_HTTP,
195
- port: mcpPort,
196
- timeout: 5000,
197
- env: {
198
- STREAMABLE_HTTP: 'true',
199
- REMOTE_AUTHORIZATION: 'true',
200
- GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
201
- SESSION_TIMEOUT_SECONDS: String(SESSION_TIMEOUT_SECONDS),
202
- }
203
- });
204
- servers.push(server);
205
- mcpUrl = `http://${HOST}:${mcpPort}/mcp`;
206
- console.log(`Session timeout: ${SESSION_TIMEOUT_SECONDS} seconds`);
207
- });
208
- after(async () => {
209
- cleanupServers(servers);
210
- if (mockGitLab) {
211
- await mockGitLab.stop();
212
- }
213
- });
214
- test('session timeout verification - activity keeps session alive', async () => {
215
- const client = new CustomHeaderClient({
216
- 'authorization': `Bearer ${MOCK_TOKEN}`
217
- });
218
- // Connect and verify it works
219
- await client.connect(mcpUrl);
220
- const tools1 = await client.listTools();
221
- assert.ok(tools1.tools.length > 0, 'Initial connection should work');
222
- console.log(' ✓ Initial connection successful');
223
- // Keep connection alive with periodic requests
224
- console.log(' Keeping session alive with requests...');
225
- for (let i = 0; i < KEEPALIVE_REQUEST_COUNT; i++) {
226
- await new Promise(resolve => setTimeout(resolve, KEEPALIVE_INTERVAL_MS));
227
- const tools = await client.listTools();
228
- assert.ok(tools.tools.length > 0, `Request ${i + 1} should succeed`);
229
- console.log(` ✓ Request ${i + 1} succeeded (session still alive)`);
230
- }
231
- await client.disconnect();
232
- console.log(' ✓ Session remained active with periodic requests');
233
- });
234
- test('session timeout expiration - inactivity expires auth', async () => {
235
- // Add a small delay to ensure server is ready/clean from previous test
236
- await new Promise(resolve => setTimeout(resolve, 1000));
237
- const baseline = await getMetrics(mcpUrl);
238
- // Step 1: Connect WITH auth header to establish session
239
- const clientWithAuth = new CustomHeaderClient({
240
- 'authorization': `Bearer ${MOCK_TOKEN}`
241
- });
242
- await clientWithAuth.connect(mcpUrl);
243
- const tools1 = await clientWithAuth.listTools();
244
- assert.ok(tools1.tools.length > 0, 'Initial connection should work');
245
- console.log(' ✓ Initial connection successful with auth');
246
- // Extract session ID using proper API
247
- const sessionId = clientWithAuth.getSessionId();
248
- assert.ok(sessionId, 'Session ID should exist');
249
- console.log(` ℹ️ Session ID: ${sessionId}`);
250
- const beforeTimeout = await getMetrics(mcpUrl);
251
- assert.strictEqual(beforeTimeout.activeSessions, baseline.activeSessions + 1, 'Session should occupy one additional active slot');
252
- assert.strictEqual(beforeTimeout.authenticatedSessions, baseline.authenticatedSessions + 1, 'Session should add one authenticated session');
253
- // Step 2: Wait for timeout WITHOUT making any requests
254
- console.log(` ⏳ Waiting ${TIMEOUT_TEST_WAIT_MS / 1000}s for timeout without activity...`);
255
- await new Promise(resolve => setTimeout(resolve, TIMEOUT_TEST_WAIT_MS));
256
- await waitForSessionDecrease(mcpUrl, beforeTimeout);
257
- console.log(' ✓ Timeout closed transport and released active session slot');
258
- // Step 3: A stale stateful session must return the MCP re-initialization signal.
259
- const response = await fetch(mcpUrl, {
260
- method: 'POST',
261
- headers: {
262
- 'Content-Type': 'application/json',
263
- 'mcp-session-id': sessionId,
264
- },
265
- body: JSON.stringify({
266
- jsonrpc: '2.0',
267
- id: 1,
268
- method: 'tools/list'
269
- })
270
- });
271
- assert.strictEqual(response.status, 404, 'Should return 404 Session Not Found');
272
- assert.deepStrictEqual(await response.json(), { error: 'Session not found' });
273
- console.log(' ✓ Expired session returned 404 so the client can re-initialize');
274
- await clientWithAuth.disconnect();
275
- });
276
- });
277
- });