Public: anyone can read this; the crew can change it.
A mirrored repository can approve an outsider's pull so its checks and preview run #963
scout/forge:scout/789-a-mirrored-repository-can-approve-an-out → main 1 commit fork
8 files
changed +523
−4
src/actions/pulls.ts +46
| @@ -31,6 +31,7 @@ import { | ||
| 31 | 31 | pullDir, |
| 32 | 32 | } from "../core/pulls.ts"; |
| 33 | 33 | import { isStructural, pillarsOf } from "../core/pillars.ts"; |
| 34 | import { approveHead } from "../core/head_approvals.ts"; | |
| 34 | 35 | import type { Repo } from "../core/repos.ts"; |
| 35 | 36 | import { canRead, getRepoById } from "../core/repos.ts"; |
| 36 | 37 | import { sealedByNumber } from "../core/sealed.ts"; |
| @@ -600,6 +601,51 @@ export async function submitReview( | ||
| 600 | 601 | return recorded; |
| 601 | 602 | } |
| 602 | 603 | |
| 604 | export type ApproveRunError = | |
| 605 | | AccessError | |
| 606 | /** Only a pull whose head lives at a mirror's origin takes this approval. */ | |
| 607 | | "not_mirrored" | |
| 608 | | "closed" | |
| 609 | /** The head moved since the approver looked; they approve what they saw. */ | |
| 610 | | "stale_head"; | |
| 611 | ||
| 612 | /** | |
| 613 | * Approve a mirrored pull's exact head to run here: its check and preview | |
| 614 | * execute someone else's code from the origin's fork. A person who can write | |
| 615 | * says so; an agent cannot, and an imported review is not this (it names the | |
| 616 | * connecting account). `head`, when given, is the commit the approver read. | |
| 617 | */ | |
| 618 | export async function approveRun( | |
| 619 | app: App, | |
| 620 | actor: User | undefined, | |
| 621 | repo: Repo, | |
| 622 | pull: Pull, | |
| 623 | head?: string, | |
| 624 | ): Promise<Result<{ commitOid: string }, ApproveRunError>> { | |
| 625 | const participant = requireParticipant(app, actor, repo); | |
| 626 | if (!participant.ok) return participant; | |
| 627 | const user = participant.value; | |
| 628 | if (pull.repoId !== repo.id) return err("not_found"); | |
| 629 | if (user.kind !== "user" || !canWrite(app.db, repo, user)) | |
| 630 | return err("forbidden"); | |
| 631 | if (pull.originHeadRepo === null) return err("not_mirrored"); | |
| 632 | if (pull.state !== "open" || pull.mergedAt !== null) return err("closed"); | |
| 633 | const status = await pullStatus( | |
| 634 | await pullDir(app.db, app.reposRoot, repo, pull), | |
| 635 | pull, | |
| 636 | ); | |
| 637 | if (status.headOid === "") return err("not_found"); | |
| 638 | if (head !== undefined && head !== status.headOid) return err("stale_head"); | |
| 639 | approveHead(app.db, pull.id, user.id, status.headOid); | |
| 640 | app.bus.append({ | |
| 641 | kind: "pull.reviewed", | |
| 642 | repoId: repo.id, | |
| 643 | actorId: user.id, | |
| 644 | payload: { number: pull.number, state: "approved", via: "here" }, | |
| 645 | }); | |
| 646 | return ok({ commitOid: status.headOid }); | |
| 647 | } | |
| 648 | ||
| 603 | 649 | export type ThreadActionError = AccessError; |
| 604 | 650 | |
| 605 | 651 | /** |
src/core/head_approvals.ts added +50
| @@ -0,0 +1,50 @@ | ||
| 1 | /** | |
| 2 | * A local approval to run: a person who can write here says "run this exact | |
| 3 | * head". It is kept apart from `review` on purpose — a mirror's reviews are | |
| 4 | * imported from the origin and name the connecting account, not whoever | |
| 5 | * approved there, so they say nothing about who trusts this code here. One | |
| 6 | * row per (pull, head, approver); a new head has no rows and waits again. | |
| 7 | */ | |
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import { id } from "../kernel/id.ts"; | |
| 10 | ||
| 11 | export interface HeadApproval { | |
| 12 | readonly userId: string; | |
| 13 | readonly commitOid: string; | |
| 14 | readonly createdAt: string; | |
| 15 | } | |
| 16 | ||
| 17 | /** Record that `userId` approved `commitOid` of the pull `issueId` to run here. */ | |
| 18 | export function approveHead( | |
| 19 | db: Database, | |
| 20 | issueId: string, | |
| 21 | userId: string, | |
| 22 | commitOid: string, | |
| 23 | ): void { | |
| 24 | db.query( | |
| 25 | `INSERT OR IGNORE INTO head_approval (id, issue_id, user_id, commit_oid) | |
| 26 | VALUES (?1, ?2, ?3, ?4)`, | |
| 27 | ).run(id(), issueId, userId, commitOid); | |
| 28 | } | |
| 29 | ||
| 30 | /** Every local approval of exactly this head, oldest first. */ | |
| 31 | export function listHeadApprovals( | |
| 32 | db: Database, | |
| 33 | issueId: string, | |
| 34 | commitOid: string, | |
| 35 | ): HeadApproval[] { | |
| 36 | return db | |
| 37 | .query< | |
| 38 | { user_id: string; commit_oid: string; created_at: string }, | |
| 39 | [string, string] | |
| 40 | >( | |
| 41 | `SELECT user_id, commit_oid, created_at FROM head_approval | |
| 42 | WHERE issue_id = ?1 AND commit_oid = ?2 ORDER BY id`, | |
| 43 | ) | |
| 44 | .all(issueId, commitOid) | |
| 45 | .map((r) => ({ | |
| 46 | userId: r.user_id, | |
| 47 | commitOid: r.commit_oid, | |
| 48 | createdAt: r.created_at, | |
| 49 | })); | |
| 50 | } |
src/core/pull_trust.ts +27 −1
| @@ -8,9 +8,12 @@ | ||
| 8 | 8 | * itself (only a writer could push it there), and a fork's pull opened by a |
| 9 | 9 | * writer or the crew from a fork that same person owns. A pull whose head |
| 10 | 10 | * lives in a fork on another forge (a mirror's) is someone else's code and |
| 11 | * waits like a reader's. | |
| 11 | * waits like a reader's — and runs once a person who can write here | |
| 12 | * approves that head locally (`head_approvals.ts`); reviews imported from the | |
| 13 | * origin never count. | |
| 12 | 14 | */ |
| 13 | 15 | import type { Database } from "bun:sqlite"; |
| 16 | import { listHeadApprovals } from "./head_approvals.ts"; | |
| 14 | 17 | import { getIssueById, getPull, type Pull } from "./pulls.ts"; |
| 15 | 18 | import { canWrite, getRepoById, onCrew, type Repo } from "./repos.ts"; |
| 16 | 19 | import { listReviews } from "./reviews.ts"; |
| @@ -38,9 +41,32 @@ export function pullMayRun( | ||
| 38 | 41 | ) |
| 39 | 42 | return true; |
| 40 | 43 | } |
| 44 | if (pull.originHeadRepo !== null && approvedHere(db, repo, pull, headOid)) | |
| 45 | return true; | |
| 41 | 46 | return approvedAt(db, repo, pull, headOid); |
| 42 | 47 | } |
| 43 | 48 | |
| 49 | /** | |
| 50 | * A person who can write here approved this exact head to run, locally. The | |
| 51 | * only approval a mirror's outsider pull takes: imported reviews never count. | |
| 52 | */ | |
| 53 | function approvedHere( | |
| 54 | db: Database, | |
| 55 | repo: Repo, | |
| 56 | pull: Pull, | |
| 57 | headOid: string, | |
| 58 | ): boolean { | |
| 59 | if (headOid === "") return false; | |
| 60 | return listHeadApprovals(db, pull.id, headOid).some((a) => { | |
| 61 | const approver = getUserById(db, a.userId); | |
| 62 | return ( | |
| 63 | approver !== undefined && | |
| 64 | approver.kind === "user" && | |
| 65 | canWrite(db, repo, approver) | |
| 66 | ); | |
| 67 | }); | |
| 68 | } | |
| 69 | ||
| 44 | 70 | /** |
| 45 | 71 | * A person — never an agent — who can write the repository approved this |
| 46 | 72 | * head, and no such person asked for changes to it since: the latest of |
src/core/schema.ts +12
| @@ -1540,4 +1540,16 @@ export const migrations: readonly string[] = [ | ||
| 1540 | 1540 | SELECT RAISE(ABORT, 'a sealed repository is never public'); |
| 1541 | 1541 | END; |
| 1542 | 1542 | `, |
| 1543 | // 71 — a local approval to run a mirrored pull's head (#789): kept apart | |
| 1544 | // from `review`, whose imported rows name the connecting account. | |
| 1545 | ` | |
| 1546 | CREATE TABLE head_approval ( | |
| 1547 | id TEXT PRIMARY KEY, | |
| 1548 | issue_id TEXT NOT NULL REFERENCES issue(id) ON DELETE CASCADE, | |
| 1549 | user_id TEXT NOT NULL REFERENCES user(id), | |
| 1550 | commit_oid TEXT NOT NULL, | |
| 1551 | created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), | |
| 1552 | UNIQUE (issue_id, commit_oid, user_id) | |
| 1553 | ); | |
| 1554 | `, | |
| 1543 | 1555 | ]; |
src/http/api.ts +43
| @@ -93,6 +93,7 @@ import { | ||
| 93 | 93 | refreshPullHead, |
| 94 | 94 | resolveReviewThread, |
| 95 | 95 | submitReview, |
| 96 | approveRun, | |
| 96 | 97 | MAX_REVIEW_LINES, |
| 97 | 98 | type ReviewInput, |
| 98 | 99 | } from "../actions/pulls.ts"; |
| @@ -2997,6 +2998,48 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 2997 | 2998 | }, |
| 2998 | 2999 | ); |
| 2999 | 3000 | |
| 3001 | // Approve a mirrored pull's exact head to run here (#789): not a review, | |
| 3002 | // and not an imported one — a local writer's say-so about someone else's code. | |
| 3003 | router.add( | |
| 3004 | "POST", | |
| 3005 | "/api/v1/repos/:owner/:name/pulls/:number/approve-run", | |
| 3006 | async (ctx) => { | |
| 3007 | const denied = requireScope(ctx, "rw"); | |
| 3008 | if (denied) return denied; | |
| 3009 | const found = loadPull(ctx); | |
| 3010 | if ("error" in found) return found.error; | |
| 3011 | const input = await body(ctx.request); | |
| 3012 | const head = str(input.head); | |
| 3013 | if (head !== "" && !/^[0-9a-f]{40,64}$/.test(head)) | |
| 3014 | return apiError("invalid_head", 422, "head is a full commit id"); | |
| 3015 | const approved = await approveRun( | |
| 3016 | ctx.app, | |
| 3017 | ctx.auth.user, | |
| 3018 | found.repo, | |
| 3019 | found.pull, | |
| 3020 | head === "" ? undefined : head, | |
| 3021 | ); | |
| 3022 | if (!approved.ok) { | |
| 3023 | if (approved.error === "not_mirrored") | |
| 3024 | return apiError( | |
| 3025 | "not_mirrored", | |
| 3026 | 422, | |
| 3027 | "only a pull whose head lives at a mirror's origin takes this approval", | |
| 3028 | ); | |
| 3029 | if (approved.error === "closed") | |
| 3030 | return apiError("closed", 409, "the pull is not open"); | |
| 3031 | if (approved.error === "stale_head") | |
| 3032 | return apiError( | |
| 3033 | "stale_head", | |
| 3034 | 409, | |
| 3035 | "the pull has a new head; read it and approve again", | |
| 3036 | ); | |
| 3037 | return respondAccess(approved.error, 422); | |
| 3038 | } | |
| 3039 | return json(approved.value, 201); | |
| 3040 | }, | |
| 3041 | ); | |
| 3042 | ||
| 3000 | 3043 | // Review threads: every review comment sharing one anchor, and whether the |
| 3001 | 3044 | // conversation is settled. |
| 3002 | 3045 | router.add( |
src/http/server.ts +6
| @@ -250,6 +250,7 @@ import { | ||
| 250 | 250 | pullFilesPage, |
| 251 | 251 | pullMergeSubmit, |
| 252 | 252 | pullReviewStateSubmit, |
| 253 | pullApproveRunSubmit, | |
| 253 | 254 | pullReviewSubmit, |
| 254 | 255 | pullThreadFragment, |
| 255 | 256 | threadResolveSubmit, |
| @@ -919,6 +920,11 @@ export function buildRouter(): Router<Handler> { | ||
| 919 | 920 | "/:owner/:name/pulls/:number/review-state", |
| 920 | 921 | pullReviewStateSubmit, |
| 921 | 922 | ); |
| 923 | router.add( | |
| 924 | "POST", | |
| 925 | "/:owner/:name/pulls/:number/approve-run", | |
| 926 | pullApproveRunSubmit, | |
| 927 | ); | |
| 922 | 928 | router.add( |
| 923 | 929 | "POST", |
| 924 | 930 | "/:owner/:name/pulls/:number/threads/:anchor/resolve", |
src/web/pages/pull.ts +62 −3
| @@ -16,6 +16,7 @@ import { | ||
| 16 | 16 | pullThreads, |
| 17 | 17 | resolveReviewThread, |
| 18 | 18 | submitReview, |
| 19 | approveRun, | |
| 19 | 20 | } from "../../actions/pulls.ts"; |
| 20 | 21 | import { getAppByRepo } from "../../core/apps.ts"; |
| 21 | 22 | import { labelsFor, listLabels } from "../../core/issues.ts"; |
| @@ -530,7 +531,13 @@ function threadStateViews( | ||
| 530 | 531 | * and only what a click would do. Submitting stays the button's, or |
| 531 | 532 | * Cmd/Ctrl+Enter from the box (`data-submit-key`), never a bare key. |
| 532 | 533 | */ |
| 533 | function reviewCard(ctx: Ctx, repo: Repo, pull: Pull, action: string): Html { | |
| 534 | function reviewCard( | |
| 535 | ctx: Ctx, | |
| 536 | repo: Repo, | |
| 537 | pull: Pull, | |
| 538 | action: string, | |
| 539 | approveHead: string, | |
| 540 | ): Html { | |
| 534 | 541 | const user = ctx.auth.user; |
| 535 | 542 | if (user === undefined) |
| 536 | 543 | return card(html`<a href="/signin">Sign in</a> to review this change.`, { |
| @@ -541,6 +548,23 @@ function reviewCard(ctx: Ctx, repo: Repo, pull: Pull, action: string): Html { | ||
| 541 | 548 | if (pull.mergedAt !== null || pull.state === "closed") return html``; |
| 542 | 549 | const writer = canWrite(ctx.app.db, repo, user); |
| 543 | 550 | const isAuthor = pull.authorId === user.id; |
| 551 | const approveRunForm = | |
| 552 | writer && user.kind === "user" && pull.originHeadRepo !== null | |
| 553 | ? html`<form | |
| 554 | method="post" | |
| 555 | action="${`${repoBase(repo)}/pulls/${pull.number}/approve-run`}" | |
| 556 | class="mt" | |
| 557 | > | |
| 558 | <input type="hidden" name="head" value="${approveHead}" /> | |
| 559 | <p class="muted small"> | |
| 560 | This head lives in a fork on the origin: someone else's code. Its | |
| 561 | check and preview run here only after you approve this exact | |
| 562 | commit; a new push waits again. Reviews imported from the origin do | |
| 563 | not count. | |
| 564 | </p> | |
| 565 | ${btn("Approve to run here", { icon: "check" })} | |
| 566 | </form>` | |
| 567 | : html``; | |
| 544 | 568 | const options: { value: string; label: string; hint: string; key: string }[] = |
| 545 | 569 | []; |
| 546 | 570 | // A reader's change runs nothing here until a writer approves it: the |
| @@ -618,7 +642,7 @@ function reviewCard(ctx: Ctx, repo: Repo, pull: Pull, action: string): Html { | ||
| 618 | 642 | <span class="spacer"></span> |
| 619 | 643 | ${btn("Submit review", { variant: "primary", icon: "check" })} |
| 620 | 644 | </div> |
| 621 | </form>`, | |
| 645 | </form>${approveRunForm}`, | |
| 622 | 646 | { |
| 623 | 647 | extra: "mt review-card", |
| 624 | 648 | head: html`${icon("eye")} |
| @@ -760,7 +784,7 @@ export async function pullFilesPage(ctx: Ctx): Promise<Response> { | ||
| 760 | 784 | ${holdCard(ctx, repo, pull, { act: false })} |
| 761 | 785 | ${mergeBox(ctx, repo, pull, status, mayMerge, by, check, isApp)} |
| 762 | 786 | <div class="split"> |
| 763 | <div>${reviewCard(ctx, repo, pull, `${thread}/review-state`)}</div> | |
| 787 | <div>${reviewCard(ctx, repo, pull, `${thread}/review-state`, status.headOid)}</div> | |
| 764 | 788 | <aside> |
| 765 | 789 | ${assigneeCard(ctx, repo, pull, `${thread}/assignee`)} |
| 766 | 790 | ${labelsCard(ctx, repo, pull, applied, allLabels, `${thread}/labels`)} |
| @@ -970,6 +994,41 @@ export async function pullReviewStateSubmit(ctx: Ctx): Promise<Response> { | ||
| 970 | 994 | }); |
| 971 | 995 | } |
| 972 | 996 | |
| 997 | /** POST /:owner/:name/pulls/:number/approve-run — let this exact head run here. */ | |
| 998 | export async function pullApproveRunSubmit(ctx: Ctx): Promise<Response> { | |
| 999 | const found = pullContext(ctx); | |
| 1000 | if (found instanceof Response) return found; | |
| 1001 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 1002 | const form = await readForm(ctx, "rw"); | |
| 1003 | if (form instanceof Response) return form; | |
| 1004 | const dest = `${repoBase(found.repo)}/pulls/${found.pull.number}`; | |
| 1005 | const head = field(form, "head"); | |
| 1006 | const approved = await approveRun( | |
| 1007 | ctx.app, | |
| 1008 | ctx.auth.user, | |
| 1009 | found.repo, | |
| 1010 | found.pull, | |
| 1011 | /^[0-9a-f]{40,64}$/.test(head) ? head : undefined, | |
| 1012 | ); | |
| 1013 | if (!approved.ok) | |
| 1014 | return flashTo(ctx, dest, { | |
| 1015 | tone: "danger", | |
| 1016 | message: | |
| 1017 | approved.error === "forbidden" || approved.error === "unauthorized" | |
| 1018 | ? "Only a person with write access can approve code to run here." | |
| 1019 | : approved.error === "stale_head" | |
| 1020 | ? "The pull has a new head since you looked. Read it, then approve again." | |
| 1021 | : approved.error === "not_mirrored" | |
| 1022 | ? "Only a mirrored pull needs this approval." | |
| 1023 | : approved.error === "closed" | |
| 1024 | ? "That pull request is closed." | |
| 1025 | : "That pull request is no longer here.", | |
| 1026 | }); | |
| 1027 | return flashTo(ctx, dest, { | |
| 1028 | message: "Approved to run here. Its check and preview start now.", | |
| 1029 | }); | |
| 1030 | } | |
| 1031 | ||
| 973 | 1032 | /** POST …/pulls/:number/threads/:anchor/{resolve,unresolve}. */ |
| 974 | 1033 | export function threadResolveSubmit( |
| 975 | 1034 | resolved: boolean, |
test/mirrored-pull-approval.test.ts added +277
| @@ -0,0 +1,277 @@ | ||
| 1 | /** | |
| 2 | * A mirrored pull whose head lives in a fork on the origin is someone else's | |
| 3 | * code. Imported reviews never let it run; a local approval of its exact head | |
| 4 | * by a person who can write here does (#789). | |
| 5 | */ | |
| 6 | ||
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { newApp } from "../src/actions/apps.ts"; | |
| 12 | import { addToCrew, createAgent } from "../src/actions/crew.ts"; | |
| 13 | import { approveRun, openPull } from "../src/actions/pulls.ts"; | |
| 14 | import { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts"; | |
| 15 | import { createApp, type App } from "../src/app.ts"; | |
| 16 | import { AppsRuntime } from "../src/apps/runtime.ts"; | |
| 17 | import { startChecks, type ChecksHandle } from "../src/checks/service.ts"; | |
| 18 | import type { AppRecord } from "../src/core/apps.ts"; | |
| 19 | import type { Pull } from "../src/core/pulls.ts"; | |
| 20 | import type { Repo } from "../src/core/repos.ts"; | |
| 21 | import { submitReview as recordReview } from "../src/core/reviews.ts"; | |
| 22 | import { pullMayRun } from "../src/core/pull_trust.ts"; | |
| 23 | import { createToken } from "../src/core/tokens.ts"; | |
| 24 | import { listRuns } from "../src/core/runs.ts"; | |
| 25 | import { createUser, type User } from "../src/core/users.ts"; | |
| 26 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 27 | import { quietLogs } from "./helpers/globals.ts"; | |
| 28 | ||
| 29 | quietLogs(); | |
| 30 | ||
| 31 | const checkJson = (run: string) => | |
| 32 | `{"check": {"run": ${JSON.stringify(run)}, "install": ""}}\n`; | |
| 33 | ||
| 34 | describe("a mirrored pull from an origin fork runs only on a local writer approval", () => { | |
| 35 | let dataDir: string; | |
| 36 | let app: App; | |
| 37 | let servers: Servers; | |
| 38 | let checks: ChecksHandle; | |
| 39 | let runtime: AppsRuntime; | |
| 40 | let alice: User; | |
| 41 | let carol: User; | |
| 42 | let bot: User; | |
| 43 | let lib: Repo; | |
| 44 | let notes: Repo; | |
| 45 | let notesApp: AppRecord; | |
| 46 | ||
| 47 | const runsFor = ( | |
| 48 | repo: Repo, | |
| 49 | kind: "check" | "deploy", | |
| 50 | pull: Pull, | |
| 51 | commit?: string, | |
| 52 | ) => | |
| 53 | listRuns(app.db, repo.id, { kind, limit: 100 }).filter( | |
| 54 | (r) => | |
| 55 | r.env === `pull-${pull.number}` && | |
| 56 | (commit === undefined || r.commitOid === commit), | |
| 57 | ); | |
| 58 | ||
| 59 | const forks = new Map<string, Repo>(); | |
| 60 | ||
| 61 | /** Long enough for the event handlers to have queued whatever they would. */ | |
| 62 | const settle = () => Bun.sleep(400); | |
| 63 | ||
| 64 | async function forkPull( | |
| 65 | who: User, | |
| 66 | repo: Repo, | |
| 67 | branch: string, | |
| 68 | ): Promise<{ pull: Pull; fork: Repo; head: string }> { | |
| 69 | // One fork per person and repository; each test takes its own branch. | |
| 70 | const key = `${who.id}:${repo.id}`; | |
| 71 | let fork = forks.get(key); | |
| 72 | if (fork === undefined) { | |
| 73 | const forked = await forkRepo(app, who, repo, `${repo.name}-fork`); | |
| 74 | if (!forked.ok) throw new Error(String(forked.error)); | |
| 75 | fork = forked.value; | |
| 76 | forks.set(key, fork); | |
| 77 | } | |
| 78 | const committed = await commitToBranch(app, who, fork, { | |
| 79 | branch, | |
| 80 | message: "From the fork", | |
| 81 | files: [{ path: `${branch}.md`, content: "hi\n" }], | |
| 82 | }); | |
| 83 | if (!committed.ok) throw new Error(JSON.stringify(committed.error)); | |
| 84 | const opened = await openPull(app, who, repo, { | |
| 85 | title: `From ${who.username}`, | |
| 86 | baseBranch: "main", | |
| 87 | headBranch: branch, | |
| 88 | headRepo: fork, | |
| 89 | }); | |
| 90 | if (!opened.ok) throw new Error(String(opened.error)); | |
| 91 | expect(opened.value.crossRepo).toBe(true); | |
| 92 | return { pull: opened.value, fork, head: committed.value.commitOid }; | |
| 93 | } | |
| 94 | ||
| 95 | beforeAll(async () => { | |
| 96 | dataDir = await mkdtemp(join(tmpdir(), "forge-fork-approval-")); | |
| 97 | app = createApp({ dataDir, port: 0, host: "forge.test" }); | |
| 98 | servers = await serve(app); | |
| 99 | checks = startChecks(app, { forgeUrl: servers.url, concurrency: 1 }); | |
| 100 | runtime = new AppsRuntime(app, { | |
| 101 | domain: "apps.test", | |
| 102 | scheme: "http", | |
| 103 | publicPort: servers.port, | |
| 104 | forgeUrl: servers.url, | |
| 105 | concurrency: 1, | |
| 106 | }); | |
| 107 | await runtime.start(); | |
| 108 | const people: User[] = []; | |
| 109 | for (const [username, first] of [ | |
| 110 | ["alice", true], | |
| 111 | ["carol", false], | |
| 112 | ] as const) { | |
| 113 | const made = await createUser(app.db, { | |
| 114 | trusted: true, | |
| 115 | username, | |
| 116 | email: `${username}@forge.local`, | |
| 117 | password: "a-good-passphrase", | |
| 118 | adminIfFirst: first, | |
| 119 | }); | |
| 120 | if (!made.ok) throw new Error(made.error); | |
| 121 | people.push(made.value); | |
| 122 | } | |
| 123 | [alice, carol] = people as [User, User]; | |
| 124 | const agent = await createAgent(app, alice, { username: "bot" }); | |
| 125 | if (!agent.ok) throw new Error(String(agent.error)); | |
| 126 | bot = agent.value.user; | |
| 127 | ||
| 128 | const made = await createRepo(app, alice, { | |
| 129 | name: "lib", | |
| 130 | visibility: "public", | |
| 131 | }); | |
| 132 | if (!made.ok) throw new Error(String(made.error)); | |
| 133 | lib = made.value; | |
| 134 | const declared = await commitToBranch(app, alice, lib, { | |
| 135 | message: "Declare a check", | |
| 136 | files: [{ path: "forge.json", content: checkJson("true") }], | |
| 137 | }); | |
| 138 | if (!declared.ok) throw new Error(JSON.stringify(declared.error)); | |
| 139 | expect(addToCrew(app, alice, lib, "bot").ok).toBe(true); | |
| 140 | ||
| 141 | const madeApp = await newApp(app, alice, { | |
| 142 | name: "notes", | |
| 143 | description: "Notes", | |
| 144 | visibility: "public", | |
| 145 | }); | |
| 146 | if (!madeApp.ok) throw new Error(String(madeApp.error)); | |
| 147 | notes = madeApp.value.repo; | |
| 148 | notesApp = madeApp.value.app; | |
| 149 | }, 120_000); | |
| 150 | ||
| 151 | afterAll(async () => { | |
| 152 | await checks.stop(); | |
| 153 | await runtime.stop(); | |
| 154 | servers.stop(); | |
| 155 | app.close(); | |
| 156 | await rm(dataDir, { recursive: true, force: true }); | |
| 157 | }); | |
| 158 | ||
| 159 | /** The pull as a mirror holds it: its head is at the origin's fork. */ | |
| 160 | const mirrored = (pull: Pull): Pull => { | |
| 161 | app.db.run("UPDATE pull SET origin_head_repo = ?1 WHERE issue_id = ?2", [ | |
| 162 | "octo/lib", | |
| 163 | pull.id, | |
| 164 | ]); | |
| 165 | return { ...pull, originHeadRepo: "octo/lib" }; | |
| 166 | }; | |
| 167 | ||
| 168 | test("runs nothing; an imported review, even a writer's, does not count", async () => { | |
| 169 | const one = await forkPull(carol, lib, "imported"); | |
| 170 | const pull = mirrored(one.pull); | |
| 171 | recordReview(app.db, { | |
| 172 | issueId: pull.id, | |
| 173 | authorId: alice.id, | |
| 174 | state: "approved", | |
| 175 | commitOid: one.head, | |
| 176 | originRemoteId: "r1", | |
| 177 | originAuthor: "octo-maintainer", | |
| 178 | }); | |
| 179 | expect(pullMayRun(app.db, lib, pull, one.head)).toBe(false); | |
| 180 | await settle(); | |
| 181 | expect(runsFor(lib, "check", pull)).toHaveLength(0); | |
| 182 | }); | |
| 183 | ||
| 184 | test("a local writer approval of the head runs the check and the preview", async () => { | |
| 185 | const one = await forkPull(carol, lib, "local"); | |
| 186 | const two = await forkPull(carol, notes, "local"); | |
| 187 | const pulls: [Repo, Pull, string][] = [ | |
| 188 | [lib, mirrored(one.pull), one.head], | |
| 189 | [notes, mirrored(two.pull), two.head], | |
| 190 | ]; | |
| 191 | for (const [repo, pull, head] of pulls) { | |
| 192 | // A reader cannot, and says so; neither can the crew. | |
| 193 | const byCarol = await approveRun(app, carol, repo, pull); | |
| 194 | expect(byCarol.ok).toBe(false); | |
| 195 | const byBot = await approveRun(app, bot, repo, pull); | |
| 196 | expect(byBot.ok).toBe(false); | |
| 197 | expect(pullMayRun(app.db, repo, pull, head)).toBe(false); | |
| 198 | // Approving a head the writer did not see is refused. | |
| 199 | const stale = await approveRun(app, alice, repo, pull, "0".repeat(40)); | |
| 200 | expect(stale.ok ? "" : stale.error).toBe("stale_head"); | |
| 201 | const done = await approveRun(app, alice, repo, pull, head); | |
| 202 | expect(done.ok && done.value.commitOid).toBe(head); | |
| 203 | expect(pullMayRun(app.db, repo, pull, head)).toBe(true); | |
| 204 | } | |
| 205 | await settle(); | |
| 206 | expect(runsFor(lib, "check", pulls[0]![1], one.head).length).toBeGreaterThan( | |
| 207 | 0, | |
| 208 | ); | |
| 209 | expect( | |
| 210 | runsFor(notes, "deploy", pulls[1]![1], two.head).length, | |
| 211 | ).toBeGreaterThan(0); | |
| 212 | }, 60_000); | |
| 213 | ||
| 214 | test("a new head waits again", async () => { | |
| 215 | const { pull: opened, fork, head } = await forkPull(carol, lib, "moves"); | |
| 216 | const pull = mirrored(opened); | |
| 217 | expect((await approveRun(app, alice, lib, pull)).ok).toBe(true); | |
| 218 | expect(pullMayRun(app.db, lib, pull, head)).toBe(true); | |
| 219 | const again = await commitToBranch(app, carol, fork, { | |
| 220 | branch: "moves", | |
| 221 | message: "Again", | |
| 222 | files: [{ path: "moves.md", content: "again\n" }], | |
| 223 | }); | |
| 224 | if (!again.ok) throw new Error(JSON.stringify(again.error)); | |
| 225 | expect(pullMayRun(app.db, lib, pull, again.value.commitOid)).toBe(false); | |
| 226 | await settle(); | |
| 227 | expect(runsFor(lib, "check", pull, again.value.commitOid)).toHaveLength(0); | |
| 228 | }, 60_000); | |
| 229 | ||
| 230 | test("an approval is only for a mirrored pull", async () => { | |
| 231 | const { pull } = await forkPull(carol, lib, "plain"); | |
| 232 | const refused = await approveRun(app, alice, lib, pull); | |
| 233 | expect(refused.ok ? "" : refused.error).toBe("not_mirrored"); | |
| 234 | }); | |
| 235 | ||
| 236 | test("the API and the pull page offer it to a writer", async () => { | |
| 237 | const { pull: opened, head } = await forkPull(carol, lib, "http"); | |
| 238 | const pull = mirrored(opened); | |
| 239 | const signed = await fetch(`${servers.url}/signin`, { | |
| 240 | method: "POST", | |
| 241 | body: new URLSearchParams({ | |
| 242 | username: "alice", | |
| 243 | password: "a-good-passphrase", | |
| 244 | }), | |
| 245 | redirect: "manual", | |
| 246 | }); | |
| 247 | const cookie = `${(signed.headers.get("set-cookie") ?? "").split(";")[0]!}; forge_mode=studio`; | |
| 248 | const page = await fetch( | |
| 249 | `${servers.url}/alice/lib/pulls/${pull.number}/files`, | |
| 250 | { headers: { cookie } }, | |
| 251 | ).then((r) => r.text()); | |
| 252 | expect(page).toContain("Approve to run here"); | |
| 253 | expect(page).toContain(`value="${head}"`); | |
| 254 | ||
| 255 | const route = `${servers.url}/api/v1/repos/alice/lib/pulls/${pull.number}/approve-run`; | |
| 256 | const anonymous = await fetch(route, { method: "POST", body: "{}" }); | |
| 257 | expect(anonymous.status).toBeGreaterThanOrEqual(400); | |
| 258 | expect(pullMayRun(app.db, lib, pull, head)).toBe(false); | |
| 259 | const asReader = await fetch(route, { | |
| 260 | method: "POST", | |
| 261 | headers: { | |
| 262 | authorization: `Bearer ${createToken(app.db, carol.id, "t", "rw").token}`, | |
| 263 | }, | |
| 264 | body: "{}", | |
| 265 | }); | |
| 266 | expect(asReader.status).toBeGreaterThanOrEqual(400); | |
| 267 | const asWriter = await fetch(route, { | |
| 268 | method: "POST", | |
| 269 | headers: { | |
| 270 | authorization: `Bearer ${createToken(app.db, alice.id, "t", "rw").token}`, | |
| 271 | }, | |
| 272 | body: JSON.stringify({ head }), | |
| 273 | }); | |
| 274 | expect(asWriter.status).toBe(201); | |
| 275 | expect(pullMayRun(app.db, lib, pull, head)).toBe(true); | |
| 276 | }); | |
| 277 | }); |
new above
offline