diff --git a/src/hooks/useGitHubOAuth.test.ts b/src/hooks/useGitHubOAuth.test.ts new file mode 100644 index 00000000..7899815f --- /dev/null +++ b/src/hooks/useGitHubOAuth.test.ts @@ -0,0 +1,153 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { renderHook, act } from '@testing-library/react'; +import { useGitHubOAuth } from './useGitHubOAuth'; +import { TestApp } from '@/test/TestApp'; + +// Mock crypto.subtle for PKCE testing +const mockCryptoSubtle = { + digest: vi.fn(), +}; + +const mockCrypto = { + getRandomValues: vi.fn(), + randomUUID: vi.fn(), + subtle: mockCryptoSubtle, +}; + +Object.defineProperty(global, 'crypto', { + value: mockCrypto, + writable: true, +}); + +// Mock btoa for base64 encoding +global.btoa = vi.fn((str: string) => Buffer.from(str, 'binary').toString('base64')); + +describe('useGitHubOAuth PKCE', () => { + beforeEach(() => { + vi.clearAllMocks(); + localStorage.clear(); + + // Setup crypto mocks + mockCrypto.getRandomValues.mockImplementation((array: Uint8Array) => { + // Fill with predictable values for testing + for (let i = 0; i < array.length; i++) { + array[i] = i % 256; + } + return array; + }); + + mockCrypto.randomUUID.mockReturnValue('test-state-uuid'); + + // Mock SHA-256 digest to return predictable hash + mockCryptoSubtle.digest.mockResolvedValue( + new Uint8Array([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]) + ); + }); + + afterEach(() => { + localStorage.clear(); + }); + + it('should validate state parameter in callback', async () => { + // Setup stored state + localStorage.setItem('github_oauth_state', 'correct-state'); + localStorage.setItem('github_oauth_code_verifier', 'test-verifier'); + + const { result } = renderHook(() => useGitHubOAuth(), { + wrapper: TestApp, + }); + + // Mock fetch for token exchange and user info + const mockFetch = vi.fn() + .mockResolvedValueOnce({ + ok: true, + json: () => Promise.resolve({ access_token: 'test-token' }), + }) + .mockResolvedValueOnce({ + ok: true, + json: () => Promise.resolve({ login: 'testuser' }), + }); + + global.fetch = mockFetch; + + let success: boolean | undefined; + await act(async () => { + success = await result.current.handleCallback('test-code', 'correct-state'); + }); + + expect(success).toBe(true); + expect(localStorage.getItem('github_oauth_state')).toBeNull(); + expect(localStorage.getItem('github_oauth_code_verifier')).toBeNull(); + }); + + it('should reject invalid state parameter', async () => { + localStorage.setItem('github_oauth_state', 'correct-state'); + localStorage.setItem('github_oauth_code_verifier', 'test-verifier'); + + const { result } = renderHook(() => useGitHubOAuth(), { + wrapper: TestApp, + }); + + let success: boolean | undefined; + await act(async () => { + success = await result.current.handleCallback('test-code', 'wrong-state'); + }); + + expect(success).toBe(false); + expect(result.current.error).toBe('Invalid OAuth state parameter'); + // Should clean up on error + expect(localStorage.getItem('github_oauth_state')).toBeNull(); + expect(localStorage.getItem('github_oauth_code_verifier')).toBeNull(); + }); + + it('should reject missing code verifier', async () => { + localStorage.setItem('github_oauth_state', 'correct-state'); + // Don't set code verifier + + const { result } = renderHook(() => useGitHubOAuth(), { + wrapper: TestApp, + }); + + let success: boolean | undefined; + await act(async () => { + success = await result.current.handleCallback('test-code', 'correct-state'); + }); + + expect(success).toBe(false); + expect(result.current.error).toBe('PKCE code verifier not found. Please restart the OAuth flow.'); + }); + + it('should include code_verifier in token request', async () => { + localStorage.setItem('github_oauth_state', 'correct-state'); + localStorage.setItem('github_oauth_code_verifier', 'test-verifier'); + + const { result } = renderHook(() => useGitHubOAuth(), { + wrapper: TestApp, + }); + + const mockFetch = vi.fn() + .mockResolvedValueOnce({ + ok: true, + json: () => Promise.resolve({ access_token: 'test-token' }), + }) + .mockResolvedValueOnce({ + ok: true, + json: () => Promise.resolve({ login: 'testuser' }), + }); + + global.fetch = mockFetch; + + await act(async () => { + await result.current.handleCallback('test-code', 'correct-state'); + }); + + // Check that the token request includes the code verifier + expect(mockFetch).toHaveBeenCalledWith( + expect.stringContaining('github.com/login/oauth/access_token'), + expect.objectContaining({ + method: 'POST', + body: expect.stringContaining('"code_verifier":"test-verifier"'), + }) + ); + }); +}); \ No newline at end of file diff --git a/src/hooks/useGitHubOAuth.ts b/src/hooks/useGitHubOAuth.ts index aafd41ad..0b64aa80 100644 --- a/src/hooks/useGitHubOAuth.ts +++ b/src/hooks/useGitHubOAuth.ts @@ -25,7 +25,28 @@ export function useGitHubOAuth() { import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET ); - const initiateOAuth = useCallback(() => { + // Generate a cryptographically secure random string for PKCE code verifier + const generateCodeVerifier = (): string => { + const array = new Uint8Array(32); + crypto.getRandomValues(array); + return btoa(String.fromCharCode(...array)) + .replace(/\+/g, '-') + .replace(/\//g, '_') + .replace(/=/g, ''); + }; + + // Create SHA-256 hash of the code verifier for PKCE code challenge + const generateCodeChallenge = async (codeVerifier: string): Promise => { + const encoder = new TextEncoder(); + const data = encoder.encode(codeVerifier); + const digest = await crypto.subtle.digest('SHA-256', data); + return btoa(String.fromCharCode(...new Uint8Array(digest))) + .replace(/\+/g, '-') + .replace(/\//g, '_') + .replace(/=/g, ''); + }; + + const initiateOAuth = useCallback(async () => { const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID; if (!clientId) { @@ -33,19 +54,36 @@ export function useGitHubOAuth() { return; } - // Generate a random state parameter for security - const state = crypto.randomUUID(); - localStorage.setItem('github_oauth_state', state); + try { + // Generate PKCE parameters + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); - // Redirect to GitHub OAuth - const params = new URLSearchParams({ - client_id: clientId, - redirect_uri: window.location.origin + '/oauth/github', - scope: 'repo', - state: state, - }); + // Generate a random state parameter for security + const state = crypto.randomUUID(); - window.location.href = `https://github.com/login/oauth/authorize?${params.toString()}`; + // Store both state and code verifier for later use + localStorage.setItem('github_oauth_state', state); + localStorage.setItem('github_oauth_code_verifier', codeVerifier); + + // Redirect to GitHub OAuth with PKCE parameters + const params = new URLSearchParams({ + client_id: clientId, + redirect_uri: window.location.origin + '/oauth/github', + scope: 'repo', + state: state, + code_challenge: codeChallenge, + code_challenge_method: 'S256', + }); + + window.location.href = `https://github.com/login/oauth/authorize?${params.toString()}`; + } catch (error) { + console.error('Failed to initiate OAuth with PKCE:', error); + setState(prev => ({ + ...prev, + error: 'Failed to generate PKCE parameters. Please try again.' + })); + } }, []); const handleCallback = useCallback(async (code: string, state: string) => { @@ -58,8 +96,15 @@ export function useGitHubOAuth() { throw new Error('Invalid OAuth state parameter'); } - // Clean up stored state + // Get the stored code verifier for PKCE + const codeVerifier = localStorage.getItem('github_oauth_code_verifier'); + if (!codeVerifier) { + throw new Error('PKCE code verifier not found. Please restart the OAuth flow.'); + } + + // Clean up stored values localStorage.removeItem('github_oauth_state'); + localStorage.removeItem('github_oauth_code_verifier'); const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID; const clientSecret = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET; @@ -68,18 +113,22 @@ export function useGitHubOAuth() { throw new Error('GitHub OAuth credentials not configured'); } - // Exchange code for access token + // Exchange code for access token with PKCE code verifier + const tokenRequestBody = { + client_id: clientId, + client_secret: clientSecret, + code: code, + redirect_uri: window.location.origin + '/oauth/github', + code_verifier: codeVerifier, + }; + const tokenResponse = await fetch('https://corsproxy.io/?url=https://github.com/login/oauth/access_token', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, - body: JSON.stringify({ - client_id: clientId, - client_secret: clientSecret, - code: code, - }), + body: JSON.stringify(tokenRequestBody), }); if (!tokenResponse.ok) { @@ -116,6 +165,11 @@ export function useGitHubOAuth() { return true; } catch (error) { console.error('GitHub OAuth error:', error); + + // Clean up any remaining OAuth data on error + localStorage.removeItem('github_oauth_state'); + localStorage.removeItem('github_oauth_code_verifier'); + setState(prev => ({ ...prev, isLoading: false, diff --git a/src/pages/GitHubOAuth.tsx b/src/pages/GitHubOAuth.tsx index 9c7faf5f..1082d935 100644 --- a/src/pages/GitHubOAuth.tsx +++ b/src/pages/GitHubOAuth.tsx @@ -17,6 +17,7 @@ export default function GitHubOAuth() { const error = searchParams.get('error'); const errorDescription = searchParams.get('error_description'); const storedState = localStorage.getItem('github_oauth_state'); + const storedCodeVerifier = localStorage.getItem('github_oauth_code_verifier'); // Handle OAuth errors if (error) { @@ -30,7 +31,7 @@ export default function GitHubOAuth() { } // Handle successful OAuth callback - if (code && state && storedState) { + if (code && state && storedState && storedCodeVerifier) { handleCallback(code, state).then((success) => { if (success) { toast({ @@ -47,6 +48,17 @@ export default function GitHubOAuth() { // Always redirect to Git settings after handling the callback navigate('/settings/git'); }); + } else if (code && state && storedState && !storedCodeVerifier) { + // Missing code verifier - likely an incomplete PKCE flow + toast({ + title: "Authentication Error", + description: "OAuth flow is incomplete. Please try connecting to GitHub again.", + variant: "destructive", + }); + // Clean up any remaining OAuth data + localStorage.removeItem('github_oauth_state'); + localStorage.removeItem('github_oauth_code_verifier'); + navigate('/settings/git'); } else { // No code or state parameters - redirect to Git settings navigate('/settings/git');