Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

feat(action): support GitHub Enterprise Cloud on ghe.com (#1713)

Michael D'Angelo5b4a553e24ef
diff --git a/.github/workflows/action-ci.yml b/.github/workflows/action-ci.yml
index 73659c89e..f1f7ebe32 100644
--- a/.github/workflows/action-ci.yml
+++ b/.github/workflows/action-ci.yml
@@ -5,6 +5,7 @@ on:
paths:
- action.yml
- github-action/**
+ - sdk/typescript/src/git-remote.ts
- plugins/codex-security/examples/completed-scan/**
- .github/workflows/action-ci.yml
pull_request: *action-changes
diff --git a/github-action/README.md b/github-action/README.md
index 02497952b..aa35b1c9a 100644
--- a/github-action/README.md
+++ b/github-action/README.md
@@ -6,7 +6,8 @@ SARIF reports.
## Quick start
-Use a GitHub-hosted Ubuntu 24.04 x64 runner on GitHub.com and an OpenAI API key
+Use a GitHub-hosted Ubuntu 24.04 x64 runner on GitHub.com or GitHub Enterprise
+Cloud on `*.ghe.com`, and an OpenAI API key
with access to the selected model. OpenAI is the default provider. See
[Inference providers](#inference-providers) for Bedrock, OpenRouter, and Fireworks.
@@ -77,6 +78,42 @@ This setup is specific to the Linux runner. Local macOS scans use the built-in
Seatbelt sandbox and do not need Bubblewrap. See the
[sandbox documentation](https://learn.chatgpt.com/docs/sandboxing) for details.
+## Supported GitHub hosts and checkout URLs
+
+The Action supports GitHub.com and GitHub Enterprise Cloud on `*.ghe.com`.
+Checkout origins can use HTTPS, SCP-style SSH (`USER@HOST:OWNER/REPO.git`),
+or an `ssh://` URL, including an explicit port 22. Repository names and hostnames
+are compared without regard to case; a `.git` suffix and trailing slash are optional.
+
+On GitHub.com, `ssh://[email protected]:443/OWNER/REPO.git` is also supported.
+GitHub does not offer this SSH-over-443 endpoint for enterprises on `ghe.com`;
+see [GitHub's SSH-over-HTTPS guidance](https://docs.github.com/en/authentication/troubleshooting-ssh/using-ssh-over-the-https-port).
+
+### GitHub Enterprise Cloud
+
+The workflows in this guide also support GitHub Enterprise Cloud with data
+residency at `https://SUBDOMAIN.ghe.com`. The Action reads `GITHUB_SERVER_URL`
+from the runner and requires the checkout origin to match that host and
+`GITHUB_REPOSITORY`. No additional Action input or GitHub token is needed.
+Use a reviewed Action commit containing this support.
+
+Keep `persist-credentials: false` and use the triggering repository and revision.
+HTTPS origins work with the checkout step above. For SSH origins, GitHub uses
+the enterprise subdomain as the username, such as
+`[email protected]:example/repo.git`.
+See [GitHub's SSH guidance](https://docs.github.com/en/enterprise-cloud@latest/admin/data-residency/network-details-for-ghecom#using-ssh-with-ghecom).
+
+Report artifacts use the runner's Actions artifact service. The separate
+`github/codeql-action/upload-sarif` step uses the enterprise's code scanning
+service and requires the permissions and availability described below.
+Enterprise policies must permit the referenced actions. For Bedrock OIDC,
+configure AWS trust for the enterprise issuer at
+`https://token.actions.SUBDOMAIN.ghe.com`; see
+[GitHub's feature differences](https://docs.github.com/en/enterprise-cloud@latest/admin/data-residency/feature-overview-for-github-enterprise-cloud-with-data-residency).
+
+GitHub Enterprise Server remains unsupported. The Linux x64 runtime and
+sandbox requirements apply on both supported GitHub Cloud hosts.
+
## Inference providers
`provider` and `model` map to `codex-security scan --provider` and `--model`.
diff --git a/github-action/dist/index.cjs b/github-action/dist/index.cjs
index 627758fc3..7ed87dc7d 100644
--- a/github-action/dist/index.cjs
+++ b/github-action/dist/index.cjs
@@ -55749,13 +55749,36 @@ async function runProcess(executable, args, options) {
});
}
+// ../sdk/typescript/src/git-remote.ts
+function parseGitRemote(remote) {
+ if (remote.includes("://")) {
+ const url2 = new URL(remote);
+ return {
+ url: url2,
+ path: url2.pathname.slice(1),
+ scpStyle: false
+ };
+ }
+ const scp = /^((?:[^@/:\s?#]+@)?(?:\[[^\]]+\]|[^@/:\s?#]+)):(.+)$/u.exec(
+ remote
+ );
+ if (scp === null) return void 0;
+ return {
+ url: new URL(`ssh://${scp[1]}`),
+ // An SCP path's ?, #, and dot segments are literal Git path characters.
+ path: scp[2],
+ scpStyle: true
+ };
+}
+
// src/targets.ts
var SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
function validateEvent(event) {
if (!["pull_request", "schedule", "workflow_dispatch", "push"].includes(event.eventName))
throw new Error(`Unsupported event: ${event.eventName}. Use pull_request, schedule, workflow_dispatch, or push. Privileged PR source-scanning triggers are not supported.`);
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(event.repository)) throw new Error("GITHUB_REPOSITORY is invalid.");
- if (event.serverUrl !== "https://github.com") throw new Error("This release supports GitHub.com only; GitHub Enterprise Server has not been validated.");
+ if (!/^https:\/\/(?:github\.com|[a-z0-9-]+\.ghe\.com)$/.test(event.serverUrl))
+ throw new Error("This release supports GitHub.com and GitHub Enterprise Cloud on *.ghe.com; GitHub Enterprise Server has not been validated.");
if (event.eventName === "pull_request") {
const pr = event.payload.pull_request;
if (!pr || pr.head?.repo?.full_name !== event.repository || pr.base?.repo?.full_name !== event.repository)
@@ -55816,11 +55839,17 @@ async function containedPath(repository, input) {
if (!info2.isFile() && !info2.isDirectory()) throw new Error("A requested path is not a regular file or directory.");
return path6;
}
-function originMatches(url2, repository) {
+function originMatches(url2, repository, serverUrl) {
try {
- if (url2.startsWith("[email protected]:")) return url2.slice(15).replace(/\.git$/, "") === repository;
- const parsed = new URL(url2);
- return ["https:", "ssh:"].includes(parsed.protocol) && parsed.hostname === "github.com" && !parsed.password && (parsed.protocol === "ssh:" ? parsed.username === "git" : !parsed.username) && parsed.pathname.replace(/^\//, "").replace(/\.git$/, "") === repository;
+ const host = new URL(serverUrl).hostname;
+ const sshUser = host === "github.com" ? "git" : host.slice(0, -".ghe.com".length);
+ const remote = parseGitRemote(url2);
+ if (!remote) return false;
+ const parsed = remote.url;
+ const ssh = parsed.protocol === "ssh:";
+ const originHost = parsed.hostname.toLowerCase();
+ const matchesHost = originHost === host || host === "github.com" && ssh && originHost === "ssh.github.com" && parsed.port === "443";
+ return matchesHost && !parsed.password && (ssh ? parsed.username === sshUser : parsed.protocol === "https:" && !parsed.username) && remote.path.replace(/\/$/, "").replace(/\.git$/, "").toLowerCase() === repository.toLowerCase();
} catch {
return false;
}
@@ -55834,7 +55863,7 @@ async function resolveTarget(inputs, event) {
if (configKeys.some((key) => /^credential\.|^http\..*extraheader$|^include\.path$|^includeif\..*\.path$|^core\.sshcommand$|^url\..*\.insteadof$/.test(key)))
throw new Error("The checkout retains Git authentication or external configuration. Use actions/checkout with persist-credentials: false and a dedicated clean job. Credential values have not been printed.");
const origin = (await git(repository, ["config", "--no-includes", "--get", "remote.origin.url"])).trim();
- if (!originMatches(origin, event.repository)) throw new Error("The checkout origin does not match GITHUB_REPOSITORY. Cross-repository checkouts are not supported.");
+ if (!originMatches(origin, event.repository, event.serverUrl)) throw new Error("The checkout origin does not match GITHUB_SERVER_URL and GITHUB_REPOSITORY. Cross-repository checkouts are not supported.");
const scannedSha = await commit(repository, "HEAD");
const pr = event.eventName === "pull_request" ? event.payload.pull_request : void 0;
if (pr && scannedSha !== pr.head.sha) throw new Error("PR scans must check out github.event.pull_request.head.sha, not the merge commit.");
diff --git a/github-action/scripts/build.mjs b/github-action/scripts/build.mjs
index be04f85ce..4f265f668 100644
--- a/github-action/scripts/build.mjs
+++ b/github-action/scripts/build.mjs
@@ -28,9 +28,9 @@ function components(packages, namespace) {
...(info.resolved ? {externalReferences: [{type: 'distribution', url: info.resolved}]} : {}),
}));
}
-const sourceFiles = (await readdir(resolve(root, 'src'))).filter(name => name.endsWith('.ts')).sort();
+const sourceFiles = Object.keys(bundle.metafile.inputs).filter(path => !path.includes('node_modules/')).sort();
const sourceHash = createHash('sha256');
-for (const file of sourceFiles) sourceHash.update(file).update('\0').update(await readFile(resolve(root, 'src', file))).update('\0');
+for (const file of sourceFiles) sourceHash.update(file).update('\0').update(await readFile(resolve(root, file))).update('\0');
const manifest = {
actionVersion, status: 'unreleased', nodeRuntime: 'node24', platform: 'linux-x64', cliVersion,
sourceSha256: sourceHash.digest('hex'), actionLockSha256: hash(await readFile(resolve(root, 'package-lock.json'))),
diff --git a/github-action/src/targets.ts b/github-action/src/targets.ts
index 5978fd3c6..f150e7fa1 100644
--- a/github-action/src/targets.ts
+++ b/github-action/src/targets.ts
@@ -2,6 +2,7 @@ import { lstat, realpath } from 'node:fs/promises';
import { resolve, relative, sep, isAbsolute } from 'node:path';
import { runProcess, safeLogLines, type ProcessResult } from './process.js';
import type { Inputs } from './inputs.js';
+import { parseGitRemote } from '../../sdk/typescript/src/git-remote.js';
export interface EventContext {
eventName: string;
@@ -25,8 +26,8 @@ export function validateEvent(event: EventContext): void {
if (!['pull_request','schedule','workflow_dispatch','push'].includes(event.eventName))
throw new Error(`Unsupported event: ${event.eventName}. Use pull_request, schedule, workflow_dispatch, or push. Privileged PR source-scanning triggers are not supported.`);
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(event.repository)) throw new Error('GITHUB_REPOSITORY is invalid.');
- // The artifact service implementation is GitHub.com-specific for this release.
- if (event.serverUrl !== 'https://github.com') throw new Error('This release supports GitHub.com only; GitHub Enterprise Server has not been validated.');
+ if (!/^https:\/\/(?:github\.com|[a-z0-9-]+\.ghe\.com)$/.test(event.serverUrl))
+ throw new Error('This release supports GitHub.com and GitHub Enterprise Cloud on *.ghe.com; GitHub Enterprise Server has not been validated.');
if (event.eventName === 'pull_request') {
const pr = event.payload.pull_request;
if (!pr || pr.head?.repo?.full_name !== event.repository || pr.base?.repo?.full_name !== event.repository)
@@ -74,14 +75,21 @@ export async function containedPath(repository: string, input: string): Promise<
return path;
}
-function originMatches(url: string, repository: string): boolean {
+function originMatches(url: string, repository: string, serverUrl: string): boolean {
// Parse without printing potentially embedded tokens.
try {
- if (url.startsWith('[email protected]:')) return url.slice(15).replace(/\.git$/, '') === repository;
- const parsed = new URL(url);
- return ['https:', 'ssh:'].includes(parsed.protocol) && parsed.hostname === 'github.com' && !parsed.password &&
- (parsed.protocol === 'ssh:' ? parsed.username === 'git' : !parsed.username) &&
- parsed.pathname.replace(/^\//, '').replace(/\.git$/, '') === repository;
+ const host = new URL(serverUrl).hostname;
+ const sshUser = host === 'github.com' ? 'git' : host.slice(0, -'.ghe.com'.length);
+ const remote = parseGitRemote(url);
+ if (!remote) return false;
+ const parsed = remote.url;
+ const ssh = parsed.protocol === 'ssh:';
+ const originHost = parsed.hostname.toLowerCase();
+ const matchesHost = originHost === host ||
+ (host === 'github.com' && ssh && originHost === 'ssh.github.com' && parsed.port === '443');
+ return matchesHost && !parsed.password &&
+ (ssh ? parsed.username === sshUser : parsed.protocol === 'https:' && !parsed.username) &&
+ remote.path.replace(/\/$/, '').replace(/\.git$/, '').toLowerCase() === repository.toLowerCase();
} catch { return false; }
}
@@ -95,7 +103,7 @@ export async function resolveTarget(inputs: Inputs, event: EventContext): Promis
if (configKeys.some(key => /^credential\.|^http\..*extraheader$|^include\.path$|^includeif\..*\.path$|^core\.sshcommand$|^url\..*\.insteadof$/.test(key)))
throw new Error('The checkout retains Git authentication or external configuration. Use actions/checkout with persist-credentials: false and a dedicated clean job. Credential values have not been printed.');
const origin = (await git(repository, ['config', '--no-includes', '--get', 'remote.origin.url'])).trim();
- if (!originMatches(origin, event.repository)) throw new Error('The checkout origin does not match GITHUB_REPOSITORY. Cross-repository checkouts are not supported.');
+ if (!originMatches(origin, event.repository, event.serverUrl)) throw new Error('The checkout origin does not match GITHUB_SERVER_URL and GITHUB_REPOSITORY. Cross-repository checkouts are not supported.');
const scannedSha = await commit(repository, 'HEAD');
const pr = event.eventName === 'pull_request' ? event.payload.pull_request : undefined;
if (pr && scannedSha !== pr.head.sha) throw new Error('PR scans must check out github.event.pull_request.head.sha, not the merge commit.');
diff --git a/github-action/tests/artifacts.test.ts b/github-action/tests/artifacts.test.ts
new file mode 100644
index 000000000..9f744ff75
--- /dev/null
+++ b/github-action/tests/artifacts.test.ts
@@ -0,0 +1,49 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { once } from 'node:events';
+import { createServer } from 'node:http';
+import { mkdtemp, readdir, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { uploadReports } from '../src/artifacts.js';
+import { parseInputs } from '../src/inputs.js';
+
+test('enterprise artifacts use the runner results service through the real client', async t => {
+ const root = await mkdtemp(join(tmpdir(), 'action-artifact-'));
+ t.after(() => rm(root, {recursive:true, force:true}));
+ const previous = {...process.env};
+ t.after(() => {
+ for (const key of Object.keys(process.env)) if (!(key in previous)) delete process.env[key];
+ Object.assign(process.env, previous);
+ });
+ const requests: {url?: string; authorization?: string; body: any}[] = [];
+ const server = createServer(async (request, response) => {
+ let body = '';
+ for await (const chunk of request) body += chunk;
+ requests.push({url:request.url, authorization:request.headers.authorization, body:JSON.parse(body)});
+ // Stop after artifact creation so this test needs no external blob service.
+ response.writeHead(200, {'Content-Type':'application/json'});
+ response.end(JSON.stringify({ok:false}));
+ });
+ server.listen(0, '127.0.0.1');
+ await once(server, 'listening');
+ t.after(() => new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve())));
+ const address = server.address();
+ assert.ok(address && typeof address !== 'string');
+ const payload = Buffer.from(JSON.stringify({scp:'Actions.Results:synthetic-run:synthetic-job'})).toString('base64url');
+ const token = `e30.${payload}.synthetic-signature`;
+ Object.assign(process.env, {
+ GITHUB_SERVER_URL:'https://example-enterprise.ghe.com',
+ ACTIONS_RESULTS_URL:`http://127.0.0.1:${address.port}`,
+ ACTIONS_RUNTIME_TOKEN:token,
+ });
+ await assert.rejects(uploadReports(new Map([['findings.json', Buffer.from('{}')]]), parseInputs(() => '', root), root),
+ /CreateArtifact: response from backend was not ok/);
+ assert.equal(requests.length, 1);
+ assert.match(requests[0].url ?? '', /\/twirp\/.*\.ArtifactService\/CreateArtifact$/);
+ assert.equal(requests[0].authorization, `Bearer ${token}`);
+ assert.equal(requests[0].body.workflow_run_backend_id, 'synthetic-run');
+ assert.equal(requests[0].body.workflow_job_run_backend_id, 'synthetic-job');
+ assert.equal(requests[0].body.name, 'codex-security');
+ assert.deepEqual(await readdir(root), []);
+});
diff --git a/github-action/tests/main.test.ts b/github-action/tests/main.test.ts
index acf53cd0a..904c8e7db 100644
--- a/github-action/tests/main.test.ts
+++ b/github-action/tests/main.test.ts
@@ -32,7 +32,7 @@ function outputValues(text: string): Record<string, string> {
return values;
}
-async function harness(t: TestContext, scenario: Scenario = 'schedule') {
+async function harness(t: TestContext, scenario: Scenario = 'schedule', serverUrl = 'https://github.com') {
const root = await realpath(await mkdtemp(join(tmpdir(), 'codex-main-test-')));
const repository = join(root, 'repo');
await mkdir(repository);
@@ -40,7 +40,7 @@ async function harness(t: TestContext, scenario: Scenario = 'schedule') {
'-c', 'user.name=Offline Test', '-c', '[email protected]', '-c', 'core.hooksPath=/dev/null', ...args,
], { cwd: repository, env: gitEnvironment(), encoding: 'utf8' }).trim();
git('init', '-q', '-b', 'main');
- git('remote', 'add', 'origin', 'https://github.com/example/repo.git');
+ git('remote', 'add', 'origin', `${serverUrl}/example/repo.git`);
await writeFile(join(repository, 'app.txt'), 'synthetic source\n');
git('add', '.'); git('commit', '-qm', 'base');
const base = git('rev-parse', 'HEAD');
@@ -69,7 +69,7 @@ async function harness(t: TestContext, scenario: Scenario = 'schedule') {
GITHUB_EVENT_PATH: eventPath, GITHUB_EVENT_NAME: scenario === 'schedule' ? 'schedule' : 'pull_request',
GITHUB_REPOSITORY: 'example/repo', GITHUB_WORKSPACE: repository, GITHUB_SHA: sha,
GITHUB_REF: scenario === 'schedule' ? 'refs/heads/main' : 'refs/pull/4/merge',
- GITHUB_ACTOR: 'trusted-maintainer', GITHUB_SERVER_URL: 'https://github.com',
+ GITHUB_ACTOR: 'trusted-maintainer', GITHUB_SERVER_URL: serverUrl,
GITHUB_OUTPUT: outputPath, GITHUB_STATE: statePath, RUNNER_TEMP: root,
OPENAI_API_KEY: 'synthetic-offline-test-key', INPUT_SUMMARY: 'true', INPUT_ANNOTATIONS: 'false',
INPUT_SCOPE: scenario === 'schedule' ? 'repository' : 'diff',
@@ -112,6 +112,7 @@ async function harness(t: TestContext, scenario: Scenario = 'schedule') {
}
if (process.env.INPUT_MODE === 'deep') coverage.mode = 'deep_repository';
sarif.runs[0].versionControlProvenance[0].revisionId = scanSha;
+ sarif.runs[0].versionControlProvenance[0].repositoryUri = `${serverUrl}/example/repo`;
await writeFile(sarifPath, JSON.stringify(sarif));
if (configuration.missingSarif) await rm(sarifPath);
const value = {manifest, coverage, findings: JSON.parse(await readFile(join(runtime.resultsDirectory, 'findings.json'), 'utf8')),
@@ -208,6 +209,32 @@ test('unrelated ambient input variables do not reject a valid scan', async (t) =
assert.ok(result.args.includes('--effort=medium'));
});
+for (const [scenario, mode] of [['schedule', 'standard'], ['pr', 'standard'], ['schedule', 'deep']] as const) {
+ test(`enterprise ${scenario} ${mode} scans preserve reports and upload identity`, async t => {
+ const serverUrl = 'https://example-enterprise.ghe.com';
+ const app = await harness(t, scenario, serverUrl);
+ app.setInput('mode', mode); app.setInput('upload-artifacts', 'true'); app.setInput('annotations', 'true');
+ let uploadedFiles: string[] = [];
+ t.mock.method(DefaultArtifactClient.prototype, 'uploadArtifact', async (_name: string, files: string[]) => {
+ assert.equal(process.env.GITHUB_SERVER_URL, serverUrl);
+ uploadedFiles = files.map(file => basename(file));
+ for (const file of files) assert.ok((await readFile(file)).length);
+ return {id:1, size:1};
+ });
+ const result = await app.run();
+ assert.equal(result.exitCode, 0); assert.equal(result.processes, 1); assert.equal(result.cleanups, 1);
+ assert.equal(result.outputs['scan-status'], 'completed'); assert.equal(result.outputs['report-status'], 'ready');
+ assert.equal(result.outputs['policy-status'], 'passed'); assert.equal(result.outputs['sarif-upload-ready'], 'true');
+ assert.equal(result.outputs['scanned-sha'], app.sha);
+ assert.equal(result.outputs['analysis-ref'], scenario === 'pr' ? 'refs/pull/4/head' : 'refs/heads/main');
+ assert.deepEqual(uploadedFiles.sort(), ['coverage.json', 'findings.json', 'results.sarif', 'scan-manifest.json']);
+ const sarif = JSON.parse(await readFile(result.outputs['sarif-path'], 'utf8'));
+ assert.equal(sarif.runs[0].versionControlProvenance[0].repositoryUri, `${serverUrl}/example/repo`);
+ assert.match(result.logs, /^::warning .*file=src\/extract\.py/m);
+ assert.match(result.summary, /Scan completed/);
+ });
+}
+
test('Deep scans forward their budget and publish completed reports with cleanup', async (t) => {
const app = await harness(t);
app.setInput('mode', 'deep'); app.setInput('max-time-hours', '1.5');
diff --git a/github-action/tests/targets.test.ts b/github-action/tests/targets.test.ts
index e93aff52c..5f3204a8a 100644
--- a/github-action/tests/targets.test.ts
+++ b/github-action/tests/targets.test.ts
@@ -46,6 +46,68 @@ test('PR target resolves merge base and preserves exact upload head identity', a
assert.equal(target.diffBase,f.base); assert.equal(target.diffHead,head);
assert.equal(target.analysisRef,'refs/pull/7/head'); assert.equal(target.publishable,true);
});
+test('GitHub Cloud checkout origins match the event host for HTTPS and SSH', async t => {
+ const f = await fixture(t); const head = await f.change();
+ for (const [host, sshUser] of [['github.com', 'git'], ['example-enterprise.ghe.com', 'example-enterprise']]) {
+ for (const origin of [
+ `https://${host}/example/repo.git`, `https://${host}:443/example/repo`,
+ `https://${host.toUpperCase()}/Example/Repo.git/`,
+ `${sshUser}@${host}:example/repo.git`, `${sshUser}@${host.toUpperCase()}:Example/Repo/`,
+ `ssh://${sshUser}@${host}/example/repo`, `ssh://${sshUser}@${host.toUpperCase()}:22/Example/Repo.git/`,
+ ]) {
+ f.run('remote', 'set-url', 'origin', origin);
+ for (const eventName of ['schedule', 'pull_request']) {
+ const event = {...f.event(head, eventName), serverUrl:`https://${host}`};
+ const target = await resolveTarget(f.inputs({scope:eventName === 'schedule' ? 'repository' : 'diff'}), event);
+ assert.equal(target.scannedSha, head); assert.equal(target.publishable, true);
+ assert.equal(target.analysisRef, eventName === 'schedule' ? 'refs/heads/main' : 'refs/pull/7/head');
+ assert.equal(target.diffBase, eventName === 'schedule' ? undefined : f.base);
+ }
+ }
+ }
+});
+test('GitHub.com checkout origins support its SSH-over-443 endpoint', async t => {
+ const f = await fixture(t);
+ f.run('remote', 'set-url', 'origin', 'ssh://[email protected]:443/example/repo.git');
+ const target = await resolveTarget(f.inputs({scope:'repository'}), f.event(f.base, 'schedule'));
+ assert.equal(target.scannedSha, f.base);
+ assert.equal(target.publishable, true);
+
+ const enterpriseEvent = {...f.event(f.base), serverUrl:'https://example-enterprise.ghe.com'};
+ await assert.rejects(resolveTarget(f.inputs(), enterpriseEvent), /origin does not match/);
+ for (const origin of ['https://ssh.github.com/example/repo.git', 'ssh://[email protected]:22/example/repo.git',
+ 'ssh://[email protected]:443/other/repo.git', 'ssh://[email protected]:443/example/repo.git']) {
+ f.run('remote', 'set-url', 'origin', origin);
+ await assert.rejects(resolveTarget(f.inputs(), f.event(f.base)), /origin does not match/);
+ }
+});
+test('SCP checkout paths remain literal when compared with the triggering repository', async t => {
+ const f = await fixture(t);
+ for (const origin of ['[email protected]:example/repo.git#suffix', '[email protected]:example/repo.git?suffix',
+ '[email protected]:other/../example/repo.git']) {
+ f.run('remote', 'set-url', 'origin', origin);
+ await assert.rejects(resolveTarget(f.inputs(), f.event(f.base)), /origin does not match/);
+ }
+});
+test('unsupported server URLs still fail eligibility', async t => {
+ const f = await fixture(t);
+ for (const serverUrl of ['', 'https://github.example.invalid', 'http://example-enterprise.ghe.com',
+ 'https://ghe.com', 'https://example-enterprise.ghe.com.example.invalid', 'https://example-enterprise-ghe.com']) {
+ assert.throws(() => validateEvent({...f.event(f.base), serverUrl}), /supports GitHub.com and GitHub Enterprise Cloud/);
+ }
+});
+test('enterprise checkout origins cannot select another host or repository', async t => {
+ const f = await fixture(t);
+ const event = {...f.event(f.base), serverUrl:'https://example-enterprise.ghe.com'};
+ for (const origin of ['https://github.com/example/repo.git', 'https://other-enterprise.ghe.com/example/repo.git',
+ '[email protected]:example/repo.git', 'https://example-enterprise.ghe.com/other/repo.git',
+ '[email protected]:other/repo.git']) {
+ f.run('remote', 'set-url', 'origin', origin);
+ await assert.rejects(resolveTarget(f.inputs(), event), /origin does not match/);
+ }
+ f.run('remote', 'set-url', 'origin', 'https://example-enterprise.ghe.com/example/repo.git');
+ await assert.rejects(resolveTarget(f.inputs(), f.event(f.base)), /origin does not match/);
+});
test('manual diff scans resolve an explicit base against the checked-out head', async t => {
const f=await fixture(t);
f.run('tag','scan-base');
@@ -120,6 +182,21 @@ test('persisted Git credentials and origin userinfo are refused without revealin
f.run('remote','set-url','origin','https://[email protected]/example/repo.git');
await assert.rejects(resolveTarget(f.inputs(),f.event(f.base)),error=>/origin/.test(String(error))&&!String(error).includes('CANARY'));
});
+test('enterprise checkouts retain the Git credential protections', async t => {
+ const f = await fixture(t);
+ const event = {...f.event(f.base), serverUrl:'https://example-enterprise.ghe.com'};
+ f.run('remote', 'set-url', 'origin', `${event.serverUrl}/example/repo.git`);
+ const key = `http.${event.serverUrl}/.extraheader`;
+ f.run('config', key, 'AUTHORIZATION: bearer synthetic-token');
+ await assert.rejects(resolveTarget(f.inputs(), event), /persist-credentials/);
+ f.run('config', '--unset', key);
+ for (const origin of ['https://[email protected]/example/repo.git',
+ 'https://example-enterprise:[email protected]/example/repo.git',
+ 'ssh://example-enterprise:[email protected]/example/repo.git']) {
+ f.run('remote', 'set-url', 'origin', origin);
+ await assert.rejects(resolveTarget(f.inputs(), event), /origin does not match/);
+ }
+});
test('worktree configuration is optional and clean linked checkouts are accepted', async t => {
const f = await fixture(t);
diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjs
index 3311b415c..b3721af7c 100644
--- a/sdk/typescript/scripts/package-dist-files.mjs
+++ b/sdk/typescript/scripts/package-dist-files.mjs
@@ -45,6 +45,7 @@ const distModules = [
"feedback",
"finding-catalogue",
"findings-import",
+ "git-remote",
"github",
"host-records-protocol",
"index",
diff --git a/sdk/typescript/src/git-remote.ts b/sdk/typescript/src/git-remote.ts
new file mode 100644
index 000000000..9190c8f12
--- /dev/null
+++ b/sdk/typescript/src/git-remote.ts
@@ -0,0 +1,32 @@
+export interface GitRemote {
+ url: URL;
+ /** Repository path without a URL's leading slash; SCP paths remain literal. */
+ path: string;
+ scpStyle: boolean;
+}
+
+/** Parse transport syntax only; callers decide which hosts and credentials are allowed. */
+export function parseGitRemote(remote: string): GitRemote | undefined {
+ if (remote.includes("://")) {
+ const url = new URL(remote);
+ return {
+ url,
+ path: url.pathname.slice(1),
+ scpStyle: false,
+ };
+ }
+ const scp = /^((?:[^@/:\s?#]+@)?(?:\[[^\]]+\]|[^@/:\s?#]+)):(.+)$/u.exec(
+ remote,
+ );
+ if (scp === null) return undefined;
+ return {
+ url: new URL(`ssh://${scp[1]}`),
+ // An SCP path's ?, #, and dot segments are literal Git path characters.
+ path: scp[2]!,
+ scpStyle: true,
+ };
+}
+
+export function isGitHubCloudHost(host: string): boolean {
+ return host === "github.com" || host.endsWith(".ghe.com");
+}
diff --git a/sdk/typescript/src/github.ts b/sdk/typescript/src/github.ts
index b1d57a081..2d734f343 100644
--- a/sdk/typescript/src/github.ts
+++ b/sdk/typescript/src/github.ts
@@ -3,6 +3,7 @@ import { promisify } from "node:util";
import { Octokit } from "@octokit/core";
import { CodexSecurityError, errorMessage } from "./errors.js";
import { resolveTrustedExecutable } from "./trusted-executable.js";
+import { isGitHubCloudHost } from "./git-remote.js";
const execFile = promisify(execFileCallback);
type GitHubAlert = Awaited<ReturnType<typeof fetchGitHubAlert>>;
@@ -88,10 +89,9 @@ export async function createAuthenticatedGitHub(
}
return new Octokit({
auth: token,
- baseUrl:
- host === "github.com" || host.endsWith(".ghe.com")
- ? `https://api.${host}`
- : `https://${host}/api/v3`,
+ baseUrl: isGitHubCloudHost(host)
+ ? `https://api.${host}`
+ : `https://${host}/api/v3`,
});
}
diff --git a/sdk/typescript/src/patch-publication.ts b/sdk/typescript/src/patch-publication.ts
index a7b834124..1ec22990e 100644
--- a/sdk/typescript/src/patch-publication.ts
+++ b/sdk/typescript/src/patch-publication.ts
@@ -1,3 +1,5 @@
+import { parseGitRemote } from "./git-remote.js";
+
export interface PatchReviewRequest {
branch: string;
title: string;
@@ -96,9 +98,10 @@ export function createGitLabPatchPublisher({
project: string;
run: RunPatchReviewCommand;
}): PatchReviewPublisher {
- const repository = project.includes("://")
- ? project
- : `ssh://${project.replace(":", "/")}`;
+ const remote = parseGitRemote(project);
+ const repository = remote?.scpStyle
+ ? `${remote.url}/${remote.path}`
+ : project;
return {
label: "Merge request",
findExisting: (branch) =>
@@ -146,6 +149,7 @@ function gitlabPatchDescription(body: string): string {
}
function remoteHost(remote: string): string | undefined {
- if (remote.includes("://")) return new URL(remote).hostname.toLowerCase();
- return /^(?:[^@/]+@)?([^:/]+):[^/]/u.exec(remote)?.[1]?.toLowerCase();
+ const parsed = parseGitRemote(remote);
+ if (parsed?.scpStyle && parsed.path.startsWith("/")) return undefined;
+ return parsed?.url.hostname.toLowerCase();
}
diff --git a/sdk/typescript/src/publication.ts b/sdk/typescript/src/publication.ts
index b217e94eb..52729ff5b 100644
--- a/sdk/typescript/src/publication.ts
+++ b/sdk/typescript/src/publication.ts
@@ -1,4 +1,5 @@
import { findingEntry } from "./value.js";
+import { isGitHubCloudHost } from "./git-remote.js";
import { isRecord } from "./record.js";
import {
loadContractWithScanDirectory,
@@ -495,10 +496,7 @@ function immutableSourceUrl(
} catch {
return undefined;
}
- if (
- remote.protocol !== "https:" ||
- (remote.hostname !== "github.com" && !remote.hostname.endsWith(".ghe.com"))
- ) {
+ if (remote.protocol !== "https:" || !isGitHubCloudHost(remote.hostname)) {
return undefined;
}
diff --git a/sdk/typescript/tests-ts/git-remote.test.ts b/sdk/typescript/tests-ts/git-remote.test.ts
new file mode 100644
index 000000000..258b3fd71
--- /dev/null
+++ b/sdk/typescript/tests-ts/git-remote.test.ts
@@ -0,0 +1,91 @@
+import { expect, test } from "bun:test";
+import { isGitHubCloudHost, parseGitRemote } from "../src/git-remote.js";
+
+test.each([
+ [
+ "https://example.test/team/project.git",
+ false,
+ "https:",
+ "",
+ "",
+ "team/project.git",
+ ],
+ [
+ "ssh://[email protected]:2222/team/project.git",
+ false,
+ "ssh:",
+ "git",
+ "2222",
+ "team/project.git",
+ ],
+ [
+ "[email protected]:team/project.git",
+ true,
+ "ssh:",
+ "git",
+ "",
+ "team/project.git",
+ ],
+ ["example.test:team/project.git", true, "ssh:", "", "", "team/project.git"],
+] as const)(
+ "parses the transport of %s",
+ (input, scpStyle, protocol, username, port, path) => {
+ const remote = parseGitRemote(input)!;
+ expect(remote).toMatchObject({ scpStyle, path });
+ expect(remote.url.hostname).toBe("example.test");
+ expect(remote.url.protocol).toBe(protocol);
+ expect(remote.url.username).toBe(username);
+ expect(remote.url.port).toBe(port);
+ },
+);
+
+test("keeps literal SCP paths separate from URL queries and fragments", () => {
+ const remote = parseGitRemote(
+ "[email protected]:team/../project.git?ref#part",
+ )!;
+ expect(remote.path).toBe("team/../project.git?ref#part");
+ expect(remote.url.search).toBe("");
+ expect(remote.url.hash).toBe("");
+});
+
+test("uses URL path semantics while preserving repository casing", () => {
+ const remote = parseGitRemote("https://example.test/Team/../Project.git/")!;
+ expect(remote.path).toBe("Project.git/");
+ expect(remote.url.pathname).toBe("/Project.git/");
+});
+
+test("leaves transport and credential eligibility to callers", () => {
+ const remote = parseGitRemote(
+ "http://synthetic:[email protected]/team/project?ref#part",
+ )!;
+ expect(remote.url.protocol).toBe("http:");
+ expect(remote.url.username).toBe("synthetic");
+ expect(remote.url.password).toBe("password");
+ expect(remote.url.search).toBe("?ref");
+ expect(remote.url.hash).toBe("#part");
+});
+
+test("preserves IPv6 hosts and explicit SSH ports", () => {
+ const remote = parseGitRemote(
+ "ssh://git@[2001:db8::1]:2222/team/project.git",
+ )!;
+ expect(remote.url.hostname).toBe("[2001:db8::1]");
+ expect(remote.url.port).toBe("2222");
+ expect(remote.path).toBe("team/project.git");
+});
+
+test("distinguishes plain paths and malformed URLs", () => {
+ expect(parseGitRemote("./team/project")).toBeUndefined();
+ expect(() => parseGitRemote("https://[invalid/team/project")).toThrow();
+});
+
+test.each([
+ ["github.com", true],
+ ["example-enterprise.ghe.com", true],
+ ["ghe.com", false],
+ ["github.example.test", false],
+ ["github.com.example.test", false],
+ ["example-enterprise.ghe.com.example.test", false],
+] as const)("recognizes GitHub Cloud host %s", (host, expected) => {
+ expect(isGitHubCloudHost(host)).toBe(expected);
+});
diff --git a/sdk/typescript/tests-ts/patch-publication.test.ts b/sdk/typescript/tests-ts/patch-publication.test.ts
index 22ed03f41..ed7c28e0b 100644
--- a/sdk/typescript/tests-ts/patch-publication.test.ts
+++ b/sdk/typescript/tests-ts/patch-publication.test.ts
@@ -180,6 +180,59 @@ test("rechecks the provider after a create response is lost", async () => {
expect(events).toEqual(["find", "push", "create", "find"]);
});
+test.each([
+ [
+ "https://gitlab.com/group/project.git",
+ "https://gitlab.com/group/project.git",
+ {},
+ ],
+ [
+ "ssh://[email protected]/group/project.git",
+ "ssh://[email protected]/group/project.git",
+ {},
+ ],
+ [
+ "[email protected]:group/project.git",
+ "ssh://[email protected]/group/project.git",
+ {},
+ ],
+ [
+ "git@[2001:db8::1]:group/subgroup/project.git",
+ "ssh://git@[2001:db8::1]/group/subgroup/project.git",
+ { GITLAB_HOST: "[2001:db8::1]" },
+ ],
+ [
+ "ssh://git@[2001:db8::1]:2222/group/project.git",
+ "ssh://git@[2001:db8::1]:2222/group/project.git",
+ { GITLAB_HOST: "[2001:db8::1]" },
+ ],
+] as const)(
+ "routes GitLab remote %s without changing the review project",
+ async (origin, expectedProject, environment) => {
+ const calls: { executable: string; args: readonly string[] }[] = [];
+ const publisher = resolvePatchReviewPublisher(
+ origin,
+ environment,
+ async (executable, args) => {
+ calls.push({ executable, args });
+ return "";
+ },
+ );
+ await publisher.findExisting(request.branch);
+ await publisher.createDraft(request);
+ expect(calls.map(({ args }) => args.slice(0, 2))).toEqual([
+ ["mr", "list"],
+ ["mr", "create"],
+ ]);
+ for (const { executable, args } of calls) {
+ expect(executable).toBe("glab");
+ expect(args[args.indexOf("--repo") + 1]).toBe(expectedProject);
+ }
+ const create = calls[1]!.args;
+ expect(create[create.indexOf("--head") + 1]).toBe(expectedProject);
+ },
+);
+
test("keeps native gh repository resolution for an unrecognized remote host", async () => {
const url = "https://forge.example.test/team/project/pull/42";
const calls: Array<readonly string[]> = [];