TypeScript
fix(github): read github.com-<name> SSH aliases through github.com (#22246)
matthias-scaleb5a5ab4ea5ca
diff --git a/packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts b/packages/source-control-github/src/server/GitHubSourceControlProvider.test.tsindex 0fb270156ce..e14b495a4ef 100644--- a/packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts+++ b/packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts@@ -288,6 +288,102 @@ describe("GitHubSourceControlProvider repository resolution", () => {assert.deepStrictEqual(paths, ["github.com repos/acme/web"]);}).pipe(Effect.provide(layer));});++ it.effect.each([+ ["github", "git@github:acme/web.git"],+ ["github.com-scale", "[email protected]:acme/web.git"],+ ["github.com-scale", "ssh://[email protected]:22/acme/web.git"],+ ] as const)("reads an SSH alias on %s through github.com (%s)", ([host, remoteUrl]) => {+ const hosts: string[] = [];+ const { layer } = harness({+ remotes: remotesOutput(["origin", remoteUrl]),+ api: {+ rest: (input) =>+ Effect.sync(() => {+ hosts.push(`${input.host} ${input.path}`);+ return restResponse({+ full_name: "acme/web",+ html_url: "https://github.com/acme/web",+ ssh_url: "[email protected]:acme/web.git",+ default_branch: "main",+ });+ }),+ },+ });+ return Effect.gen(function* () {+ const gh = yield* GitHubSourceControlProvider.make;+ const resolveWebHost = gh.resolveRemoteWebHost;+ assert.ok(resolveWebHost);+ assert.strictEqual(+ yield* resolveWebHost({+ cwd: "/repo",+ context: { ...githubContext(host), remoteUrl },+ resolveContext: () => Effect.succeed(null),+ }),+ "github.com",+ );+ yield* gh.getDefaultBranch({ cwd: "/repo" });+ yield* gh.getDefaultBranch({+ cwd: "/repo",+ context: { ...githubContext(host), remoteUrl },+ });+ assert.deepStrictEqual(hosts, ["github.com repos/acme/web", "github.com repos/acme/web"]);+ }).pipe(Effect.provide(layer));+ });++ it.effect.each(["sole", "upstream", "missing"])(+ "preserves an HTTPS context host with %s remotes",+ (mode) => {+ const paths: string[] = [];+ const remoteUrl = "https://github.com-scale/me/web.git";+ const { layer } = harness({+ remotes:+ mode === "missing"+ ? ""+ : remotesOutput(+ ["origin", remoteUrl],+ ...(mode === "upstream"+ ? ([["upstream", "https://github.com/acme/web.git"]] as const)+ : []),+ ),+ api: {+ rest: (input) =>+ Effect.sync(() => {+ paths.push(`${input.host} ${input.path}`);+ return restResponse({+ full_name: "me/web",+ html_url: "https://github.com-scale/me/web",+ ssh_url: "[email protected]:me/web.git",+ default_branch: "trunk",+ });+ }),+ },+ });+ return Effect.gen(function* () {+ const gh = yield* GitHubSourceControlProvider.make;+ const resolveWebHost = gh.resolveRemoteWebHost;+ assert.ok(resolveWebHost);+ for (const url of [remoteUrl, "[email protected]:me/web.git"]) {+ assert.strictEqual(+ yield* resolveWebHost({+ cwd: "/repo",+ context: { ...githubContext("github.com-scale"), remoteUrl: url },+ resolveContext: () => Effect.succeed(null),+ }),+ url === remoteUrl ? "github.com-scale" : "github.com-evil.example",+ );+ }+ assert.strictEqual(+ yield* gh.getDefaultBranch({+ cwd: "/repo",+ context: { ...githubContext("github.com-scale"), remoteUrl },+ }),+ "trunk",+ );+ assert.deepStrictEqual(paths, ["github.com-scale repos/me/web"]);+ }).pipe(Effect.provide(layer));+ },+ );});describe("GitHubSourceControlProvider change request lookups by head", () => {diff --git a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts b/packages/source-control-github/src/server/GitHubSourceControlProvider.tsindex bfc5fc29041..4a42e9422a5 100644--- a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts+++ b/packages/source-control-github/src/server/GitHubSourceControlProvider.ts@@ -859,6 +859,9 @@ export const make = Effect.gen(function* () {return SourceControlProvider.SourceControlProvider.of({kind: SourceControlProviderKind.make("github"),+ resolveRemoteWebHost: Effect.fn("GitHubSourceControlProvider.resolveRemoteWebHost")(+ ({ context }) => Effect.succeed(gitHubApiHostForRemote(context.remoteUrl)),+ ),// GitHub matches bare heads; read a full page to disambiguate forks by owner.headBranchProbe: ({ headSelectors }) => ({headSelectors: headSelectors.filter((selector) => !selector.includes(":")),diff --git a/packages/source-control-github/src/server/gitHubRepositoryResolution.test.ts b/packages/source-control-github/src/server/gitHubRepositoryResolution.test.tsindex 9269116ea3c..3447c3a1be2 100644--- a/packages/source-control-github/src/server/gitHubRepositoryResolution.test.ts+++ b/packages/source-control-github/src/server/gitHubRepositoryResolution.test.ts@@ -2,6 +2,7 @@ import { assert, describe, it } from "@effect/vitest";import {gitHubApiHostForRemote,+ resolveGitHubRepository,parseGitHubRepositorySelector,selectGitHubBaseRepository,} from "./gitHubRepositoryResolution.ts";@@ -48,6 +49,64 @@ describe("selectGitHubBaseRepository", () => {);});+ it("honors a marked SSH alias origin over upstream", () => {+ for (const url of [+ "[email protected]:me/web.git",+ "ssh://[email protected]:22/me/web.git",+ "git@github-work:me/web.git",+ ]) {+ const input = {+ remotes: remotes(["origin", url], ["upstream", "https://github.com/acme/web.git"]),+ resolved: "remote.origin.gh-resolved base",+ };+ assert.deepStrictEqual(select(input), { owner: "me", name: "web" }, url);+ assert.deepStrictEqual(+ resolveGitHubRepository({ ...input, hostHint: undefined, defaultHost: "github.com" }),+ { host: "github.com", locator: { host: "github.com", owner: "me", name: "web" } },+ url,+ );+ }+ });++ it("does not honor a github.com mark on a different or unrecognized host", () => {+ for (const url of [+ "[email protected]:me/web.git",+ "[email protected]:me/web.git",+ "[email protected]:me/web.git",+ "https://github.com-scale/me/web.git",+ "git@work:me/web.git",+ ]) {+ const input = {+ remotes: remotes(["origin", url], ["upstream", "https://github.com/acme/web.git"]),+ resolved: "remote.origin.gh-resolved base",+ };+ assert.strictEqual(select(input), null, url);+ assert.deepStrictEqual(+ resolveGitHubRepository({ ...input, hostHint: "github.com", defaultHost: "github.com" }),+ { host: "github.com", locator: { host: "github.com", owner: "acme", name: "web" } },+ url,+ );+ }+ });++ it("preserves selection behavior for real hosts with explicit ports", () => {+ const input = {+ remotes: remotes(["origin", "https://github.example.com:8443/me/web.git"]),+ resolved: "remote.origin.gh-resolved acme/other",+ };+ assert.strictEqual(+ selectGitHubBaseRepository({ ...input, host: "github.example.com:8443" }),+ null,+ );+ assert.deepStrictEqual(+ resolveGitHubRepository({ ...input, hostHint: undefined, defaultHost: "github.com" }),+ {+ host: "github.example.com:8443",+ locator: { host: "github.example.com:8443", owner: "me", name: "web" },+ },+ );+ });+it("leaves gh to choose when it might weigh the remotes differently", () => {for (const input of [{ remotes: "" },@@ -60,7 +119,7 @@ describe("selectGitHubBaseRepository", () => {["mirror", "[email protected]:me/web.git"],),},- { remotes: remotes(["origin", "git@github-work:me/web.git"]) },+ { remotes: remotes(["origin", "git@work:me/web.git"]) },{remotes: remotes(["origin", "[email protected]:me/web.git"],@@ -111,6 +170,136 @@ describe("gitHubApiHostForRemote", () => {});});+describe("github.com-<name> SSH aliases", () => {+ it("reads a per-account alias through github.com", () => {+ for (const url of [+ "[email protected]:scalable-so/scalablev2.git",+ "[email protected]:acme/web.git",+ "ssh://[email protected]/acme/web.git",+ "ssh://[email protected]:22/acme/web.git",+ ]) {+ assert.strictEqual(gitHubApiHostForRemote(url), "github.com", url);+ }+ });++ it("never maps a hostile or real DNS host onto github.com", () => {+ for (const [url, host] of [+ ["[email protected]:acme/web.git", "github.com-evil.example"],+ ["ssh://[email protected]/acme/web.git", "github.com-evil.example"],+ ["[email protected]:acme/web.git", "github.com.evil.example"],+ ["[email protected]:acme/web.git", null],+ ["https://github.com-scale/acme/web.git", "github.com-scale"],+ ] as const) {+ assert.strictEqual(gitHubApiHostForRemote(url), host, url);+ }+ });++ it("resolves the API host and repository from an alias remote and its host hint", () => {+ const remotes = [+ "origin\[email protected]:scalable-so/scalablev2.git (fetch)",+ "origin\[email protected]:scalable-so/scalablev2.git (push)",+ ].join("\n");+ const expected = {+ host: "github.com",+ locator: { host: "github.com", owner: "scalable-so", name: "scalablev2" },+ };+ for (const hostHint of ["github.com-scale", undefined]) {+ assert.deepStrictEqual(+ resolveGitHubRepository({ remotes, resolved: "", hostHint, defaultHost: "github.com" }),+ expected,+ );+ }+ });++ it.each([false, true])("preserves an HTTPS alias-shaped host hint (upstream: %s)", (upstream) => {+ const remotes = [+ "origin\thttps://github.com-scale/me/web.git (fetch)",+ ...(upstream ? ["upstream\thttps://github.com/acme/web.git (fetch)"] : []),+ ].join("\n");+ assert.deepStrictEqual(+ resolveGitHubRepository({+ remotes,+ resolved: "",+ hostHint: "github.com-scale",+ defaultHost: "github.com",+ }),+ {+ host: "github.com-scale",+ locator: { host: "github.com-scale", owner: "me", name: "web" },+ },+ );+ });++ it("requires matching SSH evidence to normalize a dotted hint", () => {+ for (const remotes of [+ "",+ "origin\[email protected]:me/web.git (fetch)",+ "origin\[email protected]:me/web.git (push)",+ ]) {+ assert.deepStrictEqual(+ resolveGitHubRepository({+ remotes,+ resolved: "",+ hostHint: "GitHub.com-Scale",+ defaultHost: "github.com",+ }),+ { host: "github.com-scale", locator: null },+ );+ }+ });++ it("preserves a dotted hint when matching remotes use both transports", () => {+ const entries = [+ "origin\thttps://github.com-scale/me/web.git (fetch)",+ "upstream\[email protected]:acme/web.git (fetch)",+ ];+ for (const [remotes, hostHint, resolved] of [+ [entries.join("\n"), "github.com-scale", "remote.origin.gh-resolved base"],+ [entries.join("\n"), "github.com-scale", ""],+ [entries.toReversed().join("\n"), undefined, "remote.origin.gh-resolved base"],+ [entries.toReversed().join("\n"), undefined, ""],+ ] as const) {+ assert.deepStrictEqual(+ resolveGitHubRepository({+ remotes,+ resolved,+ hostHint,+ defaultHost: "github.com",+ }),+ {+ host: "github.com-scale",+ locator: { host: "github.com-scale", owner: "me", name: "web" },+ },+ );+ }+ });++ it("retains dotless hint compatibility without remote evidence", () => {+ for (const hostHint of ["github", "github-work", "workgithub"]) {+ assert.deepStrictEqual(+ resolveGitHubRepository({ remotes: "", resolved: "", hostHint, defaultHost: hostHint }),+ { host: "github.com", locator: null },+ );+ }+ });++ it("keeps a hostile host hint and its remote off github.com", () => {+ const remotes = "origin\[email protected]:acme/web.git (fetch)";+ assert.deepStrictEqual(+ resolveGitHubRepository({+ remotes,+ resolved: "",+ hostHint: "github.com-evil.example",+ defaultHost: "github.com-evil.example",+ }),+ {+ host: "github.com-evil.example",+ locator: { host: "github.com-evil.example", owner: "acme", name: "web" },+ },+ );+ });+});+describe("parseGitHubRepositorySelector", () => {it("reads host/owner/name only when the host is a plain hostname", () => {assert.deepStrictEqual(parseGitHubRepositorySelector("GHE.corp:8443/acme/web", "github.com"), {diff --git a/packages/source-control-github/src/server/gitHubRepositoryResolution.ts b/packages/source-control-github/src/server/gitHubRepositoryResolution.tsindex 3376412f0c3..e42e428d9d9 100644--- a/packages/source-control-github/src/server/gitHubRepositoryResolution.ts+++ b/packages/source-control-github/src/server/gitHubRepositoryResolution.ts@@ -21,7 +21,7 @@ export function parseFetchRemotes(.map((match) => ({ name: match[1]!, url: match[2]! }));}-/** gh priority: marked default, upstream/github/origin, sole remote. Null if ambiguous or SSH-aliased. */+/** gh priority: marked default, upstream/github/origin, sole remote. Null if ambiguous. */export function selectGitHubBaseRepository(input: {readonly remotes: string;readonly resolved: string;@@ -30,7 +30,11 @@ export function selectGitHubBaseRepository(input: {const host = input.host.toLowerCase();const repositories = new Map<string, { readonly owner: string; readonly name: string }>();for (const remote of parseFetchRemotes(input.remotes)) {- const [remoteHost, owner, name, ...rest] = normalizeGitRemoteUrl(remote.url).split("/");+ const [normalizedHost, owner, name, ...rest] = normalizeGitRemoteUrl(remote.url).split("/");+ const remoteHost =+ normalizedHost && isSshRemoteUrl(remote.url)+ ? (apiHostForSshAlias(normalizedHost) ?? normalizedHost)+ : normalizedHost;if (remoteHost !== host || !owner || !name || rest.length > 0) return null;repositories.set(remote.name, { owner, name });}@@ -69,7 +73,7 @@ export function resolveGitHubRepository(input: {host: gitHubApiHostForRemote(remote.url),}));const host =- (input.hostHint === undefined ? undefined : apiHostForHint(input.hostHint)) ??+ (input.hostHint === undefined ? undefined : apiHostForHint(input.hostHint, fetchRemotes)) ??fetchRemotes.find((remote) => remote.name === "origin" && remote.host !== null)?.host ??fetchRemotes.find((remote) => remote.host !== null)?.host ??input.defaultHost;@@ -83,7 +87,9 @@ export function resolveGitHubRepository(input: {const rank = (name: string) => ["upstream", "github", "origin"].indexOf(name.toLowerCase());const candidates = fetchRemotes.filter(- (remote) => remote.host === host || normalizeGitRemoteUrl(remote.url).split("/")[0] === host,+ (remote) =>+ remote.host === host ||+ (remote.host === null && normalizeGitRemoteUrl(remote.url).split("/")[0] === host),).toSorted((left, right) => {const l = rank(left.name);@@ -148,18 +154,36 @@ export function parsePullRequestReference(return { kind: "branch", headSelector: trimmed };}-/** SSH aliases without a domain cannot identify an API host; default to github.com. */+// An additional dot is a real DNS host, never a github.com SSH alias.+const GITHUB_DOT_COM_SSH_ALIAS = /^github\.com-[a-z0-9_-]+$/u;++function apiHostForSshAlias(host: string): string | null | undefined {+ if (!host.includes(".")) return host.includes("github") ? "github.com" : null;+ return GITHUB_DOT_COM_SSH_ALIAS.test(host) ? "github.com" : undefined;+}++/** Recognized GitHub SSH aliases use github.com for API requests. */export function gitHubApiHostForRemote(remoteUrl: string): string | null {const remote = parseGitRemoteHost(remoteUrl);if (remote === null) return null;const host = new URL(`https://${remote.host}`).host.toLowerCase();- if (isSshRemoteUrl(remoteUrl) && !host.includes(".")) {- return host.includes("github") ? "github.com" : null;+ if (isSshRemoteUrl(remoteUrl)) {+ const aliased = apiHostForSshAlias(host);+ if (aliased !== undefined) return aliased;}return definition.recognizeRemote(remote) === null ? null : host;}-function apiHostForHint(host: string): string {+function apiHostForHint(host: string, remotes: ReadonlyArray<{ readonly url: string }>): string {const normalized = host.toLowerCase();- return !normalized.includes(".") && normalized.includes("github") ? "github.com" : normalized;+ if (GITHUB_DOT_COM_SSH_ALIAS.test(normalized)) {+ const matching = remotes.filter(+ (remote) => normalizeGitRemoteUrl(remote.url).split("/")[0] === normalized,+ );+ // A hint carries no transport; an HTTPS remote or missing evidence must not select+ // the github.com endpoint and credentials for a dotted host.+ if (matching.length === 0 || matching.some((remote) => !isSshRemoteUrl(remote.url)))+ return normalized;+ }+ return apiHostForSshAlias(normalized) ?? normalized;}