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
60 changes: 56 additions & 4 deletions src/lib/server/application/adapters/namespace-discovery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,12 @@ test("GitHub discovers credential-visible organizations and filters an explicit
{ GITHUB_CLOUD_SOURCE_TOKEN: "fixture", GITHUB_CLOUD_SOURCE_ORGS: undefined },
async () => {
const network = spyOn(globalThis, "fetch").mockImplementation((async () =>
Response.json([{ login: "one" }, { login: "two" }])) as unknown as typeof fetch);
Response.json([
{ login: "one" },
{ login: "AcTions" },
{ login: "GitHUB" },
{ login: "two" },
])) as unknown as typeof fetch);
try {
const discover = async () =>
(await discoverNamespacePage("github", 0, new AbortController().signal)).entries.map(
Expand Down Expand Up @@ -447,9 +452,16 @@ test.each([true, false])(
calls.push(url.pathname + url.search);
if (url.pathname.endsWith("/user")) return Response.json({ site_admin: siteAdmin });
return calls.length === 2
? Response.json([{ login: "first", id: 71 }], {
headers: { link: '<https://ghes.invalid/next>; rel="next"' },
})
? Response.json(
[
{ login: "AcTIONS", id: 3 },
{ login: "GItHub", id: 5 },
{ login: "first", id: 71 },
],
{
headers: { link: '<https://ghes.invalid/next>; rel="next"' },
},
)
: Response.json([{ login: "second", id: 93 }]);
}) as typeof fetch);
try {
Expand Down Expand Up @@ -519,3 +531,43 @@ test.each([
}
}),
);

test.each(["https://api.github.com", "https://api.acme.ghe.com"])(
"Every organization excludes GitHub-owned logins on %s",
(url) =>
withEnv(
{
GITHUB_CLOUD_SOURCE_URL: url === "https://api.github.com" ? undefined : url,
GITHUB_CLOUD_SOURCE_TOKEN: "fixture",
GITHUB_CLOUD_SOURCE_ORGS: undefined,
},
async () => {
using network = spyOn(globalThis, "fetch").mockImplementation((async () =>
Response.json({
data: {
enterprise: {
organizations: {
nodes: ["GitHub", "ActioNs", "engineering"].map((login) => ({ login })),
pageInfo: { hasNextPage: false, endCursor: null },
},
},
},
})) as unknown as typeof fetch);
expect(
await enterpriseNamespaces(
"github",
new AbortController().signal,
"acme",
undefined,
"cloud",
),
).toEqual({
keys: ["engineering"],
found: 1,
outOfScope: 0,
scopeVariable: "GITHUB_CLOUD_SOURCE_ORGS",
});
expect(network).toHaveBeenCalledTimes(1);
},
),
);
11 changes: 9 additions & 2 deletions src/lib/server/application/adapters/namespace-discovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ import { organizationPage, siteOrganizationPage } from "$lib/server/core/github-
import { cloudWorkspacePage } from "$lib/server/source/bitbucket/cloud-inventory";
import { getBitbucketServerSourceClient } from "$lib/server/source/bitbucket/config";
import { getGitLabSourceClient, getGitLabSourceConfig } from "$lib/server/source/gitlab/config";
import { getSourceProviderAdapter, type SourceProvider } from "$lib/source-provider";
import {
getSourceProviderAdapter,
isGitHubSystemOrganization,
type SourceProvider,
} from "$lib/source-provider";

const limit = 50;

