Diffinery

homeflare/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

Deploy: take the GitHub App's IDs from repository variables

GitHub runners need GITHUB_APP_ID, GITHUB_APP_SLUG and GITHUB_APP_CLIENT_ID
in the Worker's vars, and a deploy rebuilds the vars from wrangler.jsonc, so
values set any other way are lost on the next deploy. They are the instance's
own, like its hostname, so render-config.mjs now takes them (and
GITHUB_APP_URL) from the environment, and the Deploy workflow passes the
DIFFINERY_GITHUB_APP_* repository variables (GitHub refuses variable names
that start with GITHUB_). A value of the wrong shape stops the deploy without
printing it, in case a secret went into the wrong variable.
altug authored 1 parent 43d30bdcommit 2fcd39d933f8beaadc0ed957fe580887bddf286aBrowse files
6 files changed+125−10
Files (6)
modified.github/workflows/deploy.yml+7−0View file
@@ -7,6 +7,8 @@
77 # DIFFINERY_ZONE the Cloudflare zone for the route (default: the domain's last two labels)
88 # MAIL_DOMAIN sends from notifications@<MAIL_DOMAIN> (default DIFFINERY_DOMAIN)
99 # ACCESS_TEAM_DOMAIN e.g. example.cloudflareaccess.com
10+# DIFFINERY_GITHUB_APP_ID, DIFFINERY_GITHUB_APP_SLUG, DIFFINERY_GITHUB_APP_CLIENT_ID,
11+# DIFFINERY_GITHUB_APP_URL the GitHub App of GitHub runners (docs/self-hosting/configuration.md)
1012 #
1113 # It deploys a main commit only once CI (typecheck, unit tests and the Worker bundle) has
1214 # passed on it, so it doesn't run those itself. End-to-end tests run alongside the deploy.
@@ -77,6 +79,11 @@
7779 ACCESS_TEAM_DOMAIN: ${{ vars.ACCESS_TEAM_DOMAIN }}
7880 # Who becomes site administrator on first sign-in. Unset keeps the deployed Worker's list (scripts/bootstrap-admins.sh).
7981 BOOTSTRAP_ADMINS: ${{ vars.BOOTSTRAP_ADMINS }}
82+ # The GitHub App's IDs, for scripts/render-config.mjs. Repository variables can't start with GITHUB_.
83+ GITHUB_APP_ID: ${{ vars.DIFFINERY_GITHUB_APP_ID }}
84+ GITHUB_APP_SLUG: ${{ vars.DIFFINERY_GITHUB_APP_SLUG }}
85+ GITHUB_APP_CLIENT_ID: ${{ vars.DIFFINERY_GITHUB_APP_CLIENT_ID }}
86+ GITHUB_APP_URL: ${{ vars.DIFFINERY_GITHUB_APP_URL }}
8087 steps:
8188 - uses: actions/checkout@v4
8289 with:
modifiedapps/diffinery/docs/self-hosting/configuration.md+16−7View file
@@ -37,7 +37,7 @@
3737 | `HOSTED_JOBS_LIMIT` | Not set | No | Hosted Actions jobs the whole instance runs at once (default `80`); one account runs at most half of them, accounts run by a site administrator included. Keep it under the runner container classes' `max_instances`. Past it, hosted jobs wait as queued until one finishes. See [Limits](/docs/reference/limits#actions). |
3838 | `IMPORT_GHE_HOST` | Not set | No | The host name of a GitHub Enterprise Server (like `ghe.example.com`) that imports may download release assets from. Without it, imports download release assets only from github.com and its asset hosts, and assets of an Enterprise import are skipped with a warning. |
3939 | `GITHUB_OAUTH_CLIENT_ID` | Not set | No | The client ID of a GitHub OAuth app, for linking GitHub accounts with a GitHub sign-in instead of a gist. Needs `GITHUB_OAUTH_CLIENT_SECRET` too. See [GitHub imports](#github-imports). |
40-| `GITHUB_APP_ID`, `GITHUB_APP_SLUG`, `GITHUB_APP_CLIENT_ID` | Not set | No | The GitHub App that lets GitHub repositories run jobs on this instance's hosted runners: its App ID, its slug (the last part of `https://github.com/apps/<slug>`) and its Client ID. Needs `GITHUB_APP_CLIENT_SECRET`, `GITHUB_APP_PRIVATE_KEY` and `GITHUB_APP_WEBHOOK_SECRET` too. See [GitHub runners](#github-runners). |
40+| `GITHUB_APP_ID`, `GITHUB_APP_SLUG`, `GITHUB_APP_CLIENT_ID` | Not set | No | The GitHub App that lets GitHub repositories run jobs on this instance's hosted runners: its App ID, its slug (the last part of `https://github.com/apps/<slug>`) and its Client ID. Needs `GITHUB_APP_CLIENT_SECRET`, `GITHUB_APP_PRIVATE_KEY` and `GITHUB_APP_WEBHOOK_SECRET` too. The deploy sets them from the environment (the Deploy workflow from the `DIFFINERY_GITHUB_APP_*` repository variables). See [GitHub runners](#github-runners). |
4141 | `GITHUB_APP_URL` | Not set | No | The origin of a GitHub Enterprise Server for that app, like `https://ghe.example.com`. Default `https://github.com`. |
4242 | `IMPORT_GIT_AGENT` | Not set in production; `external` in the `dev` environment | Never in production | With `external`, an import's Git transfer doesn't start a container: it waits for an import agent started by hand (see [The dev environment](#the-dev-environment)). |
4343 | `SCHEDULE_TICK_MINUTES` | Not set | No | Minutes between the workflow scheduler's checks, a whole number from 1 to 60. Default `5`, GitHub's shortest schedule interval. Anything else counts as not set. The end-to-end tests use `1`. |
@@ -377,16 +377,25 @@
377377 | **Subscribe to events** | **Workflow job** |
378378 | **Where can this GitHub App be installed?** | **Any account** to let anyone with an account on your instance use it; **Only on this account** for your own repositories only |
379379
380-Then, on the app's page: note the **App ID** and the **Client ID**, click **Generate a new client secret**, and under **Private keys** click **Generate a private key**, which downloads a `.pem` file. Add the IDs and the slug under `vars` in `wrangler.jsonc`:
380+Then, on the app's page: note the **App ID** and the **Client ID**, click **Generate a new client secret**, and under **Private keys** click **Generate a private key**, which downloads a `.pem` file.
381381
382-```jsonc
383-"GITHUB_APP_ID": "123456",
384-"GITHUB_APP_SLUG": "diffinery-runners-for-git-example-com",
385-"GITHUB_APP_CLIENT_ID": "Iv23li...",
382+Give the deploy the IDs and the slug (the last part of `https://github.com/apps/<slug>`). They aren't secrets, but they are your instance's, so the deploy takes them from the environment, like your hostname, and `scripts/render-config.mjs` writes them into the deployed config:
383+
384+| Deploy from | Set |
385+| --- | --- |
386+| The Deploy workflow | Repository variables `DIFFINERY_GITHUB_APP_ID`, `DIFFINERY_GITHUB_APP_SLUG` and `DIFFINERY_GITHUB_APP_CLIENT_ID` (and `DIFFINERY_GITHUB_APP_URL` for GitHub Enterprise Server). GitHub doesn't allow variable names that start with `GITHUB_`, so the workflow passes them on as `GITHUB_APP_ID` and the rest. |
387+| `scripts/setup.sh` | The environment variables `GITHUB_APP_ID`, `GITHUB_APP_SLUG` and `GITHUB_APP_CLIENT_ID` (and `GITHUB_APP_URL`). |
388+
389+```sh
390+gh variable set DIFFINERY_GITHUB_APP_ID --body 123456
391+gh variable set DIFFINERY_GITHUB_APP_SLUG --body diffinery-runners-for-git-example-com
392+gh variable set DIFFINERY_GITHUB_APP_CLIENT_ID --body Iv23li...
386393 ```
387394
388-and store the secrets:
395+A value of the wrong shape, such as a slug with capital letters, stops the deploy with `GITHUB_APP_SLUG must be the slug, like diffinery-runners`. You can put them under `vars` in your copy's `wrangler.jsonc` instead; the environment wins when it has them.
389396
397+Then store the secrets:
398+
390399 ```sh
391400 cd apps/diffinery
392401 printf '%s' "$CLIENT_SECRET" | pnpm exec wrangler secret put GITHUB_APP_CLIENT_SECRET -c wrangler.deploy.jsonc
modifiedapps/diffinery/docs/self-hosting/deploy.md+6−1View file
@@ -110,6 +110,7 @@
110110 | `DIFFINERY_ZONE` | Variable, optional | The Cloudflare zone that holds the hostname, when it isn't the hostname's last two labels. |
111111 | `MAIL_DOMAIN` | Variable, optional | The domain email is sent from, when it isn't `DIFFINERY_DOMAIN`. |
112112 | `ACCESS_TEAM_DOMAIN` | Variable, optional | Your Zero Trust team domain, for example `example.cloudflareaccess.com`. Needed only when the token can't read it. |
113+| `DIFFINERY_GITHUB_APP_ID`, `DIFFINERY_GITHUB_APP_SLUG`, `DIFFINERY_GITHUB_APP_CLIENT_ID`, `DIFFINERY_GITHUB_APP_URL` | Variables, optional | The GitHub App of [GitHub runners](/docs/self-hosting/configuration#github-runners). The workflow passes them to render-config as `GITHUB_APP_ID` and the rest. |
113114
114115 The Deploy job runs in an environment named `production`, so you can also store the secrets as environment secrets there and add required reviewers to that environment.
115116
@@ -165,8 +166,12 @@
165166 | `--mail-from <address>` | No | Sets `MAIL_FROM`, overriding the `notifications@<hostname>` that `--public-url` sets. |
166167 | `--admins <emails>` | No | Sets `BOOTSTRAP_ADMINS` to the comma-separated emails, trimmed. An empty value sets it empty; without the flag, the value in `wrangler.jsonc` stays. An entry that isn't an email address stops the script with `--admins takes comma-separated email addresses; not an email address: ...`. |
167168
168-It also reads two environment variables: `RUNNER_IMAGE` (set by `scripts/runner-image.sh`) points every container at a prebuilt runner image and sets the `RUNNER_IMAGE` variable, and `TURNSTILE_SITE_KEY` (set by bootstrap from `scripts/turnstile.sh`) sets the `TURNSTILE_SITE_KEY` variable, unless `wrangler.jsonc` already sets one.
169+It also reads these environment variables:
169170
171+- `RUNNER_IMAGE` (set by `scripts/runner-image.sh`) points every container at a prebuilt runner image and sets the `RUNNER_IMAGE` variable.
172+- `TURNSTILE_SITE_KEY` (set by bootstrap from `scripts/turnstile.sh`) sets the `TURNSTILE_SITE_KEY` variable, unless `wrangler.jsonc` already sets one.
173+- `GITHUB_APP_ID`, `GITHUB_APP_SLUG`, `GITHUB_APP_CLIENT_ID` and `GITHUB_APP_URL` set the variables of the same names, for [GitHub runners](/docs/self-hosting/configuration#github-runners). One that is empty leaves the value in `wrangler.jsonc`. A value of the wrong shape stops the script with, for example, `GITHUB_APP_ID must be the App ID, a number`; the message never shows the value.
174+
170175 Without `--public-url`, the route, `PUBLIC_URL` and `MAIL_FROM` stay as they are in `wrangler.jsonc`. Bootstrap always passes `--public-url` and `--mail-from`, so a normal deploy takes them from `DIFFINERY_DOMAIN` and `MAIL_DOMAIN`.
171176
172177 For `DIFFINERY_DOMAIN=git.example.com` and `[email protected]`, the deployed config contains:
addedapps/diffinery/test/unit/deploy-github-app.test.ts+75−0View file
@@ -1,0 +1,75 @@
1+import { spawnSync } from "node:child_process";
2+import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import { afterEach, describe, expect, it } from "vitest";
6+
7+/**
8+ * The GitHub App of GitHub runners on deploy: render-config.mjs takes its IDs from the environment
9+ * (the Deploy workflow maps the DIFFINERY_GITHUB_APP_* repository variables to them), so the
10+ * repository's wrangler.jsonc names no instance's app.
11+ */
12+
13+const repo = new URL("../../../../", import.meta.url).pathname;
14+const APP = { GITHUB_APP_ID: "1234567", GITHUB_APP_SLUG: "diffinery-runners", GITHUB_APP_CLIENT_ID: "Iv23liAbCdEf", GITHUB_APP_URL: "https://ghe.example.com" };
15+
16+let dir = "";
17+afterEach(() => {
18+ if (dir) rmSync(dir, { recursive: true, force: true });
19+ dir = "";
20+});
21+
22+function tree(wranglerVars: Record<string, string> = {}): void {
23+ dir = mkdtempSync(join(tmpdir(), "github-app-"));
24+ for (const d of ["scripts", "apps/diffinery"]) mkdirSync(join(dir, d), { recursive: true });
25+ for (const f of ["jsonc.mjs", "render-config.mjs"]) copyFileSync(join(repo, "scripts", f), join(dir, "scripts", f));
26+ const cfg = readFileSync(join(repo, "apps/diffinery/wrangler.jsonc"), "utf8");
27+ const vars = Object.entries(wranglerVars).map(([k, v]) => `\n ${JSON.stringify(k)}: ${JSON.stringify(v)},`).join("");
28+ writeFileSync(join(dir, "apps/diffinery/wrangler.jsonc"), cfg.replace(/"vars": \{/, `"vars": {${vars}`));
29+}
30+
31+function render(env: Record<string, string> = {}) {
32+ const r = spawnSync("node", [join(dir, "scripts/render-config.mjs"), "--d1", "db-id", "--public-url", "https://git.example.com"], {
33+ cwd: dir,
34+ encoding: "utf8",
35+ env: { PATH: process.env.PATH, HOME: dir, ...env },
36+ });
37+ const cfg = r.status === 0 ? (JSON.parse(readFileSync(join(dir, "apps/diffinery/wrangler.deploy.jsonc"), "utf8").split("\n").slice(1).join("\n")) as { vars: Record<string, string> }) : null;
38+ return { status: r.status, stderr: r.stderr, vars: cfg?.vars ?? null };
39+}
40+
41+describe("scripts/render-config.mjs and the GitHub App", () => {
42+ it("sets the app's IDs from the environment, trimmed", () => {
43+ tree();
44+ const { vars } = render({ ...APP, GITHUB_APP_SLUG: " diffinery-runners\n" });
45+ expect(vars).toMatchObject(APP);
46+ });
47+
48+ it("leaves them out without the environment: the repository's wrangler.jsonc has none, so the feature is off", () => {
49+ tree();
50+ const { vars } = render({ GITHUB_APP_ID: "", GITHUB_APP_SLUG: "" });
51+ for (const key of Object.keys(APP)) expect(vars).not.toHaveProperty(key);
52+ });
53+
54+ it("keeps a copy's own wrangler.jsonc values when the environment has none, and the environment wins over them", () => {
55+ tree({ GITHUB_APP_ID: "42", GITHUB_APP_SLUG: "own-app" });
56+ expect(render().vars).toMatchObject({ GITHUB_APP_ID: "42", GITHUB_APP_SLUG: "own-app" });
57+ expect(render({ GITHUB_APP_ID: "7" }).vars).toMatchObject({ GITHUB_APP_ID: "7", GITHUB_APP_SLUG: "own-app" });
58+ });
59+
60+ it("refuses a value of the wrong shape without printing it", () => {
61+ tree();
62+ const pem = "-----BEGIN RSA PRIVATE KEY-----\nMIIEsecret\n-----END RSA PRIVATE KEY-----";
63+ for (const [key, value, message] of [
64+ ["GITHUB_APP_ID", pem, "GITHUB_APP_ID must be the App ID, a number"],
65+ ["GITHUB_APP_SLUG", "Diffinery Runners", "GITHUB_APP_SLUG must be the slug"],
66+ ["GITHUB_APP_CLIENT_ID", "Iv23li with space", "GITHUB_APP_CLIENT_ID must be the Client ID"],
67+ ["GITHUB_APP_URL", "https://ghe.example.com/api/v3", "GITHUB_APP_URL must be an https origin"],
68+ ] as const) {
69+ const r = render({ [key]: value });
70+ expect(r.status).not.toBe(0);
71+ expect(r.stderr).toContain(message);
72+ expect(r.stderr).not.toContain(value);
73+ }
74+ });
75+});
modifiedscripts/render-config.mjs+19−2View file
@@ -10,8 +10,9 @@
1010 // the host's last two labels) and sends email from notifications@<host>.
1111 // --admins sets BOOTSTRAP_ADMINS (comma-separated emails; bootstrap.sh passes what
1212 // scripts/bootstrap-admins.sh found). Without it, wrangler.jsonc's value stays.
13-// From the environment it takes RUNNER_IMAGE (scripts/runner-image.sh) and
14-// TURNSTILE_SITE_KEY (scripts/turnstile.sh, through bootstrap).
13+// From the environment it takes RUNNER_IMAGE (scripts/runner-image.sh),
14+// TURNSTILE_SITE_KEY (scripts/turnstile.sh, through bootstrap) and the GitHub App of GitHub
15+// runners: GITHUB_APP_ID, GITHUB_APP_SLUG, GITHUB_APP_CLIENT_ID and GITHUB_APP_URL.
1516 import { readFileSync, writeFileSync } from "node:fs";
1617 import { dirname, join } from "node:path";
1718 import { fileURLToPath } from "node:url";
@@ -57,5 +58,21 @@
5758 // The site key of the Turnstile widget scripts/turnstile.sh set up for this hostname (not a
5859 // secret). One set in wrangler.jsonc is the operator's own and wins; turnstile.sh then leaves it alone.
5960 if (process.env.TURNSTILE_SITE_KEY && !cfg.vars.TURNSTILE_SITE_KEY) cfg.vars.TURNSTILE_SITE_KEY = process.env.TURNSTILE_SITE_KEY;
61+// The GitHub App's IDs (docs/self-hosting/configuration.md#github-runners) aren't secrets, but they are
62+// the instance's own, so they come from the environment like the hostname rather than from
63+// wrangler.jsonc; one that is empty there leaves wrangler.jsonc's value. Its secrets are Worker secrets.
64+const githubApp = [
65+ ["GITHUB_APP_ID", /^\d+$/, "the App ID, a number"],
66+ ["GITHUB_APP_SLUG", /^[a-z0-9][a-z0-9-]*$/, "the slug, like diffinery-runners"],
67+ ["GITHUB_APP_CLIENT_ID", /^\S+$/, "the Client ID, like Iv23li..."],
68+ ["GITHUB_APP_URL", /^https:\/\/[^/\s]+$/, "an https origin, like https://ghe.example.com"],
69+];
70+for (const [key, shape, want] of githubApp) {
71+ const value = process.env[key]?.trim();
72+ if (!value) continue;
73+ // Not the value itself: a secret set in the wrong variable would end up in the deploy log.
74+ if (!shape.test(value)) throw new Error(`${key} must be ${want}`);
75+ cfg.vars[key] = value;
76+}
6077 writeFileSync(join(appDir, "wrangler.deploy.jsonc"), `// Generated by scripts/render-config.mjs; do not edit.\n${JSON.stringify(cfg, null, 2)}\n`);
6178 console.log(`wrote ${join(appDir, "wrangler.deploy.jsonc")}`);
modifiedscripts/setup.sh+2−0View file
@@ -16,6 +16,8 @@
1616 # DIFFINERY_ZONE the Cloudflare zone holding DIFFINERY_DOMAIN (default: its last two labels)
1717 # MAIL_DOMAIN send email from notifications@<MAIL_DOMAIN> (default DIFFINERY_DOMAIN)
1818 # ACCESS_TEAM_DOMAIN your Zero Trust team domain, e.g. example.cloudflareaccess.com, when the token can't read it
19+# GITHUB_APP_ID, GITHUB_APP_SLUG, GITHUB_APP_CLIENT_ID, GITHUB_APP_URL
20+# the GitHub App of GitHub runners (docs/self-hosting/configuration.md#github-runners)
1921 # ROLLOUT_WAIT_MINUTES how long to wait for the container rollout (default 10)
2022 #
2123 # Every step is idempotent: it creates only what is missing and keeps your data and secrets, so run