All files / src/oauth/endpoints callback.ts

100% Statements 82/82
100% Branches 38/38
100% Functions 3/3
100% Lines 81/81

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                                  221x 221x 221x 221x 221x 221x 221x 221x 221x 221x 221x 221x 221x 221x       221x                     36x                               221x 85x 85x 1x       1x     84x 84x     84x 36x 36x 36x   36x 34x 1x 1x       34x 34x   11x       11x   23x 12x             12x     13x       13x       48x 1x       1x     47x 1x       1x             46x 46x   1x 1x       1x   45x 2x       2x       43x 1x 1x       42x 3x 3x       3x     39x   39x 39x 1x       38x     32x       30x 30x     30x       30x                                         29x                     29x 1x 1x       1x     28x           28x         28x             10x     10x                    
/**
 * OAuth Callback Endpoint
 *
 * Handles the callback from GitLab after user authorization in Authorization Code Flow.
 * This endpoint receives the GitLab authorization code, exchanges it for tokens,
 * creates a session, and redirects back to the client with an MCP authorization code.
 *
 * Flow:
 * 1. User completes GitLab authorization
 * 2. GitLab redirects to /oauth/callback with code and state
 * 3. We exchange GitLab code for GitLab tokens
 * 4. We create a session with GitLab tokens
 * 5. We generate an MCP authorization code
 * 6. We redirect to client's redirect_uri with MCP code
 */
 
import { Request, Response } from 'express';
import { loadOAuthConfig } from '../config';
import { sessionStore } from '../session-store';
import { exchangeFlowCode } from '../code-exchange';
import { discardAuthCodeFlow, revokeAbandonedFlowGrant } from '../grant-revocation';
import { getGitLabUser } from '../gitlab-device-flow';
import { completeAccountLink, failAccountLink } from '../../accounts/link';
import { generateSessionId, generateAuthorizationCode, calculateTokenExpiry } from '../token-utils';
import { logInfo, logWarn, logError, logDebug, truncateId } from '../../logger';
import { GITLAB_BASE_URL } from '../../config';
import { grantedGitlabScopes } from '../granted-scopes';
import { MCP_SCOPES } from '../resource';
import { authorizationRedirect } from '../authorization-response';
import { oauthAppFor } from '../instance-app';
import { discardCompletion } from './authorize';
 
// Provider callback parameters are untrusted diagnostic content, including the error code.
// https://www.rfc-editor.org/rfc/rfc6749#section-4.1.2.1
const AUTHORIZATION_ERRORS = new Set([
  'invalid_request',
  'unauthorized_client',
  'access_denied',
  'unsupported_response_type',
  'invalid_scope',
  'server_error',
  'temporarily_unavailable',
]);
 
function authorizationErrorCode(value: unknown): string {
  return typeof value === 'string' && AUTHORIZATION_ERRORS.has(value) ? value : 'server_error';
}
 
/**
 * OAuth callback handler
 *
 * Handles GET /oauth/callback from GitLab after user authorization.
 *
 * Query parameters (from GitLab):
 * - code: GitLab authorization code
 * - state: Internal state we sent to GitLab (maps to AuthCodeFlowState)
 *
 * On success, redirects to client's redirect_uri with:
 * - code: MCP authorization code (for /token exchange)
 * - state: Original client state (for CSRF verification)
 */
