diff --git a/README.md b/README.md index c2cb3af..cc46488 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,6 @@ npm i **2. Configure GitHub access** — create a `.env` file: ```env -GITHUB_TOKEN= CLIENT_ID= CLIENT_SECRET= CREDENTIAL_KEYS='{"2026-09":""}' @@ -115,7 +114,7 @@ DB_PASSWORD= AUTH_CALLBACK=http://localhost:5000/github/auth ``` -- `GITHUB_TOKEN` — create one at with the `repo` scope. +- Content is always fetched with the repository owner's own GitHub connection; the server has no shared GitHub token. - `CREDENTIAL_KEYS` / `CREDENTIAL_ACTIVE_KEY_ID` — generate a key with `openssl rand -base64 32`. Existing installations must follow the [credential migration guide](docs/credential-encryption.md) before starting this release. - `CLIENT_ID` / `CLIENT_SECRET` — from an OAuth App at . - The App's callback must be `https:///github/auth` (matching `AUTH_CALLBACK`). diff --git a/src/config.ts b/src/config.ts index 2efef69..0bbc00c 100644 --- a/src/config.ts +++ b/src/config.ts @@ -67,7 +67,6 @@ interface Config { REDIS_HOSTNAME: string; CLIENT_ID: string; CLIENT_SECRET: string; - GITHUB_TOKEN: string; DEFAULT_QUOTA: number; MAX_FILE_FOLDER: number; MAX_FILE_SIZE: number; @@ -181,7 +180,6 @@ const config: Config = { SESSION_SECRET: "", CLIENT_ID: "CLIENT_ID", CLIENT_SECRET: "CLIENT_SECRET", - GITHUB_TOKEN: "", DEFAULT_QUOTA: 2 * 1024 * 1024 * 1024 * 8, MAX_FILE_FOLDER: 1000, MAX_FILE_SIZE: 100 * 1024 * 1024, // in b, 100MB diff --git a/src/core/Gist.ts b/src/core/Gist.ts index e638dc7..064aec9 100644 --- a/src/core/Gist.ts +++ b/src/core/Gist.ts @@ -14,7 +14,7 @@ import AnonymousError from "./AnonymousError"; import { IAnonymizedGistDocument } from "./model/anonymizedGists/anonymizedGists.types"; import AnonymizedGistModel from "./model/anonymizedGists/anonymizedGists.model"; import config from "../config"; -import { octokit } from "./GitHubUtils"; +import { octokit, ownerGitHubAccessRequired } from "./GitHubUtils"; import { ContentAnonimizer } from "./anonymize-utils"; import { createLogger } from "./logger"; @@ -59,8 +59,9 @@ export default class Gist { registerGitHubToken(token, { quotaKey: `app-user:${ownerId}`, renew: () => appUserToken(ownerId) }); return { token, connection: "github-app" }; } - return { token: (await getCredentialToken(this.owner.id, "github", { collection: "anonymizedgists", id: this._model._id })) || config.GITHUB_TOKEN, - connection: "oauth" }; + const token = await getCredentialToken(this.owner.id, "github", { collection: "anonymizedgists", id: this._model._id }); + if (!token) throw ownerGitHubAccessRequired(); + return { token, connection: "oauth" }; } async getToken() { diff --git a/src/core/GitHubUtils.ts b/src/core/GitHubUtils.ts index 8f63839..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,6 +318,11 @@ export async function checkToken(token: string) { const checkedRepositoryTokens = new WeakMap(); +/** Owner access is required; a shared operator token is never used instead. */ +export function ownerGitHubAccessRequired() { + return new AnonymousError("token_expired", { httpStatus: 401 }); +} + export async function getToken(repository: Repository) { try { return await measureStage("credential_resolution", () => resolveRepositoryToken(repository)); @@ -361,9 +368,11 @@ async function resolveRepositoryToken(repository: Repository) { return ownerAccessToken; } void notifyOwnerAccessProblem(repository.owner.id, "token_expired", { kind: "repository", id: String(repository.model._id) }); - return config.GITHUB_TOKEN; + return PUBLIC_CDN_TOKEN; } - return (await getCredentialToken(repository.owner.id, "github", { + const token = await getCredentialToken(repository.owner.id, "github", { collection: "anonymizedrepositories", id: repository.model._id, - })) || config.GITHUB_TOKEN; + }); + // Without owner access, public files are still served through jsDelivr. + return token || PUBLIC_CDN_TOKEN; } diff --git a/src/core/PullRequest.ts b/src/core/PullRequest.ts index 3662479..2c64c34 100644 --- a/src/core/PullRequest.ts +++ b/src/core/PullRequest.ts @@ -11,8 +11,7 @@ import ConferenceModel from "./model/conference/conferences.model"; import AnonymousError from "./AnonymousError"; import { IAnonymizedPullRequestDocument } from "./model/anonymizedPullRequests/anonymizedPullRequests.types"; import AnonymizedPullRequestModel from "./model/anonymizedPullRequests/anonymizedPullRequests.model"; -import config from "../config"; -import { octokit } from "./GitHubUtils"; +import { octokit, ownerGitHubAccessRequired } from "./GitHubUtils"; import { ContentAnonimizer } from "./anonymize-utils"; import { createLogger } from "./logger"; @@ -30,7 +29,9 @@ export default class PullRequest { async getToken() { if (this._model.githubAccess?.kind === "github-app") return boundAppToken(this.owner.id, this._model.githubAccess, this._model.source.repositoryFullName); - return (await getCredentialToken(this.owner.id, "github", { collection: "anonymizedpullrequests", id: this._model._id })) || config.GITHUB_TOKEN; + const token = await getCredentialToken(this.owner.id, "github", { collection: "anonymizedpullrequests", id: this._model._id }); + if (!token) throw ownerGitHubAccessRequired(); + return token; } async download() { diff --git a/src/core/Repository.ts b/src/core/Repository.ts index 0b48dec..a5d1f22 100644 --- a/src/core/Repository.ts +++ b/src/core/Repository.ts @@ -39,6 +39,7 @@ import { } from "./source/GitHubRepository"; import { getToken } from "./GitHubUtils"; import config from "../config"; +import { PUBLIC_CDN_TOKEN } from "./github-token-context"; import FileModel from "./model/files/files.model"; import AnonymizedRepositoryModel from "./model/anonymizedRepositories/anonymizedRepositories.model"; import { createLogger, serializeError } from "./logger"; @@ -737,6 +738,9 @@ export default class Repository { // Only GitHubBase can be update for the moment if (this.source instanceof GitHubBase) { const token = await this.getToken(); + // Without owner access the stored tree is still served through the CDN; + // a reviewer visit must not fail on an update that needs the GitHub API. + if (!opt?.force && token === PUBLIC_CDN_TOKEN) return; const ghRepo = await getRepositoryFromGitHub({ accessToken: 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/legacy-token-refresh.ts b/src/core/legacy-token-refresh.ts index b2721c9..4e89d9a 100644 --- a/src/core/legacy-token-refresh.ts +++ b/src/core/legacy-token-refresh.ts @@ -32,7 +32,7 @@ export async function refreshLegacyToken(ownerId: string, previous: string): Pro const body = await res.json().catch(() => null) as { token?: unknown } | null; if (typeof body?.token === "string" && body.token.length) { if (await replaceCredential(ownerId, previous, body.token)) return body.token; - return (await getCredentialToken(ownerId)) || config.GITHUB_TOKEN; + return getCredentialToken(ownerId); } } else { // Release the response connection even when only the status matters. diff --git a/src/core/source/GitHubStream.ts b/src/core/source/GitHubStream.ts index 42d47e0..7b95473 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,39 @@ export function githubRawFileUrl( )}/raw/${encodeURIComponent(commit)}/${encodedPath}`; } +const LFS_POINTER = "version https://git-lfs.github.com/spec/"; + +// Yields the content unchanged, but fails with upstream_error when it is a Git LFS pointer. +async function* lfsPointerGuard(input: AsyncIterable) { + let probe = Buffer.alloc(0); + let checked = false; + for await (const chunk of input) { + if (checked) { yield chunk; continue; } + probe = Buffer.concat([probe, Buffer.from(chunk)]); + if (probe.length < 150) continue; + if (probe.toString("utf8").startsWith(LFS_POINTER)) throw new AnonymousError("upstream_error", { httpStatus: 502 }); + checked = true; yield probe; + } + if (!checked && probe.length) { + if (probe.toString("utf8").startsWith(LFS_POINTER)) throw new AnonymousError("upstream_error", { httpStatus: 502 }); + yield probe; + } +} + +function rejectLfsPointer(input: stream.Readable): stream.Readable { + const output = stream.Readable.from(lfsPointerGuard(input), { objectMode: false }); + stopSourceOnDestroy(output, () => input.destroy()); + return output; +} + +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 }); @@ -198,29 +231,28 @@ export default class GitHubStream extends GitHubBase { active = got.stream(metadata.download_url, { hooks: { beforeRedirect: [options => { assertDownloadUrl(options.url); }] }, }); - let probe = Buffer.alloc(0); - let checked = false; - for await (const chunk of active) { - if (checked) { yield chunk; continue; } - probe = Buffer.concat([probe, Buffer.from(chunk)]); - if (probe.length < 150) continue; - if (probe.toString("utf8").startsWith("version https://git-lfs.github.com/spec/")) { - throw new AnonymousError("upstream_error", { httpStatus: 502 }); - } - checked = true; yield probe; - } - if (!checked && probe.length) { - if (probe.toString("utf8").startsWith("version https://git-lfs.github.com/spec/")) { - throw new AnonymousError("upstream_error", { httpStatus: 502 }); - } - yield probe; - } + yield* lfsPointerGuard(active); } })(), { objectMode: false }); stopSourceOnDestroy(output, () => { cancellation.abort(); active?.destroy(); }); 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 + // checks the bytes against the Git blob SHA from the stored tree. jsDelivr + // does not resolve Git LFS, and a pointer matches its blob SHA, so pointers + // are refused rather than served or cached as the file. + 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 rejectLfsPointer(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 +273,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 +608,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 9947af6..bb7f0b4 100644 --- a/test/credential-migration.test.js +++ b/test/credential-migration.test.js @@ -173,6 +173,26 @@ describeMongo("credential access (MongoDB)", function () { expect((await GistModel.collection.findOne({ _id: gist.model._id })).source.accessToken).to.equal(undefined); expect((await PullModel.collection.findOne({ _id: pull.model._id })).source.accessToken).to.equal(undefined); }); + it("never borrows a shared operator token when the owner has no GitHub access", async () => { + const Gist = require("../src/core/Gist").default; + const PullRequest = require("../src/core/PullRequest").default; + const Repository = require("../src/core/Repository").default; + process.env.GITHUB_TOKEN = "operator-token"; + try { + 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", repositoryName: "example/no-access" } })), + ]; + 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 () => { const Repository = require("../src/core/Repository").default; const repo = new Repository(await RepoModel.create({ owner: owner._id, repoId: "test-repo", source: { type: "GitHubStream" } })); diff --git a/test/public-cdn-fallback.test.js b/test/public-cdn-fallback.test.js new file mode 100644 index 0000000..abebfc0 --- /dev/null +++ b/test/public-cdn-fallback.test.js @@ -0,0 +1,63 @@ +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("refuses Git LFS pointers, which jsDelivr serves instead of the file", async () => { + const pointer = "version https://git-lfs.github.com/spec/v1\noid sha256:" + "b".repeat(64) + "\nsize 123\n"; + got.stream = () => Readable.from([pointer]); + const source = new GitHubStream({ repoId: "r", organization: "owner", repoName: "repo", commit, getToken: () => PUBLIC_CDN_TOKEN }); + const error = await (async () => { for await (const _ of await source.downloadWithFallback(PUBLIC_CDN_TOKEN, "blob-sha", "big.bin")) void _; })().catch(e => e); + expect(error.message).to.equal("upstream_error"); + }); + + it("skips the automatic refresh, which needs the GitHub API", async () => { + const Repository = require("../src/core/Repository").default; + const GitHubBase = require("../src/core/source/GitHubBase").default; + const repo = Object.create(Repository.prototype); + repo._model = { options: { update: true, expirationMode: "never" }, lastView: new Date(0), source: {} }; + Object.defineProperty(repo, "source", { value: Object.create(GitHubBase.prototype) }); + repo.getToken = async () => PUBLIC_CDN_TOKEN; + await repo.refreshIfNeeded(); + }); + + 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"); + }); +});