All files / src/oauth gitlab-device-flow.ts

99.14% Statements 116/117
94.23% Branches 49/52
100% Functions 20/20
99.13% Lines 114/115

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 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573                    233x     233x 233x 233x           233x     86x 86x   86x 86x               233x                                 74x 64x                 233x   11x 11x                 233x                   123x   71x 71x       71x 71x                   60x 6x 6x                                       233x                 171x         121x                                 233x       16x   16x     16x   16x                         16x   6x   5x           5x                             233x         45x   45x                           45x 11x 10x 10x       34x 34x         34x   7x     3x 3x     2x     4x     3x     15x 15x                                     233x         10x   5x                               233x           5x 5x 5x   5x   10x   10x 10x   9x 3x     6x 1x       6x     1x 1x         1x                 1x                             233x         34x   34x           34x   34x                   34x   6x 5x 5x                         233x       31x   31x               31x   19x   18x   18x                                 233x       3x 3x   3x               2x   1x                               233x           30x   30x             30x   30x                   30x   18x       16x 16x                     233x         12x                   12x 3x                           233x             16x   16x               16x             10x    
/**
 * GitLab Device Flow Client
 *
 * Implements the OAuth 2.0 Device Authorization Grant (RFC 8628) for GitLab.
 * This allows authentication on devices without browser access by having
 * users authenticate on a separate device.
 *
 * GitLab Device Flow documentation: https://docs.gitlab.com/api/oauth2/#device-authorization-grant
 */
 
import { GITLAB_BASE_URL } from '../config';
import { OAuthConfig } from './config';
import { GitLabDeviceResponse, GitLabTokenResponse, GitLabUserInfo } from './types';
import { logInfo, logWarn, logError, logDebug } from '../logger';
import { enhancedFetch, type FetchWithRetryOptions } from '../utils/fetch';
import { defaultOAuthApp, type GitLabOAuthApp } from './oauth-app';
 
/**
 * A GitLab OAuth endpoint answered with an error status; `oauthError` is the RFC 6749
 * section 5.2 error code when the body carried one.
 */
export class GitLabOAuthHttpError extends Error {
  constructor(
    message: string,
    readonly status: number,
    readonly oauthError?: string,
  ) {
    super(message);
    this.name = 'GitLabOAuthHttpError';
  }
}
 
// Only protocol codes cross the provider-to-diagnostics boundary, never free-form text.
// https://www.rfc-editor.org/rfc/rfc6749#section-5.2
// https://www.rfc-editor.org/rfc/rfc6749#section-4.1.2.1
// https://www.rfc-editor.org/rfc/rfc8628#section-3.5
const OAUTH_ERROR_CODES = new Set([
  'invalid_request',
  'invalid_client',
  'invalid_grant',
  'unauthorized_client',
  'unsupported_grant_type',
  'invalid_scope',
  'authorization_pending',
  'slow_down',
  'access_denied',
  'expired_token',
  'server_error',
  'temporarily_unavailable',
]);
 
/** Return an exact known protocol code without retaining any other provider content. */
function oauthErrorCode(body: unknown): string | undefined {
  if (typeof body !== 'object' || body === null || !('error' in body)) return undefined;
  return typeof body.error === 'string' && OAUTH_ERROR_CODES.has(body.error)
    ? body.error
    : undefined;
}
 
/**
 * GitLab refused the device grant for good (RFC 8628 section 3.5: access_denied,
 * expired_token; or another OAuth error a retry cannot fix). The flow cannot complete.
 */
export class DeviceGrantRefusedError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'DeviceGrantRefusedError';
  }
}
 
/**
 * Token endpoint errors that refuse the request for good (RFC 6749 section 5.2). Any other
 * body (server_error, a rate limit, an intermediary's error) is retried by the next poll
 * until the device code expires.
 */
const TERMINAL_DEVICE_ERRORS = new Set([
  'invalid_request',
  'invalid_client',
  'unauthorized_client',
  'unsupported_grant_type',
  'invalid_scope',
]);
 
/** Throw a descriptive error if the GitLab OAuth response indicates failure */
async function throwOnHttpError(response: Response, operation: string): Promise<void> {
  if (!response.ok) {
    let code: string | undefined;
    try {
      code = oauthErrorCode(JSON.parse(await response.text()));
    } catch {
      // Parsing and body-read errors can contain response excerpts; keep only the HTTP status.
    }
    logError(`Failed to ${operation}`, { status: response.status, oauthError: code });
    throw new GitLabOAuthHttpError(
      `Failed to ${operation}: ${response.status}${code ? ` ${code}` : ''}`,
      response.status,
      code,
    );
  }
}
 