Expand Down Expand Up @@ -278,7 +282,9 @@ export async function discoverNamespacePage(
) {
const page = await readPage(provider, cursor, signal, hosting);
const entries = page.entries.filter(
(item) => !validateProfileCredentialScope(provider, item.key, hosting),
(item) =>
!isGitHubSystemOrganization(item.key, provider) &&
!validateProfileCredentialScope(provider, item.key, hosting),
);
return { ...page, entries, observedAt: new Date().toISOString() };
}
Expand Down Expand Up @@ -314,6 +320,7 @@ export async function enterpriseNamespaces(
const keys = new Set<string>();
const found = new Set<string>();
function add(key: string) {
if (isGitHubSystemOrganization(key, provider)) return;
found.add(key);
// Out-of-scope entries are only counted; admission rules apply to what may be queued.
if (validateProfileCredentialScope(provider, key, hosting)) return;
Expand Down
103 changes: 103 additions & 0 deletions src/lib/server/core/github-profile-probes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
const repo = "/repos/{owner}/{repo}/";
const org = "/orgs/{org}/";
const signals = new Map([
[`${repo}code-scanning/alerts`, "code scanning"],
[`${repo}tags/protection`, "tag protection"],
[`${org}codespaces/secrets`, "Codespaces secrets"],
[`${org}installations`, "app installations"],
[`${org}properties/schema`, "custom properties"],
[`${org}dependabot/secrets`, "Dependabot secrets"],
[`${org}actions/secrets`, "Actions secrets"],
[`${org}actions/variables`, "Actions variables"],
[`${org}actions/runners`, "Actions runners"],
[`${org}teams`, "teams"],
[`${org}rulesets`, "rulesets"],
[`${repo}hooks`, "webhooks"],
[`${repo}collaborators`, "collaborators"],
]);
const unavailable = new Map<string, { expires: number; status: number }>();

function applianceUnavailable(path: string, status: number, message: string) {
if (status >= 500) return true;
if (path.endsWith("/code-scanning/alerts"))
return (
status === 403 &&
/advanced security (?:is |must be |has been )?(?:not enabled|disabled|enabled for this repository to use code scanning)/i.test(
message,
)
);
return (
status === 404 &&
[
`${repo}tags/protection`,
`${org}codespaces/secrets`,
`${org}installations`,
`${org}properties/schema`,
].includes(path)
);
}

function failureDetails(error: unknown) {
const e = error as Error & {
status?: number;
response?: { headers: Record<string, string> };
};
const status = e.status;
const headers = e.response?.headers;
const limited =
status === 403 &&
(headers?.["x-ratelimit-remaining"] === "0" ||
headers?.["retry-after"] ||
/rate limit/i.test(e.message));
return { status, headers, limited, message: e.message };
}

export function profileProbes(baseUrl: string, appliance: boolean, now = Date.now) {
const { host, origin } = new URL(baseUrl);
const summary = new Map<string, { status: number; skipped: number }>();

async function attempt<T>(path: string, send: () => Promise<T>, key?: string) {
try {
return await send();
} catch (error) {
const { status, headers, limited, message } = failureDetails(error);
if (status && headers && !limited && signals.has(path)) {
const expected = applianceUnavailable(path, status, message);
if (key && expected) {
unavailable.set(key, { status, expires: now() + 3_600_000 });
if (!summary.has(path)) summary.set(path, { status, skipped: 0 });
}
if (expected || status === 404) throw new Error("Optional GitHub probe unavailable");
}
console.warn(
`[profile] request failed on ${host} (${headers && typeof status === "number" ? status : "network"})`,
);
throw error;
}
}

return {
async request<T>(path: string, send: () => Promise<T>) {
if (!appliance || !signals.has(path)) return attempt(path, send);
const key = origin + path;
const cached = unavailable.get(key);
if (cached && cached.expires > now()) {
const entry = summary.get(path) ?? { status: cached.status, skipped: 0 };
entry.skipped++;
summary.set(path, entry);
throw new Error("Optional GitHub probe unavailable");
}
unavailable.delete(key);
return attempt(path, send, key);
},
report() {
for (const [path, { status, skipped }] of summary) {
const unit = path.startsWith(repo) ? "repositories" : "organizations";
console.info(
`[profile] ${signals.get(path)} unavailable on ${host} (${status}); skipped for ${skipped} ${unit} in this run`,
);
}
summary.clear();
},
};
}
172 changes: 171 additions & 1 deletion src/lib/server/core/github-profile-retry.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { afterEach, beforeEach, describe, expect, setSystemTime, test } from "bun:test";
import { afterEach, beforeEach, describe, expect, setSystemTime, spyOn, test } from "bun:test";
import { createProfileClient } from "./github";

// The profile client owns its retry timers so shutdown can cancel them: retry
Expand Down Expand Up @@ -229,3 +229,173 @@ describe("profile client cancellation", () => {
await client.drainProfileRequests();
});
});

const scanning = "GET /repos/{owner}/{repo}/code-scanning/alerts";
const disabled = {
message: "Advanced Security must be enabled for this repository to use code scanning.",
};

function appliance(host: string, fetch: () => Response, now?: () => number) {
let calls = 0;
const client = createProfileClient(
{ token: "fixture" },
`https://${host}/api/v3`,
new AbortController().signal,
{
now,
fetch: async () => {
calls++;
return fetch();
},
wait: async () => {},
},
);
return {
client,
calls: () => calls,
scan: (repo: string) => client.request(scanning, { owner: "private-owner", repo }),
};
}

