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
40 changes: 32 additions & 8 deletions pm-stack/projector/src/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,15 @@ async function discoverInstallationId(
headers: { authorization: `Bearer ${jwt}`, accept: "application/vnd.github+json", "user-agent": "pm-projector" },
});
if (!res.ok) return undefined;
const body = (await res.json()) as { id?: number };
if (typeof body.id === "number") {
discoveredInstallations.set(repo, body.id);
return body.id;
const body: unknown = await res.json();
// A wrong-shape 200 (null, a scalar, an array) carries no installation
// id: return undefined like the non-200 case above, so apiTokenFor
// falls through to the configured id / plain-token fallbacks instead
// of dying on a property access against null (#6954).
if (body !== null && typeof body === "object" && typeof (body as { id?: unknown }).id === "number") {
const id = (body as { id: number }).id;
discoveredInstallations.set(repo, id);
return id;
}
return undefined;
}
Expand All @@ -156,8 +161,18 @@ export async function apiTokenFor(
headers: { authorization: `Bearer ${jwt}`, accept: "application/vnd.github+json" },
});
if (!res.ok) throw new Error(`installation_token_failed_${res.status}`);
const body = (await res.json()) as { token: string };
return { kind: "app", token: body.token };
const body: unknown = await res.json();
// Only a non-empty string token is an app credential: a token-less,
// mistyped, or null reply must fail here in the module's vocabulary
// instead of returning { token: undefined } as success (every later
// call would 401 as "Bearer undefined") or throwing a raw
// property-access TypeError on null (#6954).
const token =
body !== null && typeof body === "object" ? (body as { token?: unknown }).token : undefined;
if (typeof token !== "string" || token === "") {
throw new Error("installation_token_failed_shape: access_tokens response carried no string token");
}
return { kind: "app", token };
}
if (env.GITHUB_TOKEN) return { kind: "token", token: env.GITHUB_TOKEN };
throw new Error(`no_github_credentials_for_${repo}`);
Expand Down Expand Up @@ -202,8 +217,17 @@ export async function listResource<T>(auth: GitHubAuth, initialPath: string, fet
},
});
if (!res.ok) throw new Error(`github_api_${res.status}`);
const page = (await res.json()) as T[];
out.push(...page);
const page: unknown = await res.json();
// List endpoints return arrays; any other 200 shape is an API
// error in disguise. Reject it in the module's vocabulary instead
// of a raw spread TypeError (null/object/number) or, worse,
// silently spreading a string page into per-character rows (#6954).
if (!Array.isArray(page)) {
throw new Error(
`github_api_unexpected_shape: ${url} returned ${page === null ? "null" : typeof page}, expected an array`,
);
}
out.push(...(page as T[]));
path = nextPageFromLink(res.headers.get("link"));
}
return out;
Expand Down
55 changes: 55 additions & 0 deletions pm-stack/projector/test/github.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,58 @@ describe("apiTokenFor installation resolution", () => {
expect(calls).toContain("https://api.github.com/app/installations/42/access_tokens");
});
});

describe("GitHub API response shape validation (#6954)", () => {
const auth = { kind: "token", token: "t" } as const;

test("listResource rejects non-array 200 pages in the module vocabulary, never spreads a string", async () => {
for (const bodyText of ["null", JSON.stringify({ message: "oops" }), JSON.stringify("hello"), "42"]) {
const fetchFn = async () => new Response(bodyText, { status: 200 });
const result = await listResource(auth, "repos/o/r/issues", fetchFn as unknown as typeof fetch).catch(
(error: unknown) => error,
);
expect(result).toBeInstanceOf(Error);
expect((result as Error).message).toContain("github_api_unexpected_shape");
}
});

test("discovery with a null 200 body falls back to the plain token", async () => {
const env = {
GITHUB_APP_ID: "123",
GITHUB_APP_PRIVATE_KEY: testKeyB64("pkcs8"),
GITHUB_TOKEN: "plain-token",
};
const fetchFn = async (url: string) => {
if (url === "https://api.github.com/repos/acme/null-discovery/installation") {
return new Response("null", { status: 200 });
}
return new Response("{}", { status: 404 });
};
const resolved = await apiTokenFor(env, "acme/null-discovery", fetchFn as unknown as typeof fetch);
expect(resolved).toEqual({ kind: "token", token: "plain-token" });
});

test("access-token replies without a non-empty string token fail in the module vocabulary", async () => {
const env = {
GITHUB_APP_ID: "123",
GITHUB_APP_PRIVATE_KEY: testKeyB64("pkcs8"),
GITHUB_APP_INSTALL_ID: "42",
};
for (const [repo, bodyText] of [
["acme/tok-empty-object", "{}"],
["acme/tok-null", "null"],
["acme/tok-number", JSON.stringify({ token: 123 })],
["acme/tok-blank", JSON.stringify({ token: "" })],
] as const) {
const fetchFn = async (url: string) => {
if (url.includes("/access_tokens")) return new Response(bodyText, { status: 200 });
return new Response("{}", { status: 404 });
};
const result = await apiTokenFor(env, repo, fetchFn as unknown as typeof fetch).catch(
(error: unknown) => error,
);
expect(result).toBeInstanceOf(Error);
expect((result as Error).message).toContain("installation_token_failed_shape");
}
});
});
Loading