/** JSON parsers can quote provider content; do not propagate their errors or causes. */
function readGitLabResponse<T>(response: Response, operation: string): Promise<T> {
  return response.json().catch(() => {
    logError(`Failed to read ${operation} response`, { status: response.status });
    throw new Error(`Failed to read ${operation} response: ${response.status}`);
  }) as Promise<T>;
}
 
/**
 * Shared options for OAuth endpoint calls — no retry, no rate limiting,
 * no ambient auth injection.
 *
 * skipAuth suppresses auto-injected credentials (PAT from env, cookies) so OAuth
 * endpoints only receive explicitly provided auth (Bearer token in headers or
 * client_id/secret in POST body). Caller-supplied headers are never stripped.
 *
 * rateLimitBaseUrl is set even with rate limiting disabled so enhancedFetch can
 * consistently select the correct per-instance dispatcher. Without it, OAuth paths
 * like /oauth/token don't match extractBaseUrl()'s /api/v4|/api/graphql stripping,
 * causing fallback to the global dispatcher (missing per-instance TLS settings).
 */
const OAUTH_FETCH_OPTS: Pick<
  FetchWithRetryOptions,
  'retry' | 'rateLimit' | 'rateLimitBaseUrl' | 'skipAuth'
> = {
  retry: false,
  rateLimit: false,
  rateLimitBaseUrl: GITLAB_BASE_URL,
  skipAuth: true,
};
 
/** OAuth fetch options bound to the instance the call goes to (its dispatcher and TLS). */
function oauthFetchOpts(baseUrl: string): typeof OAUTH_FETCH_OPTS {
  return { ...OAUTH_FETCH_OPTS, rateLimitBaseUrl: baseUrl };
}
 
/** Application credentials for a token request; the secret only for confidential apps. */
function clientParams(app: GitLabOAuthApp): Record<string, string> {
  return app.clientSecret
    ? { client_id: app.clientId, client_secret: app.clientSecret }
    : { client_id: app.clientId };
}
 
/**
 * Initiate the device authorization flow with GitLab
 *
 * This starts the device flow by requesting a device code and user code
 * from GitLab. The user must then visit the verification URI and enter
 * the user code to authorize the application.
 *
 * @param config - OAuth configuration
 * @param app - Instance and application to sign in with (default: OAUTH_CLIENT_ID on GITLAB_API_URL)
 * @returns Device authorization response with codes and URIs
 * @throws Error if the request fails
 */
export async function initiateDeviceFlow(
  config: OAuthConfig,
  app: GitLabOAuthApp = defaultOAuthApp(config),
): Promise<GitLabDeviceResponse> {
  const url = `${app.baseUrl}/oauth/authorize_device`;
 
  logDebug('Initiating GitLab device flow', { url, clientId: app.clientId });
 
  // Convert comma-separated scopes to space-separated (GitLab requirement)
  const scopes = app.scopes.replaceAll(',', ' ');
 
  const response = await enhancedFetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    body: new URLSearchParams({
      client_id: app.clientId,
      scope: scopes,
    }),
    ...oauthFetchOpts(app.baseUrl),
  });
 
  await throwOnHttpError(response, 'initiate device flow');
 
  const data = await readGitLabResponse<GitLabDeviceResponse>(response, 'initiate device flow');
 
  logInfo('Device flow initiated', {
    userCode: data.user_code,
    verificationUri: data.verification_uri,
    expiresIn: data.expires_in,
  });
 
  return data;
}
 
/** Outcome of one device token request. */
export type DeviceFlowPollStep =
  | { status: 'complete'; tokens: GitLabTokenResponse }
  | { status: 'pending' }
  | { status: 'slow_down' };
 
/**
 * Poll GitLab once, distinguishing `slow_down` from `authorization_pending` so the caller
 * can increase its interval (RFC 8628 section 3.5).
 *
 * @throws Error for terminal errors (expired, denied, etc.)
 */
export async function pollDeviceFlowStep(
  deviceCode: string,
  config: OAuthConfig,
  app: GitLabOAuthApp = defaultOAuthApp(config),
): Promise<DeviceFlowPollStep> {
  const url = `${app.baseUrl}/oauth/token`;
 
  const response = await enhancedFetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    body: new URLSearchParams({
      ...clientParams(app),
      device_code: deviceCode,
      grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
    }),
    ...oauthFetchOpts(app.baseUrl),
  });
 
  if (response.ok) {
    const tokens = await readGitLabResponse<GitLabTokenResponse>(response, 'poll device flow');
    logInfo('Device flow authorization completed successfully');
    return { status: 'complete', tokens };
  }
 
  let code: string | undefined;
  try {
    code = oauthErrorCode(await response.json());
  } catch {
    // A malformed proxy response must not expose parser excerpts through a polling error.
  }
 
  switch (code) {
    case 'authorization_pending':
      return { status: 'pending' };
 
    case 'slow_down':
      logDebug('Device flow: slow_down received, increasing poll interval');
      return { status: 'slow_down' };
 
    case 'expired_token':
      throw new DeviceGrantRefusedError('Device code expired. Please start a new authorization.');
 
    case 'access_denied':
      throw new DeviceGrantRefusedError('User denied the authorization request.');
 
    case 'invalid_grant':
      throw new DeviceGrantRefusedError('Invalid device code or grant.');
 
    default: {
      const message = `Device flow error: ${response.status}${code ? ` ${code}` : ''}`;
      throw code !== undefined && TERMINAL_DEVICE_ERRORS.has(code)
        ? new DeviceGrantRefusedError(message)
        : new Error(message);
    }
  }
}
 
