Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions plugins/github-watcher/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ export const dependabotAlertPath = (repo: string, number: number): string => `/r
/** The create-label REST path for one repository. */
export const labelPath = (repo: string): string => `/repos/${repo}/labels`;

/** The create-issue REST path for one repository, and the sub-issue link path under a parent. */
export const issuesPath = (repo: string): string => `/repos/${repo}/issues`;
export const subIssuesPath = (repo: string, parent: number): string => `/repos/${repo}/issues/${parent}/sub_issues`;

/** The issue a REST create answered with: its database id (what a sub-issue link names), number and URL. */
export function parseCreatedIssue(payload: unknown): { id: number; number: number; url: string | null } {
const parsed = z.object({ id: z.number(), number: z.number(), html_url: z.string().nullish() }).parse(payload);
return { id: parsed.id, number: parsed.number, url: parsed.html_url ?? null };
}

/**
* Whether a create-label response is GitHub's "this label already exists"
* (a 422), which an idempotent create reports as `existed` rather than an
Expand Down
62 changes: 61 additions & 1 deletion plugins/github-watcher/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const comment = (body: string, createdAt: string, who = "bob") => ({ author: { l
// A GitHub whose GraphQL endpoint a test scripts: one repository with one
// pull request, whose bb-managed label validates.
function fakeGitHub() {
const state = { node: pullNode() as Record<string, unknown> | null, fail: false, rejectSubIssues: false, valid: (token: string) => token.startsWith("gho_"), openPulls: [] as Array<Record<string, unknown>>, openIssues: [] as Array<Record<string, unknown>>, searchIssues: [] as Array<Record<string, unknown>>, labels: { "acme/widgets": ["bb-managed"] } as Record<string, string[]>, labelCreates: [] as string[], labelCreateStatus: 201, labelCreateMessage: "Validation Failed", dependabotAlerts: [] as unknown[], dependabotPage2: [] as unknown[], dependabotStatus: 200, dependabotMessage: "Forbidden", dependencyGraph: 1 as number | null, dependencyGraphFail: false, deployments: [] as unknown[], deploymentStatuses: {} as Record<number, unknown[]>, files: {} as Record<string, string>, commits: {} as Record<string, string>, workflowRuns: [] as unknown[], workflowRun: null as unknown, jobs: [] as unknown[], compares: {} as Record<string, string>, compareBases: {} as Record<string, { base: string; mergeBase: string }>, defaultBranch: "main" };
const state = { node: pullNode() as Record<string, unknown> | null, fail: false, rejectSubIssues: false, valid: (token: string) => token.startsWith("gho_"), openPulls: [] as Array<Record<string, unknown>>, openIssues: [] as Array<Record<string, unknown>>, searchIssues: [] as Array<Record<string, unknown>>, labels: { "acme/widgets": ["bb-managed"] } as Record<string, string[]>, labelCreates: [] as string[], labelCreateStatus: 201, labelCreateMessage: "Validation Failed", issueCreates: [] as Array<{ repo: string; body: Record<string, unknown> }>, subIssueLinks: [] as Array<{ repo: string; parent: number; body: unknown }>, issueCreateStatus: 201, issueCreateMessage: "Validation Failed", issueCreateNumber: 124, subIssueStatus: 200, subIssueMessage: "Validation Failed", dependabotAlerts: [] as unknown[], dependabotPage2: [] as unknown[], dependabotStatus: 200, dependabotMessage: "Forbidden", dependencyGraph: 1 as number | null, dependencyGraphFail: false, deployments: [] as unknown[], deploymentStatuses: {} as Record<number, unknown[]>, files: {} as Record<string, string>, commits: {} as Record<string, string>, workflowRuns: [] as unknown[], workflowRun: null as unknown, jobs: [] as unknown[], compares: {} as Record<string, string>, compareBases: {} as Record<string, { base: string; mergeBase: string }>, defaultBranch: "main" };
const calls: Array<{ token: string; variables: Record<string, unknown> }> = [];
const fetchImpl = vi.fn(async (url: string | URL, init?: RequestInit) => {
const token = ((init?.headers as Record<string, string>).authorization ?? "").replace(/^Bearer /u, "");
Expand Down Expand Up @@ -93,6 +93,24 @@ function fakeGitHub() {
state.labels[key] = [...(state.labels[key] ?? []), body.name];
return Response.json({ id: 1, name: body.name }, { status: 201 });
}
const subIssues = /\/repos\/([^/]+)\/([^/]+)\/issues\/(\d+)\/sub_issues(?:\?|$)/u.exec(u);
if (subIssues !== null && init?.method === "POST") {
if (!state.valid(token)) return Response.json({ message: "Bad credentials" }, { status: 401 });
const repo = `${subIssues[1]}/${subIssues[2]}`;
const body = JSON.parse(String(init.body)) as { sub_issue_id: number };
state.subIssueLinks.push({ repo, parent: Number(subIssues[3]), body });
if (state.subIssueStatus >= 400) return Response.json({ message: state.subIssueMessage }, { status: state.subIssueStatus });
return Response.json({ id: 999, number: state.issueCreateNumber, sub_issue_id: body.sub_issue_id });
}
const issueCreate = /\/repos\/([^/]+)\/([^/]+)\/issues(?:\?|$)/u.exec(u);
if (issueCreate !== null && init?.method === "POST") {
if (!state.valid(token)) return Response.json({ message: "Bad credentials" }, { status: 401 });
const repo = `${issueCreate[1]}/${issueCreate[2]}`;
const body = JSON.parse(String(init.body)) as Record<string, unknown>;
state.issueCreates.push({ repo, body });
if (state.issueCreateStatus >= 400) return Response.json({ message: state.issueCreateMessage }, { status: state.issueCreateStatus });
return Response.json({ id: 999, number: state.issueCreateNumber, html_url: `https://github.com/${repo}/issues/${state.issueCreateNumber}` }, { status: 201 });
}
const dependabot = /\/repos\/([^/]+)\/([^/]+)\/dependabot\/alerts(?:\?|$)/u.exec(u);
if (dependabot !== null) {
if (!state.valid(token)) return Response.json({ message: "Bad credentials" }, { status: 401 });
Expand Down Expand Up @@ -688,6 +706,48 @@ describe("stewards' source contract", () => {
expect(await w.harness.callRpc("sourceBacklog", { team: "ENG" }, STEWARDS)).toEqual({ issues: [], unsupported: true, truncated: false, errors: [] });
});

it("files a GitHub issue through sourceCreateIssue, refusing an unsigned description, a priority and anyone but the viewer (BB-360)", async () => {
const w = await setup();
const out = await w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "Add retries", description: "Calls fail once in a while.\n\n_— from bb thread thr_x_", labels: ["bb-managed"], assignee: "me" }, STEWARDS);
expect(out).toEqual({ id: "Acme/Widgets#124", key: "Acme/Widgets#124", url: "https://github.com/Acme/Widgets/issues/124" });
expect(w.github.state.issueCreates).toEqual([{ repo: "Acme/Widgets", body: { title: "Add retries", body: "Calls fail once in a while.\n\n_— from bb thread thr_x_", labels: ["bb-managed"], assignees: ["dev"] } }]);

// An unsigned description never reaches GitHub.
await expect(w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "x", description: "No signature" }, STEWARDS)).rejects.toThrow(/signature line/u);
expect(w.github.state.issueCreates).toHaveLength(1);

