Repository navigation
Add the issue dependencies API (blocked_by / blocking) #12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: chore/sync-upstream-20261116
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,184 @@ | ||
| import { beforeEach, describe, expect, it } from "vitest"; | ||
| import { | ||
| Hono, | ||
| Store, | ||
| WebhookDispatcher, | ||
| authMiddleware, | ||
| createApiErrorHandler, | ||
| createErrorHandler, | ||
| type TokenMap, | ||
| } from "@emulators/core"; | ||
| import { githubPlugin, seedFromConfig } from "../index.js"; | ||
| import { getGitHubStore } from "../store.js"; | ||
| import { MAX_ISSUE_DEPENDENCIES } from "../routes/issue-dependencies.js"; | ||
|
|
||
| const base = "http://localhost:4000"; | ||
|
|
||
| type Issue = { | ||
| id: number; | ||
| number: number; | ||
| issue_dependencies_summary: { | ||
| blocked_by: number; | ||
| blocking: number; | ||
| total_blocked_by: number; | ||
| total_blocking: number; | ||
| }; | ||
| }; | ||
|
|
||
| function createTestApp() { | ||
| const store = new Store(); | ||
| const tokenMap: TokenMap = new Map([ | ||
| ["octocat-token", { login: "octocat", id: 1, scopes: ["repo", "user"] }], | ||
| ["hubot-token", { login: "hubot", id: 2, scopes: ["repo", "user"] }], | ||
| ]); | ||
| const app = new Hono(); | ||
| app.onError(createApiErrorHandler()); | ||
| app.use("*", createErrorHandler()); | ||
| app.use("*", authMiddleware(tokenMap)); | ||
| githubPlugin.register(app as any, store, new WebhookDispatcher(), base, tokenMap); | ||
| githubPlugin.seed?.(store, base); | ||
| seedFromConfig(store, base, { | ||
| users: [{ login: "octocat" }, { login: "hubot" }], | ||
| repos: [ | ||
| { owner: "octocat", name: "alpha" }, | ||
| { owner: "octocat", name: "beta" }, | ||
| { owner: "hubot", name: "secret", private: true }, | ||
| ], | ||
| }); | ||
| return { app, store }; | ||
| } | ||
|
|
||
| describe("GitHub issue dependencies", () => { | ||
| let app: Hono; | ||
| let store: Store; | ||
|
|
||
| const call = (path: string, init: { method?: string; token?: string | null; body?: unknown } = {}) => { | ||
| const headers: Record<string, string> = {}; | ||
| const token = init.token === undefined ? "octocat-token" : init.token; | ||
| if (token) headers.Authorization = `Bearer ${token}`; | ||
| if (init.body !== undefined) headers["Content-Type"] = "application/json"; | ||
| return app.request(`${base}${path}`, { | ||
| method: init.method ?? "GET", | ||
| headers, | ||
| body: init.body === undefined ? undefined : JSON.stringify(init.body), | ||
| }); | ||
| }; | ||
|
|
||
| const createIssue = async (repo: string, token = "octocat-token"): Promise<Issue> => { | ||
| const res = await call(`/repos/${repo}/issues`, { method: "POST", token, body: { title: `Issue in ${repo}` } }); | ||
| expect(res.status).toBe(201); | ||
| return (await res.json()) as Issue; | ||
| }; | ||
|
|
||
| const addBlocker = (repo: string, number: number, issueId: unknown, token?: string | null) => | ||
| call(`/repos/${repo}/issues/${number}/dependencies/blocked_by`, { | ||
| method: "POST", | ||
| token, | ||
| body: { issue_id: issueId }, | ||
| }); | ||
|
|
||
| beforeEach(() => { | ||
| ({ app, store } = createTestApp()); | ||
| }); | ||
|
|
||
| it("adds, lists in both directions and removes an edge across repositories", async () => { | ||
| const blocked = await createIssue("octocat/alpha"); | ||
| const blocker = await createIssue("octocat/beta"); | ||
|
|
||
| const added = await addBlocker("octocat/alpha", blocked.number, blocker.id); | ||
| expect(added.status).toBe(201); | ||
| expect(((await added.json()) as Issue).id).toBe(blocker.id); | ||
|
|
||
| const blockedBy = (await ( | ||
| await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by`) | ||
| ).json()) as Issue[]; | ||
| expect(blockedBy.map((issue) => issue.id)).toEqual([blocker.id]); | ||
| const blocking = (await ( | ||
| await call(`/repos/octocat/beta/issues/${blocker.number}/dependencies/blocking`) | ||
| ).json()) as Issue[]; | ||
| expect(blocking.map((issue) => issue.id)).toEqual([blocked.id]); | ||
|
|
||
| const summary = ((await (await call(`/repos/octocat/alpha/issues/${blocked.number}`)).json()) as Issue) | ||
| .issue_dependencies_summary; | ||
| expect(summary).toEqual({ blocked_by: 1, blocking: 0, total_blocked_by: 1, total_blocking: 0 }); | ||
|
|
||
| const removed = await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by/${blocker.id}`, { | ||
| method: "DELETE", | ||
| }); | ||
| expect(removed.status).toBe(200); | ||
| expect(((await removed.json()) as Issue).id).toBe(blocker.id); | ||
| expect(await (await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by`)).json()).toEqual( | ||
| [], | ||
| ); | ||
| const again = await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by/${blocker.id}`, { | ||
| method: "DELETE", | ||
| }); | ||
| expect(again.status).toBe(404); | ||
| }); | ||
|
|
||
| it("counts only open issues in blocked_by and blocking, and all in the totals", async () => { | ||
| const blocked = await createIssue("octocat/alpha"); | ||
| const open = await createIssue("octocat/alpha"); | ||
| const closed = await createIssue("octocat/alpha"); | ||
| await addBlocker("octocat/alpha", blocked.number, open.id); | ||
| await addBlocker("octocat/alpha", blocked.number, closed.id); | ||
| await call(`/repos/octocat/alpha/issues/${closed.number}`, { method: "PATCH", body: { state: "closed" } }); | ||
|
|
||
| const summary = ((await (await call(`/repos/octocat/alpha/issues/${blocked.number}`)).json()) as Issue) | ||
| .issue_dependencies_summary; | ||
| expect(summary).toEqual({ blocked_by: 1, blocking: 0, total_blocked_by: 2, total_blocking: 0 }); | ||
| }); | ||
|
|
||
| it("rejects a self-reference, a duplicate edge and a malformed id with 422", async () => { | ||
| const blocked = await createIssue("octocat/alpha"); | ||
| const blocker = await createIssue("octocat/alpha"); | ||
| expect((await addBlocker("octocat/alpha", blocked.number, blocked.id)).status).toBe(422); | ||
| expect((await addBlocker("octocat/alpha", blocked.number, blocker.id)).status).toBe(201); | ||
| expect((await addBlocker("octocat/alpha", blocked.number, blocker.id)).status).toBe(422); | ||
| expect((await addBlocker("octocat/alpha", blocked.number, "not-a-number")).status).toBe(422); | ||
| }); | ||
|
|
||
| it("returns 404 for an unknown issue, an unknown issue id and an issue the caller cannot see", async () => { | ||
| const blocked = await createIssue("octocat/alpha"); | ||
| const hidden = await createIssue("hubot/secret", "hubot-token"); | ||
| expect((await call("/repos/octocat/alpha/issues/999/dependencies/blocked_by")).status).toBe(404); | ||
| expect((await addBlocker("octocat/alpha", blocked.number, 999_999)).status).toBe(404); | ||
| expect((await addBlocker("octocat/alpha", blocked.number, hidden.id)).status).toBe(404); | ||
| expect((await call(`/repos/hubot/secret/issues/${hidden.number}/dependencies/blocking`)).status).toBe(404); | ||
| }); | ||
|
|
||
| it("omits related issues the caller cannot see from lists", async () => { | ||
| const blocked = await createIssue("octocat/alpha"); | ||
| const hidden = await createIssue("hubot/secret", "hubot-token"); | ||
| getGitHubStore(store).issueDependencies.insert({ blocked_issue_id: blocked.id, blocking_issue_id: hidden.id }); | ||
|
|
||
| const asOctocat = await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by`); | ||
| expect(await asOctocat.json()).toEqual([]); | ||
| const asHubot = await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by`, { | ||
| token: "hubot-token", | ||
| }); | ||
| expect(((await asHubot.json()) as Issue[]).map((issue) => issue.id)).toEqual([hidden.id]); | ||
| }); | ||
|
|
||
| it("requires authentication to add an edge", async () => { | ||
| const blocked = await createIssue("octocat/alpha"); | ||
| const blocker = await createIssue("octocat/alpha"); | ||
| expect((await addBlocker("octocat/alpha", blocked.number, blocker.id, null)).status).toBe(401); | ||
| }); | ||
|
|
||
| it("paginates and caps each issue at the GitHub relationship limit", async () => { | ||
| const blocked = await createIssue("octocat/alpha"); | ||
| const blockers: Issue[] = []; | ||
| for (let i = 0; i <= MAX_ISSUE_DEPENDENCIES; i++) blockers.push(await createIssue("octocat/beta")); | ||
| for (const blocker of blockers.slice(0, MAX_ISSUE_DEPENDENCIES)) { | ||
| expect((await addBlocker("octocat/alpha", blocked.number, blocker.id)).status).toBe(201); | ||
| } | ||
| expect((await addBlocker("octocat/alpha", blocked.number, blockers[MAX_ISSUE_DEPENDENCIES]!.id)).status).toBe(422); | ||
|
|
||
| const page = await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by?per_page=20&page=3`); | ||
| expect(((await page.json()) as Issue[]).length).toBe(10); | ||
| expect(page.headers.get("Link")).toContain('rel="first"'); | ||
| const all = await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by?per_page=100`); | ||
| expect(((await all.json()) as Issue[]).length).toBe(MAX_ISSUE_DEPENDENCIES); | ||
| }); | ||
| }); |
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,102 @@ | ||||||
| import type { Context, RouteContext } from "@emulators/core"; | ||||||
| import { ApiError, parseJsonBody, parsePagination, setLinkHeader } from "@emulators/core"; | ||||||
| import type { AuthUser } from "@emulators/core"; | ||||||
| import { getGitHubStore } from "../store.js"; | ||||||
| import type { GitHubStore } from "../store.js"; | ||||||
| import type { GitHubIssue, GitHubRepo } from "../entities.js"; | ||||||
| import { assertIssueWrite, assertRepoPermission, notFoundResponse } from "../route-helpers.js"; | ||||||
| import { formatIssue, lookupRepo } from "../helpers.js"; | ||||||
|
|
||||||
| /** GitHub limits each issue to 50 relationships of each kind. */ | ||||||
| export const MAX_ISSUE_DEPENDENCIES = 50; | ||||||
|
|
||||||
| type Direction = "blocked_by" | "blocking"; | ||||||
|
|
||||||
| function canRead(gh: GitHubStore, authUser: AuthUser | undefined, repo: GitHubRepo): boolean { | ||||||
| try { | ||||||
| assertRepoPermission(gh, authUser, repo, "issues"); | ||||||
| return repo.has_issues; | ||||||
| } catch { | ||||||
| return false; | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| /** The issue in the path, visible to the caller, or 404 as on GitHub. */ | ||||||
| function pathIssue(gh: GitHubStore, c: Context, required: "read" | "write"): { repo: GitHubRepo; issue: GitHubIssue } { | ||||||
| const repo = lookupRepo(gh, c.req.param("owner")!, c.req.param("repo")!); | ||||||
| if (!repo) throw notFoundResponse(); | ||||||
| if (required === "write") assertIssueWrite(gh, c.get("authUser"), repo); | ||||||
| else assertRepoPermission(gh, c.get("authUser"), repo, "issues"); | ||||||
| if (!repo.has_issues) throw notFoundResponse(); | ||||||
| const issueNumber = Number(c.req.param("issue_number")); | ||||||
| if (!Number.isInteger(issueNumber)) throw notFoundResponse(); | ||||||
| const issue = gh.issues.findBy("repo_id", repo.id).find((i) => i.number === issueNumber && !i.is_pull_request); | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 pathIssue re-implements issues.ts findIssueForRepo.
Suggested change
🤖 Fix with your agentWhy this matterspathIssue inlines const issueNumber = Number(c.req.param("issue_number"));
if (!Number.isInteger(issueNumber)) throw notFoundResponse();
const issue = gh.issues.findBy("repo_id", repo.id).find((i) => i.number === issueNumber && !i.is_pull_request);
if (!issue) throw notFoundResponse();
return { repo, issue };
} |
||||||
| if (!issue) throw notFoundResponse(); | ||||||
| return { repo, issue }; | ||||||
| } | ||||||
|
|
||||||
| /** The other end of an edge, addressed by its issue id; it may live in another repository. */ | ||||||
| function issueById(gh: GitHubStore, authUser: AuthUser | undefined, raw: unknown): GitHubIssue { | ||||||
| const id = typeof raw === "string" && /^\d+$/.test(raw) ? Number(raw) : raw; | ||||||
| if (typeof id !== "number" || !Number.isInteger(id)) throw new ApiError(422, "Validation failed"); | ||||||
| const issue = gh.issues.get(id); | ||||||
| const repo = issue ? gh.repos.get(issue.repo_id) : undefined; | ||||||
| if (!issue || issue.is_pull_request || !repo || !canRead(gh, authUser, repo)) throw notFoundResponse(); | ||||||
| return issue; | ||||||
| } | ||||||
|
|
||||||
| function related(gh: GitHubStore, issue: GitHubIssue, direction: Direction): GitHubIssue[] { | ||||||
| const edges = | ||||||
| direction === "blocked_by" | ||||||
| ? gh.issueDependencies.findBy("blocked_issue_id", issue.id).map((edge) => edge.blocking_issue_id) | ||||||
| : gh.issueDependencies.findBy("blocking_issue_id", issue.id).map((edge) => edge.blocked_issue_id); | ||||||
| return edges.map((id) => gh.issues.get(id)).filter((other): other is GitHubIssue => !!other); | ||||||
| } | ||||||
|
|
||||||
| export function issueDependenciesRoutes({ app, store, baseUrl }: RouteContext): void { | ||||||
| const gh = getGitHubStore(store); | ||||||
|
|
||||||
| const list = (direction: Direction) => (c: Context) => { | ||||||
| const { issue } = pathIssue(gh, c, "read"); | ||||||
| const authUser = c.get("authUser"); | ||||||
| const visible = related(gh, issue, direction).filter((other) => { | ||||||
| const repo = gh.repos.get(other.repo_id); | ||||||
| return !!repo && canRead(gh, authUser, repo); | ||||||
| }); | ||||||
| const { page, per_page } = parsePagination(c); | ||||||
| setLinkHeader(c, visible.length, page, per_page); | ||||||
| const start = (page - 1) * per_page; | ||||||
| return c.json(visible.slice(start, start + per_page).map((other) => formatIssue(other, gh, baseUrl))); | ||||||
| }; | ||||||
|
|
||||||
| app.get("/repos/:owner/:repo/issues/:issue_number/dependencies/blocked_by", list("blocked_by")); | ||||||
| app.get("/repos/:owner/:repo/issues/:issue_number/dependencies/blocking", list("blocking")); | ||||||
|
|
||||||
| app.post("/repos/:owner/:repo/issues/:issue_number/dependencies/blocked_by", async (c) => { | ||||||
| const { issue } = pathIssue(gh, c, "write"); | ||||||
| const body = (await parseJsonBody(c)) as { issue_id?: unknown }; | ||||||
| const blocking = issueById(gh, c.get("authUser"), body.issue_id); | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Read-only far end lets writers publish private issue links.
Suggested change
🤖 Fix with your agentWhy this mattersPOST requires write only on the path repo and merely READ on the blocking issue's repo, so anyone with write on a public repo can attach an issue from a private repo they can only read as a blocker of a publicly readable issue. Combined with the unfiltered issue_dependencies_summary (flagged separately), this makes the writer the injection vector that publishes the existence and count of private-repo issues to every reader of the public repo. Even once the summary is caller-filtered, the linkage itself deserves a deliberate decision: either filter the summary per caller (preferred) or require stronger permission on the far-end repo for cross-repo edges. app.post("/repos/:owner/:repo/issues/:issue_number/dependencies/blocked_by", async (c) => {
const { issue } = pathIssue(gh, c, "write");
const body = (await parseJsonBody(c)) as { issue_id?: unknown };
const blocking = issueById(gh, c.get("authUser"), body.issue_id);
if (blocking.id === issue.id) throw new ApiError(422, "Validation failed"); |
||||||
| if (blocking.id === issue.id) throw new ApiError(422, "Validation failed"); | ||||||
| const existing = gh.issueDependencies.findBy("blocked_issue_id", issue.id); | ||||||
| if (existing.some((edge) => edge.blocking_issue_id === blocking.id)) throw new ApiError(422, "Validation failed"); | ||||||
| if ( | ||||||
| existing.length >= MAX_ISSUE_DEPENDENCIES || | ||||||
| gh.issueDependencies.findBy("blocking_issue_id", blocking.id).length >= MAX_ISSUE_DEPENDENCIES | ||||||
| ) { | ||||||
| throw new ApiError(422, "Validation failed"); | ||||||
| } | ||||||
| gh.issueDependencies.insert({ blocked_issue_id: issue.id, blocking_issue_id: blocking.id }); | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Dependency mutations emit no webhooks or timeline events.
Suggested change
🤖 Fix with your agentWhy this mattersEvery other mutating issue route in routes/issues.ts records an issue event (insertIssueEvent) and dispatches an if (
existing.length >= MAX_ISSUE_DEPENDENCIES ||
gh.issueDependencies.findBy("blocking_issue_id", blocking.id).length >= MAX_ISSUE_DEPENDENCIES
) {
throw new ApiError(422, "Validation failed");
}
gh.issueDependencies.insert({ blocked_issue_id: issue.id, blocking_issue_id: blocking.id });
return c.json(formatIssue(blocking, gh, baseUrl), 201);
}); |
||||||
| return c.json(formatIssue(blocking, gh, baseUrl), 201); | ||||||
| }); | ||||||
|
|
||||||
| app.delete("/repos/:owner/:repo/issues/:issue_number/dependencies/blocked_by/:issue_id", (c) => { | ||||||
| const { issue } = pathIssue(gh, c, "write"); | ||||||
| const blocking = issueById(gh, c.get("authUser"), c.req.param("issue_id")); | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 DELETE 404s when far-end issue becomes unreadable.
Suggested change
🤖 Fix with your agentWhy this mattersDELETE resolves the far end via issueById, which returns 404 unless the caller can currently READ the blocking issue's repo. If that repo later becomes private or the caller's read access is revoked, a user with write access on the path repo can no longer remove an existing edge — the dependency becomes undeletable through the API even though removal should only require write on the blocked issue. POST only needed read at creation time, so the two endpoints are inconsistent about the far end. Repro: Given octocat can read hubot/secret and write octocat/alpha, and creates edge alpha#1 blocked_by secret#2 via POST; When hubot revokes octocat's read on hubot/secret; Then DELETE /repos/octocat/alpha/issues/1/dependencies/blocked_by/2 returns 404 instead of removing the edge, and the stale dependency can never be deleted via the API. app.delete("/repos/:owner/:repo/issues/:issue_number/dependencies/blocked_by/:issue_id", (c) => {
const { issue } = pathIssue(gh, c, "write");
const blocking = issueById(gh, c.get("authUser"), c.req.param("issue_id"));
const edge = gh.issueDependencies
.findBy("blocked_issue_id", issue.id)
.find((candidate) => candidate.blocking_issue_id === blocking.id);
if (!edge) throw notFoundResponse(); |
||||||
| const edge = gh.issueDependencies | ||||||
| .findBy("blocked_issue_id", issue.id) | ||||||
| .find((candidate) => candidate.blocking_issue_id === blocking.id); | ||||||
| if (!edge) throw notFoundResponse(); | ||||||
| gh.issueDependencies.delete(edge.id); | ||||||
| return c.json(formatIssue(blocking, gh, baseUrl)); | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 DELETE returns 200+body; GitHub contract is 204.
Suggested change
🤖 Fix with your agentWhy this mattersThe DELETE dependency endpoint returns 200 with the full blocking-issue JSON body. GitHub's remove-issue-dependency contract responds 204 No Content on success, and the emulator's own destructive issue routes (e.g. DELETE /repos/:o/:r/issues/:n/lock) already follow the 204 convention. Clients written against GitHub's contract will parse this response differently than expected. if (!edge) throw notFoundResponse();
gh.issueDependencies.delete(edge.id);
return c.json(formatIssue(blocking, gh, baseUrl));
});
} |
||||||
| }); | ||||||
| } | ||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔴 issue_dependencies_summary leaks private-repo issue counts.
🤖 Fix with your agent
Why this matters
formatIssue is the shared serializer for every issue-returning endpoint (get/list/search/webhooks) but takes no authUser, and issueDependenciesSummary counts ALL dependency edges with no caller-visibility filtering — while the new list endpoints in the same PR deliberately filter edges through canRead(). Any caller who can read a public issue gets issue_dependencies_summary exposing the count, open/closed split and existence of blocker issues living in private repos they cannot see. This directly contradicts the PR's own test ("omits related issues the caller cannot see from lists") and the emulator's stated rule that private repos are invisible (404). Repro: given an octocat/alpha issue A and a private hubot/secret issue S with edge {blocked: A, blocking: S}, octocat's GET .../dependencies/blocked_by returns [] but GET /repos/octocat/alpha/issues/{A.number} returns issue_dependencies_summary {blocked_by:1, total_blocked_by:1} — octocat learns A is blocked by exactly one open issue inside a private repo. All three review agents (Security, Consistency, Bug Hunter) independently flagged this.