diff --git a/src/core/GitHubUtils.ts b/src/core/GitHubUtils.ts index b4df516..45adaea 100644 --- a/src/core/GitHubUtils.ts +++ b/src/core/GitHubUtils.ts @@ -5,7 +5,7 @@ import { refreshLegacyToken } from "./legacy-token-refresh"; import { notifyOwnerAccessProblem } from "./owner-notifications"; import AnonymizedRepositoryModel from "./model/anonymizedRepositories/anonymizedRepositories.model"; import { isConnected } from "../server/database"; -import { githubQuotaKey, githubTokenContext } from "./github-token-context"; +import { githubQuotaKey, githubTokenContext, PUBLIC_CDN_TOKEN } from "./github-token-context"; import { boundAppToken } from "./github-app"; import { Octokit } from "@octokit/rest"; import { throttling } from "@octokit/plugin-throttling"; @@ -207,6 +207,8 @@ const invalidCredentials = new InvalidCredentialBackoff(); export function octokit(token: string) { const context = githubTokenContext(token); + // The REST API needs the owner's own access; the CDN token only reads public files. + if (context?.cdnOnly) throw ownerGitHubAccessRequired(); const oct = new ThrottledOctokit({ // Managed App tokens are supplied by the renewal hook. Octokit's static // token strategy would otherwise overwrite the renewed Authorization header. @@ -316,7 +318,7 @@ export async function checkToken(token: string) { const checkedRepositoryTokens = new WeakMap(); -/** Content is fetched only with its owner's own GitHub access, never a shared operator token. */ +/** Owner access is required; a shared operator token is never used instead. */ export function ownerGitHubAccessRequired() { return new AnonymousError("token_expired", { httpStatus: 401 }); } @@ -365,11 +367,12 @@ async function resolveRepositoryToken(repository: Repository) { checkedRepositoryTokens.set(repository, ownerAccessToken); return ownerAccessToken; } - throw ownerGitHubAccessRequired(); + void notifyOwnerAccessProblem(repository.owner.id, "token_expired", { kind: "repository", id: String(repository.model._id) }); + return PUBLIC_CDN_TOKEN; } const token = await getCredentialToken(repository.owner.id, "github", { collection: "anonymizedrepositories", id: repository.model._id, }); - if (!token) throw ownerGitHubAccessRequired(); - return token; + // Without owner access, public files are still served through jsDelivr. + return token || PUBLIC_CDN_TOKEN; } diff --git a/src/core/github-token-context.ts b/src/core/github-token-context.ts index 9f9c6f3..ca7818b 100644 --- a/src/core/github-token-context.ts +++ b/src/core/github-token-context.ts @@ -1,12 +1,21 @@ import { createHash } from "crypto"; -interface TokenContext { quotaKey: string; renew: (force?: boolean) => Promise; publicRepository?: string; } +// cdnOnly means public content is read from jsDelivr, never from the GitHub API. +interface TokenContext { quotaKey: string; renew: (force?: boolean) => Promise; publicRepository?: string; cdnOnly?: boolean; } const contexts = new Map(); export function registerGitHubToken(token: string, context: TokenContext) { if (contexts.size >= 2000 && !contexts.has(token)) contexts.delete(contexts.keys().next().value!); contexts.set(token, context); } +/** + * Used when an owner has no usable GitHub access. It carries no secret and is + * recognized by every process, so the API can pass it to the streamer as is. + * jsDelivr only mirrors public repositories, so private content is never exposed. + */ +export const PUBLIC_CDN_TOKEN = "public-cdn"; +const publicCdnContext: TokenContext = { quotaKey: "public-cdn", cdnOnly: true, renew: async () => "" }; export function githubTokenContext(token: string) { + if (token === PUBLIC_CDN_TOKEN) return publicCdnContext; const context = contexts.get(token); if (!context && token.startsWith("public-read:")) throw new Error("Public repository access context expired"); return context; diff --git a/src/core/source/GitHubStream.ts b/src/core/source/GitHubStream.ts index 42d47e0..468e61a 100644 --- a/src/core/source/GitHubStream.ts +++ b/src/core/source/GitHubStream.ts @@ -20,7 +20,7 @@ import { basename, dirname } from "path"; import * as stream from "stream"; import AnonymousError from "../AnonymousError"; -import { octokit, waitForTokenGate, RateLimitDelayError } from "../GitHubUtils"; +import { octokit, ownerGitHubAccessRequired, waitForTokenGate, RateLimitDelayError } from "../GitHubUtils"; import { expandSubmodules, validUpstream, MAX_SUBMODULE_ENTRIES } from "./github-submodules"; import { IFile, UpstreamFile } from "../model/files/files.types"; import { createLogger, serializeError } from "../logger"; @@ -79,6 +79,14 @@ export function githubRawFileUrl( )}/raw/${encodeURIComponent(commit)}/${encodedPath}`; } +export function jsDelivrFileUrl(owner: string, repo: string, commit: string, filePath: string): string { + const segments = filePath.split("/"); + // Dot segments would be normalized away and could address another repository. + if (segments.some(segment => !segment || segment === "." || segment === "..")) throw new AnonymousError("invalid_path", { httpStatus: 400 }); + const path = segments.map(segment => encodeURIComponent(segment)).join("/"); + return `https://cdn.jsdelivr.net/gh/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}@${commit}/${path}`; +} + function downloadError(error: Error, filePath: string): AnonymousError { if (error instanceof AnonymousError) return error; if (error instanceof RateLimitDelayError) return new AnonymousError("github_rate_limit_exceeded", { httpStatus: 429, cause: error }); @@ -221,6 +229,19 @@ export default class GitHubStream extends GitHubBase { return output; } + // jsDelivr mirrors public GitHub repositories, so reading through it spends + // no GitHub quota. A commit-pinned URL is immutable, and the shared cache + // still checks the bytes against the Git blob SHA from the stored tree. + private downloadViaJsDelivr(filePath: string): stream.Readable { + const commit = this.data.commit; + if (!commit || !/^[a-f0-9]{40}$/.test(commit)) throw ownerGitHubAccessRequired(); + const url = jsDelivrFileUrl(this.data.organization, this.data.repoName, commit, filePath); + const assertHost = (value: URL) => { + if (value.protocol !== "https:" || value.hostname !== "cdn.jsdelivr.net") throw new AnonymousError("upstream_error", { httpStatus: 502 }); + }; + return got.stream(url, { hooks: { beforeRedirect: [options => { assertHost(options.url); }] } }); + } + private deferredRawDownload(token: string, filePath: string): stream.Readable { let active: stream.Readable | undefined; const download = () => this.downloadFileViaRaw(token, filePath); @@ -241,6 +262,9 @@ export default class GitHubStream extends GitHubBase { sha: string, filePath: string ): Promise { + if (token && githubTokenContext(token)?.cdnOnly) { + return Promise.resolve().then(() => this.downloadViaJsDelivr(filePath)); + } // Public raw downloads need no bearer token and do not consume the // unauthenticated REST API quota. GitHub also resolves LFS pointers here. if (!token || githubTokenContext(token)?.publicRepository) { @@ -573,7 +597,8 @@ export default class GitHubStream extends GitHubBase { finally { clearTimeout(deadline); limited.destroy(); content.destroy(); } return true; }); - return expected.upstream ? await fetchContent() : await this.confirmOwnerAccess(repoId, fetchContent); + // A CDN read says nothing about the owner's access, so it must not clear their access alert. + return expected.upstream || githubTokenContext(token)?.cdnOnly ? await fetchContent() : await this.confirmOwnerAccess(repoId, fetchContent); } catch (error) { if (expected.upstream && error instanceof AnonymousError && ["file_not_found", "file_not_accessible"].includes(error.message)) { diff --git a/src/core/zipStream.ts b/src/core/zipStream.ts index cc06023..851e424 100644 --- a/src/core/zipStream.ts +++ b/src/core/zipStream.ts @@ -1,3 +1,4 @@ +import { githubTokenContext } from "./github-token-context"; import { recordUpstreamFailure, recordResponseFailure } from "./request-evidence"; import got from "got"; import config from "../config"; @@ -86,9 +87,9 @@ export async function streamAnonymizedZip( let response; try { const token = await opt.getToken(); - if (!token) { - // The API already checked public access. Codeload serves public archives - // directly, avoiding the streamer's shared unauthenticated REST quota. + if (!token || githubTokenContext(token)?.cdnOnly) { + // Public archives come from codeload, which needs no token and spends no + // REST quota. jsDelivr has no archives; codeload never serves private ones. response = { url: `https://codeload.github.com/${encodeURIComponent(opt.organization)}/${encodeURIComponent(opt.repoName)}/zip/${encodeURIComponent(opt.commit || "HEAD")}` }; } else { const source = new GitHubDownload({ diff --git a/test/credential-migration.test.js b/test/credential-migration.test.js index 4cf9810..bb7f0b4 100644 --- a/test/credential-migration.test.js +++ b/test/credential-migration.test.js @@ -182,13 +182,15 @@ describeMongo("credential access (MongoDB)", function () { const resources = [ new Gist(await GistModel.create({ owner: owner._id, gistId: "no-access-gist", source: { gistId: "no-access" } })), new PullRequest(await PullModel.create({ owner: owner._id, pullRequestId: "no-access-pr", source: { pullRequestId: "2" } })), - new Repository(await RepoModel.create({ owner: owner._id, repoId: "no-access-repo", source: { type: "GitHubStream" } })), + new Repository(await RepoModel.create({ owner: owner._id, repoId: "no-access-repo", source: { type: "GitHubStream", repositoryName: "example/no-access" } })), ]; - for (const resource of resources) { + for (const resource of resources.slice(0, 2)) { const error = await resource.getToken().then(() => null, e => e); expect(error?.message).to.equal("token_expired"); expect(error.httpStatus).to.equal(401); } + // Repository files are still read from jsDelivr when public. + expect(await resources[2].getToken()).to.equal("public-cdn"); } finally { delete process.env.GITHUB_TOKEN; } }); it("refreshes a repository credential without copying it onto the repository", async () => { diff --git a/test/public-cdn-fallback.test.js b/test/public-cdn-fallback.test.js new file mode 100644 index 0000000..e988bae --- /dev/null +++ b/test/public-cdn-fallback.test.js @@ -0,0 +1,45 @@ +const { expect } = require("chai"); +const { Readable } = require("stream"); +const got = require("got"); +const { URL } = require("url"); +require("ts-node/register/transpile-only"); +const { PUBLIC_CDN_TOKEN, githubTokenForStreamer } = require("../src/core/github-token-context"); +const { octokit } = require("../src/core/GitHubUtils"); +const GitHubStream = require("../src/core/source/GitHubStream").default; +const { jsDelivrFileUrl } = require("../src/core/source/GitHubStream"); + +describe("jsDelivr access without owner credentials", function () { + const commit = "a".repeat(40); + let original; + beforeEach(() => { original = got.stream; }); + afterEach(() => { got.stream = original; }); + + it("never reaches the GitHub API and reaches the streamer unchanged", async () => { + let error; try { octokit(PUBLIC_CDN_TOKEN); } catch (e) { error = e; } + expect(error.message).to.equal("token_expired"); expect(error.httpStatus).to.equal(401); + expect(await githubTokenForStreamer(PUBLIC_CDN_TOKEN, "owner/repo")).to.equal(PUBLIC_CDN_TOKEN); + }); + + it("downloads commit-pinned bytes from jsDelivr without any credential", async () => { + const calls = []; + got.stream = (url, options) => { calls.push({ url: String(url), options }); return Readable.from(["public bytes"]); }; + const source = new GitHubStream({ repoId: "r", organization: "owner", repoName: "repo", commit, getToken: () => PUBLIC_CDN_TOKEN }); + const chunks = []; for await (const chunk of await source.downloadWithFallback(PUBLIC_CDN_TOKEN, "blob-sha", "src/a b#.py")) chunks.push(Buffer.from(chunk)); + expect(Buffer.concat(chunks).toString()).to.equal("public bytes"); + expect(calls.map(c => c.url)).to.deep.equal([`https://cdn.jsdelivr.net/gh/owner/repo@${commit}/src/a%20b%23.py`]); + expect(calls[0].options.headers).to.equal(undefined); + expect(() => calls[0].options.hooks.beforeRedirect[0]({ url: new URL("https://evil.example/x") })).to.throw("upstream_error"); + }); + + it("requires a pinned commit so a moving branch is never served", async () => { + got.stream = () => { throw new Error("must not download"); }; + const source = new GitHubStream({ repoId: "r", organization: "owner", repoName: "repo", commit: "main", getToken: () => PUBLIC_CDN_TOKEN }); + const error = await source.downloadWithFallback(PUBLIC_CDN_TOKEN, "blob-sha", "a.py").catch(e => e); + expect(error.message).to.equal("token_expired"); + }); + + it("encodes owner, repository and path segments", () => { + expect(jsDelivrFileUrl("o", "r", commit, "x/%2e")).to.equal(`https://cdn.jsdelivr.net/gh/o/r@${commit}/x/%252e`); + for (const path of ["../x", "a/./b", "a//b", ""]) expect(() => jsDelivrFileUrl("o", "r", commit, path)).to.throw("invalid_path"); + }); +});