301 lines
18 KiB
TypeScript
301 lines
18 KiB
TypeScript
// PEP-54: project secrets for agents (encrypted, env of the session, names-only MCP, masking);
|
||
// PEP-19: audit of platform secrets, two-key rotation of PEPPA_SECRET, re-encryption.
|
||
import assert from "node:assert/strict";
|
||
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
||
import { join } from "node:path";
|
||
import { after, before, describe, test } from "node:test";
|
||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||
import { eq } from "drizzle-orm";
|
||
import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
|
||
|
||
const K1 = "mock-secret-key-one";
|
||
const K2 = "mock-secret-key-two";
|
||
process.env.PEPPA_SECRET = K1;
|
||
delete process.env.PEPPA_SECRET_PREVIOUS;
|
||
const { createManagerServer } = await import("@peppa/mcp/manager");
|
||
const { projectSecrets, subscriptions, oauthTokens, events } = await import("@peppa/db");
|
||
|
||
const VALUE = "sk_test_1234567890";
|
||
let owner: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let stranger: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
|
||
before(async () => {
|
||
owner = await core.upsertUserFromGitea(db, { id: 31, login: "mock-owner" }, { access_token: "gitea-access-owner" });
|
||
stranger = await core.upsertUserFromGitea(db, { id: 32, login: "mock-stranger" }, { access_token: "gitea-access-stranger" });
|
||
await core.setPlatformAdmins(db, ["mock-owner"]);
|
||
});
|
||
after(teardown);
|
||
|
||
async function ownedProject(scenario: Parameters<typeof project>[0] = { turns: [] }) {
|
||
const p = await project(scenario);
|
||
const proj = await core.getProject(db, p.key);
|
||
await core.setProjectOwner(db, proj.id, owner.id);
|
||
return { p, proj };
|
||
}
|
||
|
||
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-client", 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("project secrets (PEP-54)", () => {
|
||
test("Завести секрет: в списке имя и автор, значение в базе зашифровано", async () => {
|
||
const { proj } = await ownedProject();
|
||
const s = await core.setProjectSecret(db, owner.id, proj.id, "STRIPE_TEST_KEY", VALUE);
|
||
assert.equal(s.name, "STRIPE_TEST_KEY");
|
||
assert.equal(s.updatedBy, "mock-owner");
|
||
const list = await core.listProjectSecrets(db, proj.id);
|
||
assert.deepEqual(list.map((x) => x.name), ["STRIPE_TEST_KEY"]);
|
||
assert.ok(!JSON.stringify(list).includes(VALUE), "the list never carries the value");
|
||
const [row] = await db.select().from(projectSecrets).where(eq(projectSecrets.projectId, proj.id));
|
||
assert.ok(!row!.valueEnc.includes(VALUE));
|
||
assert.equal(core.decrypt(row!.valueEnc), VALUE);
|
||
// Same name = replace the value.
|
||
await core.setProjectSecret(db, owner.id, proj.id, "STRIPE_TEST_KEY", "sk_test_replaced");
|
||
assert.equal((await core.projectSecretEnv(db, proj.id)).env.STRIPE_TEST_KEY, "sk_test_replaced");
|
||
assert.equal((await core.listProjectSecrets(db, proj.id)).length, 1);
|
||
const types = (await db.select().from(events).where(eq(events.projectId, proj.id))).map((e) => e.type);
|
||
assert.deepEqual(types.filter((t) => t.startsWith("secret_")), ["secret_set", "secret_set"]);
|
||
await core.deleteProjectSecret(db, owner.id, proj.id, "STRIPE_TEST_KEY");
|
||
assert.equal((await core.listProjectSecrets(db, proj.id)).length, 0);
|
||
await assert.rejects(core.deleteProjectSecret(db, owner.id, proj.id, "STRIPE_TEST_KEY"), /нет/);
|
||
});
|
||
|
||
for (const [name, error] of [
|
||
["stripe-key", /A–Z, 0–9 и _/],
|
||
["PATH", /PATH занято самой Peppa FACTORY/],
|
||
["PEPPA_DB", /PEPPA_DB занято самой Peppa FACTORY/],
|
||
["LD_PRELOAD", /занято самой Peppa FACTORY/],
|
||
] as const) {
|
||
test(`Недопустимое имя: ${name}`, async () => {
|
||
const { proj } = await ownedProject();
|
||
await assert.rejects(core.setProjectSecret(db, owner.id, proj.id, name, VALUE), error);
|
||
assert.equal((await core.listProjectSecrets(db, proj.id)).length, 0);
|
||
});
|
||
}
|
||
|
||
test("пустое и слишком большое значение отклоняются", async () => {
|
||
const { proj } = await ownedProject();
|
||
await assert.rejects(core.setProjectSecret(db, owner.id, proj.id, "EMPTY", ""), /пустое/);
|
||
await assert.rejects(core.setProjectSecret(db, owner.id, proj.id, "BIG", "x".repeat(17 * 1024)), /16 КБ/);
|
||
});
|
||
|
||
test("Чужой проект: не сохранить и не удалить", async () => {
|
||
const { proj } = await ownedProject();
|
||
await assert.rejects(core.setProjectSecret(db, stranger.id, proj.id, "MAPS_KEY", VALUE), /Не найдено/);
|
||
await core.setProjectSecret(db, owner.id, proj.id, "MAPS_KEY", VALUE);
|
||
await assert.rejects(core.deleteProjectSecret(db, stranger.id, proj.id, "MAPS_KEY"), /Не найдено/);
|
||
});
|
||
|
||
test("Агент получает секрет: env процесса, secrets_issued, файла с секретами не остаётся, терминал маскирует", async () => {
|
||
const { p, proj } = await ownedProject({ turns: [], echoEnv: ["STRIPE_TEST_KEY", "MAPS_KEY"] });
|
||
await core.setProjectSecret(db, owner.id, proj.id, "STRIPE_TEST_KEY", VALUE);
|
||
await core.setProjectSecret(db, owner.id, proj.id, "MAPS_KEY", "maps-key-abcdef");
|
||
const id = await p.start();
|
||
const env = (await p.waitLog("env echo", (e) => e.ev === "env")).env as Record<string, string>;
|
||
assert.equal(env.STRIPE_TEST_KEY, VALUE);
|
||
assert.equal(env.MAPS_KEY, "maps-key-abcdef");
|
||
|
||
const s = await p.session(id);
|
||
const issued = (await db.select().from(events).where(eq(events.sessionId, id))).find((e) => e.type === "secrets_issued");
|
||
assert.deepEqual((issued!.payload as { names: string[] }).names, ["MAPS_KEY", "STRIPE_TEST_KEY"]);
|
||
assert.ok((await core.listProjectSecrets(db, proj.id)).every((x) => x.lastUsedAt), "last given time is recorded");
|
||
|
||
// Nothing with the value is left on disk, and the tmux command has no values either.
|
||
const runDir = join(process.env.PEPPA_HOME!, "runs", `s${id}-g${s.generation}`);
|
||
assert.ok(!existsSync(join(runDir, "secrets.env")), "secrets.env is removed by the launch script");
|
||
for (const f of readdirSync(runDir)) assert.ok(!readFileSync(join(runDir, f), "utf8").includes(VALUE), `${f} has no secret value`);
|
||
|
||
// The web terminal shows •••• instead of the value.
|
||
const frames: string[] = [];
|
||
const off = runner.watchTerminal(s.tmuxName, (e) => e.type !== "end" && frames.push(e.data), { mask: await core.projectSecretMasker(db, proj.id) });
|
||
try {
|
||
await waitFor("masked line in the terminal", async () => frames.join("").includes("STRIPE_TEST_KEY=••••"));
|
||
assert.ok(!frames.join("").includes(VALUE), "the value never reaches a viewer");
|
||
} finally {
|
||
off();
|
||
}
|
||
await runner.stopSession(db, id);
|
||
});
|
||
|
||
test("Секретов нет: сессия как раньше, без secrets_issued", async () => {
|
||
const { p } = await ownedProject();
|
||
const id = await p.start();
|
||
await p.waitLog("start", (e) => e.ev === "start");
|
||
const types = (await db.select().from(events).where(eq(events.sessionId, id))).map((e) => e.type);
|
||
assert.ok(!types.includes("secrets_issued"));
|
||
await runner.stopSession(db, id);
|
||
});
|
||
|
||
test("Маскировка: шаги агента без значения, короткие значения не трогаются, многострочные — построчно", async () => {
|
||
const { proj } = await ownedProject();
|
||
await core.setProjectSecret(db, owner.id, proj.id, "STRIPE_TEST_KEY", VALUE);
|
||
await core.setProjectSecret(db, owner.id, proj.id, "SHORT", "abc");
|
||
await core.setProjectSecret(db, owner.id, proj.id, "PEM", "-----BEGIN KEY-----\nMIIBOgIBAAJBAKj34GkxFhD9\n-----END KEY-----");
|
||
const task = (await core.listTasks(db, { projectId: proj.id }))[0]!;
|
||
const sess = await core.createSession(db, { projectId: proj.id, taskId: task.id });
|
||
const row = await core.recordStep(db, sess, { tool: "Bash", kind: "command", text: `curl -H "Authorization: ${VALUE}" abc`, ok: true });
|
||
assert.equal((row.payload as { text: string }).text, 'curl -H "Authorization: ••••" abc');
|
||
const mask = await core.projectSecretMasker(db, proj.id);
|
||
assert.equal(mask("line MIIBOgIBAAJBAKj34GkxFhD9 end"), "line •••• end");
|
||
assert.equal(mask("abc"), "abc");
|
||
});
|
||
|
||
test("list_secrets: имена у агента (свой проект) и у PM, без значений; чужому — Не найдено", async () => {
|
||
const { p, proj } = await ownedProject();
|
||
await core.setProjectSecret(db, owner.id, proj.id, "STRIPE_TEST_KEY", VALUE);
|
||
await core.setProjectSecret(db, owner.id, proj.id, "MAPS_KEY", "maps-key-abcdef");
|
||
|
||
const asOwner = await mcpAs(owner);
|
||
const r = await asOwner("list_secrets", { project: p.key });
|
||
assert.equal(r.isError, false);
|
||
assert.match(r.text, /MAPS_KEY/);
|
||
assert.match(r.text, /STRIPE_TEST_KEY/);
|
||
assert.ok(!r.text.includes(VALUE));
|
||
const denied = await (await mcpAs(stranger))("list_secrets", { project: p.key });
|
||
assert.equal(denied.isError, true);
|
||
assert.match(denied.text, /Не найдено/);
|
||
|
||
// The agent's stdio MCP server: the session's project only.
|
||
const task = (await core.listTasks(db, { projectId: proj.id }))[0]!;
|
||
const sess = await core.createSession(db, { projectId: proj.id, taskId: task.id });
|
||
const client = new Client({ name: "mock-agent", version: "0" });
|
||
await client.connect(
|
||
new StdioClientTransport({ command: process.env.PEPPA_MOCK_MCP_BIN!, cwd: p.dir, env: { ...(process.env as Record<string, string>), PEPPA_SESSION_ID: String(sess.id), PEPPA_PROJECT_DIR: p.dir } }),
|
||
);
|
||
try {
|
||
const out = await client.callTool({ name: "list_secrets", arguments: {} });
|
||
const text = (out.content as Array<{ text: string }>)[0]!.text;
|
||
assert.match(text, new RegExp(`Secrets of ${p.key}`));
|
||
assert.match(text, /- MAPS_KEY\n- STRIPE_TEST_KEY/);
|
||
assert.ok(!text.includes(VALUE));
|
||
} finally {
|
||
await client.close();
|
||
}
|
||
});
|
||
});
|
||
|
||
describe("secret rotation and audit (PEP-19)", () => {
|
||
test("Переход на новый ключ: reencrypt переводит всё зашифрованное, старый ключ можно убрать", async () => {
|
||
process.env.PEPPA_SECRET = K1;
|
||
delete process.env.PEPPA_SECRET_PREVIOUS;
|
||
const { proj } = await ownedProject();
|
||
await core.setProjectSecret(db, owner.id, proj.id, "ROTATE_ME", "rotate-value-1");
|
||
const sub = await core.createSubscription(db, { provider: "claude", name: "Claude rotate", authKind: "oauth", secret: "sk-ant-oat-rotate", createdBy: owner.id });
|
||
const cookie = core.sign({ userId: owner.id });
|
||
const projHook = core.projectHookSecret(proj.id);
|
||
|
||
// K1 → K2: new key current, old one previous.
|
||
process.env.PEPPA_SECRET = K2;
|
||
process.env.PEPPA_SECRET_PREVIOUS = K1;
|
||
assert.equal(core.rotatingSecret(), true);
|
||
assert.equal(core.subscriptionSecret(sub), "sk-ant-oat-rotate", "old values still decrypt");
|
||
assert.deepEqual(core.verify(cookie), { userId: owner.id }, "the login cookie survives the switch");
|
||
const body = '{"x":1}';
|
||
const { createHmac } = await import("node:crypto");
|
||
assert.ok(core.verifyHookSignature(proj.id, body, createHmac("sha256", projHook).update(body).digest("hex")), "Gitea still signing with the old project secret is accepted");
|
||
|
||
let audit = await core.secretsAudit(db);
|
||
assert.ok(audit.encryption.rotating);
|
||
assert.ok(audit.encryption.previous >= 3, "user tokens, the subscription and the project secret wait for re-encryption");
|
||
|
||
const r = await core.reencryptAll(db, "mock-owner");
|
||
assert.ok(r.reencrypted >= 3);
|
||
assert.equal(r.unreadable.length, 0);
|
||
audit = await core.secretsAudit(db);
|
||
assert.equal(audit.encryption.previous, 0);
|
||
assert.equal(audit.platform.find((x) => x.name === "PEPPA_SECRET")!.ageDays, 0, "the key change is recorded as a rotation");
|
||
|
||
// Old key gone: everything opens with K2 alone; old cookies are refused.
|
||
delete process.env.PEPPA_SECRET_PREVIOUS;
|
||
const [s2] = await db.select().from(subscriptions).where(eq(subscriptions.id, sub.id));
|
||
assert.equal(core.subscriptionSecret(s2!), "sk-ant-oat-rotate");
|
||
assert.equal((await core.projectSecretEnv(db, proj.id)).env.ROTATE_ME, "rotate-value-1");
|
||
assert.equal(core.verify(cookie), null);
|
||
assert.equal((await core.reencryptAll(db)).reencrypted, 0, "nothing left on the old key");
|
||
});
|
||
|
||
test("MCP-токен, выданный при старом ключе, принимается во время перехода", async () => {
|
||
process.env.PEPPA_SECRET = K1;
|
||
delete process.env.PEPPA_SECRET_PREVIOUS;
|
||
const client = await core.registerClient(db, "Mock ChatGPT", ["https://chatgpt.com/cb"]);
|
||
const { createHash, randomBytes } = await import("node:crypto");
|
||
const verifier = randomBytes(32).toString("base64url");
|
||
const code = await core.issueCode(db, { clientId: client.id, redirectUri: "https://chatgpt.com/cb", codeChallenge: createHash("sha256").update(verifier).digest("base64url"), codeChallengeMethod: "S256", responseType: "code" }, owner.id);
|
||
const t = await core.exchangeToken(db, { grant_type: "authorization_code", code, client_id: client.id, redirect_uri: "https://chatgpt.com/cb", code_verifier: verifier });
|
||
|
||
process.env.PEPPA_SECRET = K2;
|
||
process.env.PEPPA_SECRET_PREVIOUS = K1;
|
||
assert.deepEqual(await core.verifyAccessToken(db, t.access_token), { userId: owner.id, clientId: client.id });
|
||
const refreshed = await core.exchangeToken(db, { grant_type: "refresh_token", refresh_token: t.refresh_token!, client_id: client.id });
|
||
delete process.env.PEPPA_SECRET_PREVIOUS;
|
||
assert.equal(await core.verifyAccessToken(db, t.access_token), null, "the old-key token stops after the transition");
|
||
assert.ok(await core.verifyAccessToken(db, refreshed.access_token), "tokens issued during the transition use the new key");
|
||
|
||
// Отозвать клиента: all live tokens of the client stop.
|
||
const audit = await core.secretsAudit(db);
|
||
// The first access token (until it expires) + the new access/refresh pair.
|
||
assert.equal(audit.oauth.find((c) => c.clientId === client.id)!.liveTokens, 3);
|
||
assert.equal(await core.revokeClientTokens(db, client.id), 3);
|
||
assert.equal(await core.verifyAccessToken(db, refreshed.access_token), null);
|
||
assert.equal((await core.secretsAudit(db)).oauth.find((c) => c.clientId === client.id), undefined);
|
||
assert.ok((await db.select().from(oauthTokens).where(eq(oauthTokens.clientId, client.id))).every((x) => x.revokedAt));
|
||
});
|
||
|
||
test("Старый ключ убран раньше времени: reencrypt сообщает «не читается» и ничего не меняет", async () => {
|
||
process.env.PEPPA_SECRET = "mock-key-a";
|
||
delete process.env.PEPPA_SECRET_PREVIOUS;
|
||
const { proj } = await ownedProject();
|
||
await core.setProjectSecret(db, owner.id, proj.id, "LOST_KEY", "lost-value");
|
||
const [before] = await db.select().from(projectSecrets).where(eq(projectSecrets.projectId, proj.id));
|
||
process.env.PEPPA_SECRET = "mock-key-b";
|
||
const r = await core.reencryptAll(db);
|
||
assert.ok(r.unreadable.some((u) => u.table === "project_secrets" && u.id === before!.id));
|
||
const [after] = await db.select().from(projectSecrets).where(eq(projectSecrets.projectId, proj.id));
|
||
assert.equal(after!.valueEnc, before!.valueEnc, "unreadable values stay as they are");
|
||
// A session still starts: the unreadable secret is skipped and reported.
|
||
const env = await core.projectSecretEnv(db, proj.id);
|
||
assert.deepEqual(env.unreadable, ["LOST_KEY"]);
|
||
// Clean up for the following tests: this database now holds values of mixed keys.
|
||
await db.delete(projectSecrets);
|
||
process.env.PEPPA_SECRET = K2;
|
||
});
|
||
|
||
test("Отчёт: статус env, возраст от отметки ротации, без значений; отметить ротацию", async () => {
|
||
const now = new Date("2026-11-14T12:00:00Z");
|
||
const env = { PEPPA_SECRET: K2, GITEA_TOKEN: "gitea-token-value-123", TELEGRAM_BOT_TOKEN: "123:telegram-token-value" } as NodeJS.ProcessEnv;
|
||
await core.setSetting(db, "secrets.rotated:TELEGRAM_BOT_TOKEN", { at: now.getTime() - 200 * 86_400_000, by: "mock-owner" });
|
||
const a = await core.secretsAudit(db, now, env);
|
||
const row = (n: string) => a.platform.find((x) => x.name === n)!;
|
||
assert.equal(row("GITEA_TOKEN").set, true);
|
||
assert.equal(row("GITEA_TOKEN").ageDays, null);
|
||
assert.equal(row("TELEGRAM_BOT_TOKEN").ageDays, 200);
|
||
assert.equal(row("TELEGRAM_BOT_TOKEN").stale, true);
|
||
assert.equal(row("GITEA_OAUTH_CLIENT_SECRET").set, false);
|
||
assert.equal(row("GITEA_BOT_PASSWORD").set, null);
|
||
assert.ok(row("GITEA_TOKEN").steps.some((s) => s.includes("write:repository")), "minimal token rights are spelled out");
|
||
const json = JSON.stringify(a);
|
||
for (const v of Object.values(env)) assert.ok(!json.includes(v!), "no value in the report");
|
||
|
||
await core.markSecretRotated(db, "TELEGRAM_BOT_TOKEN", "mock-owner", now);
|
||
assert.equal((await core.secretsAudit(db, now, env)).platform.find((x) => x.name === "TELEGRAM_BOT_TOKEN")!.ageDays, 0);
|
||
await assert.rejects(core.markSecretRotated(db, "FOO", "mock-owner"), /Неизвестный секрет платформы: FOO/);
|
||
});
|
||
|
||
test("Не суперадмин: раздел недоступен, проверка токена Gitea без токена — проблема", async () => {
|
||
assert.equal(await core.isSuperadmin(db, stranger), false);
|
||
assert.equal(await core.isSuperadmin(db, owner), true);
|
||
const r = await core.checkGiteaBotToken({ GITEA_TOKEN: "" } as NodeJS.ProcessEnv);
|
||
assert.equal(r.ok, false);
|
||
assert.match(r.problems[0]!, /не задан/);
|
||
});
|
||
});
|