Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 | 219x 219x 219x 219x 219x 219x 219x 219x 219x 219x 83x 83x 1x 1x 82x 82x 7x 7x 75x 75x 2x 2x 73x 73x 73x 6x 6x 6x 67x 67x 38x 36x 26x 26x 3x 2x 2x 219x 38x 38x 1x 1x 37x 1x 1x 36x 1x 1x 35x 34x 4x 4x 30x 1x 1x 29x 2x 2x 27x 2x 2x 25x 1x 1x 24x 24x 1x 1x 23x 23x 1x 1x 22x 21x 21x 21x 21x 1x 1x 20x 20x 20x 26x 26x 1x 1x 25x 1x 1x 24x 24x 3x 3x 21x 1x 1x 20x 20x 1x 1x 23x 19x 36x 1x 1x 18x 18x 4x 4x 2x 2x 4x 14x 1x 1x 13x 13x 13x 13x 1x 1x 12x 12x 12x 43x 43x 37x 6x 34x 51x 51x 51x | /**
* OAuth Token Endpoint
*
* Handles token requests for:
* - authorization_code: Exchange authorization code for tokens
* - refresh_token: Refresh expired access tokens
*
* This endpoint issues MCP tokens (JWTs) to clients after successful
* GitLab authentication.
*/
import { Request, Response } from 'express';
import { loadOAuthConfig, OAuthConfig } from '../config';
import { sessionStore } from '../session-store';
import {
verifyCodeChallenge,
createJWT,
generateRefreshToken,
calculateTokenExpiry,
generateUUID,
} from '../token-utils';
import { withFreshGitLabToken, GitLabGrantRevokedError } from '../gitlab-token-refresh';
import { MCP_SCOPES, defaultResource, resourceParameter } from '../resource';
import { singleValuedParams } from '../request-params';
import { authenticateClient } from '../client-auth';
import { logInfo, logWarn, logError, truncateId } from '../../logger';
import { MCPTokenResponse, OAuthErrorResponse, OAuthSession } from '../types';
import { getIpAddress } from '../../utils/request-logger';
/**
* Token endpoint handler
*
* Handles POST /token requests for token operations.
*
* Supported grant types:
* - authorization_code: Exchange code for tokens (requires code_verifier for PKCE)
* - refresh_token: Refresh access token
*/
export async function tokenHandler(req: Request, res: Response): Promise<void> {
const config = loadOAuthConfig();
if (!config) {
sendError(req, res, 500, 'server_error', 'OAuth not configured');
return;
}
// Parameters are checked before anything is consumed: a malformed request must not
// spend the code or refresh token a valid retry needs.
// `resource` may repeat (RFC 8707 section 2) and is read separately.
const params = singleValuedParams(req.body, TOKEN_PARAMS);
if (typeof params === 'string') {
sendError(req, res, 400, 'invalid_request', `${params} must not be repeated`);
return;
}
const resource = resourceParameter(
config.issuer,
(req.body as { resource?: unknown } | undefined)?.resource,
);
if (resource === null) {
sendError(req, res, 400, 'invalid_target', 'resource must name one resource of this server');
return;
}
try {
// Client authentication precedes the grant, so a request with wrong credentials
// spends no code and no refresh token.
const client = await authenticateClient(req, params);
if (!client.authenticated) {
// RFC 6749 section 5.2: a client that tried the Authorization header gets the
// scheme it should use.
if (client.challenge) res.set('WWW-Authenticate', 'Basic realm="gitlab-mcp"');
sendError(req, res, client.status, client.error, client.description);
return;
}
const authenticated = { ...params, client_id: client.clientId };
switch (params.grant_type) {
case 'authorization_code':
await handleAuthorizationCode(req, res, config, authenticated, resource);
break;
case 'refresh_token':
await handleRefreshToken(req, res, config, authenticated, resource);
break;
default:
sendError(
req,
res,
400,
'unsupported_grant_type',
`Grant type "${params.grant_type}" is not supported`,
);
}
} catch (error: unknown) {
// Storage failures must not look like a granted or a refused token.
logError('Token request failed', { err: error as Error });
sendError(req, res, 500, 'server_error', 'Token service is temporarily unavailable');
}
}
const TOKEN_PARAMS = [
'grant_type',
'code',
'code_verifier',
'redirect_uri',
'client_id',
'client_secret',
'refresh_token',
'scope',
] as const;
type TokenParams = Partial<Record<(typeof TOKEN_PARAMS)[number], string>>;
/**
* Handle authorization code grant
*
* Exchanges an authorization code for access and refresh tokens.
* Requires PKCE code_verifier to match the original code_challenge.
*/
async function handleAuthorizationCode(
req: Request,
res: Response,
config: OAuthConfig,
params: TokenParams,
resource: string | undefined,
): Promise<void> {
const { code, code_verifier, redirect_uri, client_id } = params;
// Validate required parameters
if (!code) {
sendError(req, res, 400, 'invalid_request', 'Missing authorization code');
return;
}
if (!code_verifier) {
sendError(req, res, 400, 'invalid_request', 'Missing code_verifier (PKCE required)');
return;
}
// RFC 6749 section 4.1.3: a public client identifies itself on the code exchange.
if (!client_id) {
sendError(req, res, 400, 'invalid_request', 'Missing client_id');
return;
}
// Consume before any check so a code is presented at most once, whatever the outcome
// (RFC 6749 section 4.1.2); of concurrent exchanges on any replica only one gets it.
const authCode = await sessionStore.consumeAuthCode(code);
if (!authCode) {
sendError(req, res, 400, 'invalid_grant', 'Invalid or expired authorization code');
return;
}
// Check if code has expired
if (Date.now() > authCode.expiresAt) {
sendError(req, res, 400, 'invalid_grant', 'Authorization code has expired');
return;
}
// RFC 6749 section 4.1.3: the code must have been issued to this client.
if (client_id !== authCode.clientId) {
sendError(req, res, 400, 'invalid_grant', 'Authorization code was issued to another client');
return;
}
// Verify PKCE code challenge
if (!verifyCodeChallenge(code_verifier, authCode.codeChallenge, authCode.codeChallengeMethod)) {
sendError(req, res, 400, 'invalid_grant', 'Invalid code_verifier');
return;
}
// Verify redirect_uri matches (if it was provided in authorization)
if (authCode.redirectUri && redirect_uri !== authCode.redirectUri) {
sendError(req, res, 400, 'invalid_grant', 'redirect_uri does not match');
return;
}
// Get the session created during device flow
const session = await sessionStore.getSession(authCode.sessionId);
if (!session) {
sendError(req, res, 400, 'invalid_grant', 'Session not found');
return;
}
const audience = resolveResource(config, session, resource);
if (!audience) {
sendError(req, res, 400, 'invalid_target', 'resource does not match the authorization');
return;
}
// The client completed an authorization: its registration no longer expires. Recorded
// before any token exists, and a failure fails the exchange: an expired registration
// would let these refresh tokens through as a public client's, without the secret.
await sessionStore.markClientUsed(session.clientId);
// Generate MCP tokens
const accessToken = mintAccessToken(config, session, audience, session.scopes);
const refreshToken = generateRefreshToken();
// Update session with MCP tokens
const stored = await sessionStore.updateSession(session.id, {
mcpAccessToken: accessToken,
mcpRefreshToken: refreshToken,
mcpTokenExpiry: calculateTokenExpiry(config.tokenTtl),
resource: audience,
});
if (!stored) {
sendError(req, res, 400, 'invalid_grant', 'Session not found');
return;
}
logInfo('MCP tokens issued via authorization_code grant', {
sessionId: truncateId(session.id),
userId: session.gitlabUserId,
});
// Return token response
const response: MCPTokenResponse = {
access_token: accessToken,
token_type: 'Bearer',
expires_in: config.tokenTtl,
refresh_token: refreshToken,
scope: session.scopes.join(' '),
};
res.json(response);
}
/**
* Handle refresh token grant
*
* Issues new access and refresh tokens using a valid refresh token.
* Also refreshes the underlying GitLab token if needed.
*/
async function handleRefreshToken(
req: Request,
res: Response,
config: OAuthConfig,
params: TokenParams,
resource: string | undefined,
): Promise<void> {
const { refresh_token, client_id, scope } = params;
if (!refresh_token) {
sendError(req, res, 400, 'invalid_request', 'Missing refresh_token');
return;
}
// A public client identifies itself on refresh (OAuth 2.1 section 4.3.1).
if (!client_id) {
sendError(req, res, 400, 'invalid_request', 'Missing client_id');
return;
}
// Find session by refresh token
const session = await sessionStore.getSessionByRefreshToken(refresh_token);
if (!session) {
sendError(req, res, 400, 'invalid_grant', 'Invalid refresh token');
return;
}
// RFC 6749 section 6: the refresh token is bound to the client it was issued to.
if (client_id !== session.clientId) {
sendError(req, res, 400, 'invalid_grant', 'Refresh token was issued to another client');
return;
}
const audience = resolveResource(config, session, resource);
if (!audience) {
sendError(req, res, 400, 'invalid_target', 'resource does not match the authorization');
return;
}
// RFC 6749 section 6: a refresh may narrow the scope, never widen it. Values this server
// does not grant (openid, offline_access) are ignored as at /authorize, and a request of
// only such values keeps the original grant.
const requested = (scope ?? '').split(' ').filter((s) => MCP_SCOPES.includes(s));
const tokenScopes = requested.length === 0 ? session.scopes : [...new Set(requested)];
if (!tokenScopes.every((s) => session.scopes.includes(s))) {
sendError(req, res, 400, 'invalid_scope', 'scope exceeds the original grant');
return;
}
// GitLab first: until the rotation below commits, the client's refresh token stays
// valid, so a GitLab outage costs a retry rather than the account.
let updatedSession: OAuthSession | undefined;
try {
updatedSession = await withFreshGitLabToken(session, config);
} catch (error: unknown) {
logError('Failed to refresh GitLab token', { err: error as Error });
if (error instanceof GitLabGrantRevokedError) {
sendError(
req,
res,
400,
'invalid_grant',
'GitLab no longer accepts this account; sign in again',
);
} else {
sendError(
req,
res,
503,
'temporarily_unavailable',
'GitLab is temporarily unavailable; retry the refresh',
);
}
return;
}
if (!updatedSession) {
sendError(req, res, 400, 'invalid_grant', 'Session lost during refresh');
return;
}
const accessToken = mintAccessToken(config, updatedSession, audience, tokenScopes);
const newRefreshToken = generateRefreshToken();
// The refresh token is spent exactly once, by the caller whose compare-and-set wins on
// any replica (OAuth 2.1 section 4.3.1 rotation). The session keeps its scopes: a
// narrowed request narrows only this access token, and the new refresh token carries the
// original grant (RFC 6749 section 6: its scope MUST be identical to the presented one,
// and an omitted scope means the scope originally granted).
const rotated = await sessionStore.rotateSession(session.id, refresh_token, {
mcpAccessToken: accessToken,
mcpRefreshToken: newRefreshToken,
mcpTokenExpiry: calculateTokenExpiry(config.tokenTtl),
resource: audience,
});
if (!rotated) {
sendError(req, res, 400, 'invalid_grant', 'Invalid refresh token');
return;
}
logInfo('MCP tokens refreshed via refresh_token grant', {
sessionId: truncateId(updatedSession.id),
userId: updatedSession.gitlabUserId,
});
// Return token response
const response: MCPTokenResponse = {
access_token: accessToken,
token_type: 'Bearer',
expires_in: config.tokenTtl,
refresh_token: newRefreshToken,
scope: tokenScopes.join(' '),
};
res.json(response);
}
/**
* Audience for a token request: the resource the authorization was bound to, which a
* `resource` parameter may repeat but not change (RFC 8707 section 2.2). Undefined when
* the parameter names another resource of this server.
*/
function resolveResource(
config: OAuthConfig,
session: OAuthSession,
requested: string | undefined,
): string | undefined {
const bound = session.resource;
if (requested === undefined) {
return bound ?? defaultResource(config.issuer);
}
return bound === undefined || bound === requested ? requested : undefined;
}
/** Sign an MCP access token for the session (claims per RFC 9068 section 2.2). */
function mintAccessToken(
config: OAuthConfig,
session: OAuthSession,
audience: string,
scopes: string[],
): string {
return createJWT(
{
iss: config.issuer,
sub: session.gitlabUserId.toString(),
aud: audience,
client_id: session.clientId,
jti: generateUUID(),
sid: session.id,
scope: scopes.join(' '),
gitlab_user: session.gitlabUsername,
},
config.sessionSecret,
config.tokenTtl,
);
}
/**
* Send an OAuth error response
*
* Logs the error before sending the response for debugging and monitoring.
*/
function sendError(
req: Request,
res: Response,
status: number,
error: string,
description: string,
): void {
// Log OAuth error with structured context
logWarn('OAuth token request failed', {
event: 'oauth_error',
endpoint: '/token',
ip: getIpAddress(req),
error,
description,
});
const response: OAuthErrorResponse = {
error,
error_description: description,
};
res.status(status).json(response);
}
|