// GitHub issues have no priority.
await expect(w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "x", description: "Hi\n\n_— from bb thread thr_x_", priority: "high" }, STEWARDS)).rejects.toThrow(/no priority/u);

// Only the viewer's own login (me, @me or the login) may be assigned.
expect(await w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "Mine", description: "Hi\n\n_— from bb thread thr_x_", assignee: "@me" }, STEWARDS)).toMatchObject({ key: "Acme/Widgets#124" });
await expect(w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "x", description: "Hi\n\n_— from bb thread thr_x_", assignee: "someone" }, STEWARDS)).rejects.toThrow(/own login/u);

// A parent is read before the create: it must be a same-repository issue.
w.github.state.node = issueNode();
await w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "Child", description: "Hi\n\n_— from bb thread thr_x_", parent: "Acme/Widgets#7" }, STEWARDS);
expect(w.github.state.subIssueLinks).toEqual([{ repo: "Acme/Widgets", parent: 7, body: { sub_issue_id: 999 } }]);
const before = w.github.state.issueCreates.length;
await expect(w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "Child", description: "Hi\n\n_— from bb thread thr_x_", parent: "Other/Repo#7" }, STEWARDS)).rejects.toThrow(/same repository/u);
await expect(w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "Child", description: "Hi\n\n_— from bb thread thr_x_", parent: "nonsense" }, STEWARDS)).rejects.toThrow(/not a GitHub issue key/u);
w.github.state.node = pullNode({ number: 12 });
await expect(w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "Child", description: "Hi\n\n_— from bb thread thr_x_", parent: "Acme/Widgets#12" }, STEWARDS)).rejects.toThrow(/pull request/u);
w.github.state.node = null;
await expect(w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "Child", description: "Hi\n\n_— from bb thread thr_x_", parent: "Acme/Widgets#7" }, STEWARDS)).rejects.toThrow(/does not exist/u);
expect(w.github.state.issueCreates).toHaveLength(before);

