diff --git a/.changeset/host-reload-fork-pr.md b/.changeset/host-reload-fork-pr.md new file mode 100644 index 00000000..c2feb76c --- /dev/null +++ b/.changeset/host-reload-fork-pr.md @@ -0,0 +1,6 @@ +--- +"gcb-host": patch +--- + +Reload the host broker's configuration on watch/poll/SIGHUP, as the app daemon already does, and let +`allowFork` cover lifecycle `gcb pr create` on the parent of an allowlisted fork. diff --git a/README.md b/README.md index 93f945da..b5238288 100644 --- a/README.md +++ b/README.md @@ -490,7 +490,7 @@ actions include issue create/edit/comment/close/reopen and pull request close/re merge action. For `repo fork`, review replies, reviews, pull request edit, issue edit/comment and any request that names `--repo` explicitly — every review always carries its repository, even when derived from origin — it checks the repository against the broker config's allowlist (pass -`--config`), except a `readOnly` action with `allowPublicRead`, or a catalogued action on the parent of an allowlisted fork with `allowFork` (see the configuration table). An +`--config`), except a `readOnly` action with `allowPublicRead`, or a catalogued action / `gcb pr create` on the parent of an allowlisted fork with `allowFork` (see the configuration table). An explicit `--repo` needs no checkout of that repository; without one, a checkout must exist. When there is no checkout at all, the client and host broker use the shared `~/.gcb-host/channel` instead of `.git/gcb/host-broker`; the request must carry `--repo`, and the @@ -688,7 +688,7 @@ file. ## Configuration reference -The daemon watches the configuration directory with `fs.watch` for low latency and also runs a 5-second digest poll as a safety net; if the native watcher is unavailable, polling runs alone. A valid change is applied without restarting, and an invalid one keeps the last good snapshot. Send `SIGHUP` to force a reload after fixing a file. `socketPath`, `socketMode`, `auditPath`, `auditMaxBytes` and `auditKeep` require a restart. +The daemon watches the configuration directory with `fs.watch` for low latency and also runs a 5-second digest poll as a safety net; if the native watcher is unavailable, polling runs alone. A valid change is applied without restarting, and an invalid one keeps the last good snapshot. Send `SIGHUP` to force a reload after fixing a file. `socketPath`, `socketMode`, `auditPath`, `auditMaxBytes` and `auditKeep` require a restart. `gcb host` watches the same file for allowlist, fork and action-policy changes; it needs no restart for those, and `SIGHUP` forces the same reload. The broker only reads this file. It is YAML. The loader discovers `broker.config.yml` by default; the old `broker.config.json` name is no longer discovered, so rename or convert an existing @@ -722,7 +722,7 @@ Per host, keyed exactly as git reports it (`github.com`, or `host:port` for othe | `allowForkPush` | Default `false`. Allow a **public** fork whose parent/source is an allowlisted repository. For `gcb push`, the host verifies the relation and uses the host account/SSH key; the App need not be installed on the fork. For the app credential path, the App must be installed with `contents: write`. | | `sshAccounts` | Optional map from gh login to an SSH host alias for `gcb push`, e.g. `{ "example-user": "github-example-user" }`. SSH aliases keep their own key/port/proxy settings; a login without an entry is refused rather than falling back to the default key. | | `actions` | Optional per-host action policy, e.g. `{ "pr:close": { "deny": true } }`. A global top-level `actions` deny still wins. | -| `allowFork` | Default `false`. Allow a **catalogued action** (`gcb gh …`, `gcb issue …`) on the public parent/source of an allowlisted **public** fork, after GitHub confirms the relationship. Wildcard entries are not used for inference. It does not cover the lifecycle `gcb pr create` path; that still needs the target repository in `allow`. | +| `allowFork` | Default `false`. Allow a **catalogued action** (`gcb gh …`, `gcb issue …`) and lifecycle `gcb pr create` on the public parent/source of an allowlisted **public** fork, after GitHub confirms the relationship. Wildcard entries are not used for inference. | | `github-app`: `clientId` (preferred `iss`), `appId` (fallback), `privateKeyPath` or `privateKeyPem`, `permissions`, `apiBaseUrl` (GitHub Enterprise, must be HTTPS), `apiVersion`, `installationCacheSeconds`, diff --git a/packages/host/src/commands/host.ts b/packages/host/src/commands/host.ts index 84e03bdf..e05e3a92 100644 --- a/packages/host/src/commands/host.ts +++ b/packages/host/src/commands/host.ts @@ -65,11 +65,12 @@ import { } from 'gcb-core' import { parseDocument } from 'yaml' -import { loadConfig, resolveConfigPath } from '../config.ts' +import { loadConfigSnapshot, resolveConfigPath } from '../config.ts' import { clearInheritedTokens, setHostToken, tokenKeys } from '../gh-env.ts' import { applyProxyChoice, fetcherFor, parseProxy, type ProxyChoice } from '../http.ts' import { hostConfig, parseAllowEntry, repoAllowed } from '../policy.ts' import { isForkOfRepository, isPublicRepository } from '../public-repo.ts' +import { ConfigWatcher } from '../reload.ts' const run = promisify(execFile) @@ -297,6 +298,8 @@ export async function runHostBroker(argv: readonly string[]): Promise { const configSelected = Boolean(configPath) || Boolean(process.env['GIT_BROKER_CONFIG']) || existsSync(resolvedConfig) let loadedConfig: string | null = configSelected ? resolvedConfig : null + let configWatcher: ConfigWatcher | undefined + let configDigest: string | undefined /** Remove the status file only when this process owns it. */ function removeOwnStatus(): void { try { @@ -345,9 +348,12 @@ export async function runHostBroker(argv: readonly string[]): Promise { const configFor = (): BrokerConfig => { if (config === undefined) { try { - config = loadConfig(resolvedConfig) + const snapshot = loadConfigSnapshot(resolvedConfig) + config = snapshot.config + configDigest = snapshot.digest loadedConfig = resolvedConfig writeStatus() + startConfigWatcher() } catch (error) { throw new Error( `a fork, reply or explicit repository needs the broker config allowlist: ${(error as Error).message}; pass --config or set GIT_BROKER_CONFIG`, @@ -357,6 +363,28 @@ export async function runHostBroker(argv: readonly string[]): Promise { } return config } + /** Reload the configuration after a watch or poll event; invalid files keep the last snapshot. */ + const reloadConfig = (): string => { + const snapshot = loadConfigSnapshot(resolvedConfig) + config = snapshot.config + loadedConfig = resolvedConfig + configDigest = snapshot.digest + writeStatus() + return configDigest + } + /** Start the watcher after the first accepted load, with that load's own digest as its baseline. */ + function startConfigWatcher(): void { + if (once || configWatcher !== undefined || configDigest === undefined) { + return + } + configWatcher = new ConfigWatcher({ + file: resolvedConfig, + initialDigest: configDigest, + reload: reloadConfig, + onError: error => warn(`config reload failed: ${error.message}`), + }) + configWatcher.start() + } /** Resolve one host block from the loaded configuration. */ const blockFor = (host: string) => hostConfig(configFor(), host) /** Whether the configuration denies this catalogued action for a host. */ @@ -467,6 +495,7 @@ export async function runHostBroker(argv: readonly string[]): Promise { // marker would tell the container a host broker is there and make it wait for an answer that is not // coming. process.on('exit', () => { + configWatcher?.stop() removeOwnStatus() for (const dir of advertised) { try { @@ -481,6 +510,7 @@ export async function runHostBroker(argv: readonly string[]): Promise { const stop = () => process.exit(0) process.on('SIGINT', stop) process.on('SIGTERM', stop) + process.on('SIGHUP', () => configWatcher?.check(true)) say( single === undefined @@ -1436,7 +1466,20 @@ async function openOne( } try { if (!allowed('github.com', target)) { - return { error: `repository ${target} is not in the allowlist for github.com` } + const block = blockFor('github.com') + const allowedByFork = + block?.allowFork === true && + (await forkAllows( + 'github.com', + block.allow, + target, + request.proxy, + 'apiBaseUrl' in block ? block.apiBaseUrl : undefined, + 'apiBaseUrl' in block ? block.apiVersion : undefined, + )) + if (!allowedByFork) { + return { error: `repository ${target} is not in the allowlist for github.com` } + } } } catch (error) { return { error: (error as Error).message } diff --git a/packages/host/src/config.ts b/packages/host/src/config.ts index 21ebd4d8..2ee2fed2 100644 --- a/packages/host/src/config.ts +++ b/packages/host/src/config.ts @@ -3,6 +3,7 @@ * agent container can see, and validated eagerly so a broken or over-broad configuration stops the * daemon at startup instead of silently denying (or silently allowing) at push time. */ +import { createHash } from 'node:crypto' import { existsSync, readFileSync } from 'node:fs' import path, { posix } from 'node:path' @@ -586,7 +587,19 @@ export function readConfigText(path: string): string { * @returns The validated configuration. */ export function loadConfig(path: string): BrokerConfig { - return loadConfigText(readConfigText(path), path) + return loadConfigSnapshot(path).config +} + +/** Read, validate and hash one configuration snapshot from the same bytes. */ +export function loadConfigSnapshot(path: string): { + readonly config: BrokerConfig + readonly digest: string +} { + const text = readConfigText(path) + return { + config: loadConfigText(text, path), + digest: createHash('sha256').update(text).digest('hex'), + } } /** Parse and validate configuration text already read from `path`. */ diff --git a/packages/host/src/daemon.ts b/packages/host/src/daemon.ts index 5e522b70..5e6a65c4 100644 --- a/packages/host/src/daemon.ts +++ b/packages/host/src/daemon.ts @@ -7,14 +7,13 @@ * without binding the socket, which is what a deployment script should run before restarting the * service. */ -import { createHash } from 'node:crypto' import type { Writable } from 'node:stream' import type { BrokerConfig, Provider } from 'gcb-core' import { createAudit } from './audit.ts' import { startBroker } from './broker.ts' -import { assertKeysReadable, loadConfigText, readConfigText, resolveConfigPath } from './config.ts' +import { assertKeysReadable, loadConfigSnapshot, resolveConfigPath } from './config.ts' import { createProvider } from './providers/index.ts' import type { ProviderDeps } from './providers/index.ts' import { ConfigWatcher } from './reload.ts' @@ -107,13 +106,14 @@ export async function runDaemon( const resolved = resolveConfigPath(configPath) const load = (): { config: BrokerConfig; providers: Map; digest: string } => { - const text = readConfigText(resolved) - const next = loadConfigText(text, resolved) - assertKeysReadable(next) + const snapshot = loadConfigSnapshot(resolved) + assertKeysReadable(snapshot.config) return { - config: next, - providers: buildProviders(next, { log: message => stderr.write(`gcb daemon: ${message}\n`) }), - digest: createHash('sha256').update(text).digest('hex'), + config: snapshot.config, + providers: buildProviders(snapshot.config, { + log: message => stderr.write(`gcb daemon: ${message}\n`), + }), + digest: snapshot.digest, } } let config: BrokerConfig diff --git a/test/unit/host-fork-pr.test.ts b/test/unit/host-fork-pr.test.ts new file mode 100644 index 00000000..34526862 --- /dev/null +++ b/test/unit/host-fork-pr.test.ts @@ -0,0 +1,72 @@ +/** A lifecycle `pr create` on the parent of an allowlisted fork, driven end to end. */ +import assert from 'node:assert/strict' +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, it } from 'node:test' + +import { channelDir, readResult, writeRequest } from '../../packages/core/src/host-request.ts' +import { runHostBroker } from '../../packages/host/src/commands/host.ts' + +describe('opening a pull request on a fork parent', () => { + it('allows it when allowFork is set', async () => { + const root = mkdtempSync(join(tmpdir(), 'host-broker-pr-fork-')) + const repo = join(root, 'checkout') + mkdirSync(join(repo, '.git'), { recursive: true }) + writeFileSync(join(repo, '.git', 'HEAD'), 'ref: refs/heads/main\n', 'utf8') + const config = join(root, 'broker.config.yml') + writeFileSync( + config, + `socketPath: ${join(root, 'broker.sock')}\nhosts:\n github.com:\n provider: static\n username: x\n password: y\n allowFork: true\n allow:\n - JounQin/vitehub\n`, + 'utf8', + ) + const dir = channelDir(join(repo, '.git')) + const argvFile = join(root, 'argv') + const command = join(root, 'not-gh') + writeFileSync( + command, + '#!/bin/sh\nprintf \'%s\\n\' "$@" > ' + + argvFile + + '\necho "https://github.com/vite-hub/vitehub/pull/9"\n', + 'utf8', + ) + chmodSync(command, 0o755) + const originalFetch = globalThis.fetch + const requested: string[] = [] + globalThis.fetch = (async (input: string | URL | Request) => { + const url = String(input) + requested.push(url) + if (!url.toLowerCase().endsWith('/repos/jounqin/vitehub')) { + throw new Error(`unexpected fork lookup: ${url}`) + } + return new Response( + JSON.stringify({ fork: true, parent: { full_name: 'vite-hub/vitehub' } }), + { + status: 200, + headers: { 'content-type': 'application/json' }, + }, + ) + }) as typeof fetch + try { + const id = writeRequest(dir, { + repo: 'vite-hub/vitehub', + head: 'feat/x', + base: 'next', + title: 'x', + body: '', + }) + assert.equal( + await runHostBroker(['--repo', repo, '--command', command, '--config', config, '--once']), + 0, + ) + const answer = readResult(dir, id) + assert.equal(answer?.number, 9, JSON.stringify(answer)) + const argv = readFileSync(argvFile, 'utf8').trim().split('\n') + assert.equal(argv[argv.indexOf('--repo') + 1], 'vite-hub/vitehub') + assert.deepEqual(requested, ['https://api.github.com/repos/jounqin/vitehub']) + } finally { + globalThis.fetch = originalFetch + rmSync(root, { recursive: true, force: true }) + } + }) +})