peppa/packages/testkit/test/access-hub-oauth.test.ts
peppa-bot c83454889c
All checks were successful
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 50с
peppa/build build: success за 34с
peppa/test test: success за 1416с
peppa-ci / ci (pull_request) Successful in 26m6s
PEP-252: вход в сервисы через OAuth (Google, GitHub) — поверх свежей main
Ядро (обновление токенов, «Войти заново», отзыв в сервисе), экран «Подключения»,
тексты ru/kk/en, мок и тесты. Пересобрано на main после PEP-251/258:
миграция теперь 0033_access_hub_oauth, маскировка ответа — connectionKeyForms
от текущего токена, проверка подключений принимает notify вместе с drivers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:00:23 +00:00

288 lines
17 KiB
TypeScript
Raw 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-252 Access Hub: connecting Google Sheets and GitHub by signing in (OAuth code + PKCE),
// the gateway refreshing tokens itself, «нужно войти заново», revoke in the service, another
// person's callback. Scenario names follow openspec/changes/pep-252-access-hub-oauth/specs.
import assert from "node:assert/strict";
import { after, before, describe, test } from "node:test";
import { eq, like } from "drizzle-orm";
import { core, db, project, teardown } from "./helpers.ts";
import { MockOAuthService } from "../src/mock-oauth-service.ts";
import { stripAsIs } from "@peppa/shared/i18n";
import type { ConnectionFetch } from "@peppa/core";
process.env.PEPPA_SECRET ??= "mock-access-hub-secret";
process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE = "1";
const { connections, connectionLog, agents, sessions, chatMessages } = await import("@peppa/db");
const google = new MockOAuthService("google");
const github = new MockOAuthService("github");
let googleBase: string;
let githubBase: string;
const REDIRECT = "https://forge.example.com/connections/oauth/callback";
let anna: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let boris: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
before(async () => {
googleBase = await google.start();
githubBase = await github.start();
Object.assign(process.env, {
PEPPA_OAUTH_GOOGLE_CLIENT_ID: google.clientId,
PEPPA_OAUTH_GOOGLE_CLIENT_SECRET: google.clientSecret,
PEPPA_OAUTH_GOOGLE_BASE: googleBase,
PEPPA_OAUTH_GITHUB_CLIENT_ID: github.clientId,
PEPPA_OAUTH_GITHUB_CLIENT_SECRET: github.clientSecret,
PEPPA_OAUTH_GITHUB_BASE: githubBase,
});
anna = await core.upsertUserFromGitea(db, { id: 2521, login: "mock-anna-oauth" }, { access_token: "a" });
boris = await core.upsertUserFromGitea(db, { id: 2522, login: "mock-boris-oauth" }, { access_token: "b" });
});
after(async () => {
await google.stop();
await github.stop();
await teardown();
});
/** The gateway's request goes to the mock instead of sheets.googleapis.com / api.github.com. */
const toMock = (mockBase: string): ConnectionFetch => (o) => {
const real = new URL(o.url);
const url = new URL(mockBase + real.pathname + real.search);
return core.defaultConnectionFetch({ ...o, url });
};
/** The browser: start → the service's page → back with code and state. */
async function signIn(userId: number, i: { catalogId?: string; connectionId?: number; level?: string }) {
const start = await core.startConnectionOAuth(db, userId, { ...i, redirectUri: REDIRECT });
const res = await fetch(start.url, { redirect: "manual" });
assert.equal(res.status, 302);
const back = new URL(res.headers.get("location")!);
assert.equal(back.origin + back.pathname, REDIRECT);
return { start, code: back.searchParams.get("code") ?? "", state: back.searchParams.get("state") ?? "", error: back.searchParams.get("error") };
}
async function connect(userId: number, catalogId: string, level = "read") {
const s = await signIn(userId, { catalogId, level });
return core.completeConnectionOAuth(db, userId, { state: s.state, code: s.code, cookieState: s.start.state });
}
async function agentFor(ownerId: number) {
const p = await project({ turns: [] });
const proj = await core.getProject(db, p.key);
await core.setProjectOwner(db, proj.id, ownerId);
const task = (await core.listTasks(db, { projectId: proj.id }))[0]!;
const s = await core.createSession(db, { projectId: proj.id, taskId: task.id });
const [a] = await db.insert(agents).values({ name: `Мок-агент OAuth ${s.id}` }).returning();
await db.update(sessions).set({ agentId: a!.id, container: `peppa-s${s.id}` }).where(eq(sessions.id, s.id));
return { proj, sessionId: s.id };
}
const row = async (id: number) => (await db.select().from(connections).where(eq(connections.id, id)))[0]!;
const reloginMessages = async (name: string) => (await db.select().from(chatMessages).where(like(chatMessages.text, "%Войти заново%"))).filter((m) => stripAsIs(m.text).includes(`«${name}»`)).length;
describe("Подключение входом через сервис", () => {
test("Владелец подключает Google Sheets входом", async () => {
const offer = core.oauthOffer("google-sheets");
assert.ok(offer, "the sign-in way is offered when FORGE has a Google client");
assert.deepEqual(offer!.read.map(core.scopeLabel), ["spreadsheets.readonly"]);
const s = await signIn(anna.id, { catalogId: "google-sheets", level: "read" });
const asked = google.seen.authorize.at(-1)!;
assert.equal(asked.get("scope"), "https://www.googleapis.com/auth/spreadsheets.readonly");
assert.equal(asked.get("code_challenge_method"), "S256");
assert.equal(asked.get("access_type"), "offline");
const r = await core.completeConnectionOAuth(db, anna.id, { state: s.state, code: s.code, cookieState: s.start.state });
assert.equal(r.created, true);
const c = (await core.listConnections(db, anna.id)).find((x) => x.id === r.connectionId)!;
assert.equal(c.name, "Google Sheets");
assert.equal(c.authKind, "oauth");
assert.equal(c.oauthProvider, "google");
assert.deepEqual(c.oauthScopes.map(core.scopeLabel), ["spreadsheets.readonly"]);
// Tokens: only in the sealed envelope.
const tokens = [...google.access.keys(), ...google.refresh.keys()];
const stored = await row(r.connectionId);
for (const t of tokens) {
assert.ok(!JSON.stringify(c).includes(t), "not in the owner's view");
assert.ok(!JSON.stringify(stored).includes(t), "not in the clear in the database");
}
assert.ok(stored.dekEnc && stored.secretEnc?.startsWith("v2."));
// The PKCE verifier reached the token endpoint, the client secret too.
const tok = google.seen.token.at(-1)!;
assert.ok(tok.get("code_verifier"));
});
test("Клиент не настроен — способ скрыт", async () => {
const env = { ...process.env, PEPPA_OAUTH_GITHUB_CLIENT_ID: "", PEPPA_OAUTH_GITHUB_CLIENT_SECRET: "" };
assert.equal(core.oauthOffer("github", env), null);
assert.ok(core.oauthOffer("github"));
assert.equal(core.oauthOffer("stripe"), null, "a card without sign-in");
await assert.rejects(core.startConnectionOAuth(db, anna.id, { catalogId: "github", redirectUri: REDIRECT }, env), /не настроен/);
});
test("Поток подменили: другой state, повтор, чужой пользователь", async () => {
const s = await signIn(anna.id, { catalogId: "github" });
const before = (await core.listConnections(db, anna.id)).length;
await assert.rejects(core.completeConnectionOAuth(db, anna.id, { state: s.state, code: s.code, cookieState: "other-browser" }), core.PeppaError);
// The flow is spent even by a refused try.
const s2 = await signIn(anna.id, { catalogId: "github" });
await assert.rejects(core.completeConnectionOAuth(db, boris.id, { state: s2.state, code: s2.code, cookieState: s2.start.state }), core.PeppaError, "another person signed in");
await assert.rejects(core.completeConnectionOAuth(db, anna.id, { state: s2.state, code: s2.code, cookieState: s2.start.state }), core.PeppaError, "one-shot");
assert.equal((await core.listConnections(db, anna.id)).length, before);
assert.equal((await core.listConnections(db, boris.id)).length, 0);
// «Войти заново» into someone else's connection is refused at the start.
const mine = (await core.listConnections(db, anna.id))[0]!;
await assert.rejects(core.startConnectionOAuth(db, boris.id, { connectionId: mine.id, redirectUri: REDIRECT }), /не найдено/);
});
test("Отказ на странице сервиса и непрошенные права", async () => {
google.deny = true;
const s = await signIn(anna.id, { catalogId: "google-drive" });
google.deny = false;
assert.equal(s.error, "access_denied");
assert.equal(s.code, "");
google.consentScopes = ["openid"];
try {
await assert.rejects(connect(anna.id, "google-drive"), /нужный доступ/);
} finally {
google.consentScopes = null;
}
});
});
describe("Шлюз сам обновляет токен", () => {
test("Токен истёк — агент читает таблицу", async () => {
const { connectionId } = await connect(anna.id, "google-sheets");
const { proj, sessionId } = await agentFor(anna.id);
await core.grantConnection(db, anna.id, connectionId, { projectId: proj.id, readMode: "auto" });
const fetch = toMock(googleBase);
const slug = (await row(connectionId)).slug!;
const first = await core.callConnection(db, { sessionId, connection: slug, method: "GET", path: "/v4/spreadsheets/abc" }, { fetch });
assert.equal(first.ok && first.status, 200);
assert.match(first.ok ? first.body : "", /Продажи/);
const refreshesBefore = google.seen.token.filter((f) => f.get("grant_type") === "refresh_token").length;
// Expired by its stored date: refreshed before the call.
const now = new Date(Date.now() + 2 * 3600_000);
google.expireAccess();
const second = await core.callConnection(db, { sessionId, connection: slug, method: "GET", path: "/v4/spreadsheets/abc" }, { fetch, now });
assert.equal(second.ok && second.status, 200);
assert.equal(google.seen.token.filter((f) => f.get("grant_type") === "refresh_token").length, refreshesBefore + 1);
// Expired early at the service (date says fine): 401 → one refresh → repeated.
google.expireAccess();
const third = await core.callConnection(db, { sessionId, connection: slug, method: "GET", path: "/v4/spreadsheets/abc" }, { fetch, now });
assert.equal(third.ok && third.status, 200);
// A range with «:» goes encoded (the gateway refuses a bare colon in a path).
const range = await core.callConnection(db, { sessionId, connection: slug, method: "GET", path: "/v4/spreadsheets/abc/values/A1%3AB2" }, { fetch, now });
assert.equal(range.ok && range.status, 200);
assert.ok(google.seen.api.some((x) => x.path === "/v4/spreadsheets/abc/values/A1%3AB2"), "reaches the service encoded");
// Writing is not granted: refused before any token is used.
const write = await core.callConnection(db, { sessionId, connection: slug, method: "PUT", path: "/v4/spreadsheets/abc/values/A1", body: "{}" }, { fetch, now });
assert.equal(!write.ok && write.reason, "write_denied");
// Nothing of the tokens in the journal.
const log = JSON.stringify(await db.select().from(connectionLog).where(eq(connectionLog.connectionId, connectionId)));
for (const t of [...google.access.keys(), ...google.refresh.keys()]) assert.ok(!log.includes(t));
// Daily check works with the token too.
const chk = await core.checkConnection(db, anna.id, connectionId, { fetch, now });
assert.equal(chk.status, "ok");
});
test("GitHub: агент читает репозиторий, обновление меняет и ключ обновления", async () => {
const { connectionId } = await connect(anna.id, "github");
const { proj, sessionId } = await agentFor(anna.id);
await core.grantConnection(db, anna.id, connectionId, { projectId: proj.id, readMode: "auto" });
const fetch = toMock(githubBase);
const now = new Date(Date.now() + 9 * 3600_000);
const oldRefresh = [...github.refresh.keys()];
const r = await core.callConnection(db, { sessionId, connection: "github", method: "GET", path: "/repos/mock-anna/shop" }, { fetch, now });
assert.equal(r.ok && r.status, 200);
assert.ok(oldRefresh.every((t) => !github.refresh.has(t)), "the old refresh token is spent");
const again = await core.callConnection(db, { sessionId, connection: "github", method: "GET", path: "/user" }, { fetch, now });
assert.equal(again.ok && again.status, 200, "the new refresh token was saved");
});
test("Доступ отозвали в самом сервисе — нужно войти заново, одно сообщение", async () => {
const { connectionId } = await connect(anna.id, "google-calendar");
const { proj, sessionId } = await agentFor(anna.id);
await core.grantConnection(db, anna.id, connectionId, { projectId: proj.id, readMode: "auto" });
const name = (await row(connectionId)).name;
google.revokeAll();
const fetch = toMock(googleBase);
const now = new Date(Date.now() + 2 * 3600_000);
const r = await core.callConnection(db, { sessionId, connection: connectionId, method: "GET", path: "/calendars/primary/events" }, { fetch, now });
assert.equal(!r.ok && r.reason, "needs_login");
const c = await row(connectionId);
assert.equal(c.status, "relogin");
assert.equal(c.secretEnc, null, "dead tokens are wiped");
assert.equal(await reloginMessages(name), 1);
const r2 = await core.callConnection(db, { sessionId, connection: connectionId, method: "GET", path: "/calendars/primary/events" }, { fetch, now });
assert.equal(!r2.ok && r2.reason, "needs_login");
await core.connectionCheckTick(db, { fetch, now: new Date(now.getTime() + 2 * 86400_000) });
assert.equal(await reloginMessages(name), 1, "no second message");
// The agent sees it as not working.
const seen = (await core.agentConnections(db, sessionId)).find((x) => x.id === connectionId)!;
assert.equal(seen.checkStatus, "bad_key");
// Войти заново: same connection, grants kept.
const s = await signIn(anna.id, { connectionId });
const back = await core.completeConnectionOAuth(db, anna.id, { state: s.state, code: s.code, cookieState: s.start.state });
assert.deepEqual(back, { connectionId, created: false });
assert.equal((await row(connectionId)).status, "active");
assert.equal((await core.listConnections(db, anna.id)).find((x) => x.id === connectionId)!.grants.length, 1);
const ok = await core.callConnection(db, { sessionId, connection: connectionId, method: "GET", path: "/calendars/primary/events" }, { fetch });
assert.equal(ok.ok && ok.status, 200);
assert.match(ok.ok ? ok.body : "", /поставщиком/);
});
test("Сервис обновления не отвечает — подключение не ломается", async () => {
const { connectionId } = await connect(anna.id, "google-sheets");
const { proj, sessionId } = await agentFor(anna.id);
await core.grantConnection(db, anna.id, connectionId, { projectId: proj.id, readMode: "auto" });
google.down = true;
try {
const r = await core.callConnection(db, { sessionId, connection: connectionId, method: "GET", path: "/v4/spreadsheets/x" }, { fetch: toMock(googleBase), now: new Date(Date.now() + 2 * 3600_000) });
assert.equal(!r.ok && r.reason, "upstream_error");
} finally {
google.down = false;
}
assert.equal((await row(connectionId)).status, "active");
});
test("Ключ у подключения входом заменить нельзя", async () => {
const { connectionId } = await connect(anna.id, "google-drive");
await assert.rejects(core.replaceConnectionSecret(db, anna.id, connectionId, "AIza-mock-key-123"), /Войти заново/);
});
});
describe("Отзыв доступа отзывает токен в сервисе", () => {
test("Отзыв GitHub", async () => {
const { connectionId } = await connect(anna.id, "github");
const access = [...github.access.keys()].at(-1)!;
const { proj, sessionId } = await agentFor(anna.id);
await core.grantConnection(db, anna.id, connectionId, { projectId: proj.id, readMode: "auto" });
const r = await core.revokeConnection(db, anna.id, connectionId);
assert.equal(r.remote, "revoked");
assert.ok(github.seen.revoked.includes(access));
assert.equal(github.access.size, 0);
const call = await core.callConnection(db, { sessionId, connection: connectionId, method: "GET", path: "/user" }, { fetch: toMock(githubBase) });
assert.equal(!call.ok && call.reason, "revoked");
});
test("Удаление отзывает Google", async () => {
const { connectionId } = await connect(anna.id, "google-sheets");
const refresh = [...google.refresh.keys()].at(-1)!;
await core.deleteConnection(db, anna.id, connectionId);
assert.ok(google.seen.revoked.includes(refresh));
assert.ok(!google.refresh.has(refresh));
});
test("Сервис не отвечает при отзыве", async () => {
const { connectionId } = await connect(anna.id, "google-sheets");
google.down = true;
try {
const r = await core.revokeConnection(db, anna.id, connectionId);
assert.equal(r.remote, "failed");
} finally {
google.down = false;
}
const c = await row(connectionId);
assert.equal(c.status, "revoked");
assert.equal(c.secretEnc, null);
});
});