// A unit that is not owner/repo is an error, not a silent create.
await expect(w.harness.callRpc("sourceCreateIssue", { unit: "widgets", title: "x", description: "Hi\n\n_— from bb thread thr_x_" }, STEWARDS)).rejects.toThrow(/not owner\/repo/u);
});

it("names the filed issue when a sub-issue link fails after the create (BB-360)", async () => {
const w = await setup();
w.github.state.node = issueNode();
w.github.state.subIssueStatus = 500;
await expect(w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "Child", description: "Hi\n\n_— from bb thread thr_x_", parent: "Acme/Widgets#7" }, STEWARDS)).rejects.toThrow(/filed Acme\/Widgets#124 .*could not link it under Acme\/Widgets#7/u);
expect(w.github.state.issueCreates).toHaveLength(1);
});

it("reads a repository's Dependabot alerts, naming a repository or a repo the token cannot read rather than failing", async () => {
const w = await setup();
w.github.state.dependabotAlerts = [
Expand Down
67 changes: 66 additions & 1 deletion plugins/github-watcher/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,12 @@ import {
deploymentStatusesPath,
deploymentsPath,
graphql,
issuesPath,
kindName,
labelAlreadyExists,
labelPath,
parseCompare,
parseCreatedIssue,
parseDefaultBranch,
parseDependabotAlerts,
parseDependencyGraphCount,
Expand All @@ -64,13 +66,14 @@ import {
parseWorkflowJobs,
parseWorkflowRuns,
refKey,
subIssuesPath,
workflowRunJobsPath,
workflowRunPath,
workflowRunsPath,
type Target,
} from "./github.js";
import { createHooksLoop, HOOKS_URL_ENV, type Lease, type Rejection } from "./hooks-client.js";
import { deploymentSchema, ringStewards, sourceContract, STEWARDS_PLUGIN_ID, workflowRunSchema, type AdoptableEntity, type Deployment, type EntitySnapshot, type SearchIssue, type WorkflowRun } from "./source-contract.js";
import { deploymentSchema, ringStewards, signedBy, sourceContract, STEWARDS_PLUGIN_ID, workflowRunSchema, type AdoptableEntity, type Deployment, type EntitySnapshot, type SearchIssue, type WorkflowRun } from "./source-contract.js";
import { buildUsage, createRefusals, formatUsage, usageViewSchema, type InterestView } from "./usage.js";
import { compare, createCheckQueue, createWatchStore, initialCursors, snapshotOf, WATCH_MIGRATIONS, type WatchRow } from "./watch.js";

Expand Down Expand Up @@ -248,6 +251,28 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>
});
}

/**
* One REST write with the token, for the issue create and its sub-issue
* link. A non-2xx answer throws with its status, like `restPage`; the
* token is re-read from gh on a 401 by `asDeveloper`.
*/
async function restWrite(path: string, body: unknown, signal: AbortSignal): Promise<unknown> {
return asDeveloper(async (token) => {
const response = await deps.fetch(new URL(path, apiUrl), {
method: "POST",
headers: { accept: "application/vnd.github+json", authorization: `Bearer ${token}`, "user-agent": "bb-plugin-github", "x-github-api-version": "2022-11-28", "content-type": "application/json" },
body: JSON.stringify(body),
signal,
});
const payload: unknown = await response.json().catch(() => null);
if (!response.ok) {
const message = payload !== null && typeof payload === "object" && typeof (payload as { message?: unknown }).message === "string" ? (payload as { message: string }).message : "";
throw new GitHubRequestError(`GitHub answered HTTP ${response.status}${message === "" ? "" : `: ${message}`}`, response.status);
}
return payload;
});
}

/**
* Create one label in one repository. A 422 `already_exists` is the label
* already being there, which an idempotent create reports as `existed`;
Expand Down Expand Up @@ -784,6 +809,46 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>
throw new Error("sourceComment is a Linear write; the github source does not serve it");
},

// BB-360: file an issue for the source-neutral ticket tools. The caller
// has already signed the description with the contract's signature line;
// an unsigned one is refused here. GitHub issues have no priority, so a
// priority is refused; a sub-issue's parent must be a same-repository
// issue; and the assignee is this server's own login (me, @me or the
// viewer) or none, never anyone else.
async sourceCreateIssue({ unit, title, description, labels, priority, parent, assignee }) {
if (signedBy(description) === null) throw new Error("an issue description must end with the bb thread signature line; nothing was filed");
if (priority !== undefined) throw new Error("sourceCreateIssue has no priority on the github source; GitHub issues have no priority");
const repo = parseRepo(unit);
if (repo === null) throw new Error(`${unit}: not owner/repo`);
const name = `${repo.owner}/${repo.name}`;
const viewer = parseViewer(await query(VIEWER_QUERY, {}, checkSignal()));
const who = assignee?.trim() ?? "";
const self = who === "" || who.toLowerCase() === "me" || who.toLowerCase() === "@me" || who.toLowerCase() === `@${viewer.toLowerCase()}` || who.toLowerCase() === viewer.toLowerCase();
if (!self) throw new Error(`sourceCreateIssue assigns only to this server's own login (${viewer}), not ${JSON.stringify(who)}`);
// Resolve the parent before any write, so a missing or non-issue
// parent changes nothing; a sub-issue is linked within one repository.
const parentRef = parent === undefined ? null : parseRef(parent);
if (parent !== undefined && parentRef === null) throw new Error(`parent ${JSON.stringify(parent)} is not a GitHub issue key like owner/repo#12`);
if (parentRef !== null && parentRef.repo.toLowerCase() !== name.toLowerCase()) throw new Error(`a GitHub sub-issue's parent must be in the same repository; ${parent} is not in ${name}`);
if (parentRef !== null) {
const target = await readTarget(parentRef, checkSignal());
if (target === null) throw new Error(`parent ${parent} does not exist, or it is not visible to the signed-in GitHub user`);
if (target.kind !== "issue") throw new Error(`parent ${parent} is a pull request, not an issue; a sub-issue must be an issue`);
}
const body: Record<string, unknown> = { title: title.trim(), body: description };
if (labels.length > 0) body.labels = labels;
if (who !== "") body.assignees = [viewer];
const created = parseCreatedIssue(await restWrite(issuesPath(name), body, checkSignal()));
if (parentRef !== null) {
try {
await restWrite(subIssuesPath(name, parentRef.number), { sub_issue_id: created.id }, checkSignal());
} catch (error) {
throw new Error(`filed ${name}#${created.number}${created.url === null ? "" : ` (${created.url})`}, but could not link it under ${parent}: ${errorMessage(error)}`);
}
}
return { id: `${name}#${created.number}`, key: `${name}#${created.number}`, url: created.url };
},

// A repository's Dependabot alerts, read with the token through the
// REST API. Each repository the token cannot read (no alert access,
// alerts disabled, not visible) is named in `errors`; the rest are
Expand Down
24 changes: 24 additions & 0 deletions plugins/github-watcher/source-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,30 @@ export const sourceContract = {
input: z.object({ key: z.string().min(1).max(200), body: z.string().min(1).max(20_000) }),
output: z.object({ ok: z.boolean(), url: z.string().nullable() }),
},
/**
* File a new issue in a unit: a Linear team key, or a GitHub owner/repo.
* The caller hands in a `description` that already carries the bb thread
* signature line (`signatureLine`), exactly as `sourceComment`'s body does;
* the source refuses an unsigned description, so a bug in the caller cannot
* file an unsigned issue. `priority` is a source capability (Linear's
* priority; a source with none refuses it), `parent` is the parent issue's
* key, and `assignee` names only this server's own login, or none: `me`
* always means the source's own login, and any other person is refused,
* because no steward assigns work to someone else. Additive and optional: a
* source that does not serve it is unavailable to the caller.
*/
sourceCreateIssue: {
input: z.object({
unit: z.string().min(1).max(200),
title: z.string().min(1).max(500),
description: z.string().min(1).max(50_000),
labels: z.array(z.string().min(1).max(100)).max(50).default([]),
priority: z.enum(["none", "urgent", "high", "medium", "low"]).optional(),
parent: z.string().min(1).max(200).optional(),
assignee: z.string().min(1).max(200).optional(),
}),
output: z.object({ id: z.string(), key: z.string(), url: z.string().nullable() }),
},
/**
* A team's whole open backlog, read-only: every open issue, unlabelled and
* unassigned included. One team per call -- there is no all-teams mode --
Expand Down
Loading
Loading