/**
 * Poll GitLab for device authorization completion (single attempt)
 *
 * Makes a single poll request to check if the user has completed authorization.
 * Returns the token response if authorized, null if still pending.
 *
 * @param deviceCode - Device code from initiateDeviceFlow
 * @param config - OAuth configuration
 * @param app - Application the device code was issued for
 * @returns Token response if authorized, null if pending
 * @throws Error for terminal errors (expired, denied, etc.)
 */
export async function pollDeviceFlowOnce(
  deviceCode: string,
  config: OAuthConfig,
  app: GitLabOAuthApp = defaultOAuthApp(config),
): Promise<GitLabTokenResponse | null> {
  const step = await pollDeviceFlowStep(deviceCode, config, app);
  // pending and slow_down both mean "not yet"; callers that back off use pollDeviceFlowStep.
  return step.status === 'complete' ? step.tokens : null;
}
 
/**
 * Poll GitLab for device authorization completion (with retries)
 *
 * Continuously polls GitLab until the user completes authorization,
 * the device code expires, or the user denies the request.
 *
 * @param deviceCode - Device code from initiateDeviceFlow
 * @param config - OAuth configuration
 * @param onPending - Optional callback called on each pending poll
 * @param app - Application the device code was issued for
 * @returns Token response when authorized
 * @throws Error on timeout, expiration, or denial
 */
export async function pollForToken(
  deviceCode: string,
  config: OAuthConfig,
  onPending?: () => void,
  app: GitLabOAuthApp = defaultOAuthApp(config),
): Promise<GitLabTokenResponse> {
  const startTime = Date.now();
  const timeout = config.deviceTimeout * 1000;
  let interval = config.devicePollInterval * 1000;
 
  while (Date.now() - startTime < timeout) {
    // Wait before polling
    await sleep(interval);
 
    try {
      const step = await pollDeviceFlowStep(deviceCode, config, app);
 
      if (step.status === 'complete') {
        return step.tokens;
      }
      // RFC 8628 section 3.5: slow_down adds 5 seconds to every later interval.
      if (step.status === 'slow_down') {
        interval += 5000;
      }
 
      // Still pending
      onPending?.();
    } catch (error) {
      // Re-throw terminal errors
      Eif (error instanceof Error) {
        Eif (
          error.message.includes('expired') ||
          error.message.includes('denied') ||
          error.message.includes('invalid')
        ) {
          throw error;
        }
      }
 
      // Log but continue for transient errors
      logWarn('Device flow poll error, will retry', { err: error as Error });
    }
  }
 
  throw new Error(`Device flow timeout after ${config.deviceTimeout} seconds`);
}
 
/**
 * Refresh a GitLab OAuth token
 *
 * Uses the refresh token to obtain a new access token when the current
 * one is expired or about to expire.
 *
 * @param refreshToken - GitLab refresh token
 * @param config - OAuth configuration
 * @param app - Application that issued the refresh token
 * @returns New token response
 * @throws Error if refresh fails
 */
export async function refreshGitLabToken(
  refreshToken: string,
  config: OAuthConfig,
  app: GitLabOAuthApp = defaultOAuthApp(config),
): Promise<GitLabTokenResponse> {
  const url = `${app.baseUrl}/oauth/token`;
 
  const params: Record<string, string> = {
    ...clientParams(app),
    refresh_token: refreshToken,
    grant_type: 'refresh_token',
  };
 
  logDebug('Refreshing GitLab token');
 
  const response = await enhancedFetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    body: new URLSearchParams(params),
    ...oauthFetchOpts(app.baseUrl),
  });
 
  await throwOnHttpError(response, 'refresh token');
 
  const data = await readGitLabResponse<GitLabTokenResponse>(response, 'refresh token');
  logInfo('GitLab token refreshed successfully');
  return data;
}
 
/**
 * Get the current GitLab user's information
 *
 * Uses the access token to fetch the authenticated user's profile.
 *
 * @param accessToken - GitLab access token
 * @param baseUrl - Instance that issued the token (default: GITLAB_API_URL)
 * @returns User information (id and username)
 * @throws Error if the request fails
 */
