PEP-253: тесты — секрет «только продукту», настройка проекта, переезд в подключение, отчёт; регрессия
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
b2344302c5
commit
eecdbd542f
@ -1,14 +1,14 @@
|
||||
## 1. Данные и ядро
|
||||
- [ ] 1.1 Схема и миграция: `project_secrets.agent_env`, `project_secrets.connection_id`
|
||||
- [ ] 1.2 `secrets.ts`: «кому» у секрета, настройка проекта, `projectSecretEnv` учитывает обе, `setSecretAudience`
|
||||
- [ ] 1.3 `secret-services.ts`: угадывание сервиса, подсказки для веба, `secretsAgentReport`, `secretToConnection`
|
||||
- [ ] 1.4 `provisionProject`: новым проектам настройка выкл.
|
||||
- [x] 1.1 Схема и миграция: `project_secrets.agent_env`, `project_secrets.connection_id`
|
||||
- [x] 1.2 `secrets.ts`: «кому» у секрета, настройка проекта, `projectSecretEnv` учитывает обе, `setSecretAudience`
|
||||
- [x] 1.3 `secret-services.ts`: угадывание сервиса, подсказки для веба, `secretsAgentReport`, `secretToConnection`
|
||||
- [x] 1.4 `provisionProject`: новым проектам настройка выкл.
|
||||
|
||||
## 2. Каналы
|
||||
- [ ] 2.1 Веб: список секретов (кому, сервис, «Сделать подключением», переключатель), форма с выбором и подсказкой, настройка проекта; `/secrets` — отчёт
|
||||
- [ ] 2.2 MCP `list_secrets` агента; CLI `peppa secrets agent-report [--notify]`, runner `notifySecretsReport`
|
||||
- [ ] 2.3 Переводы en/kk, словарь, «Помощь», `template/RULES.md`
|
||||
- [x] 2.1 Веб: список секретов (кому, сервис, «Сделать подключением», переключатель), форма с выбором и подсказкой, настройка проекта; `/secrets` — отчёт
|
||||
- [x] 2.2 MCP `list_secrets` агента; CLI `peppa secrets agent-report [--notify]`, runner `notifySecretsReport`
|
||||
- [x] 2.3 Переводы en/kk, словарь, «Помощь», `template/RULES.md`
|
||||
|
||||
## 3. Тесты и завершение
|
||||
- [ ] 3.1 Тест `secrets-access-hub.test.ts`; регрессия `secrets.test.ts`, `deploy.test.ts`, `access-hub*.test.ts`
|
||||
- [x] 3.1 Тест `secrets-access-hub.test.ts`; регрессия `secrets.test.ts`, `deploy.test.ts`, `access-hub*.test.ts`
|
||||
- [ ] 3.2 lint, typecheck; память; archive; PR
|
||||
|
||||
@ -56,7 +56,9 @@ const protectAlerts = async () => (await db.select().from(telegramOutbox).where(
|
||||
|
||||
describe("branch protection", () => {
|
||||
test("new project gets main protected with peppa-bot", async () => {
|
||||
await provision({ slug: "mock-prot-new", key: "MPNEW" });
|
||||
const created = await provision({ slug: "mock-prot-new", key: "MPNEW" });
|
||||
// PEP-253: agents of a new project get no secrets in their env.
|
||||
assert.equal(await core.agentSecretsEnabled(db, created.id), false);
|
||||
const r = rule("mock-prot-new")!;
|
||||
assert.deepEqual(r.push_whitelist_usernames, ["peppa-bot"]);
|
||||
assert.deepEqual(r.merge_whitelist_usernames, ["peppa-bot"]);
|
||||
|
||||
@ -162,7 +162,7 @@ describe("PEP-112: секреты проекта в выкатке", () => {
|
||||
test("Scenario: Ключ Claude для продукта — агенту не выдаётся, выкатка получает оба", async () => {
|
||||
const p = await proj();
|
||||
await core.setProjectSecret(db, pm.id, p.id, "ANTHROPIC_API_KEY", "sk-ant-mock-2");
|
||||
await core.setProjectSecret(db, pm.id, p.id, "STRIPE_TEST_KEY", "sk_test_mock$1");
|
||||
await core.setProjectSecret(db, pm.id, p.id, "STRIPE_TEST_KEY", "sk_test_mock$1", { agent: true });
|
||||
assert.deepEqual(Object.keys((await core.projectSecretEnv(db, p.id)).env), ["STRIPE_TEST_KEY"]);
|
||||
assert.deepEqual((await core.projectSecretEnv(db, p.id, "deploy")).env, { ANTHROPIC_API_KEY: "sk-ant-mock-2", STRIPE_TEST_KEY: "sk_test_mock$1" });
|
||||
await assert.rejects(core.setProjectSecret(db, pm.id, p.id, "PEPPA_HOME", "x"), /PEPPA_HOME занято самой FORGE/);
|
||||
|
||||
@ -127,8 +127,8 @@ describe("PEP-187: limits for a deceived agent", () => {
|
||||
|
||||
test("Scenario: секреты другого проекта и токены подписок агенту не попадают", async () => {
|
||||
const other = await core.getProject(db, (await mockProject({ steps: [] } as never)).key);
|
||||
await core.setProjectSecret(db, pm.id, proj.id, "MINE_KEY", "mock-mine");
|
||||
await core.setProjectSecret(db, pm.id, proj.id, "ANTHROPIC_API_KEY", "mock-product-only");
|
||||
await core.setProjectSecret(db, pm.id, proj.id, "MINE_KEY", "mock-mine", { agent: true });
|
||||
await core.setProjectSecret(db, pm.id, proj.id, "ANTHROPIC_API_KEY", "mock-product-only", { agent: true });
|
||||
const mine = (await core.projectSecretEnv(db, proj.id, "agent")).env;
|
||||
assert.deepEqual(Object.keys(mine), ["MINE_KEY"], "product-only keys stay out");
|
||||
assert.deepEqual((await core.projectSecretEnv(db, other.id, "agent")).env, {}, "another project sees none of them");
|
||||
|
||||
@ -163,7 +163,7 @@ describe("PEP-17: агент в контейнере", () => {
|
||||
await subscribed(p);
|
||||
await core.setProjectRunnerSettings(db, (await core.getProject(db, p.key)).id, { isolation: "container" });
|
||||
// PEP-54: the project's own secret goes in by name; its value never lands in launch.sh.
|
||||
await core.setProjectSecret(db, pm.id, (await core.getProject(db, p.key)).id, "STRIPE_KEY", "mock-stripe-secret-value");
|
||||
await core.setProjectSecret(db, pm.id, (await core.getProject(db, p.key)).id, "STRIPE_KEY", "mock-stripe-secret-value", { agent: true });
|
||||
const sid = await p.start();
|
||||
const s = await core.getSession(db, sid);
|
||||
assert.equal(s.container, `peppa-s${sid}`);
|
||||
|
||||
155
packages/testkit/test/secrets-access-hub.test.ts
Normal file
155
packages/testkit/test/secrets-access-hub.test.ts
Normal file
@ -0,0 +1,155 @@
|
||||
// PEP-253: project secrets «только продукту» / «агенту и продукту», the project setting «Агенты
|
||||
// получают секреты в окружение», keys of catalog services moving to Access Hub connections, the report.
|
||||
// Tests are named after the scenarios of openspec/specs/project-secrets.
|
||||
import assert from "node:assert/strict";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { stripAsIs } from "@peppa/shared/i18n";
|
||||
import { core, db, project, teardown } from "./helpers.ts";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-pep253";
|
||||
const { projectSecrets, connections, connectionGrants, chatMessages, events } = await import("@peppa/db");
|
||||
const { notifySecretsReport } = await import("@peppa/runner");
|
||||
|
||||
type U = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
let owner: U;
|
||||
let stranger: U;
|
||||
|
||||
before(async () => {
|
||||
owner = await core.upsertUserFromGitea(db, { id: 2531, login: "mock-sec-owner" }, { access_token: "mock-gitea-sec-owner" });
|
||||
stranger = await core.upsertUserFromGitea(db, { id: 2532, login: "mock-sec-stranger" }, { access_token: "mock-gitea-sec-stranger" });
|
||||
});
|
||||
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 };
|
||||
}
|
||||
|
||||
const secretRow = async (projectId: number, name: string) => (await db.select().from(projectSecrets).where(and(eq(projectSecrets.projectId, projectId), eq(projectSecrets.name, name))))[0]!;
|
||||
|
||||
describe("Кому идёт секрет", () => {
|
||||
test("Scenario: Новый секрет по умолчанию — только продукту", async () => {
|
||||
const { proj } = await ownedProject();
|
||||
const s = await core.setProjectSecret(db, owner.id, proj.id, "MAPS_KEY", "mock-maps-key-1");
|
||||
assert.equal(s.agentEnv, false);
|
||||
assert.deepEqual((await core.projectSecretEnv(db, proj.id, "agent")).env, {});
|
||||
assert.deepEqual((await core.projectSecretEnv(db, proj.id, "deploy")).env, { MAPS_KEY: "mock-maps-key-1" });
|
||||
});
|
||||
|
||||
test("Scenario: Замена значения не меняет «кому»; переключатель меняет", async () => {
|
||||
const { proj } = await ownedProject();
|
||||
await core.setProjectSecret(db, owner.id, proj.id, "STRIPE_TEST_KEY", "sk_test_mockAAAA1111", { agent: true });
|
||||
await core.setProjectSecret(db, owner.id, proj.id, "STRIPE_TEST_KEY", "sk_test_mockBBBB2222");
|
||||
assert.equal((await secretRow(proj.id, "STRIPE_TEST_KEY")).agentEnv, true);
|
||||
assert.equal((await core.projectSecretEnv(db, proj.id)).env.STRIPE_TEST_KEY, "sk_test_mockBBBB2222");
|
||||
await core.setSecretAudience(db, owner.id, proj.id, "STRIPE_TEST_KEY", false);
|
||||
assert.deepEqual((await core.projectSecretEnv(db, proj.id)).env, {});
|
||||
await assert.rejects(core.setSecretAudience(db, stranger.id, proj.id, "STRIPE_TEST_KEY", true), /Не найдено/);
|
||||
await assert.rejects(core.setSecretAudience(db, owner.id, proj.id, "NOPE", true), /нет/);
|
||||
});
|
||||
|
||||
test("Scenario: Секрет только продукту — агент его не получает, выкатка получает", async () => {
|
||||
const { p, proj } = await ownedProject({ turns: [], echoEnv: ["MAPS_KEY", "OPEN_KEY"] });
|
||||
await core.setProjectSecret(db, owner.id, proj.id, "MAPS_KEY", "mock-maps-product-only");
|
||||
await core.setProjectSecret(db, owner.id, proj.id, "OPEN_KEY", "mock-open-for-agent", { agent: true });
|
||||
const id = await p.start();
|
||||
const env = (await p.waitLog("env echo", (e) => e.ev === "env")).env as Record<string, string | null>;
|
||||
assert.equal(env.MAPS_KEY, null, "a product-only secret is not in the agent's secrets.env");
|
||||
assert.equal(env.OPEN_KEY, "mock-open-for-agent");
|
||||
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, ["OPEN_KEY"]);
|
||||
assert.deepEqual((await core.projectSecretEnv(db, proj.id, "deploy")).env, { MAPS_KEY: "mock-maps-product-only", OPEN_KEY: "mock-open-for-agent" });
|
||||
});
|
||||
|
||||
test("Scenario: Настройка выключена — агенту ни одного секрета; старый проект — как раньше", async () => {
|
||||
const { p, proj } = await ownedProject({ turns: [], echoEnv: ["OPEN_KEY"] });
|
||||
await core.setProjectSecret(db, owner.id, proj.id, "OPEN_KEY", "mock-open-key-off", { agent: true });
|
||||
assert.equal(await core.agentSecretsEnabled(db, proj.id), true, "no setting row = a project made before PEP-253");
|
||||
await core.setAgentSecretsEnabled(db, owner.id, proj.id, false);
|
||||
const id = await p.start();
|
||||
const env = (await p.waitLog("env echo", (e) => e.ev === "env")).env as Record<string, string | null>;
|
||||
assert.equal(env.OPEN_KEY, null);
|
||||
assert.ok(!(await db.select().from(events).where(eq(events.sessionId, id))).some((e) => e.type === "secrets_issued"));
|
||||
assert.deepEqual((await core.projectSecretEnv(db, proj.id, "deploy")).env, { OPEN_KEY: "mock-open-key-off" }, "the product still gets it");
|
||||
await assert.rejects(core.setAgentSecretsEnabled(db, stranger.id, proj.id, true), /Не найдено/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ключ сервиса из каталога", () => {
|
||||
test("Scenario Outline: какой сервис узнаётся по имени и значению", () => {
|
||||
const cases: Array<[string, string | null, string | null]> = [
|
||||
["STRIPE_SECRET_KEY", "sk_test_mockabcdef123", "stripe"],
|
||||
["PAYMENTS_KEY", "sk_live_mockabcdef123", "stripe"],
|
||||
["STRIPE_WEBHOOK_SECRET", "whsec_mockabcdef", null],
|
||||
["STRIPE_PUBLISHABLE_KEY", "pk_test_mockabc", null],
|
||||
["OPENAI_API_KEY", "sk-proj-mockabcdefghijklmnop", "openai"],
|
||||
["LLM_KEY", "sk-ant-mockabcdefghijkl", "anthropic"],
|
||||
["GITHUB_TOKEN", "ghp_mockabcdefghijklmnopqrstu", "github"],
|
||||
["TELEGRAM_BOT_TOKEN", "123456789:mockABCDEFGHIJKLMNOPQRSTUVWXYZ012345", "telegram"],
|
||||
["SLACK_BOT_TOKEN", "xoxb-mock-1234567890", "slack"],
|
||||
["SENTRY_DSN", "https://mock@sentry.io/1", null],
|
||||
["FEATURE_FLAGS", "beta,new-ui", null],
|
||||
["TWILIO_AUTH_TOKEN", "mocktokenonly", null],
|
||||
["SUPABASE_KEY", "mock-supabase", null],
|
||||
];
|
||||
for (const [name, value, want] of cases) assert.equal(core.guessSecretService(name, value)?.id ?? null, want, `${name}`);
|
||||
assert.ok(core.secretNameHints().some((h) => h.prefix === "STRIPE_" && h.service === "Stripe"));
|
||||
});
|
||||
|
||||
test("Scenario: Переезд ключа Stripe", async () => {
|
||||
const { p, proj } = await ownedProject({ turns: [], echoEnv: ["STRIPE_SECRET_KEY"] });
|
||||
await core.setProjectSecret(db, owner.id, proj.id, "STRIPE_SECRET_KEY", "sk_test_mockmove123456", { agent: true });
|
||||
await assert.rejects(core.secretToConnection(db, stranger.id, proj.id, "STRIPE_SECRET_KEY"), /Не найдено/);
|
||||
const r = await core.secretToConnection(db, owner.id, proj.id, "STRIPE_SECRET_KEY");
|
||||
assert.equal(r.connectionName, "Stripe");
|
||||
const [conn] = await db.select().from(connections).where(eq(connections.id, r.connectionId));
|
||||
assert.equal(conn!.ownerId, owner.id);
|
||||
assert.equal(conn!.catalogId, "stripe");
|
||||
assert.equal(core.openConnectionSecret(conn!), "sk_test_mockmove123456");
|
||||
const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, r.connectionId));
|
||||
assert.deepEqual([grant!.projectId, grant!.agentId, grant!.readMode, grant!.writeMode], [proj.id, null, "auto", "auto"]);
|
||||
const row = await secretRow(proj.id, "STRIPE_SECRET_KEY");
|
||||
assert.deepEqual([row.agentEnv, row.connectionId], [false, r.connectionId], "the secret stays, only for the product");
|
||||
await p.start();
|
||||
const env = (await p.waitLog("env echo", (e) => e.ev === "env")).env as Record<string, string | null>;
|
||||
assert.equal(env.STRIPE_SECRET_KEY, null);
|
||||
assert.equal((await core.projectSecretEnv(db, proj.id, "deploy")).env.STRIPE_SECRET_KEY, "sk_test_mockmove123456");
|
||||
await assert.rejects(core.secretToConnection(db, owner.id, proj.id, "STRIPE_SECRET_KEY"), /уже стал подключением/);
|
||||
// A second project with a Stripe key: the name is taken — «Stripe · KEY».
|
||||
const two = await ownedProject();
|
||||
await core.setProjectSecret(db, owner.id, two.proj.id, "STRIPE_KEY", "sk_test_mocktwo1234567", { agent: true });
|
||||
assert.equal((await core.secretToConnection(db, owner.id, two.proj.id, "STRIPE_KEY")).connectionName, `Stripe · ${two.proj.key}`);
|
||||
});
|
||||
|
||||
test("Scenario: Секрет не похож на ключ сервиса — переезда нет", async () => {
|
||||
const { proj } = await ownedProject();
|
||||
await core.setProjectSecret(db, owner.id, proj.id, "FEATURE_FLAGS", "beta,new-ui", { agent: true });
|
||||
await assert.rejects(core.secretToConnection(db, owner.id, proj.id, "FEATURE_FLAGS"), /Не удалось понять/);
|
||||
assert.equal((await secretRow(proj.id, "FEATURE_FLAGS")).agentEnv, true, "nothing changed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ревизия секретов", () => {
|
||||
test("Scenario: Отчёт суперадмину и сообщение владельцу один раз", async () => {
|
||||
const { proj } = await ownedProject();
|
||||
await core.setProjectSecret(db, owner.id, proj.id, "GITHUB_TOKEN", "ghp_mockreportabcdefghijklmn", { agent: true });
|
||||
await core.setProjectSecret(db, owner.id, proj.id, "MAPS_KEY", "mock-maps-report");
|
||||
const rows = await core.secretsAgentReport(db, { projectIds: [proj.id] });
|
||||
const gh = rows.find((r) => r.name === "GITHUB_TOKEN")!;
|
||||
assert.deepEqual([gh.serviceName, gh.inAgentEnv, core.shouldMove(gh)], ["GitHub", true, true]);
|
||||
assert.equal(rows.find((r) => r.name === "MAPS_KEY")!.serviceId, null);
|
||||
assert.ok(!JSON.stringify(rows).includes("ghp_mockreport"), "no values in the report");
|
||||
|
||||
const sent = await notifySecretsReport(db);
|
||||
assert.ok(sent.some((s) => s.projectKey === proj.key && s.names.join() === "GITHUB_TOKEN"));
|
||||
const chat = await core.ensureProjectChat(db, proj.id);
|
||||
const said = async () => (await db.select().from(chatMessages).where(eq(chatMessages.chatId, chat.id))).filter((m) => stripAsIs(m.text).includes("GITHUB_TOKEN"));
|
||||
assert.equal((await said()).length, 1);
|
||||
assert.ok(!(await said())[0]!.text.includes("ghp_mock"));
|
||||
assert.ok(!(await notifySecretsReport(db)).some((s) => s.projectKey === proj.key), "told once");
|
||||
assert.equal((await said()).length, 1);
|
||||
});
|
||||
});
|
||||
@ -49,7 +49,7 @@ async function mcpAs(user: typeof owner) {
|
||||
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);
|
||||
const s = await core.setProjectSecret(db, owner.id, proj.id, "STRIPE_TEST_KEY", VALUE, { agent: true });
|
||||
assert.equal(s.name, "STRIPE_TEST_KEY");
|
||||
assert.equal(s.updatedBy, "mock-owner");
|
||||
const list = await core.listProjectSecrets(db, proj.id);
|
||||
@ -97,8 +97,8 @@ describe("project secrets (PEP-54)", () => {
|
||||
|
||||
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");
|
||||
await core.setProjectSecret(db, owner.id, proj.id, "STRIPE_TEST_KEY", VALUE, { agent: true });
|
||||
await core.setProjectSecret(db, owner.id, proj.id, "MAPS_KEY", "maps-key-abcdef", { agent: true });
|
||||
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);
|
||||
@ -175,7 +175,7 @@ describe("project secrets (PEP-54)", () => {
|
||||
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.match(text, /- MAPS_KEY \(deployed product only — not in your env\)\n- STRIPE_TEST_KEY \(deployed product only/);
|
||||
assert.ok(!text.includes(VALUE));
|
||||
} finally {
|
||||
await client.close();
|
||||
@ -188,7 +188,7 @@ describe("secret rotation and audit (PEP-19)", () => {
|
||||
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");
|
||||
await core.setProjectSecret(db, owner.id, proj.id, "ROTATE_ME", "rotate-value-1", { agent: true });
|
||||
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);
|
||||
@ -254,7 +254,7 @@ describe("secret rotation and audit (PEP-19)", () => {
|
||||
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");
|
||||
await core.setProjectSecret(db, owner.id, proj.id, "LOST_KEY", "lost-value", { agent: true });
|
||||
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);
|
||||
|
||||
Loading…
Reference in New Issue
Block a user