286 lines
18 KiB
TypeScript
286 lines
18 KiB
TypeScript
// PEP-1: auth primitives, access control and project provisioning (mock-gitea + real git).
|
||
import assert from "node:assert/strict";
|
||
import { execFileSync } from "node:child_process";
|
||
import { existsSync, mkdtempSync, readFileSync } from "node:fs";
|
||
import { tmpdir } from "node:os";
|
||
import { join, resolve } from "node:path";
|
||
import { fileURLToPath } from "node:url";
|
||
import { after, before, describe, test } from "node:test";
|
||
import { core, db, runner, teardown } from "./helpers.ts";
|
||
import { MockGitea } from "../src/mock-gitea.ts";
|
||
|
||
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||
const TMP = mkdtempSync(join(tmpdir(), "peppa-web-"));
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
process.env.PEPPA_WORKSPACES = join(TMP, "workspaces");
|
||
|
||
const gitea = new MockGitea(join(TMP, "gitea"));
|
||
const ALICE = { id: 11, login: "mock-alice", token: "mock-token-alice", orgs: ["mock-team"] };
|
||
const BOB = { id: 12, login: "mock-bob", token: "mock-token-bob" };
|
||
let templateUrl = "";
|
||
let alice: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let bob: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
|
||
before(async () => {
|
||
await gitea.start();
|
||
process.env.GITEA_URL = gitea.url;
|
||
gitea.addUser(ALICE);
|
||
gitea.addUser(BOB);
|
||
// Template repo from the real template/ dir.
|
||
const tpl = gitea.addRepo("peppa-bot", "template");
|
||
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`]);
|
||
templateUrl = tpl.path;
|
||
alice = await core.upsertUserFromGitea(db, { id: ALICE.id, login: ALICE.login }, { access_token: ALICE.token, refresh_token: "r", expires_in: 3600 });
|
||
bob = await core.upsertUserFromGitea(db, { id: BOB.id, login: BOB.login }, { access_token: BOB.token });
|
||
});
|
||
after(async () => {
|
||
await gitea.stop();
|
||
await teardown();
|
||
});
|
||
|
||
const provision = async (over: Partial<Parameters<typeof runner.provisionProject>[1]> & { slug: string; key: string }) =>
|
||
runner.provisionProject(db, {
|
||
gitea: await core.giteaForUser(db, alice),
|
||
owner: ALICE.login,
|
||
ownerIsUser: true,
|
||
name: `Mock ${over.key}`,
|
||
ownerId: alice.id,
|
||
templateUrl,
|
||
...over,
|
||
});
|
||
|
||
describe("auth primitives", () => {
|
||
test("token encryption round-trips and tokens are not stored in clear", async () => {
|
||
const enc = core.encrypt("secret-token");
|
||
assert.notEqual(enc, "secret-token");
|
||
assert.equal(core.decrypt(enc), "secret-token");
|
||
assert.ok(!alice.accessTokenEnc?.includes(ALICE.token));
|
||
assert.equal(core.decrypt(alice.accessTokenEnc!), ALICE.token);
|
||
});
|
||
|
||
test("signed session payloads reject tampering", () => {
|
||
const t = core.sign({ uid: 1, exp: 1 });
|
||
assert.deepEqual(core.verify(t), { uid: 1, exp: 1 });
|
||
const [body, sig] = t.split(".");
|
||
const forged = Buffer.from(JSON.stringify({ uid: 2, exp: 1 })).toString("base64url");
|
||
assert.equal(core.verify(`${forged}.${sig}`), null);
|
||
assert.equal(core.verify(`${body}.AAAA`), null);
|
||
assert.equal(core.verify(undefined), null);
|
||
});
|
||
|
||
test("admin login link works once and expires", async () => {
|
||
const code = await core.createLoginLink(db, alice.id);
|
||
assert.equal(await core.consumeLoginLink(db, code), alice.id);
|
||
assert.equal(await core.consumeLoginLink(db, code), null, "single use");
|
||
const old = await core.createLoginLink(db, alice.id);
|
||
await core.setSetting(db, `web.login:${core.hashToken(old)}`, { userId: alice.id, expiresAt: Date.now() - 1 });
|
||
assert.equal(await core.consumeLoginLink(db, old), null, "expired");
|
||
});
|
||
|
||
test("OAuth code exchange + Gitea user → Peppa user", async () => {
|
||
gitea.oauthCodes.set("mock-code", BOB.token);
|
||
const tokens = await core.exchangeOAuthCode(gitea.url, "id", "secret", "mock-code", "http://x/auth/callback");
|
||
const me = await new core.GiteaClient(gitea.url, tokens.access_token).me();
|
||
const u = await core.upsertUserFromGitea(db, me, tokens);
|
||
assert.equal(u.id, bob.id, "same Gitea account → same Peppa user");
|
||
await assert.rejects(core.exchangeOAuthCode(gitea.url, "id", "secret", "mock-code", "http://x/auth/callback"), "code is single use");
|
||
});
|
||
});
|
||
|
||
describe("project provisioning", () => {
|
||
test("new repo: template + OpenSpec pushed, peppa-bot collaborator, owned by the user", async () => {
|
||
const p = await provision({ slug: "mock-demo", key: "MDEMO" });
|
||
assert.equal(p.ownerId, alice.id);
|
||
assert.equal(p.giteaOwner, ALICE.login);
|
||
const files = gitea.files(ALICE.login, "mock-demo");
|
||
for (const f of ["AGENTS.md", "CLAUDE.md", ".mcp.json", ".peppa/project.json", "openspec/config.yaml", "README.md"]) assert.ok(files.includes(f), `${f} pushed`);
|
||
assert.ok(!files.includes("RULES.md"), "RULES.md stays in the template repo");
|
||
assert.ok(files.some((f) => f.startsWith(".agents/skills/openspec-")), "openspec init ran (agent skills)");
|
||
assert.match(gitea.show(ALICE.login, "mock-demo", "openspec/config.yaml"), /Пеппа/, "template OpenSpec config kept");
|
||
assert.equal(JSON.parse(gitea.show(ALICE.login, "mock-demo", ".peppa/project.json")).key, "MDEMO");
|
||
assert.equal(gitea.repos.get(`${ALICE.login}/mock-demo`)!.collaborators["peppa-bot"], "write");
|
||
assert.match(execFileSync("git", ["-C", p.workspacePath, "config", "--get-all", "credential.helper"], { encoding: "utf8" }), /git-credential-peppa/);
|
||
});
|
||
|
||
// PEP-145, spec product-link: «Новый проект получает заглушку и первую выкладку».
|
||
test("new repo: the product placeholder, deploy settings and the tag of the first deploy", async () => {
|
||
const p = await core.getProject(db, "MDEMO");
|
||
const files = gitea.files(ALICE.login, "mock-demo");
|
||
for (const f of ["Dockerfile", "product/server.mjs", "product/index.html", "deploy/compose.yml"]) assert.ok(files.includes(f), `${f} pushed`);
|
||
assert.match(gitea.show(ALICE.login, "mock-demo", "product/index.html"), /Продукт создаётся/);
|
||
const cfg = JSON.parse(gitea.show(ALICE.login, "mock-demo", ".peppa/project.json"));
|
||
assert.deepEqual(cfg.deploy, { compose: "deploy/compose.yml", service: "web", port: 3000, health: "/healthz" });
|
||
const tags = gitea.repo(ALICE.login, "mock-demo").tags;
|
||
assert.equal(tags.length, 1);
|
||
assert.match(tags[0]!.name, /^deploy-staging-\d+$/);
|
||
assert.equal(tags[0]!.target, execFileSync("git", ["-C", p.workspacePath, "rev-parse", "HEAD"], { encoding: "utf8" }).trim(), "the head of the default branch");
|
||
assert.equal(await core.getPublishChoice(db, p.id), "auto", "a new project shows accepted versions to everyone by itself");
|
||
});
|
||
|
||
test("PEP-142: the same form sent twice leads to the project just created, not to «slug is taken»", async () => {
|
||
const again = await runner.justCreatedProject(db, { slug: "Mock-Demo", key: "mdemo", ownerId: alice.id });
|
||
assert.equal(again?.key, "MDEMO", "the owner's second click finds the project made a moment ago");
|
||
assert.equal(await runner.justCreatedProject(db, { slug: "mock-demo", key: "MDEMO", ownerId: bob.id }), null, "another person still gets «taken»");
|
||
assert.equal(await runner.justCreatedProject(db, { slug: "mock-demo", key: "MOTHER", ownerId: alice.id }), null, "a different key is a different project");
|
||
assert.equal(await runner.justCreatedProject(db, { slug: "mock-demo", key: "MDEMO", ownerId: alice.id }, -1), null, "an old project is not «just created»");
|
||
});
|
||
|
||
test("PEP-142: two submissions at once open one project; the next one within minutes too", async () => {
|
||
const opts = { gitea: await core.giteaForUser(db, alice), owner: ALICE.login, ownerIsUser: true, name: "Mock Twice", ownerId: alice.id, templateUrl, slug: "mock-twice", key: "MTWICE" };
|
||
const [a, b] = await Promise.all([runner.provisionProjectOnce(db, opts), runner.provisionProjectOnce(db, opts)]);
|
||
assert.equal(a.id, b.id, "both requests get the same project");
|
||
assert.equal((await runner.provisionProjectOnce(db, opts)).id, a.id, "a resubmission after creation opens it");
|
||
assert.equal((await core.listProjects(db)).filter((p) => p.slug === "mock-twice").length, 1);
|
||
await assert.rejects(
|
||
async () => runner.provisionProjectOnce(db, { ...opts, gitea: await core.giteaForUser(db, bob), owner: BOB.login, ownerId: bob.id }),
|
||
/уже занят/,
|
||
"another person still gets «taken»",
|
||
);
|
||
await assert.rejects(runner.provisionProjectOnce(db, { ...opts, key: "MOTHER" }), /уже занят/, "a different key is a different form");
|
||
});
|
||
|
||
test("project in an org the user can create repos in", async () => {
|
||
const p = await provision({ slug: "mock-team-app", key: "MTEAM", owner: "mock-team", ownerIsUser: false });
|
||
assert.equal(p.giteaOwner, "mock-team");
|
||
assert.ok(gitea.files("mock-team", "mock-team-app").includes("AGENTS.md"));
|
||
});
|
||
|
||
test("conflicts leave nothing behind in Peppa", async () => {
|
||
await assert.rejects(provision({ slug: "mock-demo", key: "MOTHER" }), /Slug "mock-demo" уже занят/);
|
||
await assert.rejects(provision({ slug: "mock-other", key: "MDEMO" }), /Ключ "MDEMO" уже занят/);
|
||
gitea.addRepo(ALICE.login, "mock-taken");
|
||
await assert.rejects(provision({ slug: "mock-taken", key: "MTAKEN" }), /уже есть/);
|
||
assert.ok(!existsSync(join(process.env.PEPPA_WORKSPACES!, "mock-taken")));
|
||
await assert.rejects(core.getProject(db, "MTAKEN"));
|
||
});
|
||
|
||
test("existing repo with code: own files kept, Peppa files added", async () => {
|
||
gitea.addRepo(ALICE.login, "mock-legacy", { files: { "AGENTS.md": "# Свои правила\n", "src/app.ts": "export {};\n" } });
|
||
const p = await provision({ slug: "mock-legacy", key: "MLEG", existing: true });
|
||
assert.equal(gitea.show(ALICE.login, "mock-legacy", "AGENTS.md"), "# Свои правила\n", "existing AGENTS.md not overwritten");
|
||
const files = gitea.files(ALICE.login, "mock-legacy");
|
||
for (const f of ["src/app.ts", ".peppa/project.json", ".mcp.json", "openspec/config.yaml"]) assert.ok(files.includes(f), f);
|
||
assert.ok(files.some((f) => f.startsWith(".agents/skills/openspec-")), "openspec init ran");
|
||
assert.ok(readFileSync(join(p.workspacePath, "src/app.ts"), "utf8"));
|
||
// PEP-145, spec product-link: «Существующий репозиторий не получает заглушку».
|
||
assert.ok(!files.includes("Dockerfile") && !files.some((f) => f.startsWith("product/")), "no placeholder in a repository with its own code");
|
||
assert.equal(JSON.parse(gitea.show(ALICE.login, "mock-legacy", ".peppa/project.json")).deploy, undefined);
|
||
assert.deepEqual(gitea.repo(ALICE.login, "mock-legacy").tags, []);
|
||
});
|
||
|
||
test("existing repo without admin rights is refused", async () => {
|
||
gitea.addRepo(ALICE.login, "mock-foreign", { admins: ["someone-else"], files: { "x.txt": "x" } });
|
||
await assert.rejects(provision({ slug: "mock-foreign", key: "MFOR", existing: true }), /Нет прав администратора/);
|
||
});
|
||
});
|
||
|
||
describe("access control", () => {
|
||
test("a user only reaches own projects", async () => {
|
||
const p = await core.getProject(db, "MDEMO");
|
||
assert.equal((await core.projectForUser(db, alice.id, p.id)).key, "MDEMO");
|
||
await assert.rejects(core.projectForUser(db, bob.id, p.id), /Не найдено/);
|
||
assert.deepEqual((await core.listUserProjects(db, bob.id)).map((x) => x.key), []);
|
||
assert.ok((await core.listUserProjects(db, alice.id)).some((x) => x.key === "MDEMO"));
|
||
});
|
||
});
|
||
|
||
describe("PEP-74: суперадмин видит все проекты", () => {
|
||
test("чужой проект открыт суперадмину и в списке «Проекты других»; обычному — «Не найдено»", async () => {
|
||
const owner = await core.upsertUserFromGitea(db, { id: 7401, login: "mock-p74-owner" }, { access_token: "x" });
|
||
const boss = await core.upsertUserFromGitea(db, { id: 7402, login: "mock-p74-boss" }, { access_token: "x" });
|
||
const other = await core.upsertUserFromGitea(db, { id: 7403, login: "mock-p74-other" }, { access_token: "x" });
|
||
const p = await core.createProject(db, { slug: "mock-p74", key: "MPSA", name: "P74", giteaOwner: "x", workspacePath: "/tmp/mock-p74", ownerId: owner.id });
|
||
await core.setPlatformAdmins(db, ["mock-p74-boss"]);
|
||
try {
|
||
assert.equal((await core.projectForUser(db, boss.id, p.id)).key, "MPSA");
|
||
await assert.rejects(core.projectForUser(db, other.id, p.id), /Не найдено/);
|
||
const list = await core.listOtherProjects(db, boss.id);
|
||
assert.ok(list.some((x) => x.key === "MPSA" && x.ownerLogin === "mock-p74-owner"));
|
||
assert.deepEqual(await core.listOtherProjects(db, other.id), []);
|
||
assert.ok(!(await core.listOtherProjects(db, owner.id)).some((x) => x.key === "MPSA"));
|
||
assert.ok(!(await core.userProjectIds(db, boss.id)).includes(p.id), "inbox and notifications stay own-only");
|
||
} finally {
|
||
await core.setPlatformAdmins(db, null);
|
||
}
|
||
});
|
||
});
|
||
|
||
describe("PEP-77: прогресс по всем проектам", () => {
|
||
test("колонки, стори в работе, ждущие «Принять»; чужие проекты — только суперадмину", async () => {
|
||
const me = await core.upsertUserFromGitea(db, { id: 7701, login: "mock-p77-me" }, { access_token: "x" });
|
||
const other = await core.upsertUserFromGitea(db, { id: 7702, login: "mock-p77-other" }, { access_token: "x" });
|
||
const a = await core.createProject(db, { slug: "mock-p77a", key: "MPRA", name: "A", giteaOwner: "x", workspacePath: "/tmp/mock-p77a", ownerId: me.id });
|
||
const b = await core.createProject(db, { slug: "mock-p77b", key: "MPRB", name: "B", giteaOwner: "x", workspacePath: "/tmp/mock-p77b", ownerId: other.id });
|
||
const mk = async (projectId: number, title: string, status?: "in_progress" | "review" | "done") => {
|
||
const t = await core.createTask(db, { projectId, title });
|
||
if (status) await core.updateTask(db, t, { status });
|
||
return t;
|
||
};
|
||
await mk(a.id, "бэклог");
|
||
const w = await mk(a.id, "в работе", "in_progress");
|
||
const r = await mk(a.id, "ревью", "review");
|
||
await mk(a.id, "готово", "done");
|
||
const archived = await mk(a.id, "в архиве", "done");
|
||
await core.setTaskArchived(db, archived, true);
|
||
await mk(b.id, "чужая", "done");
|
||
|
||
const mine = await core.progressOverview(db, me.id);
|
||
assert.deepEqual(mine.totals, { backlog: 1, inProgress: 1, review: 1, done: 1, total: 4 }, "archived stories are not counted");
|
||
assert.deepEqual(mine.mine.map((p) => p.key), ["MPRA"]);
|
||
assert.deepEqual(mine.others, []);
|
||
assert.deepEqual(mine.mine[0]!.working.map((s) => s.key), [w.key]);
|
||
assert.deepEqual(mine.mine[0]!.reviewKeys, [r.key]);
|
||
|
||
await core.setPlatformAdmins(db, ["mock-p77-me"]);
|
||
try {
|
||
const boss = await core.progressOverview(db, me.id);
|
||
const row = boss.others.find((p) => p.key === "MPRB")!;
|
||
assert.equal(row.ownerLogin, "mock-p77-other");
|
||
assert.equal(row.done, 1);
|
||
assert.equal(boss.totals.total, 4, "totals — own projects only");
|
||
} finally {
|
||
await core.setPlatformAdmins(db, null);
|
||
}
|
||
});
|
||
});
|
||
|
||
describe("новый проект: настройки по умолчанию", () => {
|
||
test("подписка владельца подключается сама; стори берутся и мержатся сами (PEP-94); продакт и аналитик включены", async () => {
|
||
const first = await provision({ slug: "mock-defaults-a", key: "MDFA" });
|
||
assert.equal(await core.projectPool(db, first.id), null, "no own subscription yet");
|
||
assert.equal(core.autonomyLevel(await core.getAutonomy(db, first.id)), "auto", "PEP-94: «Автомат»");
|
||
assert.equal((await core.getIntakeSettings(db, first.id)).enabled, true);
|
||
|
||
const sub = await core.createSubscription(db, { provider: "claude", name: "mock-defaults Claude", authKind: "oauth", secret: "sk-ant-oat01-" + "d".repeat(40), createdBy: alice.id });
|
||
const pool = await core.createPool(db, { name: "mock-defaults pool", subscriptionIds: [sub.id], createdBy: alice.id });
|
||
const second = await provision({ slug: "mock-defaults-b", key: "MDFB" });
|
||
assert.equal((await core.projectPool(db, second.id))!.id, pool.id, "connected once — not asked again");
|
||
});
|
||
});
|
||
|
||
describe("PEP-88: суперадмин управляет любым проектом", () => {
|
||
test("участники и видимость чужого проекта — суперадмину можно, постороннему нельзя", async () => {
|
||
const owner = await core.upsertUserFromGitea(db, { id: 8801, login: "mock-p88-owner" }, { access_token: "x" });
|
||
const boss = await core.upsertUserFromGitea(db, { id: 8802, login: "mock-p88-boss" }, { access_token: "x" });
|
||
// A Peppa account without Gitea: it becomes a member without a repo collaborator call.
|
||
const other = await core.registerEgovUser(db, { iin: "850505400058", name: "ДРУГОЙ УЧАСТНИК" });
|
||
const p = await core.createProject(db, { slug: "mock-p88", key: "MPMNG", name: "P88", giteaOwner: "x", workspacePath: "/tmp/mock-p88", ownerId: owner.id });
|
||
assert.equal(await runner.managesProject(db, owner, p), true);
|
||
assert.equal(await runner.managesProject(db, other, p), false);
|
||
assert.equal(await runner.managesProject(db, boss, p), false);
|
||
await assert.rejects(runner.shareProject(db, boss, p, other.login), /только владелец/);
|
||
await core.setPlatformAdmins(db, ["mock-p88-boss"]);
|
||
try {
|
||
assert.equal(await runner.managesProject(db, boss, p), true);
|
||
const r = await runner.shareProject(db, boss, p, other.login);
|
||
assert.equal(r.login, other.login);
|
||
assert.ok((await core.userProjectIds(db, other.id)).includes(p.id));
|
||
await runner.unshareProject(db, boss, p, other.login);
|
||
assert.ok(!(await core.userProjectIds(db, other.id)).includes(p.id));
|
||
await assert.rejects(runner.shareProject(db, other, p, "mock-p88-boss"), /только владелец/);
|
||
} finally {
|
||
await core.setPlatformAdmins(db, null);
|
||
}
|
||
});
|
||
});
|