export async function getGitLabUser(
  accessToken: string,
  baseUrl: string = GITLAB_BASE_URL,
): Promise<GitLabUserInfo> {
  const url = `${baseUrl}/api/v4/user`;
 
  const response = await enhancedFetch(url, {
    headers: {
      Authorization: `Bearer ${accessToken}`,
      Accept: 'application/json',
    },
    ...oauthFetchOpts(baseUrl),
  });
 
  await throwOnHttpError(response, 'get GitLab user info');
 
  const user = await readGitLabResponse<GitLabUserInfo>(response, 'get GitLab user info');
 
  logDebug('Retrieved GitLab user info', { userId: user.id, username: user.username });
 
  return {
    id: user.id,
    username: user.username,
    name: user.name,
    email: user.email,
  };
}
 
/**
 * Validate a GitLab access token
 *
 * Checks if the token is still valid by making a lightweight API call.
 *
 * @param accessToken - GitLab access token to validate
 * @param baseUrl - Instance that issued the token (default: GITLAB_API_URL)
 * @returns true if the token is valid, false otherwise
 */
export async function validateGitLabToken(
  accessToken: string,
  baseUrl: string = GITLAB_BASE_URL,
): Promise<boolean> {
  try {
    const url = `${baseUrl}/api/v4/user`;
 
    const response = await enhancedFetch(url, {
      method: 'HEAD',
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
      ...oauthFetchOpts(baseUrl),
    });
 
    return response.ok;
  } catch {
    return false;
  }
}
 
/**
 * Exchange a GitLab authorization code for tokens
 *
 * Used in Authorization Code Flow when GitLab redirects back with a code.
 *
 * @param code - Authorization code from GitLab callback
 * @param redirectUri - The redirect URI that was used in the authorization request
 * @param config - OAuth configuration
 * @param app - Application the authorization was granted to
 * @returns Token response with access and refresh tokens
 * @throws Error if the exchange fails
 */
export async function exchangeGitLabAuthCode(
  code: string,
  redirectUri: string,
  config: OAuthConfig,
  app: GitLabOAuthApp = defaultOAuthApp(config),
): Promise<GitLabTokenResponse> {
  const url = `${app.baseUrl}/oauth/token`;
 
  const params: Record<string, string> = {
    ...clientParams(app),
    code: code,
    grant_type: 'authorization_code',
    redirect_uri: redirectUri,
  };
 
  logDebug('Exchanging GitLab authorization code for tokens', { redirectUri });
 
  const response = await enhancedFetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    body: new URLSearchParams(params),
    ...oauthFetchOpts(app.baseUrl),
  });
 
  await throwOnHttpError(response, 'exchange authorization code');
 
  const data = await readGitLabResponse<GitLabTokenResponse>(
    response,
    'exchange authorization code',
  );
  logInfo('GitLab authorization code exchanged successfully');
  return data;
}
 
/**
 * Revoke a GitLab OAuth token (RFC 7009), ending the grant the token belongs to.
 *
 * @param token - GitLab access or refresh token
 * @param config - OAuth configuration
 * @param app - Application that issued the token
 * @throws Error if GitLab refuses the request
 */
export async function revokeGitLabToken(
  token: string,
  config: OAuthConfig,
  app: GitLabOAuthApp = defaultOAuthApp(config),
): Promise<void> {
  const response = await enhancedFetch(`${app.baseUrl}/oauth/revoke`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    body: new URLSearchParams({ ...clientParams(app), token }),
    ...oauthFetchOpts(app.baseUrl),
  });
 
  await throwOnHttpError(response, 'revoke GitLab token');
  logInfo('GitLab token revoked');
}
 
/**
 * Build GitLab OAuth authorization URL
 *
 * Used to redirect users to GitLab for authorization in the Authorization Code Flow.
 *
 * @param config - OAuth configuration
 * @param redirectUri - URI to redirect back to after authorization
 * @param state - State parameter for CSRF protection
 * @param app - Instance and application to sign in with
 * @returns Full authorization URL
 */
export function buildGitLabAuthUrl(
  config: OAuthConfig,
  redirectUri: string,
  state: string,
  app: GitLabOAuthApp = defaultOAuthApp(config),
): string {
  // Convert comma-separated scopes to space-separated (GitLab requirement)
  const scopes = app.scopes.replaceAll(',', ' ');
 
  const params = new URLSearchParams({
    client_id: app.clientId,
    redirect_uri: redirectUri,
    response_type: 'code',
    state: state,
    scope: scopes,
  });
 
  return `${app.baseUrl}/oauth/authorize?${params.toString()}`;
}
 
/**
 * Helper function to sleep for a specified duration
 */
function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}