@giantswarm-io/pro 1.7.15 → 1.8.0
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/package.json +1 -1
- package/src/lib/auth/provider.js +167 -40
- package/src/lib/mcp/http.js +33 -8
package/package.json
CHANGED
package/src/lib/auth/provider.js
CHANGED
|
@@ -6,7 +6,12 @@
|
|
|
6
6
|
* proxying the actual authentication to GitHub.
|
|
7
7
|
*
|
|
8
8
|
* Flow:
|
|
9
|
-
* 1. MCP client
|
|
9
|
+
* 1. MCP client obtains a client_id, either by
|
|
10
|
+
* a. registering via /register (RFC 7591 dynamic client registration), or
|
|
11
|
+
* b. using the HTTPS URL of its Client ID Metadata Document (CIMD,
|
|
12
|
+
* SEP-991) directly as client_id — PRO fetches and validates the
|
|
13
|
+
* document on first use. The AS metadata advertises this with
|
|
14
|
+
* client_id_metadata_document_supported: true.
|
|
10
15
|
* 2. MCP client initiates /authorize with PKCE
|
|
11
16
|
* 3. PRO redirects to GitHub OAuth with our app's client_id
|
|
12
17
|
* 4. GitHub redirects back to /github/callback
|
|
@@ -14,14 +19,26 @@
|
|
|
14
19
|
* 6. MCP client exchanges local code for the GitHub token via /token
|
|
15
20
|
* 7. MCP requests include the GitHub token as Bearer auth
|
|
16
21
|
*
|
|
22
|
+
* State and restarts: everything here lives in process memory. A restart
|
|
23
|
+
* drops all dynamically registered client_ids (clients on path 1a get
|
|
24
|
+
* invalid_client and must register again), every in-flight authorization
|
|
25
|
+
* session (a login that is on GitHub when the pod restarts fails at
|
|
26
|
+
* /github/callback with "Invalid or expired authorization session" and has to
|
|
27
|
+
* be started over) and every not-yet-exchanged local authorization code.
|
|
28
|
+
* CIMD clients (path 1b) are unaffected: their client_id is re-resolved from
|
|
29
|
+
* the URL, which is why muster and Claude Code use it.
|
|
30
|
+
*
|
|
17
31
|
* Environment variables:
|
|
18
32
|
* GITHUB_OAUTH_CLIENT_ID - GitHub OAuth App client ID
|
|
19
33
|
* GITHUB_OAUTH_CLIENT_SECRET - GitHub OAuth App client secret
|
|
20
|
-
* OAUTH_TRUSTED_CLIENT_IDS - Comma-separated CIMD URLs
|
|
21
|
-
*
|
|
34
|
+
* OAUTH_TRUSTED_CLIENT_IDS - Comma-separated CIMD URLs that bypass the
|
|
35
|
+
* outbound URL policy below (e.g. a muster on a
|
|
36
|
+
* cluster-internal hostname). Public HTTPS CIMD
|
|
37
|
+
* URLs need no entry here.
|
|
22
38
|
*/
|
|
23
39
|
|
|
24
40
|
import { randomUUID } from 'crypto';
|
|
41
|
+
import net from 'node:net';
|
|
25
42
|
import { logger } from '../logger.js';
|
|
26
43
|
|
|
27
44
|
// TTL for authorization sessions (10 minutes)
|
|
@@ -32,8 +49,47 @@ const TOKEN_CACHE_TTL_MS = 5 * 60 * 1000;
|
|
|
32
49
|
const MAX_CLIENTS = 1000;
|
|
33
50
|
// GitHub OAuth scopes required by PRO's tools
|
|
34
51
|
const REQUIRED_GITHUB_SCOPES = ['repo', 'project', 'read:org'];
|
|
35
|
-
// TTL for
|
|
52
|
+
// TTL for resolved Client ID Metadata Documents (1 hour) — avoids re-fetching
|
|
53
|
+
// on every authorize/token call
|
|
36
54
|
const CIMD_CACHE_TTL_MS = 60 * 60 * 1000;
|
|
55
|
+
// TTL for remembering a CIMD URL that failed to resolve, so a flood of bogus
|
|
56
|
+
// URL client_ids does not become a flood of outbound fetches
|
|
57
|
+
const CIMD_NEGATIVE_CACHE_TTL_MS = 5 * 60 * 1000;
|
|
58
|
+
// Maximum number of CIMD clients (positive and negative entries) kept in memory
|
|
59
|
+
const MAX_CIMD_CLIENTS = 1000;
|
|
60
|
+
// Outbound fetch limits for CIMD documents
|
|
61
|
+
const CIMD_FETCH_TIMEOUT_MS = 5 * 1000;
|
|
62
|
+
const CIMD_MAX_BYTES = 64 * 1024;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Whether a client_id has the shape of a Client ID Metadata Document URL that
|
|
66
|
+
* this server is willing to fetch.
|
|
67
|
+
*
|
|
68
|
+
* SEP-991 requires an HTTPS URL with a non-root path (the same shape the MCP
|
|
69
|
+
* SDK client enforces on its own clientMetadataUrl). On top of that, since the
|
|
70
|
+
* client_id is attacker-controlled and resolving it means an outbound request
|
|
71
|
+
* from inside the cluster, refuse everything that would turn the fetch into an
|
|
72
|
+
* SSRF probe: IP literals, loopback, single-label and cluster-internal
|
|
73
|
+
* hostnames, embedded credentials, fragments.
|
|
74
|
+
*/
|
|
75
|
+
export function isCimdUrl(clientId) {
|
|
76
|
+
let url;
|
|
77
|
+
try {
|
|
78
|
+
url = new URL(clientId);
|
|
79
|
+
} catch {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
if (url.protocol !== 'https:') return false;
|
|
83
|
+
if (url.pathname === '' || url.pathname === '/') return false;
|
|
84
|
+
if (url.username || url.password || url.hash) return false;
|
|
85
|
+
|
|
86
|
+
const host = url.hostname;
|
|
87
|
+
if (net.isIP(host.replace(/^\[|\]$/g, '')) !== 0) return false;
|
|
88
|
+
if (host === 'localhost' || host.endsWith('.localhost')) return false;
|
|
89
|
+
if (!host.includes('.')) return false;
|
|
90
|
+
if (/\.(local|localdomain|internal|svc|home\.arpa)$/.test(host)) return false;
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
37
93
|
|
|
38
94
|
/**
|
|
39
95
|
* Create the GitHub OAuth provider.
|
|
@@ -44,8 +100,9 @@ const CIMD_CACHE_TTL_MS = 60 * 60 * 1000;
|
|
|
44
100
|
export function createGitHubOAuthProvider(config) {
|
|
45
101
|
const { clientId, clientSecret } = config;
|
|
46
102
|
|
|
47
|
-
// Trusted
|
|
48
|
-
// time so tests can set the env var before calling
|
|
103
|
+
// Trusted CIMD URLs that bypass the outbound URL policy in isCimdUrl — read
|
|
104
|
+
// at creation time so tests can set the env var before calling
|
|
105
|
+
// createGitHubOAuthProvider.
|
|
49
106
|
const trustedClientIds = (process.env.OAUTH_TRUSTED_CLIENT_IDS || '')
|
|
50
107
|
.split(',')
|
|
51
108
|
.map(s => s.trim())
|
|
@@ -78,58 +135,128 @@ export function createGitHubOAuthProvider(config) {
|
|
|
78
135
|
}, 60_000);
|
|
79
136
|
sweepInterval.unref();
|
|
80
137
|
|
|
81
|
-
//
|
|
82
|
-
|
|
138
|
+
// Resolved CIMD clients (URL client_id → { clientInfo | undefined, expiresAt }).
|
|
139
|
+
// Kept apart from `clients` so DCR churn can never evict them, and so a
|
|
140
|
+
// stale entry can keep serving while a refresh fails.
|
|
141
|
+
const cimdClients = new Map();
|
|
83
142
|
|
|
84
143
|
/**
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
144
|
+
* Validate a fetched Client ID Metadata Document and turn it into the
|
|
145
|
+
* client info shape the MCP SDK handlers expect. Returns undefined (after
|
|
146
|
+
* logging why) when the document is unusable.
|
|
88
147
|
*/
|
|
89
|
-
|
|
90
|
-
|
|
148
|
+
function clientInfoFromCimd(clientId, doc, trusted) {
|
|
149
|
+
const reject = (reason) => {
|
|
150
|
+
logger.warn(`OAuth: Rejected CIMD ${clientId}: ${reason}`);
|
|
91
151
|
return undefined;
|
|
152
|
+
};
|
|
153
|
+
if (!doc || typeof doc !== 'object' || Array.isArray(doc)) {
|
|
154
|
+
return reject('document is not a JSON object');
|
|
92
155
|
}
|
|
93
|
-
|
|
94
|
-
//
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
156
|
+
// The document must claim the URL it was fetched from as its client_id.
|
|
157
|
+
// Trusted (allowlisted) documents may omit it, but must not contradict it.
|
|
158
|
+
if (doc.client_id !== clientId && !(trusted && doc.client_id === undefined)) {
|
|
159
|
+
return reject(`client_id ${JSON.stringify(doc.client_id)} does not match the document URL`);
|
|
160
|
+
}
|
|
161
|
+
const redirectUris = doc.redirect_uris;
|
|
162
|
+
if (!Array.isArray(redirectUris) || redirectUris.length === 0 ||
|
|
163
|
+
!redirectUris.every(u => typeof u === 'string' && URL.canParse(u))) {
|
|
164
|
+
return reject('redirect_uris must be a non-empty array of URLs');
|
|
165
|
+
}
|
|
166
|
+
// A public document cannot hold a secret and we do not support
|
|
167
|
+
// private_key_jwt, so only public clients can identify via CIMD.
|
|
168
|
+
const authMethod = doc.token_endpoint_auth_method ?? 'none';
|
|
169
|
+
if (authMethod !== 'none') {
|
|
170
|
+
return reject(`unsupported token_endpoint_auth_method ${JSON.stringify(authMethod)}`);
|
|
98
171
|
}
|
|
172
|
+
const str = (v) => (typeof v === 'string' ? v : undefined);
|
|
173
|
+
return {
|
|
174
|
+
client_id: clientId,
|
|
175
|
+
client_id_issued_at: Math.floor(Date.now() / 1000),
|
|
176
|
+
client_name: str(doc.client_name),
|
|
177
|
+
client_uri: str(doc.client_uri),
|
|
178
|
+
redirect_uris: redirectUris,
|
|
179
|
+
grant_types: Array.isArray(doc.grant_types) ? doc.grant_types : ['authorization_code'],
|
|
180
|
+
response_types: Array.isArray(doc.response_types) ? doc.response_types : ['code'],
|
|
181
|
+
token_endpoint_auth_method: 'none',
|
|
182
|
+
scope: str(doc.scope)
|
|
183
|
+
};
|
|
184
|
+
}
|
|
99
185
|
|
|
186
|
+
/**
|
|
187
|
+
* Fetch a Client ID Metadata Document. Returns the parsed JSON or undefined.
|
|
188
|
+
*/
|
|
189
|
+
async function fetchCimd(clientId) {
|
|
100
190
|
try {
|
|
101
191
|
const res = await fetch(clientId, {
|
|
102
|
-
headers: { Accept: 'application/json', 'User-Agent': 'giantswarm-pro-mcp' }
|
|
192
|
+
headers: { Accept: 'application/json', 'User-Agent': 'giantswarm-pro-mcp' },
|
|
193
|
+
redirect: 'manual',
|
|
194
|
+
signal: AbortSignal.timeout(CIMD_FETCH_TIMEOUT_MS)
|
|
103
195
|
});
|
|
104
196
|
if (!res.ok) {
|
|
105
197
|
logger.warn(`OAuth: Failed to fetch CIMD from ${clientId}: ${res.status}`);
|
|
106
198
|
return undefined;
|
|
107
199
|
}
|
|
108
|
-
const
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
token_endpoint_auth_method: metadata.token_endpoint_auth_method || 'none',
|
|
120
|
-
scope: metadata.scope
|
|
121
|
-
};
|
|
122
|
-
|
|
123
|
-
clients.set(clientId, clientInfo);
|
|
124
|
-
cimdCache.set(clientId, { expiresAt: Date.now() + CIMD_CACHE_TTL_MS });
|
|
125
|
-
logger.info(`OAuth: Auto-registered trusted client ${clientId} (${metadata.client_name || 'unknown'})`);
|
|
126
|
-
return clientInfo;
|
|
200
|
+
const declared = Number(res.headers?.get?.('content-length'));
|
|
201
|
+
if (declared > CIMD_MAX_BYTES) {
|
|
202
|
+
logger.warn(`OAuth: Rejected CIMD ${clientId}: content-length ${declared} exceeds ${CIMD_MAX_BYTES} bytes`);
|
|
203
|
+
return undefined;
|
|
204
|
+
}
|
|
205
|
+
const text = await res.text();
|
|
206
|
+
if (text.length > CIMD_MAX_BYTES) {
|
|
207
|
+
logger.warn(`OAuth: Rejected CIMD ${clientId}: body exceeds ${CIMD_MAX_BYTES} bytes`);
|
|
208
|
+
return undefined;
|
|
209
|
+
}
|
|
210
|
+
return JSON.parse(text);
|
|
127
211
|
} catch (err) {
|
|
128
212
|
logger.warn(`OAuth: Error fetching CIMD from ${clientId}: ${err.message}`);
|
|
129
213
|
return undefined;
|
|
130
214
|
}
|
|
131
215
|
}
|
|
132
216
|
|
|
217
|
+
/**
|
|
218
|
+
* Resolve a URL client_id (SEP-991) to client info by fetching and
|
|
219
|
+
* validating its Client ID Metadata Document. Results — including failures
|
|
220
|
+
* for untrusted URLs — are cached; a trusted client's last good document
|
|
221
|
+
* keeps being served while a refresh fails. Returns undefined for anything
|
|
222
|
+
* that is not an acceptable CIMD URL or whose document does not validate.
|
|
223
|
+
*/
|
|
224
|
+
async function resolveCimdClient(clientId) {
|
|
225
|
+
const trusted = trustedClientIds.includes(clientId);
|
|
226
|
+
if (!trusted && !isCimdUrl(clientId)) {
|
|
227
|
+
return undefined;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const now = Date.now();
|
|
231
|
+
const cached = cimdClients.get(clientId);
|
|
232
|
+
if (cached && now < cached.expiresAt) {
|
|
233
|
+
return cached.clientInfo;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const doc = await fetchCimd(clientId);
|
|
237
|
+
let clientInfo = doc === undefined ? undefined : clientInfoFromCimd(clientId, doc, trusted);
|
|
238
|
+
|
|
239
|
+
if (clientInfo) {
|
|
240
|
+
logger.info(`OAuth: Resolved CIMD client ${clientId} (${clientInfo.client_name || 'unknown'})`);
|
|
241
|
+
} else if (cached?.clientInfo) {
|
|
242
|
+
// Refresh failed: keep the last good document a little longer rather
|
|
243
|
+
// than locking the client out over a transient upstream problem.
|
|
244
|
+
logger.warn(`OAuth: Keeping previously resolved CIMD client ${clientId} after failed refresh`);
|
|
245
|
+
clientInfo = cached.clientInfo;
|
|
246
|
+
} else if (trusted) {
|
|
247
|
+
// Never negative-cache a trusted client: the next attempt should retry.
|
|
248
|
+
return undefined;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
if (!cimdClients.has(clientId) && cimdClients.size >= MAX_CIMD_CLIENTS) {
|
|
252
|
+
const oldestKey = cimdClients.keys().next().value;
|
|
253
|
+
cimdClients.delete(oldestKey);
|
|
254
|
+
}
|
|
255
|
+
const ttl = clientInfo && clientInfo !== cached?.clientInfo ? CIMD_CACHE_TTL_MS : CIMD_NEGATIVE_CACHE_TTL_MS;
|
|
256
|
+
cimdClients.set(clientId, { clientInfo, expiresAt: now + ttl });
|
|
257
|
+
return clientInfo;
|
|
258
|
+
}
|
|
259
|
+
|
|
133
260
|
/**
|
|
134
261
|
* Verify a GitHub access token by calling the GitHub API.
|
|
135
262
|
* Validates that the token has all required scopes.
|
|
@@ -190,8 +317,8 @@ export function createGitHubOAuthProvider(config) {
|
|
|
190
317
|
async getClient(clientId) {
|
|
191
318
|
const existing = clients.get(clientId);
|
|
192
319
|
if (existing) return existing;
|
|
193
|
-
//
|
|
194
|
-
return await
|
|
320
|
+
// URL client_ids resolve to their Client ID Metadata Document
|
|
321
|
+
return await resolveCimdClient(clientId);
|
|
195
322
|
},
|
|
196
323
|
|
|
197
324
|
registerClient(clientMetadata) {
|
package/src/lib/mcp/http.js
CHANGED
|
@@ -42,11 +42,12 @@ const sessions = {};
|
|
|
42
42
|
/**
|
|
43
43
|
* Start the MCP server with streamable HTTP transport
|
|
44
44
|
* @param {Object} options
|
|
45
|
-
* @param {number} options.port - Port to listen on (default: 8080)
|
|
45
|
+
* @param {number} options.port - Port to listen on (default: 8080; 0 picks a free port)
|
|
46
46
|
* @param {string} options.endpoint - MCP endpoint path (default: /mcp)
|
|
47
|
+
* @returns {Promise<import('http').Server>} the listening server
|
|
47
48
|
*/
|
|
48
49
|
export async function startHTTPServer(options = {}) {
|
|
49
|
-
const port = options.port
|
|
50
|
+
const port = options.port ?? (parseInt(process.env.HTTP_PORT, 10) || DEFAULT_PORT);
|
|
50
51
|
const endpoint = options.endpoint || DEFAULT_ENDPOINT;
|
|
51
52
|
|
|
52
53
|
const app = express();
|
|
@@ -63,7 +64,8 @@ export async function startHTTPServer(options = {}) {
|
|
|
63
64
|
let bearerAuthMiddleware = null;
|
|
64
65
|
|
|
65
66
|
if (oauthClientId && oauthClientSecret) {
|
|
66
|
-
const { mcpAuthRouter } = await import('@modelcontextprotocol/sdk/server/auth/router.js');
|
|
67
|
+
const { mcpAuthRouter, createOAuthMetadata } = await import('@modelcontextprotocol/sdk/server/auth/router.js');
|
|
68
|
+
const { metadataHandler } = await import('@modelcontextprotocol/sdk/server/auth/handlers/metadata.js');
|
|
67
69
|
const { requireBearerAuth } = await import('@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js');
|
|
68
70
|
const { createGitHubOAuthProvider } = await import('../auth/provider.js');
|
|
69
71
|
|
|
@@ -74,13 +76,30 @@ export async function startHTTPServer(options = {}) {
|
|
|
74
76
|
clientSecret: oauthClientSecret
|
|
75
77
|
});
|
|
76
78
|
|
|
77
|
-
|
|
78
|
-
app.use(mcpAuthRouter({
|
|
79
|
+
const authRouterOptions = {
|
|
79
80
|
provider,
|
|
80
81
|
issuerUrl,
|
|
81
82
|
scopesSupported: ['repo', 'project', 'read:org'],
|
|
82
83
|
resourceName: 'Giant Swarm PRO MCP Server'
|
|
83
|
-
}
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
// RFC 8414 authorization server metadata. mcpAuthRouter builds this same
|
|
87
|
+
// document internally but offers no way to extend it, so build it here,
|
|
88
|
+
// add the SEP-991 flag and mount the well-known route before the router:
|
|
89
|
+
// Express dispatches in registration order, so this copy wins over the
|
|
90
|
+
// router's own.
|
|
91
|
+
const oauthMetadata = {
|
|
92
|
+
...createOAuthMetadata(authRouterOptions),
|
|
93
|
+
// Clients may use the HTTPS URL of their Client ID Metadata Document as
|
|
94
|
+
// client_id instead of registering (resolved in clientsStore.getClient).
|
|
95
|
+
// Muster and Claude Code pick this path only when it is advertised; it
|
|
96
|
+
// is what lets them survive a restart of this in-memory client store.
|
|
97
|
+
client_id_metadata_document_supported: true
|
|
98
|
+
};
|
|
99
|
+
app.use('/.well-known/oauth-authorization-server', metadataHandler(oauthMetadata));
|
|
100
|
+
|
|
101
|
+
// Mount OAuth routes: /authorize, /token, /register, /.well-known/*
|
|
102
|
+
app.use(mcpAuthRouter(authRouterOptions));
|
|
84
103
|
|
|
85
104
|
// GitHub OAuth callback (not part of MCP spec — specific to our proxy)
|
|
86
105
|
app.get('/github/callback', handleGitHubCallback);
|
|
@@ -207,8 +226,12 @@ export async function startHTTPServer(options = {}) {
|
|
|
207
226
|
sweepInterval.unref();
|
|
208
227
|
|
|
209
228
|
// Start listening
|
|
210
|
-
const httpServer =
|
|
211
|
-
|
|
229
|
+
const httpServer = await new Promise((resolve, reject) => {
|
|
230
|
+
const server = app.listen(port, () => {
|
|
231
|
+
logger.info(`MCP HTTP server listening on port ${server.address().port} (endpoint: ${endpoint})`);
|
|
232
|
+
resolve(server);
|
|
233
|
+
});
|
|
234
|
+
server.once('error', reject);
|
|
212
235
|
});
|
|
213
236
|
|
|
214
237
|
// Graceful shutdown
|
|
@@ -230,4 +253,6 @@ export async function startHTTPServer(options = {}) {
|
|
|
230
253
|
|
|
231
254
|
process.on('SIGINT', shutdown);
|
|
232
255
|
process.on('SIGTERM', shutdown);
|
|
256
|
+
|
|
257
|
+
return httpServer;
|
|
233
258
|
}
|