Files

81 lines
6.8 KiB
JavaScript

import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import Database from 'better-sqlite3';
import path from 'node:path';
export async function testOAuth({ base, admin, step, restart, dataDir }) {
const metadata = await (await fetch(`${base}/.well-known/oauth-authorization-server`)).json();
assert.ok(metadata.code_challenge_methods_supported.includes('S256'));
const resource = await (await fetch(`${base}/.well-known/oauth-protected-resource/mcp`)).json();
assert.equal(resource.resource, `${base}/mcp`);
const post = (url, values, headers = {}) => fetch(url, { method: 'POST', redirect: 'manual', headers: { 'content-type': 'application/x-www-form-urlencoded', ...headers }, body: new URLSearchParams(values) });
const register = (redirect) => fetch(metadata.registration_endpoint, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ client_name: '<Test AI>', redirect_uris: [redirect], token_endpoint_auth_method: 'none', grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'] }) });
assert.equal((await register('http://evil.example/callback')).status, 400);
const client = await (await register('https://client.example/callback')).json();
const other = await (await register('https://other.example/callback')).json();
assert.ok(client.client_id);
const verifier = crypto.randomBytes(32).toString('base64url');
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
const authParams = { response_type: 'code', client_id: client.client_id, redirect_uri: client.redirect_uris[0], code_challenge: challenge, code_challenge_method: 'S256', resource: `${base}/mcp`, state: 'original-state', scope: 'collection' };
const begin = (extra = {}) => fetch(`${metadata.authorization_endpoint}?${new URLSearchParams({ ...authParams, ...extra })}`, { redirect: 'manual' });
assert.equal((await begin({ redirect_uri: 'https://evil.example/callback' })).status, 400);
assert.match((await begin({ resource: 'https://other.example/mcp' })).headers.get('location'), /error=invalid_target/);
assert.match((await begin({ code_challenge_method: 'plain' })).headers.get('location'), /error=/);
let r = await begin();
assert.equal(r.status, 303);
const cookie = r.headers.get('set-cookie').split(';')[0];
const consent = new URL(r.headers.get('location'), base);
const request = consent.searchParams.get('request');
assert.equal((await fetch(consent)).status, 400);
r = await fetch(consent, { headers: { cookie } });
assert.match(await r.text(), /&lt;Test AI&gt;/);
const form = { request, username: 'admin', password: 'adminpw1', decision: 'approve' };
assert.equal((await post(`${base}/oauth/consent`, form)).status, 400);
assert.equal((await post(`${base}/oauth/consent`, { ...form, password: 'wrong' }, { cookie })).status, 401);
r = await post(`${base}/oauth/consent`, form, { cookie });
assert.equal(r.status, 303);
const callback = new URL(r.headers.get('location'));
assert.equal(callback.origin, 'https://client.example'); assert.equal(callback.searchParams.get('state'), 'original-state');
const code = callback.searchParams.get('code');
assert.ok(code);
assert.equal((await post(`${base}/oauth/consent`, form, { cookie })).status, 400);
const exchange = { grant_type: 'authorization_code', client_id: client.client_id, code, code_verifier: verifier, redirect_uri: client.redirect_uris[0], resource: `${base}/mcp` };
assert.equal((await post(metadata.token_endpoint, { ...exchange, client_id: other.client_id })).status, 400);
assert.equal((await post(metadata.token_endpoint, { ...exchange, code_verifier: 'wrong' })).status, 400);
assert.equal((await post(metadata.token_endpoint, { ...exchange, redirect_uri: 'https://evil.example/callback' })).status, 400);
assert.equal((await post(metadata.token_endpoint, { ...exchange, resource: 'https://evil.example/mcp' })).status, 400);
await restart(); // Clients and approved codes must survive a deployment.
r = await post(metadata.token_endpoint, exchange); assert.equal(r.status, 200);
const tokens = await r.json(); assert.ok(tokens.access_token); assert.ok(tokens.refresh_token); assert.equal(tokens.expires_in, 3600);
assert.equal((await post(metadata.token_endpoint, exchange)).status, 400);
const call = (token) => fetch(`${base}/mcp`, { method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }) });
r = await call(tokens.access_token); assert.equal(r.status, 200); assert.ok((await r.json()).result.tools.length);
step('OAuth registration, consent, CSRF, PKCE, client/redirect/audience binding and code replay protection');
const refresh = { grant_type: 'refresh_token', client_id: client.client_id, refresh_token: tokens.refresh_token, resource: `${base}/mcp` };
assert.equal((await post(metadata.token_endpoint, { ...refresh, client_id: other.client_id })).status, 400);
await restart(); // Access and refresh grants must survive too.
assert.equal((await call(tokens.access_token)).status, 200);
const database = new Database(path.join(dataDir, 'indexipro.sqlite'));
database.prepare('UPDATE ai_keys SET expires_at = 1 WHERE key_hash = ?').run(crypto.createHash('sha256').update(tokens.access_token).digest('hex'));
database.close();
assert.equal((await call(tokens.access_token)).status, 401);
r = await post(metadata.token_endpoint, refresh); assert.equal(r.status, 200);
const rotated = await r.json(); assert.notEqual(rotated.refresh_token, tokens.refresh_token);
assert.equal((await post(metadata.token_endpoint, refresh)).status, 400);
assert.equal((await call(tokens.access_token)).status, 401);
assert.equal((await call(rotated.access_token)).status, 200);
// Existing Connect AI removal revokes both the access token and refresh grant.
const keys = await (await fetch(`${base}/api/aikeys`, { headers: { cookie: admin } })).json();
const key = keys.keys.find((k) => k.label === '<Test AI>'); assert.ok(key.tools_listed_at);
assert.equal((await fetch(`${base}/api/aikeys/${key.id}`, { method: 'DELETE', headers: { cookie: admin } })).status, 200);
assert.equal((await call(rotated.access_token)).status, 401);
assert.equal((await post(metadata.token_endpoint, { ...refresh, refresh_token: rotated.refresh_token })).status, 400);
step('OAuth survives restarts, enforces expiry, rotates refresh tokens and revokes removed connections');
r = await begin();
const cancelCookie = r.headers.get('set-cookie').split(';')[0];
const cancelId = new URL(r.headers.get('location'), base).searchParams.get('request');
r = await post(`${base}/oauth/consent`, { request: cancelId, decision: 'deny' }, { cookie: cancelCookie });
assert.match(r.headers.get('location'), /error=access_denied/);
step('OAuth cancellation returns safely to the registered client');
}