Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/app/api/auth/google/callback/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { NextRequest, NextResponse } from 'next/server';
import { withRateLimit } from '@/lib/ratelimit';
import { exchangeCodeForToken, getGoogleUser, getGoogleAvatarUrl } from '@/lib/google/oauth';
import {
exchangeCodeForToken,
getGoogleUser,
getGoogleAvatarUrl,
validateState,
} from '@/lib/google/oauth';
import type { AuthResponseDTO, AuthErrorDTO } from '@/types/api/auth.dto';
import { edgeLog } from '@/../infra/edge-config';

Expand Down Expand Up @@ -40,7 +45,7 @@ export async function GET(

// Verify state parameter to prevent CSRF attacks
const storedState = request.cookies.get('google_oauth_state')?.value;
if (!state || state !== storedState) {
if (!validateState(storedState, state)) {
edgeLog('error', '/api/auth/google/callback', 'Invalid state parameter');
return addHeaders(
NextResponse.json({ message: 'Invalid state parameter' }, { status: 400 }),
Expand Down
23 changes: 23 additions & 0 deletions src/lib/google/__tests__/oauth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { describe, expect, it } from 'vitest';
import { generateState, validateState } from '../oauth';

describe('Google OAuth utilities', () => {
it('generates a cryptographically random state value', () => {
const state1 = generateState();
const state2 = generateState();

expect(state1).toBeTruthy();
expect(state2).toBeTruthy();
expect(state1).not.toBe(state2);
expect(state1.length).toBeGreaterThan(32);
});

it('validates a matching OAuth state and rejects mismatches', () => {
const validState = generateState();

expect(validateState(validState, validState)).toBe(true);
expect(validateState(validState, `${validState}tampered`)).toBe(false);
expect(validateState(undefined, validState)).toBe(false);
expect(validateState(validState, null)).toBe(false);
});
});
33 changes: 31 additions & 2 deletions src/lib/google/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,39 @@ export async function getGoogleUser(accessToken: string): Promise<GoogleUser> {
}

/**
* Generate a random state parameter for OAuth
* Generate a cryptographically secure state parameter for OAuth
*/
export function generateState(): string {
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
const bytes = new Uint8Array(32);

if (typeof crypto !== 'undefined' && 'getRandomValues' in crypto) {
crypto.getRandomValues(bytes);
} else {
// Fallback for runtimes without Web Crypto support.
const randomValues = new Uint8Array(32);
for (let i = 0; i < randomValues.length; i += 1) {
randomValues[i] = Math.floor(Math.random() * 256);
}
randomValues.forEach((value, index) => {
bytes[index] = value;
});
}

return Array.from(bytes, (value) => value.toString(16).padStart(2, '0')).join('');
}

/**
* Validate an OAuth state value from the callback against the one stored in a cookie.
*/
export function validateState(
storedState: string | null | undefined,
callbackState: string | null | undefined,
): boolean {
if (!storedState || !callbackState) {
return false;
}

return storedState === callbackState;
}

/**
Expand Down
Loading