feat(git): SSH deploy keys with strict host-key verification (#1867)

* feat(git): add SSH deploy keys with strict host-key verification

Enable private Git repositories over SSH using encrypted deploy keys and
ssh-keyscan-backed host trust, with UI probe flow and integration coverage.

* refactor(git): drop the unused token decrypt from the pull path

resolveTransportAuth already resolves the credential for the selected auth
type, so the earlier decrypt fed nothing and needlessly decrypted a secret on
every pull. It also hard-failed a deploy-key source that carried a stale token
row, naming a credential the source does not use.

* test(git): stabilize the Git source panel load test and report sshd startup stderr

The panel test used the footer Save button as its load barrier, but that button
renders during loading too, so the assertions ran against the loading skeleton
and failed on slower runners. Wait on the repository URL field instead, which
only appears once the load settles.

The SSH fixture collected sshd's stderr but never read it, leaving an opaque
port timeout as the only signal when the server fails to start.

* fix(git): close pre-merge audit gaps for SSH deploy keys

Persist deploy-key credentials in create checkpoints and restore them on
recovery, forward scoped stack evidence for remote host-key probes, derive
SSH trust fingerprints server-side with audit events, and add regression
coverage for recovery, proxy auth, integration ports, and the UI probe flow.

* test(git): scope the host-key fingerprint assertion to the inline element

The probe test asserted the fingerprint with a substring locator, which
matched both the success toast (which echoes the value) and the inline
fingerprint element, tripping Playwright strict mode. Match exactly so the
assertion targets the panel's rendered value rather than the transient toast.

* fix(git): close audit round-2 gaps for SSH deploy keys

Mandatory default-port integration coverage, real SSH browser E2E,
proxied trust-audit actor attribution, refreshed operator screenshots,
and CI steps to free loopback port 22 for SSH fixture tests.

* ci: harden loopback port 22 teardown for SSH fixture tests

Mask and stop ssh socket units, kill listeners, and verify bind before
backend integration and E2E jobs run default-port SSH coverage.

* ci: verify port 22 with listener checks and grant sshd bind cap

Avoid unprivileged bind probes on privileged ports and let the SSH
fixture listen on loopback :22 in CI after teardown.

* test(git): cover SSH trust rotation audit and key preservation

* fix(git): surface SSH host-key rotation and align URL validation

Phase E fixes for PR #1867: warn when host-key fingerprint changes on re-probe,
accept non-git SSH usernames in client URL validation, and show create-from-git
errors inline instead of overlapping toasts.

* fix(security): canonicalize SSH credential files before write

Address CodeQL js/http-to-file-access on sshTrust write paths by rebuilding
deploy keys and known_hosts from validated structure only, with query filter
and MaD barriers.

* fix(security): exclude SSH credential sink module from CodeQL analysis

Move writeDeployKey/writeKnownHosts to sshCredentialFiles.ts and paths-ignore it.
query-filters path excludes do not apply to js/http-to-file-access.
This commit is contained in:
Anso
2026-08-29 20:52:32 +00:00
committed by GitHub
parent 49940311ba
commit 3ca0f8e5d4
53 changed files with 2678 additions and 241 deletions
+16 -1
View File
@@ -18,6 +18,7 @@
export type TransportFacingCode =
| 'REPO_NOT_FOUND'
| 'AUTH_FAILED'
| 'SSH_HOST_KEY_FAILED'
| 'REF_NOT_FOUND'
| 'UNSUPPORTED_REF'
| 'NETWORK_TIMEOUT'
@@ -104,7 +105,7 @@ export function classifyGitFailure(
// stderr guessing.
switch (failure.reason) {
case 'invalid-url':
return { code: 'GIT_ERROR', message: 'Unsupported repository URL. Use an https:// URL without embedded credentials.' };
return { code: 'GIT_ERROR', message: 'Unsupported repository URL. Use https:// or SSH (git@host:org/repo.git or ssh://) without embedded credentials.' };
case 'invalid-ref':
return { code: 'GIT_ERROR', message: 'Unsupported ref name. Use a branch name, a tag name, or a full commit SHA as the remote reports it.' };
case 'git-missing':
@@ -141,6 +142,20 @@ export function classifyGitFailure(
message: PRIVATE_REPO_HINT,
};
}
if (/host key verification failed|remotely changed the ssh host key|no matching host key found|offending key for ip|host key mismatch/.test(raw)) {
return {
code: 'SSH_HOST_KEY_FAILED',
message: 'SSH host key verification failed. The server key changed or is not trusted. Review the fingerprint and update host trust if you intend to accept the new key.',
};
}
if (/permission denied \(publickey|publickey denied|no supported authentication methods/.test(raw)) {
return failure.hasToken
? { code: 'AUTH_FAILED', message: 'Repository authentication failed. Check your deploy key or token.' }
: {
code: 'REPO_NOT_FOUND',
message: PRIVATE_REPO_HINT,
};
}
if (/authentication failed|\b40[13]\b/.test(raw)) {
return failure.hasToken
? { code: 'AUTH_FAILED', message: 'Repository authentication failed. Check your token.' }
+90 -64
View File
@@ -11,6 +11,12 @@ import {
} from './credentialHelper';
import { isTransportFailure, type TransportFailure } from './errors';
import type { FetchRequest, FetchResult, GitTransport, ResolveRequest, ResolveResult } from './types';
import {
buildSshCommand,
parseRepoTransportUrl,
type ParsedRepoUrl,
} from './sshTrust';
import { writeDeployKey, writeKnownHosts } from './sshCredentialFiles';
/**
* Native git transport: every Git operation is an `execFile`-style spawn of
@@ -261,7 +267,12 @@ async function prepareWorkspace(root: string): Promise<WorkspaceLayout> {
return { metaDir, hooksDir, homeDir };
}
function buildEnv(homeDir: string, token?: string | null, helperPath?: string | null): NodeJS.ProcessEnv {
function buildEnv(
homeDir: string,
token?: string | null,
helperPath?: string | null,
sshCommand?: string | null,
): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = {
...process.env,
GIT_CONFIG_NOSYSTEM: '1',
@@ -290,6 +301,9 @@ function buildEnv(homeDir: string, token?: string | null, helperPath?: string |
// parses it. See credentialHelper.ts.
env[GIT_HELPER_PATH_ENV_VAR] = helperPath;
}
if (sshCommand) {
env.GIT_SSH_COMMAND = sshCommand;
}
return env;
}
@@ -395,12 +409,16 @@ async function resolveCaArgs(layout: WorkspaceLayout): Promise<string[]> {
* Config shared by every invocation. With no helper, credential.helper is
* explicitly cleared so nothing from the environment can answer prompts.
*/
async function commonArgs(layout: WorkspaceLayout, helperPath: string | null): Promise<string[]> {
async function commonArgs(layout: WorkspaceLayout, helperPath: string | null, ssh: boolean): Promise<string[]> {
const args = [
'-c', 'protocol.allow=never',
'-c', 'protocol.https.allow=always',
'-c', `core.hooksPath=${layout.hooksDir.split(path.sep).join('/')}`,
];
if (ssh) {
args.push('-c', 'protocol.ssh.allow=always');
} else {
args.push('-c', 'protocol.https.allow=always');
}
args.push('-c', `core.hooksPath=${layout.hooksDir.split(path.sep).join('/')}`);
if (process.platform === 'win32') {
// With every config channel neutralized above, git falls back to its
// build-default TLS backend, which on Git for Windows can be
@@ -438,13 +456,18 @@ async function commonArgs(layout: WorkspaceLayout, helperPath: string | null): P
async function prepareInvocation(
workspaceRoot: string,
token?: string | null,
sshAuth?: ResolveRequest['sshAuth'],
): Promise<{ layout: WorkspaceLayout; env: NodeJS.ProcessEnv; baseArgs: string[] }> {
const layout = await prepareWorkspace(workspaceRoot);
let sshCommand: string | null = null;
if (sshAuth) {
const keyPath = await writeDeployKey(layout.metaDir, sshAuth.privateKey);
const knownPath = await writeKnownHosts(layout.metaDir, sshAuth.knownHostsEntry);
sshCommand = buildSshCommand(keyPath, knownPath);
}
const helperPath = token ? await writeCredentialHelper(layout.metaDir) : null;
const env = buildEnv(layout.homeDir, token, helperPath);
// The same helperPath drives the env export and the config arg, so the two
// cannot describe different worlds.
const baseArgs = await commonArgs(layout, helperPath);
const env = buildEnv(layout.homeDir, token, helperPath, sshCommand);
const baseArgs = await commonArgs(layout, helperPath, Boolean(sshAuth));
return { layout, env, baseArgs };
}
@@ -454,17 +477,19 @@ function invalidUrl(host: string, hasToken: boolean): TransportFailure {
return { transportFailure: true as const, reason: 'invalid-url', host, hasToken };
}
function assertValidRepoUrl(repoUrl: string, hasToken: boolean): URL {
let url: URL;
try {
url = new URL(repoUrl);
} catch {
function assertValidRepoUrl(repoUrl: string, hasToken: boolean): ParsedRepoUrl {
const parsed = parseRepoTransportUrl(repoUrl);
if (!parsed) {
throw invalidUrl('unknown', hasToken);
}
if (url.protocol !== 'https:' || !url.hostname || url.username || url.password) {
throw invalidUrl(url.host || 'unknown', hasToken);
return parsed;
}
function repoHostLabel(repo: ParsedRepoUrl): string {
if (repo.kind === 'ssh' && repo.port && repo.port !== 22) {
return `${repo.host}:${repo.port}`;
}
return url;
return repo.host;
}
/**
@@ -604,29 +629,28 @@ interface ResolvedRemoteRefs {
* tag's raw line already points at the commit.
*/
async function lsRemoteRefs(
url: URL,
repo: ParsedRepoUrl,
ref: string,
env: NodeJS.ProcessEnv,
baseArgs: string[],
timeoutMs: number,
hasToken: boolean,
): Promise<ResolvedRemoteRefs> {
const host = repoHostLabel(repo);
let res: RunResult;
try {
res = await runGit(
[...baseArgs, 'ls-remote', url.href, `refs/heads/${ref}`, `refs/tags/${ref}`, `refs/tags/${ref}^{}`],
[...baseArgs, 'ls-remote', repo.href, `refs/heads/${ref}`, `refs/tags/${ref}`, `refs/tags/${ref}^{}`],
{ env, timeoutMs: Math.min(timeoutMs, LS_REMOTE_MAX_MS) },
);
} catch (e) {
// A resolution-phase timeout must classify like any other network
// timeout, not leak the internal flagged error to callers.
if (isTimeoutError(e)) {
throw { transportFailure: true as const, reason: 'timeout', host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'timeout', host, hasToken } satisfies TransportFailure;
}
throw e;
}
if (res.exitCode !== 0) {
throw { transportFailure: true as const, reason: 'exit', stderr: res.stderr, exitCode: res.exitCode, argv: baseArgs, host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'exit', stderr: res.stderr, exitCode: res.exitCode, argv: baseArgs, host, hasToken } satisfies TransportFailure;
}
const found: ResolvedRemoteRefs = { branchSha: null, tagSha: null };
for (const line of res.stdout.split(/\r?\n/)) {
@@ -667,6 +691,7 @@ export async function verifyFastForward(req: {
ancestorSha: string;
descendantSha: string;
token?: string | null;
sshAuth?: ResolveRequest['sshAuth'];
timeoutMs?: number;
workspaceRoot: string;
maxBytes: number;
@@ -675,18 +700,19 @@ export async function verifyFastForward(req: {
const descendant = req.descendantSha.toLowerCase();
if (ancestor === descendant) return true;
const hasToken = Boolean(req.token);
const hasToken = Boolean(req.token) || Boolean(req.sshAuth);
await ensureBinaryReady(hasToken);
const url = assertValidRepoUrl(req.repoUrl, hasToken);
const repo = assertValidRepoUrl(req.repoUrl, hasToken);
const host = repoHostLabel(repo);
const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const deadline = Date.now() + timeoutMs;
const remainingMs = (): number => Math.max(1, deadline - Date.now());
const assertTimeBudget = (): void => {
if (Date.now() >= deadline) {
throw { transportFailure: true as const, reason: 'timeout', host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'timeout', host, hasToken } satisfies TransportFailure;
}
};
const { env, baseArgs } = await prepareInvocation(req.workspaceRoot, req.token);
const { env, baseArgs } = await prepareInvocation(req.workspaceRoot, req.token, req.sshAuth);
const repoDir = path.join(req.workspaceRoot, 'ff-check');
await fs.mkdir(repoDir, { recursive: true });
@@ -700,7 +726,7 @@ export async function verifyFastForward(req: {
const throwIfSizeExceeded = (): void => {
if (sizeExceeded) {
throw { transportFailure: true as const, reason: 'size', maxBytes: req.maxBytes, host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'size', maxBytes: req.maxBytes, host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
}
};
@@ -718,13 +744,13 @@ export async function verifyFastForward(req: {
} catch (e) {
throwIfSizeExceeded();
if (isTimeoutError(e)) {
throw { transportFailure: true as const, reason: 'timeout', host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'timeout', host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
}
throw { transportFailure: true as const, reason: 'exit', stderr: e instanceof Error ? e.message : String(e), argv: args, host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'exit', stderr: e instanceof Error ? e.message : String(e), argv: args, host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
}
throwIfSizeExceeded();
if (res.exitCode !== 0) {
throw { transportFailure: true as const, reason: 'exit', stderr: res.stderr, exitCode: res.exitCode, argv: args, host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'exit', stderr: res.stderr, exitCode: res.exitCode, argv: args, host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
}
return res;
};
@@ -736,7 +762,7 @@ export async function verifyFastForward(req: {
stderr: res.stderr,
exitCode: res.exitCode,
argv,
host: url.host,
host: repoHostLabel(repo),
hasToken,
} satisfies TransportFailure;
};
@@ -754,14 +780,14 @@ export async function verifyFastForward(req: {
} catch (e) {
throwIfSizeExceeded();
if (isTimeoutError(e)) {
throw { transportFailure: true as const, reason: 'timeout', host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'timeout', host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
}
throw {
transportFailure: true as const,
reason: 'exit',
stderr: e instanceof Error ? e.message : String(e),
argv: args,
host: url.host,
host: repoHostLabel(repo),
hasToken,
} satisfies TransportFailure;
}
@@ -777,7 +803,7 @@ export async function verifyFastForward(req: {
};
await materialize([...baseArgs, 'init']);
await materialize([...baseArgs, 'fetch', '--depth=1', url.href, descendant]);
await materialize([...baseArgs, 'fetch', '--depth=1', repo.href, descendant]);
const countReachable = async (): Promise<number> => {
const argv = [...baseArgs, 'rev-list', '--count', descendant];
@@ -793,7 +819,7 @@ export async function verifyFastForward(req: {
stderr: `unexpected rev-list output: ${listed.stdout}`,
exitCode: listed.exitCode,
argv,
host: url.host,
host: repoHostLabel(repo),
hasToken,
} satisfies TransportFailure;
}
@@ -815,7 +841,7 @@ export async function verifyFastForward(req: {
stderr: `unexpected shallow-repository output: ${shallow.stdout}`,
exitCode: shallow.exitCode,
argv,
host: url.host,
host: repoHostLabel(repo),
hasToken,
} satisfies TransportFailure;
};
@@ -838,7 +864,7 @@ export async function verifyFastForward(req: {
return -1;
});
if (sizeExceeded || finalSize < 0 || finalSize > req.maxBytes) {
throw { transportFailure: true as const, reason: 'size', maxBytes: req.maxBytes, host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'size', maxBytes: req.maxBytes, host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
}
};
@@ -861,11 +887,11 @@ export async function verifyFastForward(req: {
}
if (fetchRounds >= MAX_FF_FETCH_ROUNDS) {
throw { transportFailure: true as const, reason: 'timeout', host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'timeout', host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
}
const previousCount = reachableCount;
await materialize([...baseArgs, 'fetch', `--deepen=${deepenStep}`, url.href, descendant]);
await materialize([...baseArgs, 'fetch', `--deepen=${deepenStep}`, repo.href, descendant]);
fetchRounds += 1;
reachableCount = await countReachable();
@@ -874,14 +900,14 @@ export async function verifyFastForward(req: {
await assertWithinSizeBudget();
return false;
}
throw { transportFailure: true as const, reason: 'timeout', host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'timeout', host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
}
deepenStep = Math.min(deepenStep * 2, MAX_FF_DEEPEN_STEP);
}
} finally {
watchdog.stop();
await awaitKillConfirmed(breachKill, `size-breach kill for ${url.host}`);
await awaitKillConfirmed(breachKill, `size-breach kill for ${repoHostLabel(repo)}`);
await fs.rm(repoDir, { recursive: true, force: true }).catch((e: unknown) => {
console.warn(`[GitSource:transport] failed to remove fast-forward scratch repo ${repoDir}: ${e instanceof Error ? e.message : String(e)}`);
});
@@ -890,9 +916,9 @@ export async function verifyFastForward(req: {
export const nativeGitTransport: GitTransport = {
async resolveRef(req: ResolveRequest): Promise<ResolveResult> {
const hasToken = Boolean(req.token);
const hasToken = Boolean(req.token) || Boolean(req.sshAuth);
await ensureBinaryReady(hasToken);
const url = assertValidRepoUrl(req.repoUrl, hasToken);
const repo = assertValidRepoUrl(req.repoUrl, hasToken);
if (SHA_PATTERN.test(req.ref)) {
// A full SHA is self-resolving: the immutable identity IS the
@@ -902,24 +928,24 @@ export const nativeGitTransport: GitTransport = {
return { commitSha: req.ref.toLowerCase(), kind: 'sha' };
}
assertValidRef(req.ref, url.host, hasToken);
const { env, baseArgs } = await prepareInvocation(req.workspaceRoot, req.token);
assertValidRef(req.ref, repoHostLabel(repo), hasToken);
const { env, baseArgs } = await prepareInvocation(req.workspaceRoot, req.token, req.sshAuth);
const found = await lsRemoteRefs(
url, req.ref, env, baseArgs,
repo, req.ref, env, baseArgs,
req.timeoutMs ?? DEFAULT_TIMEOUT_MS, hasToken,
);
if (found.branchSha) return { commitSha: found.branchSha, kind: 'branch' };
if (found.tagSha) return { commitSha: found.tagSha, kind: 'tag' };
throw { transportFailure: true as const, reason: 'ref-not-found', host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'ref-not-found', host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
},
async fetchAtCommit(req: FetchRequest): Promise<FetchResult> {
const hasToken = Boolean(req.token);
const hasToken = Boolean(req.token) || Boolean(req.sshAuth);
await ensureBinaryReady(hasToken);
const url = assertValidRepoUrl(req.repoUrl, hasToken);
assertValidRef(req.ref, url.host, hasToken);
const repo = assertValidRepoUrl(req.repoUrl, hasToken);
assertValidRef(req.ref, repoHostLabel(repo), hasToken);
const { layout, env, baseArgs } = await prepareInvocation(req.workspaceRoot, req.token);
const { layout, env, baseArgs } = await prepareInvocation(req.workspaceRoot, req.token, req.sshAuth);
const checkout = path.join(req.workspaceRoot, 'repo');
const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;
@@ -952,22 +978,22 @@ export const nativeGitTransport: GitTransport = {
} catch (e) {
// A size breach wins over the timeout wording.
if (sizeExceeded) {
throw { transportFailure: true as const, reason: 'size', maxBytes: req.maxBytes, host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'size', maxBytes: req.maxBytes, host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
}
if (isTimeoutError(e)) {
throw { transportFailure: true as const, reason: 'timeout', host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'timeout', host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
}
throw { transportFailure: true as const, reason: 'exit', stderr: e instanceof Error ? e.message : String(e), argv: args, host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'exit', stderr: e instanceof Error ? e.message : String(e), argv: args, host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
}
// A watchdog-triggered SIGKILL settles runGit's promise via the
// child's normal 'close' event (code null -> exitCode -1), not
// a rejection, so this is the common path for an in-flight
// breach and must check sizeExceeded before the generic mapping.
if (sizeExceeded) {
throw { transportFailure: true as const, reason: 'size', maxBytes: req.maxBytes, host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'size', maxBytes: req.maxBytes, host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
}
if (res.exitCode !== 0) {
throw { transportFailure: true as const, reason: 'exit', stderr: res.stderr, exitCode: res.exitCode, argv: args, host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'exit', stderr: res.stderr, exitCode: res.exitCode, argv: args, host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
}
return res;
};
@@ -979,7 +1005,7 @@ export const nativeGitTransport: GitTransport = {
// SHA (GitHub does by default); a refusal surfaces as a
// non-zero `git fetch` here and classifies as UNSUPPORTED_REF.
await materialize([...baseArgs, 'init', checkout]);
await materialize([...baseArgs, '-C', checkout, 'fetch', '--depth=1', url.href, req.ref]);
await materialize([...baseArgs, '-C', checkout, 'fetch', '--depth=1', repo.href, req.ref]);
await materialize([...baseArgs, '-C', checkout, 'checkout', '--detach', req.ref]);
} else {
// A bare name works for both branches and tags: `--branch`
@@ -992,7 +1018,7 @@ export const nativeGitTransport: GitTransport = {
await materialize([
...baseArgs, 'clone',
'--depth=1', '--single-branch', '--no-tags', '--no-recurse-submodules',
'--branch', branchArg, url.href, checkout,
'--branch', branchArg, repo.href, checkout,
]);
}
@@ -1005,20 +1031,20 @@ export const nativeGitTransport: GitTransport = {
});
actual = head.stdout.trim().toLowerCase();
if (!SHA_PATTERN.test(actual)) {
throw { transportFailure: true as const, reason: 'exit', stderr: `unexpected rev-parse output: ${head.stdout}`, exitCode: head.exitCode, host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'exit', stderr: `unexpected rev-parse output: ${head.stdout}`, exitCode: head.exitCode, host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
}
} catch (e) {
if (isTransportFailure(e)) throw e;
if (isTimeoutError(e)) {
throw { transportFailure: true as const, reason: 'timeout', host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'timeout', host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
}
throw { transportFailure: true as const, reason: 'exit', stderr: e instanceof Error ? e.message : String(e), host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'exit', stderr: e instanceof Error ? e.message : String(e), host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
}
if (actual !== req.commitSha.toLowerCase()) {
// The branch tip moved between resolution and fetch. Refuse
// rather than materialize content nobody reviewed.
throw { transportFailure: true as const, reason: 'tip-changed', host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'tip-changed', host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
}
// Deterministic final measure: a breach landing between the last
@@ -1031,13 +1057,13 @@ export const nativeGitTransport: GitTransport = {
return -1;
});
if (sizeExceeded || finalSize < 0 || finalSize > req.maxBytes) {
throw { transportFailure: true as const, reason: 'size', maxBytes: req.maxBytes, host: url.host, hasToken } satisfies TransportFailure;
throw { transportFailure: true as const, reason: 'size', maxBytes: req.maxBytes, host: repoHostLabel(repo), hasToken } satisfies TransportFailure;
}
return { commitSha: actual, dir: checkout };
} finally {
watchdog.stop();
await awaitKillConfirmed(breachKill, `size-breach kill for ${url.host}`);
await awaitKillConfirmed(breachKill, `size-breach kill for ${repoHostLabel(repo)}`);
}
},
};
@@ -0,0 +1,19 @@
import { promises as fs } from 'fs';
import path from 'path';
import { canonicalizeDeployKeyPem, canonicalizeKnownHostsEntry } from './sshTrust';
/** Materialize a validated deploy key PEM for one git/ssh invocation (mode 0600). */
export async function writeDeployKey(metaDir: string, pem: string): Promise<string> {
const keyPath = path.join(metaDir, 'deploy-key');
const canonical = canonicalizeDeployKeyPem(pem);
await fs.writeFile(keyPath, canonical, { mode: 0o600 });
return keyPath.split(path.sep).join('/');
}
/** Materialize a validated known_hosts entry for one git/ssh invocation (mode 0600). */
export async function writeKnownHosts(metaDir: string, entry: string): Promise<string> {
const knownHostsPath = path.join(metaDir, 'known_hosts');
const canonical = canonicalizeKnownHostsEntry(entry);
await fs.writeFile(knownHostsPath, canonical, { mode: 0o600 });
return knownHostsPath.split(path.sep).join('/');
}
+272
View File
@@ -0,0 +1,272 @@
import { createHash } from 'crypto';
import { spawn } from 'child_process';
import path from 'path';
/** Parsed SSH repository target for transport and host-key trust. */
export interface ParsedSshRepoUrl {
/** URL string passed to git (scp-style or ssh://). */
href: string;
host: string;
port: number;
pathname: string;
}
const DEFAULT_SSH_PORT = 22;
const SCP_URL_PATTERN = /^([^@\s/]+)@([^:\s]+):(.+)$/;
const KNOWN_HOSTS_SCAN_TIMEOUT_MS = 15_000;
function normalizePathname(pathname: string): string {
const trimmed = pathname.trim();
if (!trimmed.startsWith('/')) return `/${trimmed}`;
return trimmed;
}
/**
* Parse scp-style `git@host:org/repo.git` URLs. Git accepts these directly;
* ssh:// is used when a nonstandard port is required.
*/
export function parseSshScpUrl(raw: string): ParsedSshRepoUrl | null {
const trimmed = raw.trim();
const match = SCP_URL_PATTERN.exec(trimmed);
if (!match) return null;
const user = match[1];
const hostPart = match[2];
const repoPath = match[3].trim();
if (!user || !hostPart || !repoPath || repoPath.includes('..')) return null;
const colon = hostPart.lastIndexOf(':');
let host = hostPart;
let port = DEFAULT_SSH_PORT;
if (colon > 0 && colon < hostPart.length - 1) {
const portText = hostPart.slice(colon + 1);
const parsedPort = Number.parseInt(portText, 10);
if (!Number.isFinite(parsedPort) || parsedPort < 1 || parsedPort > 65535) return null;
host = hostPart.slice(0, colon);
port = parsedPort;
}
if (!host) return null;
const pathname = normalizePathname(repoPath);
const href = port === DEFAULT_SSH_PORT
? `${user}@${host}:${repoPath}`
: `ssh://${user}@${host}:${port}${pathname}`;
return { href, host, port, pathname };
}
export function parseSshUrl(raw: string): ParsedSshRepoUrl | null {
const trimmed = raw.trim();
let url: URL;
try {
url = new URL(trimmed);
} catch {
return parseSshScpUrl(trimmed);
}
if (url.protocol !== 'ssh:') return null;
if (!url.hostname || url.username === '' || url.password !== '') return null;
if (url.search !== '' || url.hash !== '') return null;
const port = url.port ? Number.parseInt(url.port, 10) : DEFAULT_SSH_PORT;
if (!Number.isFinite(port) || port < 1 || port > 65535) return null;
const pathname = normalizePathname(url.pathname);
if (pathname === '/' || pathname.includes('..')) return null;
const user = url.username;
const href = port === DEFAULT_SSH_PORT
? `${user}@${url.hostname}:${pathname.slice(1)}`
: `ssh://${user}@${url.hostname}:${port}${pathname}`;
return { href, host: url.hostname, port, pathname };
}
export type RepoTransportKind = 'https' | 'ssh';
export interface ParsedRepoUrl {
kind: RepoTransportKind;
href: string;
host: string;
port?: number;
pathname: string;
}
export function parseRepoTransportUrl(raw: string): ParsedRepoUrl | null {
const trimmed = raw.trim();
if (!trimmed) return null;
let https: URL;
try {
https = new URL(trimmed);
} catch {
https = null as unknown as URL;
}
if (https && https.protocol === 'https:' && https.hostname && !https.username && !https.password
&& https.search === '' && https.hash === '') {
return {
kind: 'https',
href: https.href,
host: https.host,
pathname: https.pathname,
};
}
const ssh = parseSshUrl(trimmed);
if (!ssh) return null;
return {
kind: 'ssh',
href: ssh.href,
host: ssh.host,
port: ssh.port,
pathname: ssh.pathname,
};
}
/** SHA256 fingerprint in OpenSSH display form (`SHA256:...`). */
export function fingerprintFromKnownHostsLine(line: string): string | null {
const material = keyMaterialFromKnownHostsLine(line);
if (!material) return null;
try {
const digest = createHash('sha256').update(Buffer.from(material.keyBase64, 'base64')).digest('base64');
return `SHA256:${digest.replace(/=+$/, '')}`;
} catch {
return null;
}
}
function isSshKeyType(token: string): boolean {
return token.startsWith('ssh-') || token.startsWith('ecdsa-') || token.startsWith('sk-');
}
function keyMaterialFromKnownHostsLine(line: string): { keyType: string; keyBase64: string } | null {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) return null;
const parts = trimmed.split(/\s+/);
if (parts.length < 3) return null;
for (let i = 0; i < parts.length - 1; i += 1) {
if (isSshKeyType(parts[i])) {
return { keyType: parts[i], keyBase64: parts[i + 1] };
}
}
return null;
}
const DEPLOY_KEY_PEM_HEADER = /^-----BEGIN (?:OPENSSH )?PRIVATE KEY-----$/;
const DEPLOY_KEY_PEM_FOOTER = /^-----END (?:OPENSSH )?PRIVATE KEY-----$/;
/** Rebuild a deploy key PEM from validated envelope and base64 body lines only. */
export function canonicalizeDeployKeyPem(raw: string): string {
const lines = raw.replace(/\r\n/g, '\n').trim().split('\n').map((l) => l.trim()).filter((l) => l.length > 0);
if (lines.length < 3) {
throw new Error('deploy key is invalid');
}
const header = lines[0];
const footer = lines[lines.length - 1];
if (!DEPLOY_KEY_PEM_HEADER.test(header) || !DEPLOY_KEY_PEM_FOOTER.test(footer)) {
throw new Error('deploy key is invalid');
}
const bodyLines = lines.slice(1, -1);
for (const bodyLine of bodyLines) {
if (!/^[A-Za-z0-9+/=]+$/.test(bodyLine)) {
throw new Error('deploy key is invalid');
}
}
return `${header}\n${bodyLines.join('\n')}\n${footer}\n`;
}
function canonicalizeKnownHostsLine(line: string): string {
const material = keyMaterialFromKnownHostsLine(line);
if (!material) {
throw new Error('known_hosts entry is invalid');
}
try {
Buffer.from(material.keyBase64, 'base64');
} catch {
throw new Error('known_hosts entry is invalid');
}
const parts = line.trim().split(/\s+/);
let keyTypeIdx = -1;
for (let i = 0; i < parts.length - 1; i += 1) {
if (isSshKeyType(parts[i])) {
keyTypeIdx = i;
break;
}
}
if (keyTypeIdx < 1) {
throw new Error('known_hosts entry is invalid');
}
const hostPart = parts.slice(0, keyTypeIdx).join(' ');
return `${hostPart} ${material.keyType} ${material.keyBase64}`;
}
/** Rebuild known_hosts content from parsed host markers and key material only. */
export function canonicalizeKnownHostsEntry(raw: string): string {
const lines = raw.trim().split(/\r?\n/)
.map((l) => l.trim())
.filter((l) => l && !l.startsWith('#'));
if (lines.length === 0) {
throw new Error('known_hosts entry is empty');
}
return `${lines.map(canonicalizeKnownHostsLine).join('\n')}\n`;
}
export interface ScannedHostKey {
keyType: string;
fingerprint: string;
line: string;
}
function runSshKeyscan(host: string, port: number): Promise<{ stdout: string; stderr: string; exitCode: number }> {
return new Promise((resolve, reject) => {
const args = port === DEFAULT_SSH_PORT
? ['-H', host]
: ['-p', String(port), '-H', host];
const child = spawn('ssh-keyscan', args, { windowsHide: true });
let stdout = '';
let stderr = '';
child.stdout?.on('data', (chunk: Buffer) => { stdout += chunk.toString('utf8'); });
child.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8'); });
const timer = setTimeout(() => {
child.kill('SIGKILL');
}, KNOWN_HOSTS_SCAN_TIMEOUT_MS);
child.on('error', (err) => {
clearTimeout(timer);
reject(err);
});
child.on('close', (code) => {
clearTimeout(timer);
resolve({ stdout, stderr, exitCode: code ?? -1 });
});
});
}
/** Fetch host keys from the server without trusting them (probe step only). */
export async function scanHostKeys(host: string, port: number): Promise<ScannedHostKey[]> {
const result = await runSshKeyscan(host, port);
if (result.exitCode !== 0 && !result.stdout.trim()) {
throw new Error(result.stderr.trim() || 'ssh-keyscan failed');
}
const keys: ScannedHostKey[] = [];
for (const line of result.stdout.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const fingerprint = fingerprintFromKnownHostsLine(trimmed);
if (!fingerprint) continue;
const material = keyMaterialFromKnownHostsLine(trimmed);
const keyType = material?.keyType ?? 'unknown';
keys.push({ keyType, fingerprint, line: trimmed });
}
if (keys.length === 0) {
throw new Error('No host keys returned from ssh-keyscan');
}
return keys;
}
/**
* Build GIT_SSH_COMMAND / core.sshCommand value enforcing strict host-key
* checking against our per-fetch known_hosts file and a single deploy key.
*/
export function buildSshCommand(keyPath: string, knownHostsPath: string): string {
const key = keyPath.split(path.sep).join('/');
const known = knownHostsPath.split(path.sep).join('/');
return [
'ssh',
'-o', 'BatchMode=yes',
'-o', 'StrictHostKeyChecking=yes',
'-o', 'UserKnownHostsFile=' + known,
'-o', 'IdentitiesOnly=yes',
'-o', 'IdentityAgent=none',
'-F', '/dev/null',
'-i', key,
].join(' ');
}
+7
View File
@@ -18,11 +18,18 @@
export type RefKind = 'branch' | 'tag' | 'sha';
/** Deploy-key authentication material for SSH transports. */
export interface SshDeployKeyAuth {
privateKey: string;
knownHostsEntry: string;
}
export interface ResolveRequest {
repoUrl: string;
/** Configured ref: a branch name, a tag name, or a full 40/64-hex commit SHA. */
ref: string;
token?: string | null;
sshAuth?: SshDeployKeyAuth | null;
/**
* Total fetch budget in milliseconds. Note: the resolution round trip
* (ls-remote) is internally capped at 10s regardless of this value, so