Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(skills): report a revoked GitHub sign-in when skill import is refused

Ooi Pin Jun2093e34e550f
diff --git a/server/routes/bot-skills.test.ts b/server/routes/bot-skills.test.ts
index edaeb72d9a..acd1158303 100644
--- a/server/routes/bot-skills.test.ts
+++ b/server/routes/bot-skills.test.ts
@@ -7,7 +7,9 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { DATA_DIR, type AppConfig } from "../config.ts";
import { provideGithubSignIn } from "../github/token.ts";
import { json, readBody } from "../harness/http.ts";
+import { personKey } from "../person-key.ts";
import type { RequestAuth } from "../request-auth.ts";
+import type { SessionRecord } from "../sessions.ts";
import { installLibrarySkill, readLibrarySkillFile, setLibrarySkillEveryBot } from "../skill-library.ts";
import type { Store } from "../store.ts";
import { installSkill, listSkills, resolveBotSkills } from "../skills.ts";
@@ -87,10 +89,10 @@ describe("whose GitHub sign-in a bot import uses", () => {
const OWNER = "gho_ownerSignInMustNotLeak";
const SKILL_MD = "---\nname: pdf\ndescription: Does pdf things.\n---\n\n# pdf\n";
- async function importAs(auth: RequestAuth) {
+ async function importAs(auth: RequestAuth, team = false) {
const asked: Array<string | null | undefined> = [];
provideGithubSignIn({
- token: async (audience) => { asked.push(audience); return audience === "owner" ? TOKEN : OWNER; },
+ token: async (audience) => { asked.push(audience); return audience ? TOKEN : OWNER; },
reportAuthFailure: () => {},
signedIn: () => true,
});
@@ -110,7 +112,7 @@ describe("whose GitHub sign-in a bot import uses", () => {
listBotSkills: () => [],
readBotSkillFile: () => null,
stagedSkillListing: (staged) => staged,
- team: false,
+ team,
})];
const server = createServer(async (req, res) => {
const url = new URL(req.url ?? "/", "http://localhost");
@@ -150,6 +152,38 @@ describe("whose GitHub sign-in a bot import uses", () => {
expect(JSON.stringify({ body, calls })).not.toContain(OWNER);
expect(JSON.stringify({ body, calls })).not.toContain(TOKEN);
});
+
+ const memberSession = (email: string): RequestAuth => ({
+ kind: "session",
+ via: "cookie",
+ scopes: ["client"],
+ session: {
+ id: "s-1", tokenHash: "0".repeat(64), label: "Ada", scopes: ["client"], createdAt: 1, lastSeenAt: 1, expiresAt: 9_000,
+ email, teamRole: "member", membershipAuthority: "team",
+ } as SessionRecord,
+ });
+
+ it("asks for that member's person key on a Team Cloud", async () => {
+ const key = personKey({ id: "", email: "[email protected]" });
+ const { status, body, calls, asked } = await importAs(memberSession("[email protected]"), true);
+ expect(status).toBe(201);
+ const api = calls.filter((call) => call.url.startsWith("https://api.github.com/"));
+ const raw = calls.filter((call) => call.url.startsWith("https://raw.githubusercontent.com/"));
+ expect(api.length).toBeGreaterThan(0);
+ expect(raw.length).toBeGreaterThan(0);
+ expect(asked).toEqual([key]);
+ expect(api.every((call) => call.headers.get("authorization") === `Bearer ${TOKEN}`)).toBe(true);
+ expect(raw.every((call) => call.headers.get("authorization") === null)).toBe(true);
+ expect(JSON.stringify(body)).not.toContain(TOKEN);
+ });
+
+ it("does not look up a token on a Team Cloud when this session has no member sign-in", async () => {
+ const { status, calls, asked } = await importAs({ kind: "loopback", scopes: ["admin"] } as RequestAuth, true);
+ expect(status).toBe(201);
+ expect(calls.some((call) => call.url.startsWith("https://api.github.com/"))).toBe(true);
+ expect(asked).toEqual([]);
+ expect(calls.every((call) => call.headers.get("authorization") === null)).toBe(true);
+ });
});
const learned = (name: string) => `---\nname: ${name}\ndescription: A skill.\n---\n\n# ${name}\n\nSteps.\n`;
diff --git a/server/skill-fetch.test.ts b/server/skill-fetch.test.ts
index e2550cbcac..6574721d56 100644
--- a/server/skill-fetch.test.ts
+++ b/server/skill-fetch.test.ts
@@ -98,7 +98,7 @@ describe("importing a skill's whole folder", () => {
let lookups = 0;
const [skill] = ok(await fetchSkillFromSource("https://github.com/a/b/tree/main/skills/pdf", recorded.fetch, undefined, async () => {
lookups += 1;
- return SIGNED_IN;
+ return { token: SIGNED_IN };
}));
expect(skill!.github?.commit).toBe(github.commitOf("a/b"));
const api = apiCalls(recorded.calls);
@@ -122,7 +122,7 @@ describe("importing a skill's whole folder", () => {
let lookups = 0;
const [skill] = ok(await fetchSkillFromSource("https://github.com/a/b/tree/main/skills/pdf", recorded.fetch, undefined, async () => {
lookups += 1;
- return null;
+ return { token: null };
}));
expect(skill!.files.length).toBeGreaterThan(0);
const api = apiCalls(recorded.calls);
@@ -145,7 +145,7 @@ describe("importing a skill's whole folder", () => {
});
const github = fakeGitHub({ "a/b": PDF_SKILL });
const recorded = recordingFetch(github.fetch);
- ok(await fetchSkillFromSource("a/b", recorded.fetch, undefined, async () => null));
+ ok(await fetchSkillFromSource("a/b", recorded.fetch, undefined, async () => ({ token: null })));
expect(recorded.calls.every((call) => call.headers.get("authorization") === null)).toBe(true);
expect(JSON.stringify(recorded.calls)).not.toContain(OWNER_SIGN_IN);
expect(asked).toEqual([]);
@@ -163,7 +163,7 @@ describe("importing a skill's whole folder", () => {
});
expect(await githubToken(null)).toBe(OWNER_SIGN_IN);
asked.length = 0;
- expect(await skillImportToken(null)).toBeNull();
+ expect(await skillImportToken(null)).toEqual({ token: null });
expect(asked).toEqual([]);
const github = fakeGitHub({ "a/b": PDF_SKILL });
const recorded = recordingFetch(github.fetch);
@@ -310,7 +310,7 @@ describe("importing a skill's whole folder", () => {
const github = fakeGitHub({ "a/b": PDF_SKILL });
const [skill] = ok(await fetchSkillFromSource("https://github.com/a/b/tree/main/skills/pdf", github.fetch));
const recorded = recordingFetch(github.fetch);
- expect(await latestSkillCommit(skill!.github!, recorded.fetch, async () => SIGNED_IN)).toBe(github.commitOf("a/b"));
+ expect(await latestSkillCommit(skill!.github!, recorded.fetch, async () => ({ token: SIGNED_IN }))).toBe(github.commitOf("a/b"));
const lookups = recorded.calls.filter((call) => call.url.includes("/commits/"));
expect(lookups.length).toBeGreaterThan(0);
expect(lookups.every((call) => call.headers.get("authorization") === `Bearer ${SIGNED_IN}` && call.headers.get("accept") === "application/vnd.github.sha")).toBe(true);
@@ -409,7 +409,7 @@ describe("skill fetch host pinning", () => {
"https://skills.sh/vercel-labs/skills/find-skills",
recorded.fetch,
undefined,
- async () => SIGNED_IN,
+ async () => ({ token: SIGNED_IN }),
));
expect(skill!.source).toBe("github.com/vercel-labs/skills/skills/search-helper");
const urls = recorded.calls.map((call) => call.url);
@@ -455,7 +455,7 @@ describe("skill fetch host pinning", () => {
}
return github.fetch(input, init);
}) as typeof fetch;
- const result = await fetchSkillFromSource("a/b", fetcher, undefined, async () => SIGNED_IN);
+ const result = await fetchSkillFromSource("a/b", fetcher, undefined, async () => ({ token: SIGNED_IN }));
const urls = vi.mocked(fetcher).mock.calls.map(([input]) => String(input));
expect(urls.some((url) => url.startsWith("https://api.github.com/") && url.includes("/commits/"))).toBe(true);
expect(urls).not.toContain(offhost);
@@ -468,20 +468,65 @@ describe("skill fetch host pinning", () => {
it("leaves a sign-in that cannot be a header out of the error", async () => {
const credential = "gho_not\r\na header";
+ const refused: string[] = [];
const fetcher = vi.fn(async () => new Response("no", { status: 401 })) as typeof fetch;
- const result = await fetchSkillFromSource("owner/repo", fetcher, undefined, async () => credential);
+ const result = await fetchSkillFromSource("owner/repo", fetcher, undefined, async () => ({ token: credential, refused: () => { refused.push(credential); } }));
expect(result).toEqual({ error: expect.stringContaining("401") });
expect(JSON.stringify(result)).not.toContain("gho_not");
expect(new Headers(vi.mocked(fetcher).mock.calls[0]?.[1]?.headers).get("authorization")).toBeNull();
+ expect(refused).toEqual([]);
});
- it("reports one refused API request and leaves the credential out of the error", async () => {
+ it("reports one refused API request for the audience whose token was sent", async () => {
+ const member = "p_adaaaaaaaaaaaaaaaaaaaaa";
+ const refused: Array<string | null | undefined> = [];
+ const asked: Array<string | null | undefined> = [];
+ provideGithubSignIn({
+ token: async (audience) => { asked.push(audience); return audience === member ? SIGNED_IN : null; },
+ reportAuthFailure: (audience) => { refused.push(audience); },
+ signedIn: () => true,
+ });
const fetcher = vi.fn(async () => new Response("no", { status: 401 })) as typeof fetch;
- const result = await fetchSkillFromSource("owner/repo", fetcher, undefined, async () => SIGNED_IN);
+ const result = await fetchSkillFromSource("owner/repo", fetcher, undefined, () => skillImportToken(member));
expect(fetcher).toHaveBeenCalledTimes(1);
expect(result).toEqual({ error: expect.stringContaining("401") });
expect(JSON.stringify(result)).not.toContain(SIGNED_IN);
expect(new Headers(vi.mocked(fetcher).mock.calls[0]?.[1]?.headers).get("authorization")).toBe(`Bearer ${SIGNED_IN}`);
+ expect(asked).toEqual([member]);
+ expect(refused).toEqual([member]);
+ });
+
+ it("reports the server sign-in when its own API request is refused", async () => {
+ const refused: Array<string | null | undefined> = [];
+ provideGithubSignIn({
+ token: async () => SIGNED_IN,
+ reportAuthFailure: (audience) => { refused.push(audience); },
+ signedIn: () => true,
+ });
+ const fetcher = vi.fn(async () => new Response("no", { status: 401 })) as typeof fetch;
+ const result = await fetchSkillFromSource("owner/repo", fetcher);
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ expect(result).toEqual({ error: expect.stringContaining("401") });
+ expect(JSON.stringify(result)).not.toContain(SIGNED_IN);
+ expect(refused).toEqual(["owner"]);
+ });
+
+ it("does not report an anonymous API refusal", async () => {
+ const refused: Array<string | null | undefined> = [];
+ const asked: Array<string | null | undefined> = [];
+ provideGithubSignIn({
+ token: async (audience) => { asked.push(audience); return OWNER_SIGN_IN; },
+ reportAuthFailure: (audience) => { refused.push(audience); },
+ signedIn: () => true,
+ });
+ const fetcher = vi.fn(async () => new Response("no", { status: 401 })) as typeof fetch;
+ const result = await fetchSkillFromSource("owner/repo", fetcher, undefined, () => skillImportToken(null));
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ expect(result).toEqual({ error: expect.stringContaining("401") });
+ expect(new Headers(vi.mocked(fetcher).mock.calls[0]?.[1]?.headers).get("authorization")).toBeNull();
+ expect(asked).toEqual([]);
+ expect(refused).toEqual([]);
+ expect(JSON.stringify(result)).not.toContain(OWNER_SIGN_IN);
});
it("downloads only from the pinned raw host, with redirects refused", async () => {
diff --git a/server/skill-fetch.ts b/server/skill-fetch.ts
index 530c96e43b..6831e23e20 100644
--- a/server/skill-fetch.ts
+++ b/server/skill-fetch.ts
@@ -3,7 +3,7 @@ import { z } from "zod";
import type { GitHubSkillOrigin, SkippedSkillFile } from "../shared/skill-import.ts";
import { SKILL_FILE_MAX_BYTES } from "../shared/skill-md.ts";
-import { githubToken } from "./github/token.ts";
+import { githubToken, reportGithubAuthFailure } from "./github/token.ts";
import { planSkillFolder, SKILL_FOLDER_LIMITS, type FolderEntry, type SkillFolderFile } from "./skill-folder.ts";
const API = "https://api.github.com";
@@ -16,9 +16,18 @@ const PARALLEL_DOWNLOADS = 4;
class ImportLimitError extends Error {}
class GitHubApiError extends Error {}
-/** A refused audience (`null`) stays anonymous. `githubToken(null)` is the server sign-in off a Team Cloud. */
-export function skillImportToken(audience?: string | null): Promise<string | null> {
- return audience === null ? Promise.resolve(null) : githubToken(audience);
+export interface SkillImportSignIn {
+ token: string | null;
+ /** Set only when `token` is this audience's sign-in. A 401 on a request that sent it marks that sign-in stale. */
+ refused?(): void;
+}
+
+/** A refused audience (`null`) stays anonymous and has no `refused`. `githubToken(null)` is the server sign-in off a Team Cloud. */
+export function skillImportToken(audience?: string | null): Promise<SkillImportSignIn> {
+ if (audience === null) return Promise.resolve({ token: null });
+ return githubToken(audience).then((token) => token
+ ? { token, refused: () => reportGithubAuthFailure(audience ?? "owner") }
+ : { token: null });
}
function requestHref(input: Parameters<typeof fetch>[0]): string {
@@ -48,16 +57,17 @@ function withBearer(input: Parameters<typeof fetch>[0], init: RequestInit | unde
function boundedImportFetch(
fetcher: typeof fetch,
cancel?: AbortSignal,
- authorization: () => Promise<string | null> = () => skillImportToken(),
+ authorization: () => Promise<SkillImportSignIn> = () => skillImportToken(),
): typeof fetch {
let apiRequests = 0;
let downloads = 0;
let bytes = 0;
- let credential: Promise<string | null> | undefined;
+ let reported = false;
+ let credential: Promise<SkillImportSignIn> | undefined;
const timeout = AbortSignal.timeout(IMPORT_LIMITS.ms);
const signal = cancel ? AbortSignal.any([timeout, cancel]) : timeout;
// `gh auth token` starts a process; a null answer stays null for this import.
- const credentialOnce = (): Promise<string | null> => (credential ??= (async () => authorization())());
+ const credentialOnce = (): Promise<SkillImportSignIn> => (credential ??= (async () => authorization())());
return async (input, init) => {
const api = isGitHubApiRequest(input);
if (api ? ++apiRequests > IMPORT_LIMITS.apiRequests : ++downloads > IMPORT_LIMITS.downloads) {
@@ -65,15 +75,21 @@ function boundedImportFetch(
}
signal.throwIfAborted();
const sent: RequestInit = { ...init, signal };
+ let carried: SkillImportSignIn["refused"];
if (api) {
- const token = await credentialOnce();
- const headers = token ? withBearer(input, init, token) : null;
+ const signIn = await credentialOnce();
+ const headers = signIn.token ? withBearer(input, init, signIn.token) : null;
if (headers) {
sent.headers = headers;
sent.redirect = "error";
+ carried = signIn.refused;
}
}
const response = await fetcher(input, sent);
+ if (carried && response.status === 401 && !reported) {
+ reported = true;
+ carried();
+ }
if (!response.ok) {
await response.body?.cancel().catch(() => {});
return response;
@@ -404,7 +420,7 @@ export async function fetchSkillFromSource(
input: string,
fetcher: typeof fetch = fetch,
cancel?: AbortSignal,
- authorization?: () => Promise<string | null>,
+ authorization?: () => Promise<SkillImportSignIn>,
): Promise<{ skills: FetchedSkill[] } | { error: string }> {
const parsed = parseSkillSource(input);
if ("error" in parsed) return parsed;
@@ -426,7 +442,7 @@ export async function fetchSkillFromSource(
export async function latestSkillCommit(
origin: GitHubSkillOrigin,
fetcher: typeof fetch = fetch,
- authorization?: () => Promise<string | null>,
+ authorization?: () => Promise<SkillImportSignIn>,
): Promise<string | { error: string }> {
try {
return await resolveCommit(origin.owner, origin.repo, origin.ref, boundedImportFetch(fetcher, undefined, authorization));
diff --git a/server/skill-request-card.test.ts b/server/skill-request-card.test.ts
index 68dc66434f..f6f93b0596 100644
--- a/server/skill-request-card.test.ts
+++ b/server/skill-request-card.test.ts
@@ -76,7 +76,7 @@ describe("importedSkillRequest", () => {
{ action: "import", source: "https://github.com/acme/skills/tree/main/skills/pdf" },
fetcher,
undefined,
- async () => token,
+ async () => ({ token }),
);
expect(body).toMatchObject({ action: "create", skill_md: SKILL("pdf") });
const api = calls.filter((call) => call.url.startsWith("https://api.github.com/"));
diff --git a/server/skill-request-card.ts b/server/skill-request-card.ts
index e23dafa8a4..34ae2e3f20 100644
--- a/server/skill-request-card.ts
+++ b/server/skill-request-card.ts
@@ -1,7 +1,7 @@
import { createHash } from "node:crypto";
import { redactSecretsInText } from "./redact.ts";
-import { fetchSkillFromSource } from "./skill-fetch.ts";
+import { fetchSkillFromSource, type SkillImportSignIn } from "./skill-fetch.ts";
import { isSkillReferencePath, MAX_SKILL_REFERENCES, STAGED_SKILL_REFERENCE_MAX_BYTES } from "./skill-storage.ts";
import { listSkills, readSkillFile, readSkillReferences, STAGED_GIST_MAX } from "./skills.ts";
import type { SkillRequestCardData } from "../shared/skill-request.ts";
@@ -60,7 +60,7 @@ export async function importedSkillRequest<T extends Record<string, unknown>>(
body: T,
fetcher: typeof fetch = fetch,
cancel?: AbortSignal,
- authorization?: () => Promise<string | null>,
+ authorization?: () => Promise<SkillImportSignIn>,
): Promise<T | { importError: string }> {
if (body.action !== "import") return body;
const source = typeof body.source === "string" ? body.source.trim() : "";