diff --git a/.changeset/verify-oauth-state.md b/.changeset/verify-oauth-state.md new file mode 100644 index 000000000..f8a3d4416 --- /dev/null +++ b/.changeset/verify-oauth-state.md @@ -0,0 +1,5 @@ +--- +'@keystatic/core': patch +--- + +Verify the OAuth state parameter in the GitHub callback. diff --git a/packages/keystatic/src/api/generic.integration.test.ts b/packages/keystatic/src/api/generic.integration.test.ts new file mode 100644 index 000000000..3746b3c92 --- /dev/null +++ b/packages/keystatic/src/api/generic.integration.test.ts @@ -0,0 +1,213 @@ +/** @vitest-environment node */ +import http from 'node:http'; +import { AddressInfo } from 'node:net'; +import { afterAll, beforeAll, beforeEach, expect, test, vi } from 'vitest'; +import { config } from '../config'; +import { makeGenericAPIRouteHandler } from './generic'; + +// runs the real login and callback handlers behind a node http server and +// points the GitHub token request at a local stub server + +const realFetch = globalThis.fetch; + +let tokenRequests: URL[] = []; +let githubOrigin: string; +let appOrigin: string; +const servers: http.Server[] = []; + +function listen(server: http.Server) { + servers.push(server); + return new Promise(resolve => { + server.listen(0, '127.0.0.1', () => { + const { port } = server.address() as AddressInfo; + resolve(`http://127.0.0.1:${port}`); + }); + }); +} + +beforeAll(async () => { + githubOrigin = await listen( + http.createServer((req, res) => { + const url = new URL(req.url!, 'http://localhost'); + if ( + req.method === 'POST' && + url.pathname === '/login/oauth/access_token' + ) { + tokenRequests.push(url); + res.setHeader('content-type', 'application/json'); + res.end( + JSON.stringify({ + access_token: `access-${url.searchParams.get('code')}`, + expires_in: 28800, + refresh_token: 'refresh-token', + refresh_token_expires_in: 15897600, + scope: '', + token_type: 'bearer', + }) + ); + return; + } + res.statusCode = 404; + res.end(); + }) + ); + + const handler = makeGenericAPIRouteHandler({ + clientId: 'client-id', + clientSecret: 'client-secret', + secret: 'a'.repeat(32), + config: config({ storage: { kind: 'github', repo: 'owner/repo' } }), + }); + appOrigin = await listen( + http.createServer(async (req, res) => { + const result = await handler({ + url: new URL(req.url!, appOrigin).toString(), + method: req.method!, + headers: { + get: name => { + const val = req.headers[name.toLowerCase()]; + return (Array.isArray(val) ? val[0] : val) ?? null; + }, + }, + json: async () => ({}), + }); + const grouped = new Map(); + for (const [key, value] of (result.headers ?? []) as [string, string][]) { + grouped.set(key, [...(grouped.get(key) ?? []), value]); + } + for (const [key, value] of grouped) res.setHeader(key, value); + res.statusCode = result.status ?? 200; + res.end(result.body); + }) + ); + + vi.stubGlobal( + 'fetch', + (input: string | URL | Request, init?: RequestInit) => { + const url = new URL(input instanceof Request ? input.url : input); + if (url.origin === 'https://github.com') { + return realFetch(`${githubOrigin}${url.pathname}${url.search}`, init); + } + return realFetch(input, init); + } + ); +}); + +afterAll(async () => { + vi.unstubAllGlobals(); + await Promise.all( + servers.map(server => new Promise(resolve => server.close(resolve))) + ); +}); + +beforeEach(() => { + tokenRequests = []; +}); + +// a tiny cookie jar for one browser +function makeBrowser() { + const jar = new Map(); + return { + jar, + async get(path: string) { + const res = await realFetch(`${appOrigin}${path}`, { + redirect: 'manual', + headers: { + cookie: [...jar].map(([key, value]) => `${key}=${value}`).join('; '), + }, + }); + const setCookies = res.headers.getSetCookie(); + for (const setCookie of setCookies) { + const [pair] = setCookie.split(';'); + const index = pair.indexOf('='); + const key = pair.slice(0, index); + const value = pair.slice(index + 1); + if (/max-age=0/i.test(setCookie)) jar.delete(key); + else jar.set(key, value); + } + return { res, setCookies, location: res.headers.get('location') }; + }, + }; +} + +async function startLogin(browser: ReturnType, query = '') { + const { res, location } = await browser.get( + `/api/keystatic/github/login${query}` + ); + expect(res.status).toBe(307); + const authorizeUrl = new URL(location!); + expect(authorizeUrl.origin).toBe('https://github.com'); + const state = authorizeUrl.searchParams.get('state'); + expect(state).toBeTruthy(); + return state!; +} + +test('normal login signs in and clears the state cookie', async () => { + const browser = makeBrowser(); + const state = await startLogin(browser); + expect(browser.jar.has(`ks-${state}`)).toBe(true); + + const { res, location } = await browser.get( + `/api/keystatic/github/oauth/callback?code=good&state=${state}` + ); + expect(res.status).toBe(307); + expect(location).toBe('/keystatic'); + expect(tokenRequests.map(x => x.searchParams.get('code'))).toEqual(['good']); + expect(browser.jar.get('keystatic-gh-access-token')).toBe('access-good'); + expect(browser.jar.has(`ks-${state}`)).toBe(false); +}); + +test('login with from redirects back to the deep link', async () => { + const browser = makeBrowser(); + const from = 'branch/main/collection/posts'; + const state = await startLogin(browser, `?from=${encodeURIComponent(from)}`); + + const { res, location } = await browser.get( + `/api/keystatic/github/oauth/callback?code=good&state=${state}` + ); + expect(res.status).toBe(307); + expect(location).toBe(`/keystatic/${from}`); + expect(tokenRequests).toHaveLength(1); +}); + +test('a forged callback with the attacker state is rejected without a token request', async () => { + // the attacker starts a login in their own browser and gets their own code + const attacker = makeBrowser(); + const attackerState = await startLogin(attacker); + + // the victim is sent to the callback with the attacker's code and state + const victim = makeBrowser(); + for (const query of [ + `code=attacker&state=${attackerState}`, + 'code=attacker', + ]) { + const { res, setCookies } = await victim.get( + `/api/keystatic/github/oauth/callback?${query}` + ); + expect(res.status).toBe(400); + expect(setCookies).toEqual([]); + } + // also when the victim has a login of their own in progress + await startLogin(victim); + const { res } = await victim.get( + `/api/keystatic/github/oauth/callback?code=attacker&state=${attackerState}` + ); + expect(res.status).toBe(400); + + expect(tokenRequests).toEqual([]); + expect(victim.jar.has('keystatic-gh-access-token')).toBe(false); +}); + +test('the GitHub App install popup closes without a token request or cookies', async () => { + const browser = makeBrowser(); + const { res, setCookies } = await browser.get( + '/api/keystatic/github/oauth/callback?code=install&state=close' + ); + expect(res.status).toBe(200); + expect(res.headers.get('content-type')).toBe('text/html'); + const body = await res.text(); + expect(body).toContain("localStorage.setItem('ks-refetch-installations'"); + expect(body).toContain('window.close()'); + expect(setCookies).toEqual([]); + expect(tokenRequests).toEqual([]); +}); diff --git a/packages/keystatic/src/api/generic.test.ts b/packages/keystatic/src/api/generic.test.ts new file mode 100644 index 000000000..baebf4d36 --- /dev/null +++ b/packages/keystatic/src/api/generic.test.ts @@ -0,0 +1,135 @@ +/** @vitest-environment node */ +import { afterEach, beforeEach, expect, test, vi } from 'vitest'; +import { config } from '../config'; +import { makeGenericAPIRouteHandler } from './generic'; +import { KeystaticRequest } from './internal-utils'; + +const origin = 'http://localhost:3000'; + +const handler = makeGenericAPIRouteHandler({ + clientId: 'client-id', + clientSecret: 'client-secret', + secret: 'a'.repeat(32), + config: config({ storage: { kind: 'github', repo: 'owner/repo' } }), +}); + +function makeRequest(path: string, cookieHeader?: string): KeystaticRequest { + return { + url: `${origin}${path}`, + method: 'GET', + headers: { + get: name => + name.toLowerCase() === 'cookie' ? cookieHeader ?? null : null, + }, + json: async () => ({}), + }; +} + +function getHeaders(res: { headers?: unknown }) { + return (res.headers ?? []) as [string, string][]; +} + +function getSetCookies(res: { headers?: unknown }) { + return getHeaders(res) + .filter(([key]) => key === 'Set-Cookie') + .map(([, value]) => value); +} + +const fetchMock = vi.fn(); + +beforeEach(() => { + vi.stubGlobal('fetch', fetchMock); + fetchMock.mockResolvedValue({ + ok: true, + json: async () => ({ + access_token: 'access-token', + expires_in: 28800, + refresh_token: 'refresh-token', + refresh_token_expires_in: 15897600, + scope: '', + token_type: 'bearer', + }), + }); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +test('callback without state is rejected without calling GitHub', async () => { + const res = await handler( + makeRequest('/api/keystatic/github/oauth/callback?code=abc') + ); + expect(res.status).toBe(400); + expect(getSetCookies(res)).toEqual([]); + expect(fetchMock).not.toHaveBeenCalled(); +}); + +test('callback with state but no state cookie is rejected', async () => { + const res = await handler( + makeRequest('/api/keystatic/github/oauth/callback?code=abc&state=1234') + ); + expect(res.status).toBe(400); + expect(fetchMock).not.toHaveBeenCalled(); +}); + +test('callback with a state cookie for a different state is rejected', async () => { + const res = await handler( + makeRequest( + '/api/keystatic/github/oauth/callback?code=abc&state=1234', + 'ks-5678=%2F' + ) + ); + expect(res.status).toBe(400); + expect(fetchMock).not.toHaveBeenCalled(); +}); + +test('callback with a matching state cookie signs in and clears the state cookie', async () => { + const res = await handler( + makeRequest( + '/api/keystatic/github/oauth/callback?code=abc&state=1234', + 'ks-1234=branch%2Fmain' + ) + ); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(res.status).toBe(307); + expect(getHeaders(res)).toContainEqual([ + 'Location', + '/keystatic/branch/main', + ]); + const setCookies = getSetCookies(res); + expect(setCookies.some(x => x.startsWith('keystatic-gh-access-token='))).toBe( + true + ); + expect( + setCookies.some(x => x.startsWith('keystatic-gh-refresh-token=')) + ).toBe(true); + const stateCookie = setCookies.find(x => x.startsWith('ks-1234=')); + expect(stateCookie).toMatch(/^ks-1234=;/); + expect(stateCookie).toContain('Max-Age=0'); + expect(stateCookie).toContain('Path=/api/keystatic/github/oauth/callback'); +}); + +test('callback for the GitHub App install popup does not exchange the code', async () => { + const res = await handler( + makeRequest('/api/keystatic/github/oauth/callback?code=abc&state=close') + ); + expect(res.status).toBe(200); + expect(getSetCookies(res)).toEqual([]); + expect(fetchMock).not.toHaveBeenCalled(); +}); + +test('login without from still sets a state cookie', async () => { + const res = await handler(makeRequest('/api/keystatic/github/login')); + expect(res.status).toBe(307); + const location = getHeaders(res).find(([key]) => key === 'Location')?.[1]; + const state = new URL(location!).searchParams.get('state'); + expect(state).toMatch(/^[0-9a-f]{20}$/); + const setCookies = getSetCookies(res); + expect(setCookies).toHaveLength(1); + expect(setCookies[0]).toMatch(new RegExp(`^ks-${state}=`)); + expect(setCookies[0]).toContain('HttpOnly'); + expect(setCookies[0]).toContain('SameSite=Lax'); + expect(setCookies[0]).toContain('Max-Age=600'); + expect(setCookies[0]).toContain('Path=/api/keystatic/github/oauth/callback'); +}); diff --git a/packages/keystatic/src/api/generic.ts b/packages/keystatic/src/api/generic.ts index f74d5e810..33d989b35 100644 --- a/packages/keystatic/src/api/generic.ts +++ b/packages/keystatic/src/api/generic.ts @@ -32,6 +32,8 @@ type InnerAPIRouteConfig = { const keystaticRouteRegex = /^branch\/[^]+(\/collection\/[^/]+(|\/(create|item\/[^/]+))|\/singleton\/[^/]+)?$/; +const oauthStateCookiePath = '/api/keystatic/github/oauth/callback'; + const keyToEnvVar = { clientId: 'KEYSTATIC_GITHUB_CLIENT_ID', clientSecret: 'KEYSTATIC_GITHUB_CLIENT_SECRET', @@ -218,8 +220,23 @@ async function githubOauthCallback( if (typeof code !== 'string') { return { status: 400, body: 'Bad Request' }; } + if (state === 'close') { + // the GitHub App install popup opened from the fork flow, the user is + // already signed in so the code is not exchanged here + return { + headers: [['Content-Type', 'text/html']], + body: "", + status: 200, + }; + } const cookies = cookie.parse(req.headers.get('cookie') ?? ''); const fromCookie = state ? cookies['ks-' + state] : undefined; + if (typeof fromCookie !== 'string') { + return { + status: 400, + body: 'Invalid OAuth state. Please try signing in again.', + }; + } const from = typeof fromCookie === 'string' && keystaticRouteRegex.test(fromCookie) ? fromCookie @@ -245,13 +262,10 @@ async function githubOauthCallback( } const headers = await getTokenCookies(tokenData, config); - if (state === 'close') { - return { - headers: [...headers, ['Content-Type', 'text/html']], - body: "", - status: 200, - }; - } + headers.push([ + 'Set-Cookie', + immediatelyExpiringCookie('ks-' + state, oauthStateCookiePath), + ]); return redirect(`/keystatic${from ? `/${from}` : ''}`, headers); } @@ -377,9 +391,6 @@ async function githubLogin( 'redirect_uri', `${reqUrl.origin}/api/keystatic/github/oauth/callback` ); - if (from === '/') { - return redirect(url.toString()); - } url.searchParams.set('state', state); return redirect(url.toString(), [ [ @@ -387,10 +398,10 @@ async function githubLogin( cookie.serialize('ks-' + state, from, { sameSite: 'lax', secure: process.env.NODE_ENV === 'production', - // 1 day - maxAge: 60 * 60 * 24, - expires: new Date(Date.now() + 60 * 60 * 24 * 1000), - path: '/', + // 10 minutes + maxAge: 60 * 10, + expires: new Date(Date.now() + 60 * 10 * 1000), + path: oauthStateCookiePath, httpOnly: true, }), ], @@ -407,11 +418,11 @@ async function createdGithubApp( return handleGitHubAppCreation(req, slugEnvVarName); } -function immediatelyExpiringCookie(name: string) { +function immediatelyExpiringCookie(name: string, path = '/') { return cookie.serialize(name, '', { secure: process.env.NODE_ENV === 'production', sameSite: 'lax', - path: '/', + path, maxAge: 0, expires: new Date(), }); diff --git a/packages/keystatic/src/app/fork-repo.test.tsx b/packages/keystatic/src/app/fork-repo.test.tsx new file mode 100644 index 000000000..6d2339f90 --- /dev/null +++ b/packages/keystatic/src/app/fork-repo.test.tsx @@ -0,0 +1,111 @@ +import { act, render, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, expect, test, vi } from 'vitest'; +import { GitHubConfig } from '../config'; +import { ForkRepoDialog } from './fork-repo'; + +const mocks = vi.hoisted(() => ({ + fetch: vi.fn(), + getAuth: vi.fn(), + query: vi.fn(), +})); + +vi.mock('./auth', () => ({ getAuth: mocks.getAuth })); + +vi.mock('urql', () => ({ + useClient: () => ({ query: () => ({ toPromise: mocks.query }) }), +})); + +vi.mock('./shell/data', () => ({ GitHubAppShellQuery: {} })); + +vi.mock('react-aria/useLocalizedStringFormatter', () => ({ + useLocalizedStringFormatter: () => ({ format: (key: string) => key }), +})); + +vi.mock('@keystar/ui/button', () => ({ + Button: (props: { children?: unknown }) => props.children, + ButtonGroup: (props: { children?: unknown }) => props.children, +})); +vi.mock('@keystar/ui/dialog', () => ({ + Dialog: (props: { children?: unknown }) => props.children, +})); +vi.mock('@keystar/ui/slots', () => ({ + Content: (props: { children?: unknown }) => props.children, +})); +vi.mock('@keystar/ui/typography', () => ({ + Heading: (props: { children?: unknown }) => props.children, + Text: (props: { children?: unknown }) => props.children, +})); +vi.mock('@keystar/ui/notice', () => ({ + Notice: (props: { children?: unknown }) => props.children, +})); +vi.mock('@keystar/ui/layout', () => ({ + Flex: (props: { children?: unknown }) => props.children, +})); +vi.mock('@keystar/ui/link', () => ({ + TextLink: (props: { children?: unknown }) => props.children, +})); + +const config: GitHubConfig = { + storage: { kind: 'github', repo: 'owner/repo' }, +}; + +beforeEach(() => { + vi.stubGlobal('fetch', mocks.fetch); + mocks.getAuth.mockResolvedValue({ accessToken: 'token' }); + mocks.query.mockResolvedValue({ + data: { + repository: { forks: { nodes: [{ viewerPermission: 'WRITE' }] } }, + }, + }); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + mocks.fetch.mockReset(); + mocks.getAuth.mockReset(); + mocks.query.mockReset(); +}); + +async function installAppInPopup() { + const onCreate = vi.fn(); + const result = render( + {}} onCreate={onCreate} /> + ); + await act(async () => { + window.dispatchEvent( + new StorageEvent('storage', { + key: 'ks-refetch-installations', + newValue: 'true', + }) + ); + }); + await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1)); + return result; +} + +test('refreshes the token before refetching after the install popup closes', async () => { + mocks.fetch.mockResolvedValue({ ok: true, status: 200 }); + await installAppInPopup(); + expect(mocks.fetch).toHaveBeenCalledWith( + '/api/keystatic/github/refresh-token', + { method: 'POST' } + ); + expect(mocks.fetch.mock.invocationCallOrder[0]).toBeLessThan( + mocks.getAuth.mock.invocationCallOrder[0] + ); + expect(mocks.query).toHaveBeenCalledTimes(1); +}); + +test('continues with the existing token when the refresh request fails', async () => { + mocks.fetch.mockRejectedValue(new TypeError('Failed to fetch')); + const { queryByText } = await installAppInPopup(); + expect(mocks.getAuth).toHaveBeenCalledTimes(1); + expect(queryByText('Failed to fetch')).toBeNull(); +}); + +test('continues with the existing token when there is no refresh token', async () => { + mocks.fetch.mockResolvedValue({ ok: false, status: 401 }); + const { queryByText } = await installAppInPopup(); + expect(mocks.getAuth).toHaveBeenCalledTimes(1); + expect(queryByText('Unauthorized')).toBeNull(); +}); diff --git a/packages/keystatic/src/app/fork-repo.tsx b/packages/keystatic/src/app/fork-repo.tsx index bc513f873..c8e7f6855 100644 --- a/packages/keystatic/src/app/fork-repo.tsx +++ b/packages/keystatic/src/app/fork-repo.tsx @@ -34,6 +34,15 @@ export function ForkRepoDialog(props: { event.newValue === 'true' ) { localStorage.removeItem('ks-refetch-installations'); + // the install popup doesn't sign in again, so try to get a token + // issued after the install. if this fails, the existing token is used + try { + await fetch('/api/keystatic/github/refresh-token', { + method: 'POST', + }); + } catch { + // ignore + } try { const auth = await getAuth(props.config); if (!auth) throw new Error('Unauthorized');