299 lines
11 KiB
TypeScript
299 lines
11 KiB
TypeScript
import { test, expect } from '@playwright/test';
|
|
import type { Page } from '@playwright/test';
|
|
import AxeBuilder from '@axe-core/playwright';
|
|
import { createHash, randomBytes } from 'node:crypto';
|
|
import { createServer } from 'node:http';
|
|
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
import { readFixture } from '../fixture.js';
|
|
import { Store } from '../../src/store.js';
|
|
import type { Credentials } from '../../src/store.js';
|
|
import { Vault } from '../../src/crypto.js';
|
|
|
|
const f = readFixture();
|
|
const receiver = createServer((_req, res) => {
|
|
res.setHeader('Content-Type', 'text/plain');
|
|
res.end('Connection complete.');
|
|
});
|
|
let callback: string;
|
|
test.beforeAll(async () => {
|
|
await new Promise<void>((done) => receiver.listen(0, '127.0.0.1', done));
|
|
const address = receiver.address();
|
|
if (!address || typeof address === 'string') throw new Error('Callback receiver did not start.');
|
|
callback = 'http://127.0.0.1:' + address.port + '/callback';
|
|
});
|
|
test.afterAll(async () => {
|
|
await new Promise<void>((done) => receiver.close(() => done()));
|
|
});
|
|
async function setup() {
|
|
const response = await fetch(f.origin + '/oauth/register', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
client_name: 'MCP test client',
|
|
redirect_uris: [callback],
|
|
token_endpoint_auth_method: 'none',
|
|
grant_types: ['authorization_code', 'refresh_token'],
|
|
response_types: ['code'],
|
|
}),
|
|
});
|
|
expect(response.status).toBe(201);
|
|
const registration = await response.json();
|
|
const verifier = randomBytes(32).toString('base64url');
|
|
const state = randomBytes(20).toString('hex');
|
|
const params = new URLSearchParams({
|
|
client_id: registration.client_id,
|
|
response_type: 'code',
|
|
redirect_uri: callback,
|
|
scope: 'gitza:access',
|
|
resource: f.origin + '/mcp',
|
|
state,
|
|
code_challenge: createHash('sha256').update(verifier).digest('base64url'),
|
|
code_challenge_method: 'S256',
|
|
});
|
|
return {
|
|
clientId: String(registration.client_id),
|
|
verifier,
|
|
state,
|
|
url: f.origin + '/oauth/authorize?' + params,
|
|
};
|
|
}
|
|
async function login(page: Page, url: string) {
|
|
await page.goto(url);
|
|
if (page.url().includes('/user/login')) {
|
|
await page.locator('input[name="user_name"]').fill('alice');
|
|
await page.locator('input[name="password"]').fill(f.password);
|
|
await page.getByRole('button', { name: 'Sign in', exact: true }).click();
|
|
}
|
|
if (page.url().startsWith(f.upstream)) {
|
|
await page
|
|
.getByRole('button', { name: /grant access|authorize application|authorize|approve/i })
|
|
.click();
|
|
}
|
|
await expect(page.getByRole('heading', { name: 'Connect to Gitza', exact: true })).toBeVisible();
|
|
}
|
|
async function exchange(code: string, clientId: string, verifier: string) {
|
|
return fetch(f.origin + '/oauth/token', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
body: new URLSearchParams({
|
|
grant_type: 'authorization_code',
|
|
client_id: clientId,
|
|
redirect_uri: callback,
|
|
code,
|
|
code_verifier: verifier,
|
|
resource: f.origin + '/mcp',
|
|
}),
|
|
});
|
|
}
|
|
async function connect(accessToken: string) {
|
|
const client = new Client({ name: 'http-e2e', version: '1' });
|
|
await client.connect(
|
|
new StreamableHTTPClientTransport(new URL(f.origin + '/mcp'), {
|
|
requestInit: { headers: { Authorization: 'Bearer ' + accessToken } },
|
|
}),
|
|
);
|
|
return client;
|
|
}
|
|
|
|
test('browser OAuth, consent, HTTP tools, refresh and immediate revocation', async ({ page }) => {
|
|
const auth = await setup();
|
|
await login(page, auth.url);
|
|
expect((await new AxeBuilder({ page }).analyze()).violations).toEqual([]);
|
|
await page.screenshot({ path: 'test-results/consent-desktop.png', fullPage: true });
|
|
await page.setViewportSize({ width: 390, height: 844 });
|
|
await page.screenshot({ path: 'test-results/consent-mobile.png', fullPage: true });
|
|
await page.getByLabel('alice/project', { exact: true }).check();
|
|
await page.getByLabel('Also create issues, add comments and open pull requests').check();
|
|
await page.getByRole('button', { name: 'Connect selected repositories' }).click();
|
|
await page.waitForURL(callback + '**');
|
|
const returned = new URL(page.url());
|
|
expect(returned.searchParams.get('state')).toBe(auth.state);
|
|
const code = returned.searchParams.get('code')!;
|
|
expect(code).toBeTruthy();
|
|
const r = await exchange(code, auth.clientId, auth.verifier);
|
|
expect(r.status).toBe(200);
|
|
const token = await r.json();
|
|
// Expire the stored upstream access credential to exercise a real refresh grant.
|
|
const state = new Store(f.env.DATABASE_URL!, new Vault(f.env.MCP_ENCRYPTION_KEYS!));
|
|
try {
|
|
const rows =
|
|
await state.sql`SELECT account_id, login, credential FROM upstream_accounts WHERE login = 'alice'`;
|
|
const account = rows[0]!;
|
|
const credentials = state.vault.open<Credentials>(
|
|
account.credential,
|
|
'account:' + account.account_id,
|
|
);
|
|
await state.account(account.account_id, account.login, { ...credentials, expires_at: 0 });
|
|
} finally {
|
|
await state.close();
|
|
}
|
|
const client = await connect(token.access_token);
|
|
try {
|
|
expect((await client.listTools()).tools).toHaveLength(15);
|
|
expect(
|
|
(
|
|
await client.callTool({
|
|
name: 'get_file',
|
|
arguments: { repository: 'alice/project', path: 'src/hello.txt' },
|
|
})
|
|
).isError,
|
|
).not.toBe(true);
|
|
expect(
|
|
(
|
|
await client.callTool({
|
|
name: 'create_issue',
|
|
arguments: { repository: 'alice/project', title: 'OAuth test issue' },
|
|
})
|
|
).isError,
|
|
).not.toBe(true);
|
|
expect(
|
|
(await client.callTool({ name: 'get_repository', arguments: { repository: 'bob/private' } }))
|
|
.isError,
|
|
).toBe(true);
|
|
} finally {
|
|
await client.close();
|
|
}
|
|
const refresh = await fetch(f.origin + '/oauth/token', {
|
|
method: 'POST',
|
|
body: new URLSearchParams({
|
|
grant_type: 'refresh_token',
|
|
client_id: auth.clientId,
|
|
refresh_token: token.refresh_token,
|
|
resource: f.origin + '/mcp',
|
|
}),
|
|
});
|
|
expect(refresh.status).toBe(200);
|
|
const rotated = await refresh.json();
|
|
expect(rotated.refresh_token).not.toBe(token.refresh_token);
|
|
await page.goto(f.origin + '/connections');
|
|
await expect(page.getByRole('heading', { name: 'MCP test client' })).toBeVisible();
|
|
expect((await new AxeBuilder({ page }).analyze()).violations).toEqual([]);
|
|
await page.getByRole('button', { name: 'Revoke connection' }).click();
|
|
await expect(page.getByText('You have no active connections.', { exact: false })).toBeVisible();
|
|
const denied = await fetch(f.origin + '/mcp', {
|
|
method: 'POST',
|
|
headers: {
|
|
Authorization: 'Bearer ' + rotated.access_token,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: '{}',
|
|
});
|
|
expect(denied.status).toBe(401);
|
|
const reused = await exchange(code, auth.clientId, auth.verifier);
|
|
expect(reused.status).toBe(400);
|
|
const store = new Store(f.env.DATABASE_URL!, new Vault(f.env.MCP_ENCRYPTION_KEYS!));
|
|
try {
|
|
const audit = await store.sql`SELECT * FROM audit_events`;
|
|
expect(audit.some((r) => r.tool === 'create_issue')).toBe(true);
|
|
expect(JSON.stringify(audit)).not.toContain('OAuth test issue');
|
|
expect(JSON.stringify(audit)).not.toContain(token.access_token);
|
|
const stored = await store.sql`SELECT credential FROM upstream_accounts`;
|
|
expect(JSON.stringify(stored)).not.toContain('access_token');
|
|
} finally {
|
|
await store.close();
|
|
}
|
|
});
|
|
|
|
test('read-only consent denies writes and cancellation grants nothing', async ({ page }) => {
|
|
const auth = await setup();
|
|
await login(page, auth.url);
|
|
await page.getByLabel('alice/project', { exact: true }).check();
|
|
await page.getByRole('button', { name: 'Connect selected repositories' }).click();
|
|
await page.waitForURL(callback + '**');
|
|
const r = await exchange(
|
|
new URL(page.url()).searchParams.get('code')!,
|
|
auth.clientId,
|
|
auth.verifier,
|
|
);
|
|
expect(r.status).toBe(200);
|
|
const token = await r.json();
|
|
const client = await connect(token.access_token);
|
|
try {
|
|
expect(
|
|
(
|
|
await client.callTool({
|
|
name: 'create_issue',
|
|
arguments: { repository: 'alice/project', title: 'Must not exist' },
|
|
})
|
|
).isError,
|
|
).toBe(true);
|
|
} finally {
|
|
await client.close();
|
|
}
|
|
const other = await setup();
|
|
await login(page, other.url);
|
|
await page.getByRole('button', { name: 'Cancel', exact: true }).click();
|
|
await page.waitForURL(callback + '**');
|
|
expect(new URL(page.url()).searchParams.get('error')).toBe('access_denied');
|
|
await page.goto(f.origin + '/connections');
|
|
await page.getByRole('button', { name: 'Disconnect all and remove stored credential' }).click();
|
|
const denied = await fetch(f.origin + '/mcp', {
|
|
method: 'POST',
|
|
headers: { Authorization: 'Bearer ' + token.access_token, 'Content-Type': 'application/json' },
|
|
body: '{}',
|
|
});
|
|
expect(denied.status).toBe(401);
|
|
});
|
|
|
|
test('rejects incorrect PKCE, resource indicators, callback state and CSRF', async ({ page }) => {
|
|
const auth = await setup();
|
|
await login(page, auth.url);
|
|
const csrfResponse = await page.request.post(
|
|
f.origin + new URL(page.url()).pathname + '/consent',
|
|
{ form: { csrf: 'incorrect', decision: 'allow', repositories: 'alice/project' } },
|
|
);
|
|
expect(csrfResponse.status()).toBe(400);
|
|
await page.reload();
|
|
await page.getByLabel('alice/project', { exact: true }).check();
|
|
await page.getByRole('button', { name: 'Connect selected repositories' }).click();
|
|
await page.waitForURL(callback + '**');
|
|
const r = await exchange(
|
|
new URL(page.url()).searchParams.get('code')!,
|
|
auth.clientId,
|
|
randomBytes(32).toString('base64url'),
|
|
);
|
|
expect(r.status).toBe(400);
|
|
const badResource = new URL(auth.url);
|
|
badResource.searchParams.set('resource', 'https://evil.example/mcp');
|
|
await page.goto(badResource.href);
|
|
await page.waitForURL(callback + '**');
|
|
expect(new URL(page.url()).searchParams.get('error')).toBe('invalid_target');
|
|
const badState = await page.request.get(f.origin + '/auth/callback?state=unknown&code=fake');
|
|
expect(badState.status()).toBe(400);
|
|
});
|
|
|
|
test('refresh-token reuse revokes the entire connection', async ({ page }) => {
|
|
const auth = await setup();
|
|
await login(page, auth.url);
|
|
await page.getByLabel('alice/project', { exact: true }).check();
|
|
await page.getByRole('button', { name: 'Connect selected repositories' }).click();
|
|
await page.waitForURL(callback + '**');
|
|
const response = await exchange(
|
|
new URL(page.url()).searchParams.get('code')!,
|
|
auth.clientId,
|
|
auth.verifier,
|
|
);
|
|
expect(response.status).toBe(200);
|
|
const token = await response.json();
|
|
const refresh = () =>
|
|
fetch(f.origin + '/oauth/token', {
|
|
method: 'POST',
|
|
body: new URLSearchParams({
|
|
grant_type: 'refresh_token',
|
|
client_id: auth.clientId,
|
|
refresh_token: token.refresh_token,
|
|
resource: f.origin + '/mcp',
|
|
}),
|
|
});
|
|
const rotated = await refresh();
|
|
expect(rotated.status).toBe(200);
|
|
const next = await rotated.json();
|
|
expect((await refresh()).status).toBe(400);
|
|
const denied = await fetch(f.origin + '/mcp', {
|
|
method: 'POST',
|
|
headers: { Authorization: 'Bearer ' + next.access_token, 'Content-Type': 'application/json' },
|
|
body: '{}',
|
|
});
|
|
expect(denied.status).toBe(401);
|
|
});
|