peppa/packages/testkit/test/access-hub.test.ts
2026-11-24 15:16:12 +00:00

549 lines
33 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-234 Access Hub: users' own connections, agents' grants (deny by default), server-side
// gateway, instant revoke, journal without secrets. Scenario names follow
// openspec/changes/pep-234-access-hub/specs/access-hub/spec.md.
import assert from "node:assert/strict";
import { createServer, type IncomingHttpHeaders, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { after, before, describe, test } from "node:test";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { eq, sql } from "drizzle-orm";
import { core, db, project, teardown } from "./helpers.ts";
process.env.PEPPA_SECRET ??= "mock-access-hub-secret";
process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE = "1"; // the mock service listens on 127.0.0.1
const { createAgentServer } = await import("@peppa/mcp/agent");
const { connections, connectionLog, agents, sessions, events } = await import("@peppa/db");
const KEY = "sk_live_mock_ABCDEF123456";
const KEY_B = "sk_live_mock_boris_999999";
// A mock external service: records what reached it, echoes the key back to test masking.
const seen: Array<{ method: string; url: string; headers: IncomingHttpHeaders; body: string }> = [];
let mock: Server;
let base: string;
let anna: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let boris: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let asel: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
before(async () => {
mock = createServer((req, res) => {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => {
seen.push({ method: req.method!, url: req.url!, headers: req.headers, body });
if (req.url!.startsWith("/api/redirect")) {
res.writeHead(302, { location: "http://169.254.169.254/latest" });
return res.end();
}
res.writeHead(200, { "content-type": "application/json", "x-secret-echo": String(req.headers.authorization ?? "") });
res.end(JSON.stringify({ ok: true, path: req.url, echo: req.headers.authorization ?? req.headers["x-api-key"] ?? null }));
});
});
await new Promise<void>((r) => mock.listen(0, "127.0.0.1", r));
base = `http://127.0.0.1:${(mock.address() as AddressInfo).port}/api`;
anna = await core.upsertUserFromGitea(db, { id: 2341, login: "mock-anna" }, { access_token: "a" });
boris = await core.upsertUserFromGitea(db, { id: 2342, login: "mock-boris" }, { access_token: "b" });
asel = await core.upsertUserFromGitea(db, { id: 2343, login: "mock-asel" }, { access_token: "c" });
await core.setPlatformAdmins(db, ["mock-asel"]);
});
after(async () => {
await new Promise<void>((r) => mock.close(() => r()));
await teardown();
});
async function ownedProject(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]!;
return { proj, task };
}
let agentSeq = 0;
async function agentSession(projectId: number, taskId: number, o: { container?: boolean; agentId?: number } = {}) {
const s = await core.createSession(db, { projectId, taskId });
let agentId = o.agentId;
if (agentId == null) {
const [a] = await db.insert(agents).values({ name: `Мок-агент ${++agentSeq}-${Date.now()}` }).returning();
agentId = a!.id;
}
await db.update(sessions).set({ agentId, container: o.container === false ? null : `peppa-s${s.id}` }).where(eq(sessions.id, s.id));
return { sessionId: s.id, agentId };
}
const call = (sessionId: number, connection: string | number, method: string, path: string, extra: { body?: string; contentType?: string } = {}) => core.callConnection(db, { sessionId, connection, method, path, ...extra });
async function mcpAgent(sessionId: number, key: string) {
const [a, b] = InMemoryTransport.createLinkedPair();
await createAgentServer(db, { defaultKey: key, sessionId, lockProject: true }).connect(a);
const client = new Client({ name: "mock-agent", version: "0" });
await client.connect(b);
return 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 };
};
}
describe("Подключение внешнего сервиса", () => {
test("Подключение сохраняется без показа ключа", async () => {
const c = await core.createConnection(db, anna.id, { name: "CRM", baseUrl: base, secret: KEY });
assert.equal(c.status, "active");
assert.equal(c.hasKey, true);
const list = await core.listConnections(db, anna.id);
assert.ok(!JSON.stringify(list).includes(KEY), "the list never carries the key");
const [row] = await db.select().from(connections).where(eq(connections.id, c.id));
assert.ok(row!.secretEnc && !row!.secretEnc.includes(KEY), "stored encrypted");
assert.equal(core.openConnectionSecret(row!), KEY);
// PEP-19/254: the connection's own data key takes part in PEPPA_SECRET rotation.
const audit = await core.secretsAudit(db);
assert.ok(audit.encryption.columns.some((col) => col.table === "connections" && col.column === "dek_enc" && col.total >= 1));
});
test("Небезопасный адрес отклоняется", async () => {
const was = process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE;
delete process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE;
try {
for (const url of ["http://user:pass@127.0.0.1/admin", "http://crm.example.com/api", "https://u:p@crm.example.com/", "https://crm.example.com/api?x=1", "https://127.0.0.1/", "https://10.0.0.5/", "https://[::1]/", "https://localhost/", "https://169.254.169.254/", "ftp://crm.example.com/"]) {
await assert.rejects(core.createConnection(db, anna.id, { name: `bad ${url}`, baseUrl: url, secret: KEY }), core.PeppaError, url);
}
const ok = await core.createConnection(db, anna.id, { name: "Public", baseUrl: "https://crm.example.com/api/", secret: KEY });
assert.equal(ok.baseUrl, "https://crm.example.com/api");
} finally {
process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE = was;
}
});
});
describe("Подключения изолированы между пользователями", () => {
test("Чужое подключение не видно и не управляется — даже суперадмином", async () => {
const c = await core.createConnection(db, anna.id, { name: "CRM-own", baseUrl: base, secret: KEY });
await core.createConnection(db, boris.id, { name: "CRM-own", baseUrl: base, secret: KEY_B });
for (const u of [boris, asel]) {
const theirs = await core.listConnections(db, u.id);
assert.ok(!theirs.some((x) => x.id === c.id), `${u.login} does not see anna's connection`);
assert.ok(!JSON.stringify(theirs).includes(KEY));
const { proj } = await ownedProject(u.id);
await assert.rejects(core.grantConnection(db, u.id, c.id, { projectId: proj.id, operations: "GET /" }), /Подключение не найдено/);
await assert.rejects(core.revokeConnection(db, u.id, c.id), /Подключение не найдено/);
await assert.rejects(core.replaceConnectionSecret(db, u.id, c.id, "x".repeat(10)), /Подключение не найдено/);
await assert.rejects(core.deleteConnection(db, u.id, c.id), /Подключение не найдено/);
assert.equal((await core.connectionJournal(db, u.id)).filter((r) => r.connectionId === c.id).length, 0);
}
});
test("Разрешение можно дать только в свой проект", async () => {
const c = await core.createConnection(db, anna.id, { name: "CRM-proj", baseUrl: base, secret: KEY });
const { proj } = await ownedProject(boris.id);
await assert.rejects(core.grantConnection(db, anna.id, c.id, { projectId: proj.id, operations: "GET /items" }), /Не найдено/);
});
test("Агент проекта Бориса не может использовать ключ Анны", async () => {
const a = await core.createConnection(db, anna.id, { name: "Shared-name", baseUrl: base, secret: KEY });
const { proj: annaProj } = await ownedProject(anna.id);
await core.grantConnection(db, anna.id, a.id, { projectId: annaProj.id, operations: "GET /items" });
const { proj, task } = await ownedProject(boris.id);
const { sessionId } = await agentSession(proj.id, task.id);
const byId = await call(sessionId, a.id, "GET", "/items");
assert.deepEqual(byId, { ok: false, reason: "unknown_connection" });
const byName = await call(sessionId, "Shared-name", "GET", "/items");
assert.deepEqual(byName, { ok: false, reason: "unknown_connection" });
});
});
describe("Разрешения агентам, по умолчанию запрет", () => {
test("Разрешённая операция выполняется: ключ подставляет шлюз, в ответе он замаскирован, журнал без секретов", async () => {
const c = await core.createConnection(db, anna.id, { name: "CRM-allow", baseUrl: base, secret: KEY });
const { proj, task } = await ownedProject(anna.id);
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, operations: "GET /items" });
const { sessionId } = await agentSession(proj.id, task.id);
seen.length = 0;
const r = await call(sessionId, "CRM-allow", "GET", "/items/5?token=topsecret-query");
assert.equal(r.ok, true);
if (!r.ok) return;
assert.equal(r.status, 200);
assert.equal(seen.length, 1);
assert.equal(seen[0]!.url, "/api/items/5?token=topsecret-query");
assert.equal(seen[0]!.headers.authorization, `Bearer ${KEY}`);
assert.ok(!r.body.includes(KEY), "the key is masked in the answer");
assert.match(r.body, /Bearer ••••/);
const log = await core.connectionJournal(db, anna.id, { connectionId: c.id });
assert.equal(log.length, 1);
assert.equal(log[0]!.decision, "allowed");
assert.equal(log[0]!.path, "/items/5");
assert.equal(log[0]!.projectKey, proj.key);
assert.ok(log[0]!.agentName);
const raw = JSON.stringify(await db.select().from(connectionLog));
assert.ok(!raw.includes(KEY) && !raw.includes("topsecret-query"), "the journal holds no key and no query");
});
test("Свой заголовок ключа; заголовки агента не проходят", async () => {
const c = await core.createConnection(db, anna.id, { name: "CRM-header", baseUrl: base, secret: KEY, authKind: "header", authHeader: "X-Api-Key" });
const { proj, task } = await ownedProject(anna.id);
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, operations: ["POST /orders"] });
const { sessionId } = await agentSession(proj.id, task.id);
seen.length = 0;
const r = await call(sessionId, c.id, "POST", "/orders", { body: '{"n":1}' });
assert.equal(r.ok, true);
assert.equal(seen[0]!.headers["x-api-key"], KEY);
assert.equal(seen[0]!.headers.authorization, undefined);
assert.equal(seen[0]!.headers["content-type"], "application/json");
assert.equal(seen[0]!.body, '{"n":1}');
// A header injection through the content type is refused.
const bad = await call(sessionId, c.id, "POST", "/orders", { body: "{}", contentType: "application/json\r\nAuthorization: Bearer evil" });
assert.deepEqual(bad, { ok: false, reason: "bad_request" });
});
const cases: Array<[string, string, string, string]> = [
["SHOP", "DELETE", "/items/5", "operation_denied"],
["SHOP", "GET", "/itemsX", "operation_denied"],
["SHOP", "GET", "/items/../admin", "bad_path"],
["SHOP", "GET", "/items/%2e%2e/admin", "bad_path"],
["SHOP", "GET", "/items/%2fadmin", "bad_path"],
["SHOP", "GET", "//evil.example.com/items", "bad_path"],
["SHOP", "GET", "/items\\..\\admin", "bad_path"],
["SHOP", "GET", "/items@evil.example.com", "bad_path"],
["SHOP", "GET", "http://evil.example.com/items", "bad_path"],
["SHOP", "TRACE", "/items", "bad_request"],
["SHOP", "GET", "/orders", "operation_denied"],
["BLOG", "GET", "/items", "unknown_connection"],
];
for (const [projectName, method, path, reason] of cases) {
test(`Неразрешённое отклоняется: ${projectName} ${method} ${path} → ${reason}`, async () => {
const c = await core.createConnection(db, anna.id, { name: `CRM-deny-${method}-${path}`, baseUrl: base, secret: KEY });
const shop = await ownedProject(anna.id);
const blog = await ownedProject(anna.id);
await core.grantConnection(db, anna.id, c.id, { projectId: shop.proj.id, operations: "GET /items" });
const where = projectName === "SHOP" ? shop : blog;
const { sessionId } = await agentSession(where.proj.id, where.task.id);
seen.length = 0;
const r = await call(sessionId, c.id, method, path);
assert.deepEqual(r, { ok: false, reason });
assert.equal(seen.length, 0, "the service got nothing");
if (reason !== "unknown_connection") {
const log = await core.connectionJournal(db, anna.id, { connectionId: c.id });
assert.equal(log[0]!.decision, "denied");
assert.equal(log[0]!.reason, reason);
}
});
}
test("Разрешение конкретному агенту не действует для другого агента проекта", async () => {
const c = await core.createConnection(db, anna.id, { name: "CRM-agent", baseUrl: base, secret: KEY });
const { proj, task } = await ownedProject(anna.id);
const first = await agentSession(proj.id, task.id);
const second = await agentSession(proj.id, task.id);
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, agentId: first.agentId, operations: "GET /items" });
assert.equal((await call(first.sessionId, c.id, "GET", "/items")).ok, true);
assert.deepEqual(await call(second.sessionId, c.id, "GET", "/items"), { ok: false, reason: "no_grant" });
assert.deepEqual(await core.agentConnections(db, second.sessionId), []);
assert.equal((await core.agentConnections(db, first.sessionId))[0]!.name, "CRM-agent");
});
test("Агент без изоляции не получает доступ", async () => {
const c = await core.createConnection(db, anna.id, { name: "CRM-noiso", baseUrl: base, secret: KEY });
const { proj, task } = await ownedProject(anna.id);
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, operations: "GET /items" });
const { sessionId } = await agentSession(proj.id, task.id, { container: false });
seen.length = 0;
assert.deepEqual(await call(sessionId, c.id, "GET", "/items"), { ok: false, reason: "not_isolated" });
assert.equal(seen.length, 0);
assert.deepEqual(await core.agentConnections(db, sessionId), []);
// No session at all (a manual `claude`): refused.
assert.deepEqual(await core.callConnection(db, { sessionId: null, connection: c.id, method: "GET", path: "/items" }), { ok: false, reason: "no_session" });
});
test("Частота ограничена", async () => {
const c = await core.createConnection(db, anna.id, { name: "CRM-rate", baseUrl: base, secret: KEY });
const { proj, task } = await ownedProject(anna.id);
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, operations: "GET /items" });
const { sessionId } = await agentSession(proj.id, task.id);
const fake: import("@peppa/core").ConnectionFetch = async () => ({ status: 200, contentType: "text/plain", body: Buffer.from("ok"), truncated: false });
for (let i = 0; i < core.CONNECTION_RATE_PER_MIN; i++) assert.equal((await core.callConnection(db, { sessionId, connection: c.id, method: "GET", path: "/items" }, { fetch: fake })).ok, true);
assert.deepEqual(await core.callConnection(db, { sessionId, connection: c.id, method: "GET", path: "/items" }, { fetch: fake }), { ok: false, reason: "rate_limited" });
});
});
describe("Мгновенный отзыв", () => {
test("Отзыв блокирует следующий запрос и стирает ключ; новый ключ включает снова", async () => {
const c = await core.createConnection(db, anna.id, { name: "CRM-revoke", baseUrl: base, secret: KEY });
const { proj, task } = await ownedProject(anna.id);
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, operations: "GET /items" });
const { sessionId } = await agentSession(proj.id, task.id);
assert.equal((await call(sessionId, c.id, "GET", "/items")).ok, true);
await core.revokeConnection(db, anna.id, c.id);
seen.length = 0;
assert.deepEqual(await call(sessionId, c.id, "GET", "/items"), { ok: false, reason: "revoked" });
assert.equal(seen.length, 0);
const [row] = await db.select().from(connections).where(eq(connections.id, c.id));
assert.equal(row!.secretEnc, null, "the stored key is wiped");
assert.deepEqual(await core.agentConnections(db, sessionId), []);
const ev = await db.select().from(events).where(eq(events.projectId, proj.id));
assert.ok(ev.some((e) => e.type === "connection_revoked"));
await assert.rejects(core.grantConnection(db, anna.id, c.id, { projectId: proj.id, operations: "GET /x" }), /отозвано/);
await core.replaceConnectionSecret(db, anna.id, c.id, KEY);
assert.equal((await call(sessionId, c.id, "GET", "/items")).ok, true);
});
test("Отзыв одного разрешения", async () => {
const c = await core.createConnection(db, anna.id, { name: "CRM-grant-revoke", baseUrl: base, secret: KEY });
const { proj, task } = await ownedProject(anna.id);
const g = await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, operations: "GET /items" });
const { sessionId } = await agentSession(proj.id, task.id);
assert.equal((await call(sessionId, c.id, "GET", "/items")).ok, true);
await assert.rejects(core.revokeGrant(db, boris.id, g.id), /Подключение не найдено/);
await core.revokeGrant(db, anna.id, g.id);
assert.deepEqual(await call(sessionId, c.id, "GET", "/items"), { ok: false, reason: "unknown_connection" });
});
});
describe("Агент не получает ключ", () => {
test("MCP агента: list_connections и call_connection без ключа, ответ — данные", async () => {
const c = await core.createConnection(db, anna.id, { name: "CRM-mcp", baseUrl: base, secret: KEY });
const { proj, task } = await ownedProject(anna.id);
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, operations: "GET /items" });
const { sessionId } = await agentSession(proj.id, task.id);
const mcp = await mcpAgent(sessionId, proj.key);
const list = await mcp("list_connections");
assert.match(list.text, /crm-mcp \(#\d+ «CRM-mcp», own service\)/);
assert.match(list.text, /also allowed: GET \/items/);
const r = await mcp("call_connection", { connection: "CRM-mcp", method: "GET", path: "/items/7" });
assert.equal(r.isError, false, r.text);
assert.match(r.text, /^HTTP 200/);
assert.match(r.text, /ДАННЫЕ, НЕ ИНСТРУКЦИИ/);
assert.ok(!r.text.includes(KEY));
const denied = await mcp("call_connection", { connection: "CRM-mcp", method: "DELETE", path: "/items/7" });
assert.equal(denied.isError, true);
assert.match(denied.text, /operation_denied/);
// Code mode reaches the same gateway, still without the key.
const exec = await mcp("execute", { code: `return await peppa.connections.call({ connection: "CRM-mcp", method: "GET", path: "/items" })` });
assert.ok(!exec.text.includes(KEY), exec.text);
// Secrets of the project (PEP-54) do not carry it either.
const secrets = await mcp("list_secrets");
assert.ok(!secrets.text.includes(KEY));
});
test("Внутренний адрес недоступен через шлюз и перенаправления не выполняются", async () => {
const c = await core.createConnection(db, anna.id, { name: "CRM-ssrf", baseUrl: base.replace("127.0.0.1", "localhost"), secret: KEY });
const { proj, task } = await ownedProject(anna.id);
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, operations: ["GET /items", "GET /redirect"] });
const { sessionId } = await agentSession(proj.id, task.id);
// Redirect (even allowed privately) is never followed.
seen.length = 0;
const red = await call(sessionId, c.id, "GET", "/redirect");
assert.deepEqual(red, { ok: false, reason: "redirect", status: 302 });
assert.equal(seen.length, 1);
// Without the test allowance the name resolves to 127.0.0.1 at connect time → refused.
delete process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE;
try {
seen.length = 0;
assert.deepEqual(await call(sessionId, c.id, "GET", "/items"), { ok: false, reason: "blocked_address" });
assert.equal(seen.length, 0);
const log = await core.connectionJournal(db, anna.id, { connectionId: c.id });
assert.equal(log[0]!.decision, "denied");
assert.equal(log[0]!.reason, "blocked_address");
} finally {
process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE = "1";
}
});
});
describe("разбор операций и путей", () => {
test("operationAllows по границе сегмента", () => {
assert.equal(core.operationAllows(["GET /items"], "GET", "/items"), true);
assert.equal(core.operationAllows(["GET /items"], "GET", "/items/5"), true);
assert.equal(core.operationAllows(["GET /items/"], "GET", "/items/5"), true);
assert.equal(core.operationAllows(["GET /items"], "GET", "/itemsX"), false);
assert.equal(core.operationAllows(["GET /items"], "POST", "/items"), false);
assert.equal(core.operationAllows(["GET /"], "GET", "/anything/x"), true);
assert.throws(() => core.normalizeOperations("* /items"), core.PeppaError);
assert.throws(() => core.normalizeOperations("GET items"), core.PeppaError);
assert.throws(() => core.normalizeOperations(""), core.PeppaError);
assert.deepEqual(core.normalizeOperations("get /items/\nPOST /orders, GET /items"), ["GET /items", "POST /orders"]);
});
test("isBlockedAddress", () => {
for (const ip of ["127.0.0.1", "10.1.2.3", "172.16.0.1", "192.168.1.1", "169.254.169.254", "100.64.0.1", "0.0.0.0", "::1", "fd00::1", "fe80::1", "::ffff:127.0.0.1", "224.0.0.1"]) assert.equal(core.isBlockedAddress(ip), true, ip);
for (const ip of ["8.8.8.8", "1.1.1.1", "2606:4700:4700::1111"]) assert.equal(core.isBlockedAddress(ip), false, ip);
});
});
// ---------- PEP-258: the key never reaches the agent in any form ----------
// Scenario names follow openspec/changes/pep-258-access-hub-key-leak/specs/access-hub/spec.md.
/** What a careless/hostile service may echo back; checked independently of connectionKeyForms. */
function trapForms(key: string): Record<string, string> {
const b64 = (s: string) => Buffer.from(s).toString("base64");
return {
raw: key,
base64: b64(key),
base64url: Buffer.from(key).toString("base64url"),
basicHeader: `Basic ${b64(key)}`,
base64InJson1: b64(`{"token":"${key}"}`),
base64InJson2: b64(`x{"t":"${key}"}`),
base64InJson3: b64(`xy{"t":"${key}"}`),
base64Wrapped: (b64(`-----BEGIN-----\n${key}\n${key}\n${key}`).match(/.{1,20}/g) ?? []).join("\r\n"),
uri: encodeURIComponent(key),
uriLower: encodeURIComponent(key).replace(/%[0-9A-F]{2}/g, (m) => m.toLowerCase()),
form: new URLSearchParams({ k: key }).toString().slice(2),
hex: Buffer.from(key).toString("hex"),
HEX: Buffer.from(key).toString("hex").toUpperCase(),
json: JSON.stringify(key).slice(1, -1).replace(/\//g, "\\/"),
unicode: [...key].map((c) => `\\u${c.codePointAt(0)!.toString(16).padStart(4, "0")}`).join(""),
};
}
/** Every way to read the key (or the basic password) back out of a text: plain, URL, JSON, hex, base64 at any offset, unwrapped. */
function leaks(text: string, secrets: string[]): string[] {
const found: string[] = [];
const candidates = new Set<string>([text, text.replace(/\r?\n/g, "")]);
for (const t of [...candidates]) {
try {
candidates.add(decodeURIComponent(t));
} catch {}
try {
candidates.add(decodeURIComponent(t.replace(/\+/g, " ")));
} catch {}
candidates.add(t.replace(/\\u([0-9a-fA-F]{4})/g, (_, h) => String.fromCharCode(parseInt(h, 16))).replace(/\\\//g, "/"));
for (const run of t.match(/[0-9a-fA-F]{8,}/g) ?? []) for (const o of [0, 1]) candidates.add(Buffer.from(run.slice(o), "hex").toString("latin1") + Buffer.from(run.slice(o), "hex").toString("utf8"));
for (const run of t.match(/[A-Za-z0-9+/_-]{8,}/g) ?? []) for (let o = 0; o < 4; o++) candidates.add(Buffer.from(run.slice(o), "base64").toString("utf8"));
}
for (const c of candidates) for (const s of secrets) if (c.includes(s)) found.push(`${s.slice(0, 6)}… in ${JSON.stringify(c.slice(0, 120))}`);
return found;
}
const TRAP_LIMIT = 256 * 1024;
let trap: Server;
let trapOrigin: string;
/** Pulls the key out of a request the way the service sees it, for every placement. */
function keyOf(req: { url?: string; headers: IncomingHttpHeaders }): string {
const u = new URL(req.url!, "http://x");
const auth = String(req.headers.authorization ?? "");
if (auth.startsWith("Bearer ")) return auth.slice(7);
if (auth.startsWith("Basic ")) return Buffer.from(auth.slice(6), "base64").toString("utf8");
if (req.headers["x-trap-key"]) return String(req.headers["x-trap-key"]);
if (u.searchParams.get("trap_key")) return u.searchParams.get("trap_key")!;
const m = /\/bot([^/]+)\//.exec(u.pathname);
return m ? decodeURIComponent(m[1]!) : "";
}
before(async () => {
trap = createServer((req, res) => {
req.resume();
req.on("end", () => {
const key = keyOf(req);
const forms = trapForms(key);
const path = new URL(req.url!, "http://x").pathname;
const leakHeaders = { "x-echo-key": encodeURIComponent(key), "set-cookie": `s=${forms.base64}`, "www-authenticate": `Bearer realm="${forms.uri}"` };
if (path.endsWith("/trap/redirect")) {
res.writeHead(302, { ...leakHeaders, location: `https://evil.example/collect?k=${forms.uri}` });
return res.end(`moved: ${key}`);
}
if (path.endsWith("/trap/error")) {
res.writeHead(500, { ...leakHeaders, "content-type": "text/plain" });
return res.end(`Error: invalid token ${key}\n at checkAuth (/srv/app/auth.js:12:7) [header=${forms.basicHeader}]\n at handler (/srv/app/index.js:40:3) url=${forms.uri}`);
}
if (path.endsWith("/trap/big")) {
// The key starts 6 bytes before the gateway's 256 KB cut.
res.writeHead(200, { ...leakHeaders, "content-type": "text/plain" });
return res.end("x".repeat(TRAP_LIMIT - 6) + key + "y".repeat(1000));
}
res.writeHead(200, { ...leakHeaders, "content-type": `application/json; charset=utf-8; boundary=${forms.uri}` });
res.end(JSON.stringify({ ...forms, message: `Your token is ${key}`, nested: { wrapped: forms.base64Wrapped } }, null, 1));
});
});
await new Promise<void>((r) => trap.listen(0, "127.0.0.1", r));
trapOrigin = `http://127.0.0.1:${(trap.address() as AddressInfo).port}`;
});
after(async () => {
await new Promise<void>((r) => trap.close(() => r()));
});
describe("Ключ в другой форме тоже скрыт (PEP-258)", () => {
// Special characters exercise every encoding (header values are ASCII only); the path placement allows only [A-Za-z0-9:_.-].
const SPECIAL = "mock-user:sk_live_TRAP/7f+3a9c=ключ&x y";
const kinds: Array<{ kind: string; secret: string; input: (n: string) => Parameters<typeof core.createConnection>[2] }> = [
{ kind: "bearer", secret: SPECIAL.replace(/[^\x20-\x7e]/g, "Q"), input: (name) => ({ name, baseUrl: `${trapOrigin}/api`, secret: SPECIAL.replace(/[^\x20-\x7e]/g, "Q") }) },
{ kind: "header", secret: SPECIAL.replace(/[^\x20-\x7e]/g, "Q"), input: (name) => ({ name, baseUrl: `${trapOrigin}/api`, secret: SPECIAL.replace(/[^\x20-\x7e]/g, "Q"), authKind: "header", authHeader: "X-Trap-Key" }) },
{ kind: "basic", secret: SPECIAL, input: (name) => ({ name, baseUrl: `${trapOrigin}/api`, secret: SPECIAL, authKind: "basic" }) },
{ kind: "query", secret: SPECIAL, input: (name) => ({ name, baseUrl: `${trapOrigin}/api`, secret: SPECIAL, authKind: "query", authHeader: "trap_key" }) },
{ kind: "path", secret: "123456789:AAH_mock-TRAP.key_7f3a9c", input: (name) => ({ name, catalogId: "telegram", secret: "123456789:AAH_mock-TRAP.key_7f3a9c" }) },
];
for (const k of kinds) {
test(`Тест-ловушка: способ ключа ${k.kind} — ни одна форма ключа не доходит до агента`, async () => {
const name = `Trap-${k.kind}`;
const c = await core.createConnection(db, anna.id, k.input(name));
// The catalog card's address is fixed (api.telegram.org): point the row at the trap for the test.
if (k.kind === "path") await db.update(connections).set({ baseUrl: trapOrigin }).where(eq(connections.id, c.id));
const { proj, task } = await ownedProject(anna.id);
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, operations: "GET /trap" });
const { sessionId } = await agentSession(proj.id, task.id);
const secrets = [k.secret, ...(k.kind === "basic" ? [k.secret.slice(k.secret.indexOf(":") + 1)] : [])];
const seenByAgent: string[] = [];
// 1. The gateway itself, every trap route.
const body = await call(sessionId, c.id, "GET", "/trap/body");
assert.equal(body.ok, true, JSON.stringify(body));
if (body.ok) {
assert.match(body.body, /••••/, "the service did echo the key");
assert.ok(body.contentType?.startsWith("application/json"));
}
const err = await call(sessionId, c.id, "GET", "/trap/error");
assert.equal(err.ok && err.status, 500);
const red = await call(sessionId, c.id, "GET", "/trap/redirect");
assert.deepEqual(red, { ok: false, reason: "redirect", status: 302 }, "a redirect is never followed, its address never returned");
const big = await call(sessionId, c.id, "GET", "/trap/big");
assert.equal(big.ok && big.truncated, true);
if (big.ok) assert.ok(big.body.endsWith("••••"), "the cut beginning of the key is masked");
seenByAgent.push(JSON.stringify([body, err, red, big]));
// 2. The agent's MCP: direct tool and code mode (PEP-212), answers and errors.
const mcp = await mcpAgent(sessionId, proj.key);
for (const p of ["/trap/body", "/trap/error", "/trap/redirect", "/trap/big"]) {
const r = await mcp("call_connection", { connection: c.slug ?? name, method: "GET", path: p });
seenByAgent.push(r.text);
const ex = await mcp("execute", { code: `return await peppa.connections.call({ connection: ${JSON.stringify(c.slug ?? name)}, method: "GET", path: ${JSON.stringify(p)} })` });
seenByAgent.push(ex.text);
}
const exErr = await mcp("execute", { code: `try { await peppa.connections.call({ connection: ${JSON.stringify(c.slug ?? name)}, method: "GET", path: "/trap/redirect" }) } catch (e) { return String(e && e.stack || e) }` });
seenByAgent.push(exErr.text);
seenByAgent.push((await mcp("list_connections")).text, (await mcp("list_secrets")).text, (await mcp("get_task", { task: task.key })).text);
// 3. The agent's environment (PEP-54) and the session's steps.
seenByAgent.push(JSON.stringify(await core.projectSecretEnv(db, proj.id, "agent")), JSON.stringify(await core.projectSecretEnv(db, proj.id, "deploy")));
seenByAgent.push(JSON.stringify(await core.sessionSteps(db, sessionId, 200)));
// 4. Nothing stored anywhere: every table of the database (journal, events, chats, settings…).
const tables = (await db.all<{ name: string }>(sql`SELECT name FROM sqlite_master WHERE type = 'table'`)).map((t) => t.name);
for (const t of tables) seenByAgent.push(JSON.stringify(await db.all(sql.raw(`SELECT * FROM "${t}"`))));
for (const text of seenByAgent) assert.deepEqual(leaks(text, secrets), [], text.slice(0, 300));
// The journal has the calls — without query, key or body.
const log = await core.connectionJournal(db, anna.id, { connectionId: c.id });
assert.ok(log.length >= 8);
assert.ok(log.every((l) => l.path.startsWith("/trap/")));
});
}
test("Маскировка: base64 внутри длинной строки, переносы, обрезанный хвост", () => {
const key = "sk_live_TRAP_7f3a9c_long";
const forms = core.connectionKeyForms(key, "bearer");
for (const [name, form] of Object.entries(trapForms(key))) {
const out = core.maskConnectionKey(`before ${form} after`, forms);
assert.deepEqual(leaks(out, [key]), [], `${name}: ${out}`);
}
// A short tail that is not a key prefix stays as is; the beginning of the key at the cut is masked.
assert.equal(core.maskConnectionKey("abc xyz", forms, { truncated: true }), "abc xyz");
assert.equal(core.maskConnectionKey("data sk_live_TR", forms, { truncated: true }), "data ••••");
assert.equal(core.maskConnectionKey("data sk_live_TR", forms), "data sk_live_TR", "not cut — not a key");
// basic: the password alone is masked, the login is not.
const basic = core.connectionKeyForms("anna@example.com:pa55word!", "basic");
assert.equal(core.maskConnectionKey("user anna@example.com pass pa55word!", basic), "user anna@example.com pass ••••");
// Ordinary data is untouched.
assert.equal(core.maskConnectionKey('{"items":[1,2,3],"name":"Анна"}', forms), '{"items":[1,2,3],"name":"Анна"}');
});
});