peppa/packages/testkit/test/oauth.test.ts
Асель 498013472f PEP-58: Bugsink — production errors become Peppa incidents and tasks
- infra: Bugsink 2.6.3 in docker (infra/bugsink, scripts/bugsink-up.sh), database
  bugsink in Peppa's Postgres, Traefik route bugsink.telecom.quest
- packages/bugsink: REST API client + custom-webhook payload parsing
- incidents (migration 0011): incident_settings, error_sources, incidents; ingest from
  webhook POST /api/hooks/bugsink/<secret> and a 2-minute poll in the watchdog
- incident policy per project: notify / backlog (default) / start / ask (Telegram
  buttons) / triage (claude -p with the owner's token, falls back to ask)
- daily task cap, environments, ignore pattern; manual "fixed" until PEP-57;
  REGRESSED returns the task to the backlog
- web «Ошибки» section, bot buttons, MCP tools for agents and the PM, help, RULES.md
- testkit: mock-bugsink, mock-triage, incidents.test.ts (one test per scenario,
  plus a live run against the real Bugsink with PEPPA_LIVE_BUGSINK=1)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 14:31:32 +05:00

240 lines
15 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-8: OAuth 2.1 server and the PM MCP tools served to remote clients (ChatGPT).
import assert from "node:assert/strict";
import { createHash, randomBytes } from "node:crypto";
import { after, before, describe, test } from "node:test";
import { core, db, project, runner, teardown } from "./helpers.ts";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { eq } from "drizzle-orm";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const { createManagerServer } = await import("@peppa/mcp/manager");
const REDIRECT = "https://chatgpt.com/connector_platform_oauth_redirect";
let owner: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let stranger: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
before(async () => {
owner = await core.upsertUserFromGitea(db, { id: 21, login: "mock-owner" }, { access_token: "x" });
stranger = await core.upsertUserFromGitea(db, { id: 22, login: "mock-stranger" }, { access_token: "y" });
});
after(teardown);
const pkce = () => {
const verifier = randomBytes(32).toString("base64url");
return { verifier, challenge: createHash("sha256").update(verifier).digest("base64url") };
};
async function authorize(clientId: string, userId: number, challenge: string) {
return core.issueCode(db, { clientId, redirectUri: REDIRECT, codeChallenge: challenge, codeChallengeMethod: "S256", responseType: "code" }, userId);
}
describe("OAuth server", () => {
test("dynamic registration accepts https/localhost redirects only", async () => {
await assert.rejects(core.registerClient(db, "bad", ["http://evil.example/cb"]), /redirect_uris/);
await assert.rejects(core.registerClient(db, "bad", []), /redirect_uris/);
const c = await core.registerClient(db, "ChatGPT", [REDIRECT, "http://localhost:8765/cb"]);
assert.match(c.id, /^peppa-/);
});
test("authorize request validation", async () => {
const c = await core.registerClient(db, "ChatGPT", [REDIRECT]);
const ok = { clientId: c.id, redirectUri: REDIRECT, codeChallenge: pkce().challenge, codeChallengeMethod: "S256", responseType: "code" };
await core.checkAuthorizeRequest(db, ok);
await assert.rejects(core.checkAuthorizeRequest(db, { ...ok, clientId: "nope" }), /Неизвестное приложение/);
await assert.rejects(core.checkAuthorizeRequest(db, { ...ok, redirectUri: "https://other.example/cb" }), /не зарегистрирован/);
await assert.rejects(core.checkAuthorizeRequest(db, { ...ok, codeChallengeMethod: "plain" }), /PKCE/);
});
test("code + PKCE → tokens; replay, wrong verifier and wrong redirect are refused", async () => {
const c = await core.registerClient(db, "ChatGPT", [REDIRECT]);
const { verifier, challenge } = pkce();
const code = await authorize(c.id, owner.id, challenge);
const base = { grant_type: "authorization_code", client_id: c.id, redirect_uri: REDIRECT };
const t = await core.exchangeToken(db, { ...base, code, code_verifier: verifier });
assert.equal(t.token_type, "Bearer");
assert.deepEqual(await core.verifyAccessToken(db, t.access_token), { userId: owner.id, clientId: c.id });
await assert.rejects(core.exchangeToken(db, { ...base, code, code_verifier: verifier }), /already used/);
const p2 = pkce();
const code2 = await authorize(c.id, owner.id, p2.challenge);
await assert.rejects(core.exchangeToken(db, { ...base, code: code2, code_verifier: pkce().verifier }), /PKCE/);
const p3 = pkce();
const code3 = await authorize(c.id, owner.id, p3.challenge);
await assert.rejects(core.exchangeToken(db, { ...base, redirect_uri: "https://other.example/cb", code: code3, code_verifier: p3.verifier }), /mismatch/);
assert.equal(await core.verifyAccessToken(db, "garbage"), null);
});
test("refresh tokens rotate; revoking the app kills its tokens", async () => {
const c = await core.registerClient(db, "ChatGPT revoke", [REDIRECT]);
const { verifier, challenge } = pkce();
const t1 = await core.exchangeToken(db, { grant_type: "authorization_code", client_id: c.id, redirect_uri: REDIRECT, code: await authorize(c.id, owner.id, challenge), code_verifier: verifier });
const t2 = await core.exchangeToken(db, { grant_type: "refresh_token", refresh_token: t1.refresh_token, client_id: c.id });
await assert.rejects(core.exchangeToken(db, { grant_type: "refresh_token", refresh_token: t1.refresh_token }), /invalid/, "old refresh token is single use");
assert.ok(await core.verifyAccessToken(db, t2.access_token));
assert.ok((await core.connectedApps(db, owner.id)).some((a) => a.clientId === c.id));
assert.ok((await core.revokeApp(db, owner.id, c.id)) > 0);
assert.equal(await core.verifyAccessToken(db, t2.access_token), null);
await assert.rejects(core.exchangeToken(db, { grant_type: "refresh_token", refresh_token: t2.refresh_token }), /invalid/);
assert.ok(!(await core.connectedApps(db, owner.id)).some((a) => a.clientId === c.id));
});
});
async function mcpAs(user: typeof owner) {
const [a, b] = InMemoryTransport.createLinkedPair();
await createManagerServer(db, user, "https://peppa.test").connect(a);
const client = new Client({ name: "mock-chatgpt", version: "0" });
await client.connect(b);
const call = async (name: string, args: Record<string, unknown> = {}) => {
const r = await client.callTool({ name, arguments: args });
return { text: (r.content as Array<{ text: string }>)[0]!.text, isError: !!r.isError };
};
return { client, call };
}
describe("PM tools over MCP", () => {
test("list, create, move (starts an agent), inbox, answer; strangers see nothing", async () => {
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "2", question: "Какой порт?", options: ["8080", "3000"] } }], [{ say: "Ок." }]] });
const proj = await core.getProject(db, p.key);
await core.setProjectOwner(db, proj.id, owner.id);
const { client, call } = await mcpAs(owner);
const tools = (await client.listTools()).tools;
assert.deepEqual(tools.map((t) => t.name).sort(), ["add_member", "answer_question", "create_goal", "create_project", "create_task", "decide_incident", "get_incident", "get_incident_policy", "get_task", "list_goals", "list_inbox", "list_incidents", "list_members", "list_projects", "list_tasks", "move_task", "remove_member", "resolve_incident", "set_incident_policy", "update_goal", "update_task"]);
assert.equal(tools.find((t) => t.name === "list_tasks")?.annotations?.readOnlyHint, true);
assert.equal(tools.find((t) => t.name === "move_task")?.annotations?.readOnlyHint, false);
assert.match((await call("list_projects")).text, new RegExp(`${p.key} — `));
const created = await call("create_task", { project: p.key, title: "Из ChatGPT: порт сервиса" });
assert.match(created.text, new RegExp(`Created ${p.key}-2`));
assert.match((await call("list_tasks", { project: p.key, column: "backlog" })).text, /Из ChatGPT/);
const moved = await call("move_task", { task: `${p.key}-2`, to: "in_progress" });
assert.match(moved.text, /agent session #\d+ started/);
const sid = Number(/#(\d+)/.exec(moved.text)![1]);
const q = await p.waitQuestion(sid, "question");
assert.match((await call("list_inbox")).text, new RegExp(`#${q.id} ${p.key}-2 · question`));
assert.match((await call("answer_question", { question_id: q.id, answer: "3000" })).text, /Delivered/);
await p.waitLog("answer reached the agent", (e) => e.ev === "prompt" && String(e.prompt).includes(": 3000"));
const s = await mcpAs(stranger);
assert.match((await s.call("list_projects")).text, /No projects/);
const denied = await s.call("move_task", { task: `${p.key}-2`, to: "backlog" });
assert.ok(denied.isError);
assert.match(denied.text, /Не найдено/);
assert.ok((await s.call("answer_question", { question_id: q.id, answer: "x" })).isError);
assert.match((await call("move_task", { task: `${p.key}-2`, to: "backlog" })).text, /1 session\(s\) stopped/);
});
});
describe("update_task over MCP", () => {
test("title only, description only, both — goal, status and sessions untouched", async () => {
const p = await project({ turns: [] });
const proj = await core.getProject(db, p.key);
await core.setProjectOwner(db, proj.id, owner.id);
const goal = await core.createGoal(db, proj.id, "Цель для правки");
const ref = await core.createTask(db, { projectId: proj.id, goalId: goal.id, title: "Начать делать", description: "старое описание" });
const { client, call } = await mcpAs(owner);
assert.equal((await client.listTools()).tools.find((t) => t.name === "update_task")?.annotations?.readOnlyHint, false);
const snapshot = async () => {
const t = (await core.resolveTask(db, ref.key)).task;
return { title: t.title, description: t.description, goalId: t.goalId, status: t.status, sessions: (await core.listSessions(db, { taskId: t.id })).length };
};
const r1 = await call("update_task", { task: ref.key, title: "Новое название" });
assert.ok(!r1.isError, r1.text);
assert.match(r1.text, new RegExp(`# ${ref.key}: Новое название`));
assert.deepEqual(await snapshot(), { title: "Новое название", description: "старое описание", goalId: goal.id, status: "backlog", sessions: 0 });
const desc = "Сделать доску.\n\nУсловия готовности:\n- пункт 1\n- пункт 2";
const r2 = await call("update_task", { task: ref.key, description: desc });
assert.match(r2.text, /Условия готовности/);
assert.deepEqual(await snapshot(), { title: "Новое название", description: desc, goalId: goal.id, status: "backlog", sessions: 0 });
const r3 = await call("update_task", { task: ref.key, title: "Оба поля", description: "оба описания" });
assert.match(r3.text, /Оба поля/);
assert.match(r3.text, /оба описания/);
assert.match(r3.text, /Цель: #\d+ Цель для правки/);
assert.deepEqual(await snapshot(), { title: "Оба поля", description: "оба описания", goalId: goal.id, status: "backlog", sessions: 0 });
assert.ok((await call("update_task", { task: ref.key })).isError, "nothing to update");
const s = await mcpAs(stranger);
const denied = await s.call("update_task", { task: ref.key, title: "чужое" });
assert.ok(denied.isError);
assert.match(denied.text, /Не найдено/);
assert.equal((await snapshot()).title, "Оба поля");
const evs = await db.select().from((await import("@peppa/db")).events).where(eq((await import("@peppa/db")).events.taskId, ref.task.id));
assert.equal(evs.filter((e) => e.type === "task_updated").length, 3, "each edit is in the task's event log");
});
});
describe("goals, task goal and project creation over MCP", () => {
test("server instructions explain the model", async () => {
const { client } = await mcpAs(owner);
assert.match(client.getInstructions() ?? "", /project .*goals .*tasks/s);
});
test("create/update goals; move a task between goals and detach; foreign goal refused", async () => {
const p = await project({ turns: [] });
const proj = await core.getProject(db, p.key);
await core.setProjectOwner(db, proj.id, owner.id);
const { call } = await mcpAs(owner);
const g1 = Number(/goal #(\d+)/.exec((await call("create_goal", { project: p.key, title: "Цель один", description: "зачем" })).text)![1]);
const g2 = Number(/goal #(\d+)/.exec((await call("create_goal", { project: p.key, title: "Цель два" })).text)![1]);
assert.match((await call("list_goals", { project: p.key })).text, /Цель один[\s\S]*Цель два/);
assert.match((await call("update_goal", { project: p.key, goal_id: g1, title: "Цель первая" })).text, /Цель первая \[open\]/);
const t = await call("create_task", { project: p.key, title: "Задача в цели", goal_id: g1 });
const key = /Created (\S+):/.exec(t.text)![1]!;
assert.match((await call("update_task", { task: key, goal_id: g2 })).text, /Цель: #\d+ Цель два/);
const moved = (await core.resolveTask(db, key)).task;
assert.equal(moved.goalId, g2);
assert.equal(moved.title, "Задача в цели");
assert.equal(moved.status, "backlog");
await call("update_task", { task: key, goal_id: null });
assert.equal((await core.resolveTask(db, key)).task.goalId, null);
const other = await project({ turns: [] });
const foreignGoal = await core.createGoal(db, (await core.getProject(db, other.key)).id, "Чужая цель");
assert.ok((await call("update_task", { task: key, goal_id: foreignGoal.id })).isError, "goal of another project");
assert.ok((await call("update_goal", { project: p.key, goal_id: foreignGoal.id, title: "взлом" })).isError);
assert.match((await call("update_goal", { project: p.key, goal_id: g1, status: "done" })).text, /\[done\]/);
assert.doesNotMatch((await call("list_goals", { project: p.key })).text, /Цель первая/);
});
test("create_project through MCP, owned by the user", async () => {
const { MockGitea } = await import("../src/mock-gitea.ts");
const { mkdtempSync } = await import("node:fs");
const { tmpdir } = await import("node:os");
const { join, resolve } = await import("node:path");
const { fileURLToPath } = await import("node:url");
const { execFileSync } = await import("node:child_process");
const tmp = mkdtempSync(join(tmpdir(), "peppa-mcp-proj-"));
const gitea = await new MockGitea(join(tmp, "gitea")).start();
const prevUrl = process.env.GITEA_URL;
try {
process.env.GITEA_URL = gitea.url;
process.env.PEPPA_WORKSPACES = join(tmp, "ws");
gitea.addUser({ id: 41, login: "mock-mcp-owner", token: "mock-token-mcp" });
const tpl = gitea.addRepo("peppa-bot", "template");
const root = resolve(fileURLToPath(import.meta.url), "../../../..");
execFileSync("bash", ["-c", `cd ${JSON.stringify(join(root, "template"))} && T=$(mktemp -d) && cp -R . "$T" && cd "$T" && git init -q -b main && git add -A && git -c user.name=t -c user.email=t@t commit -qm tpl && git push -q ${JSON.stringify(tpl.path)} main`]);
process.env.PEPPA_TEMPLATE_URL = tpl.path;
const u = await core.upsertUserFromGitea(db, { id: 41, login: "mock-mcp-owner" }, { access_token: "mock-token-mcp" });
const { call } = await mcpAs(u);
const r = await call("create_project", { name: "Mock MCP project", slug: "mock-mcp-proj", key: "MMCP" });
assert.ok(!r.isError, r.text);
assert.match(r.text, /Created project MMCP/);
assert.equal((await core.getProject(db, "MMCP")).ownerId, u.id);
assert.ok(gitea.files("mock-mcp-owner", "mock-mcp-proj").includes("AGENTS.md"));
assert.match((await call("list_projects")).text, /MMCP — Mock MCP project/);
assert.ok((await call("create_project", { name: "dup", slug: "mock-mcp-proj", key: "MMCP2" })).isError, "duplicate refused");
} finally {
process.env.GITEA_URL = prevUrl;
delete process.env.PEPPA_TEMPLATE_URL;
await gitea.stop();
}
});
});