Tests du serveur : relais, quotas, IP réelle, OAuth sans état, MCP, site

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pierre MARTIN
2026-11-18 05:10:31 +01:00
co-authored by Claude Opus 5.5
parent 508bab9a8e
commit 91ee787ba0
5 changed files with 748 additions and 0 deletions
+235
View File
@@ -0,0 +1,235 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { createOAuth, loadServerSecret, isAcceptableRedirect, TTL } from "../../server/oauth.js";
import { deriveKeys, encryptEvent, generateSyncKey } from "../../app/domain/sync-crypto.js";
import { startServer, push, pkce, connect, rpc } from "./helpers.js";
import crypto from "node:crypto";
const REDIRECT = "https://claude.ai/api/mcp/auth_callback";
/** Un journal existant sur le relais, pour une clé neuve. @param {Awaited<ReturnType<typeof startServer>>} s */
async function journal(s) {
const syncKey = generateSyncKey();
const k = await deriveKeys(syncKey);
const event = { id: "w1", at: "2026-11-18T08:00:00.000Z", device: "pc", v: 1, type: "WeightRecorded", data: { date: "2026-11-18", kg: 80 } };
assert.equal((await push(s, k.journalId, k.authToken, [await encryptEvent(k.encKey, event)])).status, 200);
return syncKey;
}
/** @param {Awaited<ReturnType<typeof startServer>>} s @param {object} body */
const authorize = (s, body) => s.fetch("/oauth/authorize", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
/** @param {Awaited<ReturnType<typeof startServer>>} s @param {Record<string, string>} form */
const token = (s, form) => s.fetch("/oauth/token", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(form) });
/** @param {Awaited<ReturnType<typeof startServer>>} s */
async function register(s, uris = [REDIRECT]) {
const r = await s.fetch("/oauth/register", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ client_name: "Claude", redirect_uris: uris }) });
return { status: r.status, body: await r.json() };
}
test("métadonnées OAuth et ressource protégée, sur l'adresse publique", async () => {
const s = await startServer();
try {
const as = await (await s.fetch("/.well-known/oauth-authorization-server")).json();
assert.equal(as.issuer, s.publicUrl);
assert.equal(as.token_endpoint, s.publicUrl + "/oauth/token");
assert.deepEqual(as.code_challenge_methods_supported, ["S256"]);
for (const p of ["/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp"]) {
const pr = await (await s.fetch(p)).json();
assert.equal(pr.resource, s.publicUrl + "/mcp");
assert.deepEqual(pr.authorization_servers, [s.publicUrl]);
}
const r = await s.fetch("/mcp", { method: "POST" });
assert.equal(r.status, 401);
assert.equal(r.headers.get("www-authenticate"), `Bearer resource_metadata="${s.publicUrl}/.well-known/oauth-protected-resource/mcp"`);
} finally {
await s.close();
}
});
test("enregistrement sans état : le client survit à un redémarrage (même secret), un client falsifié est refusé", async () => {
const s = await startServer();
try {
const { status, body } = await register(s);
assert.equal(status, 201);
assert.deepEqual(body.redirect_uris, [REDIRECT]);
assert.equal(body.token_endpoint_auth_method, "none");
assert.equal(fs.readdirSync(s.dataDir).join(","), ".server-secret", "rien d'autre n'est écrit");
assert.equal((fs.statSync(path.join(s.dataDir, ".server-secret")).mode & 0o777), 0o600);
// « Redémarrage » : une nouvelle instance relit le même secret.
const again = createOAuth({ secret: loadServerSecret(s.dataDir) });
assert.deepEqual(again.readClient(body.client_id)?.redirectUris, [REDIRECT]);
// Autre secret : inconnu.
assert.equal(createOAuth({ secret: crypto.randomBytes(32) }).readClient(body.client_id), null);
// Client falsifié : adresses de retour changées sans la signature.
const [, mac] = body.client_id.split(".");
const forged = Buffer.from(JSON.stringify({ r: ["https://pirate.example/cb"], n: "Claude" })).toString("base64url") + "." + mac;
const { challenge } = pkce();
const base = { redirect_uri: "https://pirate.example/cb", code_challenge: challenge, code_challenge_method: "S256", response_type: "code" };
let r = await s.fetch("/oauth/authorize?" + new URLSearchParams({ ...base, client_id: forged }));
assert.equal(r.status, 400);
assert.match(await r.text(), /Client inconnu/);
// Vrai client, adresse non enregistrée : refus sans redirection.
r = await s.fetch("/oauth/authorize?" + new URLSearchParams({ ...base, client_id: body.client_id }));
assert.equal(r.status, 400);
assert.equal(r.headers.get("location"), null);
assert.equal((await register(s, ["http://pirate.example/cb"])).status, 400, "http hors boucle locale refusé");
assert.equal((await register(s, [])).status, 400);
} finally {
await s.close();
}
});
test("adresses de retour acceptées : https, boucle locale, schéma d'application", () => {
assert.ok(isAcceptableRedirect("https://chatgpt.com/connector_platform_oauth_redirect"));
assert.ok(isAcceptableRedirect("http://localhost:33418/callback"));
assert.ok(isAcceptableRedirect("http://127.0.0.1/cb"));
assert.ok(isAcceptableRedirect("com.example.app:/cb"));
assert.ok(!isAcceptableRedirect("javascript:alert(1)"));
assert.ok(!isAcceptableRedirect("https://a.example/cb#x"));
assert.ok(!isAcceptableRedirect("http://a.example/cb"));
});
test("GET /oauth/authorize : vers la page de l'app ; sans PKCE S256, erreur renvoyée au client", async () => {
const s = await startServer();
try {
const { body } = await register(s);
const { challenge } = pkce();
const params = { client_id: body.client_id, redirect_uri: REDIRECT, response_type: "code", state: "xyz", code_challenge: challenge, code_challenge_method: "S256" };
let r = await s.fetch("/oauth/authorize?" + new URLSearchParams(params));
assert.equal(r.status, 302);
const location = r.headers.get("location") ?? "";
assert.match(location, /^\/#\/connecter-ia\?/);
const forwarded = new URLSearchParams(location.split("?")[1]);
assert.equal(forwarded.get("client_id"), body.client_id);
assert.equal(forwarded.get("state"), "xyz");
assert.equal(forwarded.get("client_name"), "Claude");
for (const changed of [{ code_challenge_method: "plain" }, { code_challenge: "" }]) {
r = await s.fetch("/oauth/authorize?" + new URLSearchParams({ ...params, ...changed }));
assert.equal(r.status, 302);
const back = new URL(r.headers.get("location") ?? "");
assert.equal(back.origin + back.pathname, REDIRECT);
assert.equal(back.searchParams.get("error"), "invalid_request");
assert.equal(back.searchParams.get("state"), "xyz");
}
} finally {
await s.close();
}
});
test("POST /oauth/authorize : PKCE obligatoire, clé valide et journal existant exigés, clé jamais renvoyée", async () => {
const s = await startServer();
try {
const syncKey = await journal(s);
const { body: client } = await register(s);
const { challenge } = pkce();
const ok = { client_id: client.client_id, redirect_uri: REDIRECT, state: "s", code_challenge: challenge, code_challenge_method: "S256", sync_key: syncKey };
const fails = [
[{ code_challenge: undefined }, "invalid_request"],
[{ code_challenge_method: "plain" }, "invalid_request"],
[{ sync_key: "pas une clé" }, "invalid_sync_key"],
[{ sync_key: generateSyncKey() }, "unknown_journal"],
[{ redirect_uri: "https://ailleurs.example/cb" }, "invalid_request"],
];
for (const [change, error] of fails) {
const r = await authorize(s, { ...ok, ...change });
const text = await r.text();
assert.equal(r.status, 400, JSON.stringify(change));
assert.equal(JSON.parse(text).error, error);
assert.ok(!text.includes(syncKey.slice(0, 9)), "la clé n'apparaît pas dans l'erreur");
}
const r = await authorize(s, { ...ok, sync_key: syncKey.toLowerCase().replace(/-/g, " ") });
assert.equal(r.status, 200);
const { redirect } = await r.json();
const u = new URL(redirect);
assert.equal(u.origin + u.pathname, REDIRECT);
assert.equal(u.searchParams.get("state"), "s");
assert.ok(!redirect.includes(syncKey.replace(/-/g, "").slice(0, 8)), "la clé est chiffrée dans le code");
} finally {
await s.close();
}
});
test("échange : code à usage unique, vérificateur PKCE exigé, rafraîchissement, jetons vers le MCP", async () => {
const s = await startServer();
try {
const syncKey = await journal(s);
const { body: client } = await register(s);
const { verifier, challenge } = pkce();
const r = await authorize(s, { client_id: client.client_id, redirect_uri: REDIRECT, code_challenge: challenge, code_challenge_method: "S256", sync_key: syncKey });
const code = new URL((await r.json()).redirect).searchParams.get("code") ?? "";
const form = { grant_type: "authorization_code", code, client_id: client.client_id, redirect_uri: REDIRECT };
let t = await token(s, form);
assert.equal(t.status, 400, "sans code_verifier");
assert.equal((await t.json()).error, "invalid_grant");
t = await token(s, { ...form, code_verifier: pkce().verifier });
assert.equal(t.status, 400, "mauvais code_verifier");
t = await token(s, { ...form, code_verifier: verifier, redirect_uri: "https://claude.ai/autre" });
assert.equal(t.status, 400, "autre redirect_uri");
t = await token(s, { ...form, code_verifier: verifier });
assert.equal(t.status, 200);
const tokens = await t.json();
assert.equal(tokens.token_type, "Bearer");
assert.equal(tokens.expires_in, 3600);
t = await token(s, { ...form, code_verifier: verifier });
assert.equal(t.status, 400, "code déjà utilisé");
assert.match((await t.json()).error_description, /déjà utilisé/);
// Le jeton d'accès ouvre le MCP ; un jeton de rafraîchissement, non.
assert.equal((await rpc(s, tokens.access_token, "ping")).result !== undefined, true);
assert.equal((await s.fetch("/mcp", { method: "POST", headers: { authorization: "Bearer " + tokens.refresh_token } })).status, 401);
const refreshed = await token(s, { grant_type: "refresh_token", refresh_token: tokens.refresh_token, client_id: client.client_id });
assert.equal(refreshed.status, 200);
const next = await refreshed.json();
assert.ok((await rpc(s, next.access_token, "tools/list")).result.tools.length > 0);
// Rafraîchissement par un autre client : refusé.
const { body: other } = await register(s, ["https://chatgpt.com/connector_platform_oauth_redirect"]);
assert.equal((await token(s, { grant_type: "refresh_token", refresh_token: tokens.refresh_token, client_id: other.client_id })).status, 400);
assert.equal((await token(s, { grant_type: "password" })).status, 400);
} finally {
await s.close();
}
});
test("jetons expirés : code après 5 min, accès après 1 h, rafraîchissement après 90 jours", () => {
let t = Date.parse("2026-11-18T10:00:00Z");
const oauth = createOAuth({ secret: crypto.randomBytes(32), now: () => t });
const { client_id } = oauth.register({ redirect_uris: [REDIRECT] });
const { verifier, challenge } = pkce();
const request = oauth.checkAuthorization({ client_id, redirect_uri: REDIRECT, code_challenge: challenge, code_challenge_method: "S256" });
const key = generateSyncKey();
const code = new URL(oauth.authorize(request, client_id, key)).searchParams.get("code") ?? "";
t += TTL.codeMs + 1;
assert.throws(() => oauth.token({ grant_type: "authorization_code", code, code_verifier: verifier }), /expiré/);
t -= 2;
const tokens = oauth.token({ grant_type: "authorization_code", code, code_verifier: verifier });
assert.equal(oauth.verifyAccess(tokens.access_token), key);
t += TTL.accessMs + 1;
assert.equal(oauth.verifyAccess(tokens.access_token), null);
assert.ok(oauth.token({ grant_type: "refresh_token", refresh_token: tokens.refresh_token }).access_token);
t += TTL.refreshMs;
assert.throws(() => oauth.token({ grant_type: "refresh_token", refresh_token: tokens.refresh_token }), /expiré/);
// Un jeton altéré ou d'une autre nature n'ouvre rien.
assert.equal(oauth.verifyAccess(tokens.refresh_token), null);
assert.equal(oauth.verifyAccess("abc"), null);
});
test("parcours complet en une fonction (helpers) : sert aux tests MCP", async () => {
const s = await startServer();
try {
const { tokens } = await connect(s, await journal(s));
assert.ok(tokens.access_token);
} finally {
await s.close();
}
});