From 74d1115bdd5e1c5daac614e87b4e953080d075b4 Mon Sep 17 00:00:00 2001 From: zaniebot <242828183+zaniebot@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:33:45 +0000 Subject: [PATCH] Add the GitHub proxy action --- .github/workflows/test-github-proxy.yml | 35 +++ README.md | 2 + github-proxy/README.md | 73 ++++++ github-proxy/action.yml | 27 +++ github-proxy/action/action.test.js | 294 ++++++++++++++++++++++++ github-proxy/action/main.js | 76 ++++++ github-proxy/action/post.js | 40 ++++ github-proxy/action/validation.js | 27 +++ 8 files changed, 574 insertions(+) create mode 100644 .github/workflows/test-github-proxy.yml create mode 100644 github-proxy/README.md create mode 100644 github-proxy/action.yml create mode 100644 github-proxy/action/action.test.js create mode 100644 github-proxy/action/main.js create mode 100644 github-proxy/action/post.js create mode 100644 github-proxy/action/validation.js diff --git a/.github/workflows/test-github-proxy.yml b/.github/workflows/test-github-proxy.yml new file mode 100644 index 0000000..78ab963 --- /dev/null +++ b/.github/workflows/test-github-proxy.yml @@ -0,0 +1,35 @@ +name: Test GitHub proxy action + +on: + pull_request: + paths: + - github-proxy/** + - .github/workflows/test-github-proxy.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + test: + name: Node 24 (${{ matrix.os }}) + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version: "24" + package-manager-cache: false + - name: Test proxy configuration and revocation + run: node --test github-proxy/action/action.test.js diff --git a/README.md b/README.md index c45e16d..2b28754 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,8 @@ Shared GitHub Actions for Astral projects. - [Simple token service](simple-token-service/): exchange GitHub Actions OIDC tokens for scoped GitHub App installation tokens. +- [GitHub proxy](github-proxy/): configure Git pushes through a branch-scoped proxy + capability. - [Key-value store](key-value-store/): share workflow state within a GitHub Actions OIDC namespace. - [Rust workspace cache](rust-workspace-cache/): cache workspace crates and prune diff --git a/github-proxy/README.md b/github-proxy/README.md new file mode 100644 index 0000000..d524439 --- /dev/null +++ b/github-proxy/README.md @@ -0,0 +1,73 @@ +# GitHub proxy + +Configure a Git remote to push through a GitHub proxy using an encrypted +capability for one repository, branch, and expected previous head. The action sets +a repository-scoped authorization header in the local Git configuration and +changes the remote's push URL. + +Request the capability from a token service deployment that supports +`delivery: github-proxy`. Keep that exchange in a trusted setup job with +`id-token: write`, then pass the capability to a separate reusable workflow as an +explicitly declared secret. See the +[token service action](../simple-token-service/README.md#branch-scoped-proxy-delivery) +for the issuer inputs. + +The receiving workflow can configure its remote as follows: + +```yaml +on: + workflow_call: + secrets: + proxy_capability: + required: true + +permissions: + contents: read + +jobs: + agent: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@ + with: + persist-credentials: false + - uses: astral-sh/github-actions/github-proxy@ + with: + proxy-url: ${{ vars.PROXY_API_URL }} + capability: ${{ secrets.proxy_capability }} + repository: example-org/example-repo + - run: git push origin HEAD:automation/fix-123 +``` + +The push must match the repository, branch, and expected previous head authorized +by the capability. Keep `id-token: write` out of the receiving job: an applicable +service policy could otherwise let it request a raw installation token. Pass the +capability through the declared secret so GitHub masks it before logging action inputs; do not hand it off through +ordinary inputs, environment variables, shell interpolation, or `secrets: inherit`. + +The issuing job leaves the capability output unmasked so GitHub can transfer it +between jobs. Treat it as a bearer credential: never print it or upload it as an +artifact. This action stores it in the checkout's `.git/config`; never archive or +upload `.git`. Use GitHub-hosted or isolated ephemeral runners. + +Pin actions to full commit SHAs. Check out the repository before configuring the +proxy, and use `persist-credentials: false` so checkout does not install a separate +Git credential. + +## Inputs + +| Input | Description | +| ------------ | ---------------------------------------------------------------------------------- | +| `proxy-url` | Required HTTPS origin of the deployed GitHub proxy. | +| `capability` | Required encrypted capability from the token service, passed as a declared secret. | +| `repository` | Required target repository in `OWNER/REPO` form. | +| `remote` | Git remote to configure. Defaults to `origin`. | + +## Outputs + +| Output | Description | +| --------- | ------------------------------------------------------------------ | +| `git-url` | HTTPS push URL for the configured repository, without credentials. | + +The post action attempts to revoke the underlying installation token when the job +finishes, including after a failed step. A failed revocation logs a warning. diff --git a/github-proxy/action.yml b/github-proxy/action.yml new file mode 100644 index 0000000..ff113b5 --- /dev/null +++ b/github-proxy/action.yml @@ -0,0 +1,27 @@ +name: Configure a branch-scoped GitHub proxy +description: Configure Git to push through a short-lived, exact-branch GitHub proxy capability. + +inputs: + proxy-url: + description: HTTPS origin of the deployed GitHub proxy. + required: true + capability: + description: Encrypted branch-scoped capability issued by the token service. + required: true + repository: + description: GitHub repository authorized by the capability, in OWNER/REPO form. + required: true + remote: + description: Git remote whose push URL should use the proxy. + required: false + default: origin + +outputs: + git-url: + description: Credential-free HTTPS push URL for the configured repository. + +runs: + using: node24 + main: action/main.js + post: action/post.js + post-if: always() diff --git a/github-proxy/action/action.test.js b/github-proxy/action/action.test.js new file mode 100644 index 0000000..cfa33d4 --- /dev/null +++ b/github-proxy/action/action.test.js @@ -0,0 +1,294 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const { execFileSync } = require("node:child_process"); +const { mkdtempSync, rmSync } = require("node:fs"); +const { tmpdir } = require("node:os"); +const { join } = require("node:path"); +const test = require("node:test"); + +const { run: runMain } = require("./main.js"); +const { run: runPost } = require("./post.js"); +const { validateCapability } = require("./validation.js"); + +function environment(overrides = {}) { + return { + "INPUT_PROXY-URL": "https://proxy.example", + INPUT_CAPABILITY: "opaque_ciphertext-123", + INPUT_REPOSITORY: "octo/widgets", + INPUT_REMOTE: "origin", + GITHUB_STATE: "state", + GITHUB_OUTPUT: "output", + ...overrides, + }; +} + +test("configures a credential-free push URL and masks the scoped capability", () => { + const calls = []; + const files = new Map(); + const output = []; + runMain({ + env: environment(), + execFile: (command, arguments_) => calls.push([command, arguments_]), + appendFile: (file, value) => files.set(file, `${files.get(file) || ""}${value}`), + write: (value) => output.push(value), + }); + + assert.deepEqual(calls, [ + ["git", ["config", "--local", "--replace-all", "http.https://proxy.example/octo/widgets.git.extraheader", ""]], + ["git", ["config", "--local", "--add", "http.https://proxy.example/octo/widgets.git.extraheader", "AUTHORIZATION: Bearer opaque_ciphertext-123"]], + ["git", ["config", "--local", "http.https://proxy.example/.postBuffer", "4194304"]], + ["git", ["remote", "set-url", "--push", "origin", "https://proxy.example/octo/widgets.git"]], + ]); + assert.deepEqual(output, ["::add-mask::opaque_ciphertext-123\n"]); + assert.match(files.get("output"), /^git-url=https:\/\/proxy.example\/octo\/widgets.git$/mu); + assert.doesNotMatch(files.get("output"), /opaque_ciphertext-123/u); + assert.match(files.get("state"), /^proxyUrl=https:\/\/proxy.example$/mu); + assert.match(files.get("state"), /^capability=opaque_ciphertext-123$/mu); +}); + +test("keeps proxy credentials independent for repositories sharing an origin", (context) => { + const directory = mkdtempSync(join(tmpdir(), "aghs-github-proxy-")); + context.after(() => rmSync(directory, { recursive: true, force: true })); + const execFile = (command, arguments_) => execFileSync(command, arguments_, { + cwd: directory, + encoding: "utf8", + env: { + ...process.env, + GIT_CONFIG_GLOBAL: join(directory, "global.gitconfig"), + GIT_CONFIG_NOSYSTEM: "1", + GIT_CONFIG_COUNT: "0", + }, + }); + const git = (...arguments_) => execFile("git", arguments_).trim(); + git("init", "--quiet"); + git("config", "--local", "http.extraheader", "X-Global: preserved"); + git("config", "--local", "http.https://proxy.example/.extraheader", "X-Origin: preserved"); + + const repositories = [ + { remote: "origin", repository: "octo/widgets", capability: "widgets-capability" }, + { remote: "tools", repository: "octo/tools", capability: "tools-capability" }, + ]; + for (const { remote, repository, capability } of repositories) { + git("remote", "add", remote, `https://github.com/${repository}.git`); + runMain({ + env: environment({ + INPUT_REMOTE: remote, + INPUT_REPOSITORY: repository, + INPUT_CAPABILITY: capability, + GITHUB_STATE: join(directory, `${remote}.state`), + GITHUB_OUTPUT: join(directory, `${remote}.output`), + }), + execFile, + write: () => {}, + }); + } + + for (const { remote, repository, capability } of repositories) { + const gitUrl = `https://proxy.example/${repository}.git`; + assert.equal(git("remote", "get-url", "--push", remote), gitUrl); + for (const suffix of ["", "/info/refs?service=git-receive-pack", "/git-receive-pack"]) { + assert.equal( + git("config", "--get-urlmatch", "http.extraheader", `${gitUrl}${suffix}`), + `AUTHORIZATION: Bearer ${capability}`, + ); + } + assert.equal(git("config", "--get-urlmatch", "http.postBuffer", gitUrl), "4194304"); + } + + for (const repository of ["octo/unconfigured", "octo/widgets.git-backup"]) { + assert.equal( + git("config", "--get-urlmatch", "http.extraheader", `https://proxy.example/${repository}.git`), + "X-Origin: preserved", + ); + } + assert.equal( + git("config", "--get-urlmatch", "http.extraheader", "https://github.com/octo/widgets.git"), + "X-Global: preserved", + ); +}); + +test("records revocation state before Git configuration can fail", () => { + for (const failingCommand of [0, 1, 2, 3]) { + const files = new Map(); + let commandCount = 0; + + assert.throws(() => runMain({ + env: environment(), + execFile: () => { + if (commandCount++ === failingCommand) { + throw new Error("Git command failed with opaque_ciphertext-123"); + } + }, + appendFile: (file, value) => files.set(file, `${files.get(file) || ""}${value}`), + write: () => {}, + }), (error) => { + assert.match(error.message, /unable to configure the GitHub proxy/u); + assert.doesNotMatch(error.message, /opaque_ciphertext-123/u); + return true; + }); + + assert.match(files.get("state"), /^proxyUrl=https:\/\/proxy.example$/mu); + assert.match(files.get("state"), /^capability=opaque_ciphertext-123$/mu); + assert.equal(files.has("output"), false); + } +}); + +test("rejects unsafe proxy URLs, repositories, remotes, and capabilities", () => { + for (const overrides of [ + { "INPUT_PROXY-URL": "http://proxy.example" }, + { "INPUT_PROXY-URL": "https://proxy.example@attacker.example" }, + { "INPUT_PROXY-URL": "https://proxy.example/path" }, + { "INPUT_PROXY-URL": "https://proxy.example//" }, + { "INPUT_PROXY-URL": "https://proxy.example?query=1" }, + { "INPUT_PROXY-URL": "https://proxy.example#fragment" }, + { INPUT_REPOSITORY: "../widgets" }, + { INPUT_REPOSITORY: `${"a".repeat(40)}/widgets` }, + { INPUT_REPOSITORY: `octo/${"a".repeat(101)}` }, + { INPUT_REMOTE: "--upload-pack=evil" }, + { INPUT_REMOTE: "." }, + { INPUT_REMOTE: ".." }, + { INPUT_REMOTE: ".hidden" }, + { INPUT_REMOTE: "origin." }, + { INPUT_REMOTE: "origin..invalid" }, + { INPUT_REMOTE: "origin.lock" }, + { INPUT_CAPABILITY: "bad token" }, + { INPUT_CAPABILITY: "a".repeat(8192 + 1) }, + ]) { + assert.throws(() => runMain({ + env: environment(overrides), + execFile: () => {}, + appendFile: () => {}, + write: () => {}, + })); + } +}); + +test("limits capabilities to the proxy's encoded capability limit", () => { + const largestCapability = "a".repeat(8192); + assert.equal(validateCapability(largestCapability), largestCapability); + assert.throws(() => validateCapability("a".repeat(8192 + 1))); +}); + +test("preserves revocation state when repository or remote validation fails", () => { + for (const overrides of [{ INPUT_REPOSITORY: "../widgets" }, { INPUT_REMOTE: ".." }]) { + const files = new Map(); + assert.throws(() => runMain({ + env: environment(overrides), + execFile: () => assert.fail("Git must not run"), + appendFile: (file, value) => files.set(file, `${files.get(file) || ""}${value}`), + write: () => {}, + })); + assert.match(files.get("state"), /^capability=opaque_ciphertext-123$/mu); + } +}); + +test("revokes the capability in the agent job post step", async () => { + const calls = []; + const signals = []; + const signal = {}; + await runPost({ + env: { + "INPUT_PROXY-URL": "https://proxy.example/", + STATE_proxyUrl: "https://proxy.example", + STATE_capability: "opaque", + }, + fetchImpl: async (url, options) => { + calls.push({ url, options }); + return { ok: true, status: 204 }; + }, + makeTimeoutSignal: (delay) => { + signals.push(delay); + return signal; + }, + }); + + assert.deepEqual(signals, [30_000]); + assert.deepEqual(calls, [{ + url: "https://proxy.example/session", + options: { + method: "DELETE", + headers: { authorization: "Bearer opaque" }, + redirect: "error", + signal, + }, + }]); +}); + +test("reports revocation failures without failing cleanup", async () => { + const warnings = []; + await runPost({ + env: { + "INPUT_PROXY-URL": "https://proxy.example", + STATE_proxyUrl: "https://proxy.example", + STATE_capability: "opaque", + }, + fetchImpl: async () => ({ ok: false, status: 502 }), + warn: (message) => warnings.push(message), + }); + assert.match(warnings[0], /request failed \(502\)/u); +}); + +test("reports timed out revocation without failing cleanup", async () => { + const warnings = []; + await runPost({ + env: { + "INPUT_PROXY-URL": "https://proxy.example", + STATE_proxyUrl: "https://proxy.example", + STATE_capability: "opaque", + }, + fetchImpl: async () => { + throw new Error("revocation timed out"); + }, + makeTimeoutSignal: () => ({}), + warn: (message) => warnings.push(message), + }); + assert.equal(warnings.length, 1); + assert.match(warnings[0], /revocation timed out/u); +}); + +test("refuses to send a capability when revocation state is invalid", async () => { + for (const env of [ + { + "INPUT_PROXY-URL": "https://proxy.example", + STATE_proxyUrl: "http://attacker.example", + STATE_capability: "opaque", + }, + { + "INPUT_PROXY-URL": "https://proxy.example", + STATE_proxyUrl: "https://proxy.example/another-path", + STATE_capability: "opaque", + }, + { + "INPUT_PROXY-URL": "https://proxy.example", + STATE_proxyUrl: "https://attacker.example", + STATE_capability: "opaque", + }, + { + "INPUT_PROXY-URL": "https://proxy.example", + STATE_proxyUrl: "https://proxy.example", + STATE_capability: "bad token", + }, + ]) { + const warnings = []; + await runPost({ + env, + fetchImpl: () => assert.fail("invalid state must not trigger a request"), + warn: (message) => warnings.push(message), + }); + assert.equal(warnings.length, 1); + } +}); + +test("skips revocation when setup did not persist complete state", async () => { + for (const env of [ + {}, + { STATE_proxyUrl: "https://proxy.example" }, + { STATE_capability: "opaque" }, + ]) { + await runPost({ + env, + fetchImpl: () => assert.fail("incomplete state must not trigger a request"), + }); + } +}); diff --git a/github-proxy/action/main.js b/github-proxy/action/main.js new file mode 100644 index 0000000..f260f1c --- /dev/null +++ b/github-proxy/action/main.js @@ -0,0 +1,76 @@ +"use strict"; + +const { execFileSync } = require("node:child_process"); +const { appendFileSync } = require("node:fs"); + +const { validateCapability, validateProxyUrl } = require("./validation.js"); + +function fileCommand(file, name, value, appendFile = appendFileSync) { + if (!file || /[\r\n]/u.test(value)) { + throw new Error(`invalid GitHub Actions value for ${name}`); + } + appendFile(file, `${name}=${value}\n`); +} + +function runGit(execFile, arguments_, description) { + try { + execFile("git", arguments_); + } catch { + throw new Error(`unable to configure the GitHub proxy: ${description}`); + } +} + +function run({ + env = process.env, + execFile = execFileSync, + appendFile = appendFileSync, + write = process.stdout.write.bind(process.stdout), +} = {}) { + const root = validateProxyUrl(env["INPUT_PROXY-URL"]); + const capability = validateCapability(env.INPUT_CAPABILITY || ""); + + write(`::add-mask::${capability}\n`); + fileCommand(env.GITHUB_STATE, "proxyUrl", root, appendFile); + fileCommand(env.GITHUB_STATE, "capability", capability, appendFile); + + const repository = env.INPUT_REPOSITORY || ""; + const repositoryParts = repository.split("/"); + if (repositoryParts.length !== 2 || repositoryParts.some((part, index) => ( + !/^[A-Za-z0-9_.-]+$/u.test(part) || + part.length > (index === 0 ? 39 : 100) || + part === "." || + part === ".." + ))) { + throw new Error("repository must be OWNER/REPO"); + } + const remote = env.INPUT_REMOTE || "origin"; + if ( + !/^[A-Za-z0-9_.-]+$/u.test(remote) || + remote.startsWith("-") || + remote.startsWith(".") || + remote.endsWith(".") || + remote.endsWith(".lock") || + remote.includes("..") + ) { + throw new Error("remote must be a safe Git remote name"); + } + + const gitUrl = `${root}/${repository}.git`; + const authorizationKey = `http.${gitUrl}.extraheader`; + runGit(execFile, ["config", "--local", "--replace-all", authorizationKey, ""], "authorization reset"); + runGit(execFile, ["config", "--local", "--add", authorizationKey, `AUTHORIZATION: Bearer ${capability}`], "authorization"); + runGit(execFile, ["config", "--local", `http.${root}/.postBuffer`, "4194304"], "push buffering"); + runGit(execFile, ["remote", "set-url", "--push", remote, gitUrl], "push URL"); + fileCommand(env.GITHUB_OUTPUT, "git-url", gitUrl, appendFile); +} + +if (require.main === module) { + try { + run(); + } catch (error) { + console.error(error.message); + process.exitCode = 1; + } +} + +module.exports = { run }; diff --git a/github-proxy/action/post.js b/github-proxy/action/post.js new file mode 100644 index 0000000..fc15b43 --- /dev/null +++ b/github-proxy/action/post.js @@ -0,0 +1,40 @@ +"use strict"; + +const { validateCapability, validateProxyUrl } = require("./validation.js"); + +const REVOCATION_TIMEOUT_MS = 30_000; + +async function run({ + env = process.env, + fetchImpl = globalThis.fetch, + makeTimeoutSignal = (delay) => AbortSignal.timeout(delay), + warn = console.warn, +} = {}) { + if (!env.STATE_proxyUrl || !env.STATE_capability) { + return; + } + try { + const proxyUrl = validateProxyUrl(env.STATE_proxyUrl); + if (proxyUrl !== validateProxyUrl(env["INPUT_PROXY-URL"])) { + throw new Error("saved proxy URL does not match the action input"); + } + const capability = validateCapability(env.STATE_capability); + const response = await fetchImpl(`${proxyUrl}/session`, { + method: "DELETE", + headers: { authorization: `Bearer ${capability}` }, + redirect: "error", + signal: makeTimeoutSignal(REVOCATION_TIMEOUT_MS), + }); + if (!response.ok) { + throw new Error(`request failed (${response.status})`); + } + } catch (error) { + warn(`Unable to revoke the GitHub proxy capability: ${error.message}`); + } +} + +if (require.main === module) { + run().catch((error) => console.warn(error.message)); +} + +module.exports = { run }; diff --git a/github-proxy/action/validation.js b/github-proxy/action/validation.js new file mode 100644 index 0000000..f0f784d --- /dev/null +++ b/github-proxy/action/validation.js @@ -0,0 +1,27 @@ +"use strict"; + +const MAX_CAPABILITY_LENGTH = 8192; + +function validateProxyUrl(value) { + const proxyUrl = new URL(value || ""); + if ( + proxyUrl.protocol !== "https:" || + proxyUrl.username || + proxyUrl.password || + proxyUrl.pathname !== "/" || + proxyUrl.search || + proxyUrl.hash + ) { + throw new Error("proxy-url must be a credential-free HTTPS origin"); + } + return proxyUrl.origin; +} + +function validateCapability(value) { + if (!/^[A-Za-z0-9_-]+$/u.test(value) || value.length > MAX_CAPABILITY_LENGTH) { + throw new Error("capability must be an opaque base64url value"); + } + return value; +} + +module.exports = { validateCapability, validateProxyUrl };