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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ try {
}
```

Options are `port`, `hostname`, `baseUrl`, `seed`, and `tokens`. The instance exposes `url`, `generatedSecrets`, `reset()`, and `close()`. Seeding uses the retained [upstream GitHub config](packages/@emulators/github/README.md). Tokens resolve to actual seeded user IDs. Omitted GitHub App keys are generated and returned through `generatedSecrets` in the programmatic API; the CLI does not print private keys.
Options are `port`, `hostname`, `baseUrl`, `seed`, and `tokens`. Unlike upstream, tokens are checked strictly by default: a bearer token the seed did not configure and the emulator did not issue (for example one issued before `reset()`) gets `401 Bad credentials` (set `strict_scopes: false` in the seed for upstream's default-user fallback), and private repositories answer `404` to callers who cannot see them. The instance exposes `url`, `generatedSecrets`, `reset()`, and `close()`. Seeding uses the retained [upstream GitHub config](packages/@emulators/github/README.md). Tokens resolve to actual seeded user IDs. Omitted GitHub App keys are generated and returned through `generatedSecrets` in the programmatic API; the CLI does not print private keys.

Each instance has independent in-memory state. Reset replays its seed and clears dynamic OAuth and installation tokens while retaining generated App keys. Closing an instance releases its HTTP listener. The baseline retains upstream's in-memory backend; SQLite is planned as a later consistency improvement. In-flight webhook cancellation across reset is not guaranteed by this baseline.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,22 @@ describe("GitHub issue dependencies", () => {
token: "hubot-token",
});
expect(((await asHubot.json()) as Issue[]).map((issue) => issue.id)).toEqual([hidden.id]);
// The shared issue payload never counts a blocker some readers of this issue cannot see.
const summary = ((await (await call(`/repos/octocat/alpha/issues/${blocked.number}`)).json()) as Issue)
.issue_dependencies_summary;
expect(summary).toEqual({ blocked_by: 0, blocking: 0, total_blocked_by: 0, total_blocking: 0 });
});

it("treats an edge to an issue the caller cannot read as not found, and rejects a malformed id", 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 path = `/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by`;
expect((await call(`${path}/not-a-number`, { method: "DELETE" })).status).toBe(422);
// Same status as an id with no edge at all, so a writer cannot probe for hidden blockers.
expect((await call(`${path}/${hidden.id}`, { method: "DELETE" })).status).toBe(404);
expect((await call(`${path}/999999`, { method: "DELETE" })).status).toBe(404);
expect(getGitHubStore(store).issueDependencies.findBy("blocked_issue_id", blocked.id)).toHaveLength(1);
});

it("requires authentication to add an edge", async () => {
Expand Down
189 changes: 189 additions & 0 deletions packages/@emulators/github/src/__tests__/issue-types.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
import { beforeEach, describe, expect, it, vi } 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";

const base = "http://localhost:4000";

type IssueType = { id: number; name: string; is_enabled: boolean; description: string | null };
type Issue = { number: number; type: IssueType | null };

function createTestApp() {
const store = new Store();
const tokenMap: TokenMap = new Map([
["admin-token", { login: "admin", id: 1, scopes: ["repo", "user", "read:org"] }],
["outsider-token", { login: "outsider", id: 2, scopes: ["repo", "user", "read:org"] }],
]);
const webhooks = new WebhookDispatcher();
const app = new Hono();
app.onError(createApiErrorHandler());
app.use("*", createErrorHandler());
app.use("*", authMiddleware(tokenMap));
githubPlugin.register(app as any, store, webhooks, base, tokenMap);
githubPlugin.seed?.(store, base);
seedFromConfig(store, base, {
users: [{ login: "admin" }, { login: "outsider" }],
orgs: [
{ login: "acme", members: [{ login: "admin", role: "admin" }] },
{
login: "custom",
members: [{ login: "admin", role: "admin" }],
issue_types: [
{ name: "Epic", description: "A large body of work" },
{ name: "Chore", is_enabled: false },
],
},
{ login: "untyped", members: [{ login: "admin", role: "admin" }], issue_types: [] },
],
repos: [
{ owner: "acme", name: "widget" },
{ owner: "custom", name: "tool" },
{ owner: "admin", name: "personal" },
],
});
// Installations on acme: one granted nothing, one granted issues read.
const acmeId = getGitHubStore(store).orgs.findOneBy("login", "acme")!.id;
for (const [token, permissions] of [
["bare-installation-token", {}],
["issues-installation-token", { issues: "read" }],
] as const) {
tokenMap.set(token, {
login: "acme-app[bot]",
id: 9000,
scopes: [],
installation: {
installationId: 1,
appId: 1,
accountId: acmeId,
accountType: "Organization",
permissions,
repositoryIds: [],
repositorySelection: "all",
},
});
}
return { app, webhooks };
}

describe("GitHub issue types", () => {
let app: Hono;
let webhooks: WebhookDispatcher;
const call = (path: string, init: { method?: string; token?: string | null; body?: unknown } = {}) => {
const headers: Record<string, string> = {};
const token = init.token === undefined ? "admin-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 names = async (res: Response) => ((await res.json()) as IssueType[]).map((type) => type.name);

beforeEach(() => {
({ app, webhooks } = createTestApp());
});

it("seeds GitHub's default types, custom types or none per organization", async () => {
expect(await names(await call("/orgs/acme/issue-types"))).toEqual(["Task", "Bug", "Feature"]);
const custom = (await (await call("/orgs/custom/issue-types")).json()) as IssueType[];
expect(custom.map((type) => [type.name, type.is_enabled, type.description])).toEqual([
["Epic", true, "A large body of work"],
["Chore", false, null],
]);
expect(await names(await call("/orgs/untyped/issue-types"))).toEqual([]);
});

it("lists a repository's types from its organization, and none for a personal repository", async () => {
expect(await names(await call("/repos/acme/widget/issue-types"))).toEqual(["Task", "Bug", "Feature"]);
expect(await names(await call("/repos/admin/personal/issue-types"))).toEqual([]);
});

it("hides an organization's types from non-members", async () => {
expect((await call("/orgs/acme/issue-types", { token: "outsider-token" })).status).toBe(404);
expect((await call("/orgs/acme/issue-types", { token: null })).status).toBe(404);
expect((await call("/orgs/missing/issue-types")).status).toBe(404);
});

it("lets an installation on the organization list its types only with issues or metadata read", async () => {
expect((await call("/orgs/acme/issue-types", { token: "bare-installation-token" })).status).toBe(403);
const granted = await call("/orgs/acme/issue-types", { token: "issues-installation-token" });
expect(await names(granted)).toEqual(["Task", "Bug", "Feature"]);
expect((await call("/orgs/custom/issue-types", { token: "issues-installation-token" })).status).toBe(404);
});

it("records a timeline event and sends issues typed or untyped when the type changes", async () => {
const dispatch = vi.spyOn(webhooks, "dispatch");
const issue = (await (
await call("/repos/acme/widget/issues", { method: "POST", body: { title: "Typed" } })
).json()) as Issue;
const patch = (body: unknown) =>
call(`/repos/acme/widget/issues/${issue.number}`, { method: "PATCH", body: body as Record<string, unknown> });
await patch({ type: "Bug" });
await patch({ type: "Feature" });
await patch({ type: "Feature" });
await patch({ type: null });

const typeHooks = dispatch.mock.calls
.filter(([event, action]) => event === "issues" && (action === "typed" || action === "untyped"))
.map(([, action, payload]) => [action, (payload as { type: IssueType | null }).type?.name]);
expect(typeHooks).toEqual([
["typed", "Bug"],
["typed", "Feature"],
["untyped", "Feature"],
]);
const events = (await (await call(`/repos/acme/widget/issues/${issue.number}/events`)).json()) as {
event: string;
}[];
expect(events.map((e) => e.event).filter((e) => e.startsWith("issue_type"))).toEqual([
"issue_type_added",
"issue_type_changed",
"issue_type_removed",
]);
});

it("sets, changes and clears an issue's type by name", async () => {
const created = await call("/repos/acme/widget/issues", { method: "POST", body: { title: "Typed", type: "bug" } });
expect(created.status).toBe(201);
const issue = (await created.json()) as Issue;
expect(issue.type?.name).toBe("Bug");

const changed = await call(`/repos/acme/widget/issues/${issue.number}`, {
method: "PATCH",
body: { type: "Feature" },
});
expect(((await changed.json()) as Issue).type?.name).toBe("Feature");
const untouched = await call(`/repos/acme/widget/issues/${issue.number}`, {
method: "PATCH",
body: { title: "Renamed" },
});
expect(((await untouched.json()) as Issue).type?.name).toBe("Feature");
const cleared = await call(`/repos/acme/widget/issues/${issue.number}`, { method: "PATCH", body: { type: null } });
expect(((await cleared.json()) as Issue).type).toBeNull();

const plain = await call("/repos/acme/widget/issues", { method: "POST", body: { title: "Untyped" } });
expect(((await plain.json()) as Issue).type).toBeNull();
});

it("rejects an unknown, disabled or personal-repository type with 422 and writes nothing", async () => {
const before = ((await (await call("/repos/custom/tool/issues?state=all")).json()) as unknown[]).length;
for (const type of ["Bug", "Chore", ""]) {
const res = await call("/repos/custom/tool/issues", { method: "POST", body: { title: "Rejected", type } });
expect(res.status, type).toBe(422);
}
expect(((await (await call("/repos/custom/tool/issues?state=all")).json()) as unknown[]).length).toBe(before);
expect(
(await call("/repos/admin/personal/issues", { method: "POST", body: { title: "Personal", type: "Task" } }))
.status,
).toBe(422);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -1014,6 +1014,44 @@ describe("app webhook_url delivery", () => {
expect(body.installation.id).toBe(55);
});

it("gives each app webhook delivery its own GUID, even within the same millisecond", async () => {
vi.spyOn(Date, "now").mockReturnValue(1_700_000_000_000);
try {
const { app } = createTestApp({
users: [{ login: "octocat" }],
repos: [{ owner: "octocat", name: "hello-world" }],
apps: [
{
app_id: 550,
slug: "delivery-app",
name: "Delivery App",
private_key: "fake-key",
events: ["issues"],
webhook_url: "https://delivery.example/webhook",
installations: [{ installation_id: 57, account: "octocat", repository_selection: "all" }],
},
],
});

for (const title of ["First delivery", "Second delivery"]) {
await app.request(`${base}/repos/octocat/hello-world/issues`, {
method: "POST",
headers: { ...authHeaders(), "Content-Type": "application/json" },
body: JSON.stringify({ title }),
});
}

const ids = mockFetch.mock.calls
.filter((c) => c[0] === "https://delivery.example/webhook")
.map((c) => ((c[1] as RequestInit).headers as Record<string, string>)["X-GitHub-Delivery"]);
expect(ids).toHaveLength(2);
for (const id of ids) expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);
expect(new Set(ids).size).toBe(2);
} finally {
vi.restoreAllMocks();
}
});

it("signs app webhook delivery with webhook_secret", async () => {
const secret = "app-webhook-secret";
const { app } = createTestApp({
Expand Down
12 changes: 12 additions & 0 deletions packages/@emulators/github/src/entities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ export interface GitHubIssue extends Entity {
closed_at: string | null;
closed_by_id: number | null;
is_pull_request: boolean;
/** Organization issue type; absent on rows written before issue types existed. */
type_id?: number | null;
}

export interface GitHubPullRequest extends Entity {
Expand Down Expand Up @@ -237,6 +239,16 @@ export interface GitHubIssueEvent extends Entity {
rename: { from: string; to: string } | null;
}

/** An organization's issue type (Task, Bug, Feature by default). */
export interface GitHubIssueType extends Entity {
node_id: string;
org_id: number;
name: string;
description: string | null;
color: string | null;
is_enabled: boolean;
}

/** A directed "blocked by" edge: `blocked_issue_id` cannot proceed until `blocking_issue_id` is done. */
export interface GitHubIssueDependency extends Entity {
blocked_issue_id: number;
Expand Down
37 changes: 34 additions & 3 deletions packages/@emulators/github/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
GitHubOrg,
GitHubRepo,
GitHubIssue,
GitHubIssueType,
GitHubPullRequest,
GitHubLabel,
GitHubMilestone,
Expand Down Expand Up @@ -374,6 +375,7 @@ export function formatIssue(issue: GitHubIssue, store: GitHubStore, baseUrl: str
assignee: assignees[0] ?? null,
assignees,
milestone: milestone ? formatMilestone(milestone, repo, store, baseUrl) : null,
type: issueTypeJson(issue, store),
comments: issue.comments,
created_at: issue.created_at,
updated_at: issue.updated_at,
Expand All @@ -388,16 +390,45 @@ export function formatIssue(issue: GitHubIssue, store: GitHubStore, baseUrl: str
};
}

/** Counts as GitHub reports them: `blocked_by` and `blocking` count open issues, the totals count all. */
export function formatIssueType(type: GitHubIssueType) {
return {
id: type.id,
node_id: type.node_id,
name: type.name,
description: type.description,
color: type.color,
created_at: type.created_at,
updated_at: type.updated_at,
is_enabled: type.is_enabled,
};
}

function issueTypeJson(issue: GitHubIssue, store: GitHubStore) {
const type = issue.type_id ? store.issueTypes.get(issue.type_id) : undefined;
return type ? formatIssueType(type) : null;
}

export function findIssueForRepo(gh: GitHubStore, repoId: number, issueNumber: number): GitHubIssue | undefined {
return gh.issues.findBy("repo_id", repoId).find((i) => i.number === issueNumber && !i.is_pull_request);
}

/**
* Counts as GitHub reports them: `blocked_by` and `blocking` count open issues, the totals count all.
* The issue payload is shared by every reader, so only related issues every reader of this issue can
* see are counted: those in the same repository or in a public one. The dependency list endpoints,
* which know the caller, return the rest to callers who may see them.
*/
function issueDependenciesSummary(issue: GitHubIssue, store: GitHubStore) {
const visibleToAllReaders = (other: GitHubIssue | undefined): other is GitHubIssue =>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Dependency summary undercounts for authorized callers.

Suggested change
const visibleToAllReaders = (other: GitHubIssue | undefined): other is GitHubIssue =>
Either document the discrepancy in the README next to the dependency endpoints ("summary counts only same-repo/public blockers even for authorized callers"), or thread the caller into the summary where one is known (per-request GETs) and keep the reader-agnostic filter only for shared webhook payloads.
🤖 Fix with your agent
Fix this code review finding (aictrl-dev/github-emulator PR #13, packages/@emulators/github/src/helpers.ts:422-431):

Problem: Dependency summary undercounts for authorized callers
Detail: issueDependenciesSummary now drops cross-repo private far-ends for every reader, so a caller who CAN read both ends (e.g. the owner of both private repos) gets issue_dependencies_summary.blocked_by = 0 from GET /repos/o/r/issues/N while GET /repos/o/r/issues/N/dependencies/blocked_by on the same issue returns the edge; webhook payload counts are undercounted the same way. The doc comment shows the shared-payload rationale is deliberate, but the summary/list contradiction for fully-authorized callers (who see 0 blockers on the issue yet 1 edge in the list) is neither documented in the README nor matches GitHub, where the summary counts all stored edges.
Suggested fix: Either document the discrepancy in the README next to the dependency endpoints ("summary counts only same-repo/public blockers even for authorized callers"), or thread the caller into the summary where one is known (per-request GETs) and keep the reader-agnostic filter only for shared webhook payloads.

Implement the fix on the PR head branch and add a regression test that fails before the fix and passes after.
Why this matters

issueDependenciesSummary now drops cross-repo private far-ends for every reader, so a caller who CAN read both ends (e.g. the owner of both private repos) gets issue_dependencies_summary.blocked_by = 0 from GET /repos/o/r/issues/N while GET /repos/o/r/issues/N/dependencies/blocked_by on the same issue returns the edge; webhook payload counts are undercounted the same way. The doc comment shows the shared-payload rationale is deliberate, but the summary/list contradiction for fully-authorized callers (who see 0 blockers on the issue yet 1 edge in the list) is neither documented in the README nor matches GitHub, where the summary counts all stored edges.

function issueDependenciesSummary(issue: GitHubIssue, store: GitHubStore) {
  const visibleToAllReaders = (other: GitHubIssue | undefined): other is GitHubIssue =>
    !!other && (other.repo_id === issue.repo_id || store.repos.get(other.repo_id)?.visibility === "public");
  const blockers = store.issueDependencies
    .findBy("blocked_issue_id", issue.id)
    .map((edge) => store.issues.get(edge.blocking_issue_id))
    .filter(visibleToAllReaders);
  const blocked = store.issueDependencies
    .findBy("blocking_issue_id", issue.id)

!!other && (other.repo_id === issue.repo_id || store.repos.get(other.repo_id)?.visibility === "public");
const blockers = store.issueDependencies
.findBy("blocked_issue_id", issue.id)
.map((edge) => store.issues.get(edge.blocking_issue_id))
.filter((other): other is GitHubIssue => !!other);
.filter(visibleToAllReaders);
const blocked = store.issueDependencies
.findBy("blocking_issue_id", issue.id)
.map((edge) => store.issues.get(edge.blocked_issue_id))
.filter((other): other is GitHubIssue => !!other);
.filter(visibleToAllReaders);
return {
blocked_by: blockers.filter((other) => other.state === "open").length,
blocking: blocked.filter((other) => other.state === "open").length,
Expand Down
Loading
Loading