export async function callbackHandler(req: Request, res: Response): Promise<void> {
  const config = loadOAuthConfig();
  if (!config) {
    res.status(500).json({
      error: 'server_error',
      error_description: 'OAuth not configured',
    });
    return;
  }
 
  const query = req.query;
  const { code, state, error } = query as Record<string, string | undefined>;
 
  // Handle GitLab error responses
  if (Object.hasOwn(query, 'error')) {
    const safeError = authorizationErrorCode(error);
    const description = 'GitLab authorization failed';
    logWarn('GitLab authorization error', { error: safeError });
    // Redirect to client with error if we can find the flow state
    if (state) {
      const flow = await sessionStore.consumeAuthCodeFlow(state).catch((err: unknown) => {
        logError('Failed to read authorization flow', { err: err as Error });
        return undefined;
      });
      // An earlier delivery may have exchanged the code and kept its tokens for a retry;
      // the flow is spent now, so nothing else would end that grant.
      if (flow) await revokeAbandonedFlowGrant(flow, config);
      if (flow?.link) {
        // The reason is in the log above; the page shows no text taken from the request.
        failAccountLink(
          res,
          'GitLab did not authorize the account. Ask for a new link in the chat to try again.',
        );
        return;
      }
      if (flow) {
        res.redirect(
          authorizationRedirect(flow.clientRedirectUri, config.issuer, {
            error: safeError,
            error_description: description,
            state: flow.clientState,
          }),
        );
        return;
      }
    }
    res.status(400).json({
      error: safeError,
      error_description: description,
    });
    return;
  }
 
  // Validate required parameters
  if (!code) {
    res.status(400).json({
      error: 'invalid_request',
      error_description: 'Missing authorization code from GitLab',
    });
    return;
  }
 
  if (!state) {
    res.status(400).json({
      error: 'invalid_request',
      error_description: 'Missing state parameter',
    });
    return;
  }
 
  // The flow stays until the account is set up: GitLab's code works once, so a callback
  // that fails after the exchange keeps the issued tokens with the flow and a retried
  // callback finishes with them.
  let flow;
  try {
    flow = await sessionStore.getAuthCodeFlow(state);
  } catch (err: unknown) {
    logError('Failed to read authorization flow', { err: err as Error });
    res.status(503).json({
      error: 'temporarily_unavailable',
      error_description: 'Authorization storage is unavailable. Please try again.',
    });
    return;
  }
  if (!flow) {
    res.status(400).json({
      error: 'invalid_request',
      error_description: 'Invalid or expired state. Please start authorization again.',
    });
    return;
  }
 
  // Linking another account ends on a page of its own, not at a client's redirect URI.
  if (flow.link) {
    await completeAccountLink(res, state, flow, code, config);
    return;
  }
 
  // Check if flow has expired
  if (Date.now() > flow.expiresAt) {
    await discardAuthCodeFlow(state, flow, config);
    res.status(400).json({
      error: 'invalid_request',
      error_description: 'Authorization flow expired. Please start again.',
    });
    return;
  }
 
  try {
    // The instance chosen at /authorize; never another one if it is no longer configured.
    const app = await oauthAppFor(config, flow.selectedInstance);
    if (!app) {
      throw new Error('GitLab instance is no longer configured');
    }
 
    const gitlabTokens =
      flow.gitlabTokens ?? (await exchangeFlowCode(state, flow, code, config, app));
 
    // Get GitLab user info
    const userInfo = await getGitLabUser(gitlabTokens.access_token, app.baseUrl);
 
    // The session and code are stored before the flow is consumed: until then the flow
    // keeps GitLab's tokens, so a storage failure here is retried by reloading the callback.
    const sessionId = generateSessionId();
    const now = Date.now();
 
    // Generate MCP authorization code for the client
    const mcpAuthCode = generateAuthorizationCode();
 
    // Create session with GitLab tokens before the code that references it.
    // MCP tokens will be set when the authorization code is exchanged via /token
    await sessionStore.createSession({
      id: sessionId,
      mcpAccessToken: '', // Set on /token
      mcpRefreshToken: '', // Set on /token
      mcpTokenExpiry: 0, // Set on /token
      gitlabAccessToken: gitlabTokens.access_token,
      gitlabRefreshToken: gitlabTokens.refresh_token,
      gitlabTokenExpiry: calculateTokenExpiry(gitlabTokens.expires_in),
      gitlabScopes: grantedGitlabScopes(gitlabTokens.scope, flow.requestedGitlabScopes),
      gitlabUserId: userInfo.id,
      gitlabUsername: userInfo.username,
      gitlabApiUrl: flow.selectedInstance ?? GITLAB_BASE_URL,
      instanceLabel: flow.selectedInstanceLabel,
      clientId: flow.clientId,
      scopes: flow.scopes ?? [...MCP_SCOPES],
      resource: flow.resource,
      createdAt: now,
      updatedAt: now,
    });
 
    // Store MCP authorization code (single-use, expires in 10 minutes)
    await sessionStore.storeAuthCode({
      code: mcpAuthCode,
      sessionId,
      clientId: flow.clientId,
      codeChallenge: flow.codeChallenge,
      codeChallengeMethod: flow.codeChallengeMethod,
      redirectUri: flow.clientRedirectUri,
      expiresAt: now + 10 * 60 * 1000, // 10 minutes
    });
 
    // Exactly one callback completes the flow; another one removes what it created.
    if (!(await sessionStore.consumeAuthCodeFlow(state))) {
      await discardCompletion(sessionId, mcpAuthCode);
      res.status(400).json({
        error: 'invalid_request',
        error_description: 'Authorization was already completed.',
      });
      return;
    }
 
    logInfo('Authorization Code Flow completed successfully', {
      sessionId: truncateId(sessionId),
      userId: userInfo.id,
      username: userInfo.username,
    });
 
    logDebug('Redirecting to client with authorization code', {
      redirectUri: flow.clientRedirectUri,
    });
 
    // Redirect to client with MCP authorization code
    res.redirect(
      authorizationRedirect(flow.clientRedirectUri, config.issuer, {
        code: mcpAuthCode,
        state: flow.clientState,
      }),
    );
  } catch (error: unknown) {
    logError('Failed to complete authorization code flow', { err: error as Error });
 
    // The flow is kept unless it was completed, so the callback can be retried
    res.redirect(
      authorizationRedirect(flow.clientRedirectUri, config.issuer, {
        error: 'server_error',
        error_description:
          error instanceof Error ? error.message : 'Failed to complete authorization',
        state: flow.clientState,
      }),
    );
  }
}