test("runs reuse a cached unavailable signal for an hour on the same appliance", async () => {
const host = "scan.example";
let clock = Date.now();
const make = (origin = host) =>
appliance(
origin,
() => Response.json(disabled, { status: 403 }),
() => clock,
);
const info = spyOn(console, "info").mockImplementation(() => {});
const error = spyOn(console, "error").mockImplementation(() => {});
const warn = spyOn(console, "warn").mockImplementation(() => {});
try {
const first = make();
for (const repo of ["a", "b", "c"])
await expect(first.scan(repo)).rejects.toThrow("Optional GitHub probe unavailable");
expect(first.calls()).toBe(1);
await first.client.drainProfileRequests();
const second = make();
await expect(second.scan("d")).rejects.toThrow();
await second.client.drainProfileRequests();
expect(second.calls()).toBe(0);
expect(info.mock.calls).toEqual(
[2, 1].map((n) => [
`[profile] code scanning unavailable on scan.example (403); skipped for ${n} repositories in this run`,
]),
);
const other = make("other-scan.example");
await expect(other.scan("e")).rejects.toThrow();
expect(other.calls()).toBe(1);
clock += 3_599_999;
await expect(second.scan("before-expiry")).rejects.toThrow();
expect(second.calls()).toBe(0);
clock++;
await expect(second.scan("f")).rejects.toThrow();
expect(second.calls()).toBe(1);
expect(error).not.toHaveBeenCalled();
expect(warn).not.toHaveBeenCalled();
} finally {
info.mockRestore();
error.mockRestore();
warn.mockRestore();
}
});

test.each([
["GET /repos/{owner}/{repo}/tags/protection", 404],
["GET /orgs/{org}/codespaces/secrets", 404],
["GET /orgs/{org}/installations", 404],
["GET /orgs/{org}/properties/schema", 404],
["GET /orgs/{org}/dependabot/secrets", 500],
] as const)("appliance caches %s after one HTTP %i", async (route, status) => {
const run = appliance("features.example", () => Response.json({}, { status }));
for (const org of ["first", "second"])
await expect(run.client.request(route, { org, owner: org, repo: "project" })).rejects.toThrow();
expect(run.calls()).toBe(1);
});

test.each([401, 403, 429])(
"authentication and throttling failures stay visible and do not suppress scanning (%i)",
async (status) => {
let first = true;
const run = appliance("permissions.example", () => {
if (!first) return Response.json([]);
first = false;
return Response.json({ message: "private diagnostic" }, { status });
});
const warn = spyOn(console, "warn").mockImplementation(() => {});
try {
if (status === 429) await run.scan("a");
else await expect(run.scan("a")).rejects.toMatchObject({ status });
await run.scan("b");
expect(run.calls()).toBe(status === 429 ? 3 : 2);
expect(warn.mock.calls).toEqual([
[`[profile] request failed on permissions.example (${status})`],
]);
} finally {
warn.mockRestore();
}
},
);

test("Retry-After on an optional 503 does not cause a retry", async () => {
const run = appliance("maintenance.example", () =>
Response.json({}, { status: 503, headers: { "retry-after": "1" } }),
);
await expect(
run.client.request("GET /orgs/{org}/actions/secrets", { org: "one" }),
).rejects.toThrow();
expect(run.calls()).toBe(1);
});

test("rate-limited scanning retries even when the response mentions Advanced Security", async () => {
let limited = true;
const run = appliance("limit.example", () => {
if (!limited) return Response.json([]);
limited = false;
return Response.json(disabled, { status: 403, headers: { "retry-after": "1" } });
});
await run.scan("first");
await run.scan("second");
expect(run.calls()).toBe(3);
});

test.each([
"GET /orgs/{org}/actions/secrets",
"GET /orgs/{org}/actions/variables",
"GET /orgs/{org}/actions/runners",
"GET /orgs/{org}/teams",
"GET /orgs/{org}/rulesets",
"GET /repos/{owner}/{repo}/hooks",
"GET /repos/{owner}/{repo}/collaborators",
scanning,
] as const)("a subsequent run skips %s after a cached HTTP 502", async (route) => {
const make = () => appliance("optional.example", () => Response.json({}, { status: 502 }));
const first = make();
const second = make();
const request = (run: typeof first) =>
run.client.request(route, { org: "org", owner: "org", repo: "repo" });
await expect(request(first)).rejects.toThrow("Optional GitHub probe unavailable");
await expect(request(second)).rejects.toThrow("Optional GitHub probe unavailable");
expect(first.calls()).toBe(1);
expect(second.calls()).toBe(0);
});

test("optional transport failures log safe metadata and leave the signal available", async () => {
using warn = spyOn(console, "warn").mockImplementation(() => {});
let failing = true;
const run = appliance("transport.example", () => {
if (failing) {
failing = false;
throw new Error("private network diagnostic");
}
return Response.json([]);
});
await run.scan("private-repo");
await run.scan("another");
expect(run.calls()).toBe(3);
expect(warn.mock.calls).toHaveLength(1);
for (const call of warn.mock.calls)
expect(call).toEqual(["[profile] request failed on transport.example (network)"]);
});
Loading