fix(server): recognize authenticated GitHub Enterprise hosts (#11059)

Co-authored-by: Claude Code <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-10-08 19:46:02 +00:00
1 parent 740f591221
commit cdd331b6c3
6 files changed
+388 -20

No files matched your search

@@ -516,6 +516,53 @@ function makeService(input: {
);
}
it.effect("lists GitHub Enterprise PRs for a stored unknown repository after host discovery", () =>
Effect.gen(function* () {
const service = yield* makeService({
projects: [
project({
id: "p1",
title: "enterprise",
workspaceRoot: "/repo",
repository: "team/project",
provider: "unknown",
host: "code.example.test",
}),
],
providers: [
fakeProvider("github", {
/** Supplies a PR only after verifying discovery retained the Enterprise repository target. */
listChangeRequests: ({ host, repository }) => {
assert.strictEqual(host, "code.example.test");
assert.strictEqual(repository, "team/project");
return Effect.succeed({
items: [changeRequest(42, "2026-07-05T00:00:00Z")],
truncated: false,
continues: false,
});
},
}),
],
/** Stands in for discovery claiming the custom host as GitHub. */
resolveHandle: ({ context }) => {
assert.ok(context);
return Effect.succeed({
context: {
...context,
provider: { ...context.provider, kind: "github", name: "GitHub Self-Hosted" },
},
provider: undefined as never,
});
},
});
const result = yield* service.list({ state: "open" });
assert.deepStrictEqual(
result.entries.map(({ host, number }) => [host, number]),
[["code.example.test", 42]],
);
}),
);
it.effect("refines unknown self-hosted GitLab projects before listing merge requests", () =>
Effect.gen(function* () {
let refinementCalls = 0;
@@ -1,3 +1,4 @@
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
@@ -74,6 +75,7 @@ function harness(input: {
readonly remotes: string;
readonly api: Partial<GitHubApi.GitHubApi["Service"]>;
readonly localBranches?: ReadonlyArray<string>;
readonly resolved?: string;
/** Fails the local branch listing, the first git read a checkout makes. */
readonly gitFailure?: unknown;
}) {
@@ -110,7 +112,9 @@ function harness(input: {
const process = Layer.mock(VcsProcess.VcsProcess)({
run: (args) =>
Effect.succeed(
args.args[0] === "remote" ? processOutput(input.remotes) : processOutput("", 1),
args.args[0] === "remote"
? processOutput(input.remotes)
: processOutput(input.resolved ?? "", input.resolved ? 0 : 1),
),
});
const layer = Layer.mergeAll(
@@ -965,3 +969,196 @@ it("names the environment token that overrides the Settings choice", () => {
);
assert.strictEqual(auth.accounts?.[2]?.environmentVariable, "GH_TOKEN");
});
it.live.each([
"[email protected]:team/project.git",
"ssh://[email protected]/team/project.git",
"https://code.example.test/team/project.git",
])("keeps Enterprise operations on the selected remote: %s", (remoteUrl) => {
const graphql: GitHubApi.GitHubGraphQlInput[] = [];
const rest: GitHubApi.GitHubRestInput[] = [];
const api = {
graphql: (input: GitHubApi.GitHubGraphQlInput) =>
Effect.sync(() => {
graphql.push(input);
const pr = {
...node(42, "feature", "team"),
url: "https://code.example.test/team/project/pull/42",
isCrossRepository: false,
headRepository: { name: "project", nameWithOwner: "team/project" },
};
return encodeJson({
data: {
repository:
input.operation === "getPullRequest" ? { pullRequest: pr } : { h0: { nodes: [pr] } },
},
});
}),
rest: (input: GitHubApi.GitHubRestInput) =>
Effect.sync(() => {
rest.push(input);
return restResponse({
full_name: "team/project",
html_url: `https://${input.host}/team/project`,
ssh_url: `git@${input.host}:team/project.git`,
default_branch: "main",
});
}),
};
const { layer, git } = harness({
remotes: remotesOutput(
["origin", "[email protected]:team/project.git"],
["enterprise", remoteUrl],
),
api,
});
return Effect.gen(function* () {
const provider = yield* GitHubSourceControlProvider.make;
const fs = yield* FileSystem.FileSystem;
const bodyFile = yield* fs.makeTempFileScoped({ suffix: ".md" });
yield* fs.writeFileString(bodyFile, "Enterprise PR");
const input = {
cwd: "/repo",
context: {
provider: {
kind: "github" as const,
name: "GitHub Self-Hosted",
baseUrl: "https://code.example.test",
},
remoteName: "enterprise",
remoteUrl,
},
};
for (const state of ["open", "closed"] as const) {
const prs = yield* provider.listChangeRequests({
...input,
state,
headSelector: "feature",
});
assert.strictEqual(prs[0]?.url, "https://code.example.test/team/project/pull/42");
}
yield* provider.getChangeRequest({ ...input, reference: "42" });
yield* provider.getChangeRequest({ ...input, reference: "feature" });
yield* provider.createChangeRequest({
...input,
baseRefName: "main",
headSelector: "feature",
title: "PR",
bodyFile,
});
assert.strictEqual(yield* provider.getDefaultBranch(input), "main");
yield* provider.checkoutChangeRequest({ ...input, reference: "42" });
yield* provider.getRepositoryCloneUrls({ ...input, repository: "team/other" });
yield* provider.getRepositoryCloneUrls({ ...input, repository: "github.com/team/explicit" });
assert.strictEqual(graphql.length, 5);
for (const request of graphql) {
assert.strictEqual(request.host, "code.example.test");
assert.strictEqual(request.variables?.owner, "team");
assert.strictEqual(request.variables?.name, "project");
}
assert.deepStrictEqual(
rest.map(({ host, path }) => [host, path]),
[
["code.example.test", "repos/team/project/pulls"],
["code.example.test", "repos/team/project"],
["code.example.test", "repos/team/other"],
["github.com", "repos/team/explicit"],
],
);
assert.deepStrictEqual(git.find(([name]) => name === "fetchRemoteTrackingBranch")?.[1], {
cwd: "/repo",
remoteName: "enterprise",
remoteBranch: "feature",
});
}).pipe(Effect.provide(layer), Effect.provideService(HostProcessEnvironment, {}), Effect.scoped);
});
it.effect.each([
{ host: "github.com", resolved: "", envRepository: "", expected: "acme/web" },
{ host: "code.example.test", resolved: "", envRepository: "", expected: "acme/web" },
{
host: "github.com",
resolved: "remote.origin.gh-resolved base",
envRepository: "",
expected: "me/web",
},
{
host: "code.example.test",
resolved: "remote.origin.gh-resolved base",
envRepository: "",
expected: "me/web",
},
{
host: "github.com",
resolved: "remote.upstream.gh-resolved acme/other",
envRepository: "",
expected: "acme/other",
},
{
host: "code.example.test",
resolved: "remote.upstream.gh-resolved acme/other",
envRepository: "",
expected: "acme/other",
},
{ host: "github.com", resolved: "", envRepository: "chosen/repo", expected: "chosen/repo" },
{
host: "code.example.test",
resolved: "",
envRepository: "chosen/repo",
expected: "chosen/repo",
},
])(
"preserves repository precedence on $host: $resolved $envRepository",
({ host, resolved, envRepository, expected }) => {
const targets: string[] = [];
const { layer } = harness({
remotes: remotesOutput(
["origin", `git@${host}:me/web.git`],
["upstream", `git@${host}:acme/web.git`],
),
resolved,
api: {
rest: (input) =>
Effect.sync(() => {
targets.push(`${input.host}/${input.path}`);
return restResponse({
full_name: expected,
html_url: `https://${host}/${expected}`,
ssh_url: `git@${host}:${expected}.git`,
default_branch: "main",
});
}),
},
});
return Effect.gen(function* () {
const provider = yield* GitHubSourceControlProvider.make;
const fs = yield* FileSystem.FileSystem;
const bodyFile = yield* fs.makeTempFileScoped();
yield* fs.writeFileString(bodyFile, "Body");
const input = {
cwd: "/repo",
context: {
provider: { kind: "github" as const, name: "GitHub", baseUrl: `https://${host}` },
remoteName: "origin",
remoteUrl: `git@${host}:me/web.git`,
},
};
yield* provider.getDefaultBranch(input);
yield* provider.createChangeRequest({
...input,
baseRefName: "main",
headSelector: "me:feature",
title: "PR",
bodyFile,
});
assert.deepStrictEqual(targets, [
`${host}/repos/${expected}`,
`${host}/repos/${expected}/pulls`,
]);
}).pipe(
Effect.provide(layer),
Effect.provideService(HostProcessEnvironment, { GH_REPO: envRepository }),
Effect.scoped,
);
},
);
@@ -30,6 +30,7 @@ import {
type NormalizedGitHubPullRequestRecord,
} from "./gitHubPullRequests.ts";
import {
gitHubApiHostForRemote,
parseFetchRemotes,
parseGitHubRepositorySelector,
parsePullRequestReference,
@@ -255,7 +256,30 @@ export const makeDiscovery = Effect.gen(function* () {
},
} satisfies SourceControlProviderDiscoveryItem;
}),
refineUnknownRemote: () => Effect.succeed(null),
/**
* Claims a custom host GitHub holds a credential for, from whichever source supplies it
* (Settings, the environment or gh). A host turned off in Settings is claimed too, so its
* error says so instead of "unsupported host".
*/
refineUnknownRemote: ({ context }) => {
// Identity resolution also probes providers before a web base URL is known.
const url = URL.parse(context.provider.baseUrl);
if (!url?.host) return Effect.succeed(null);
return api.credential(url.host).pipe(
Effect.as(true),
Effect.catchTags({ GitHubHostDisabledError: () => Effect.succeed(true) }),
Effect.orElseSucceed(() => false),
Effect.map((known) =>
known
? ({
kind: "github",
name: "GitHub Self-Hosted",
baseUrl: context.provider.baseUrl,
} as const)
: null,
),
);
},
} satisfies SourceControlManagedCliDiscoverySpec;
});
@@ -469,13 +493,18 @@ export const make = Effect.gen(function* () {
});
/**
* The repository `gh` would act on in `cwd`: GH_REPO, else the remote `gh` would pick, else
* the remote the caller resolved the provider from, else the best-ranked GitHub remote.
* Uses GH_REPO, then gh's remote selection on the detected host. The provider context is
* a fallback when the checkout's remotes cannot resolve that repository.
*/
const resolveRepository = Effect.fn("GitHubSourceControlProvider.resolveRepository")(
function* (input: { readonly cwd: string; readonly host?: string | undefined }) {
function* (input: {
readonly cwd: string;
readonly host?: string | undefined;
readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
}) {
const envRepository = environment.GH_REPO?.trim();
const defaultHost = (input.host ?? environment.GH_HOST ?? "github.com").toLowerCase();
const hostHint = input.host ?? contextHost(input.context);
const defaultHost = (hostHint ?? environment.GH_HOST ?? "github.com").toLowerCase();
if (envRepository) {
const locator = parseGitHubRepositorySelector(envRepository, defaultHost);
if (locator !== null) return locator;
@@ -487,10 +516,18 @@ export const make = Effect.gen(function* () {
const { host, locator } = resolveGitHubRepository({
remotes: remotes?.exitCode === 0 ? remotes.stdout : "",
resolved: resolved?.exitCode === 0 ? resolved.stdout : "",
hostHint: input.host,
hostHint,
defaultHost,
});
if (locator !== null) return locator;
if (input.context) {
const remote = normalizeGitRemoteUrl(input.context.remoteUrl);
const fallback = parseGitHubRepositorySelector(
`${host}/${remote.slice(remote.indexOf("/") + 1)}`,
host,
);
if (fallback !== null) return fallback;
}
return yield* failure(
`No GitHub repository on ${host} was found among this checkout's git remotes.`,
);
@@ -583,10 +620,11 @@ export const make = Effect.gen(function* () {
readonly headSelector: string;
readonly state: PullRequestListState;
readonly limit: number;
readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
readonly host?: string | undefined;
readonly allowReserve: boolean;
}) {
const locator = yield* resolveRepository({ cwd: input.cwd, host: input.host });
const locator = yield* resolveRepository(input);
const limit = Math.min(Math.max(Math.trunc(input.limit), 1), 100);
// `owner:branch` names a fork's branch. GitHub filters on the branch name only, so the
// owner is matched on the rows it returns.
@@ -613,6 +651,7 @@ export const make = Effect.gen(function* () {
function* (input: {
readonly cwd: string;
readonly reference: string;
readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
readonly host?: string | undefined;
}) {
const parsed = parsePullRequestReference(input.reference);
@@ -625,6 +664,7 @@ export const make = Effect.gen(function* () {
state,
limit: 1,
host: input.host,
context: input.context,
allowReserve: true,
});
const [open] = yield* lookup("open");
@@ -632,10 +672,7 @@ export const make = Effect.gen(function* () {
if (found === undefined) return yield* notFound("No pull request has this head branch.");
return found;
}
const locator =
parsed.kind === "url"
? parsed.locator
: yield* resolveRepository({ cwd: input.cwd, host: input.host });
const locator = parsed.kind === "url" ? parsed.locator : yield* resolveRepository(input);
const decodeDetail = "GitHub returned an invalid pull request.";
const decoded = yield* graphqlJson(
{
@@ -715,11 +752,11 @@ export const make = Effect.gen(function* () {
readonly cwd: string;
readonly reference: string;
readonly force?: boolean;
readonly context?: SourceControlProvider.SourceControlProviderContext;
}) {
const reference = parsePullRequestReference(input.reference);
const pullRequest = yield* readPullRequest({ cwd: input.cwd, reference: input.reference });
const base =
reference.kind === "url" ? reference.locator : yield* resolveRepository({ cwd: input.cwd });
const pullRequest = yield* readPullRequest(input);
const base = reference.kind === "url" ? reference.locator : yield* resolveRepository(input);
const baseNameWithOwner = `${base.owner}/${base.name}`.toLowerCase();
const headNameWithOwner = pullRequest.headRepositoryNameWithOwner ?? null;
const isCrossRepository =
@@ -735,8 +772,10 @@ export const make = Effect.gen(function* () {
const remoteFor = (nameWithOwner: string) =>
parseFetchRemotes(remotes).find(
(remote) =>
(gitHubApiHostForRemote(remote.url) ??
normalizeGitRemoteUrl(remote.url).split("/")[0]) === base.host &&
normalizeGitRemoteUrl(remote.url).split("/").slice(1).join("/") ===
nameWithOwner.toLowerCase(),
nameWithOwner.toLowerCase(),
)?.name ?? null;
const baseRemote = Effect.suspend(() => {
const known = remoteFor(baseNameWithOwner);
@@ -920,6 +959,7 @@ export const make = Effect.gen(function* () {
state: input.state,
limit: input.limit ?? (input.state === "open" ? 1 : 20),
host: contextHost(input.context),
context: input.context,
allowReserve,
}),
),
@@ -937,7 +977,7 @@ export const make = Effect.gen(function* () {
),
createChangeRequest: (input) =>
Effect.gen(function* () {
const locator = yield* resolveRepository({ cwd: input.cwd });
const locator = yield* resolveRepository(input);
const body = yield* fileSystem
.readFileString(input.bodyFile)
.pipe(
@@ -969,7 +1009,7 @@ export const make = Effect.gen(function* () {
),
getRepositoryCloneUrls: (input) =>
Effect.gen(function* () {
const fallbackHost = (yield* resolveRepository({ cwd: input.cwd }).pipe(
const fallbackHost = (yield* resolveRepository(input).pipe(
Effect.map((locator) => locator.host),
Effect.orElseSucceed(() => environment.GH_HOST ?? "github.com"),
)).toLowerCase();
@@ -1020,6 +1060,7 @@ export const make = Effect.gen(function* () {
const locator = yield* resolveRepository({
cwd: input.cwd,
host: contextHost(input.context),
context: input.context,
});
const repository = yield* readRepository(locator);
const branch = repository.default_branch?.trim() ?? "";
@@ -4,6 +4,7 @@ import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Redacted from "effect/Redacted";
import { ChildProcessSpawner } from "effect/process";
import { VcsRepositoryDetectionError } from "@t3tools/contracts";
@@ -16,6 +17,7 @@ import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
import * as BitbucketApi from "./BitbucketApi.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as GitHubApi from "./GitHubApi.ts";
import * as GitHubCredentials from "./GitHubCredentials.ts";
import * as GitLabCli from "./GitLabCli.ts";
import * as ForgejoCli from "./ForgejoCli.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
@@ -97,7 +99,11 @@ function makeRegistry(input: {
Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
Layer.mock(BitbucketApi.BitbucketApi)({}),
ServerSettings.ServerSettingsService.layerTest(),
Layer.mock(GitHubApi.GitHubApi)(input.githubApi ?? {}),
Layer.mock(GitHubApi.GitHubApi)({
// No GitHub credential unless a test supplies one, so custom hosts stay unclaimed.
credential: (host) => Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })),
...input.githubApi,
}),
Layer.mock(GitVcsDriver.GitVcsDriver)({}),
Layer.mock(GitLabCli.GitLabCli)(input.gitlab ?? {}),
Layer.mock(ForgejoCli.ForgejoCli)({ listLogins: () => Effect.succeed([]) }),
@@ -355,3 +361,75 @@ it.effect(
}
}).pipe(Effect.scoped),
);
it.effect.each([
{ name: "a credential", credential: "found", expected: "github" },
// Claimed so the error says the host is turned off, not that it is unsupported.
{ name: "a host turned off in Settings", credential: "disabled", expected: "github" },
{ name: "no credential", credential: "missing", expected: "unknown" },
] as const)("resolves custom-host remotes with $name", (scenario) =>
Effect.gen(function* () {
const hosts: Array<string> = [];
const commands: Array<string> = [];
const registry = yield* makeRegistry({
remotes: [{ name: "origin", url: "[email protected]:team/project.git" }],
process: {
run: ({ command }) => {
commands.push(command);
return Effect.succeed(processOutput(""));
},
},
githubApi: {
credential: (host) => {
hosts.push(host);
return scenario.credential === "found"
? Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:fingerprint` })
: scenario.credential === "disabled"
? Effect.fail(new GitHubCredentials.GitHubHostDisabledError({ host }))
: Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host }));
},
},
});
const handle = yield* registry.resolveHandle({ cwd: "/repo" });
assert.strictEqual(handle.provider.kind, scenario.expected);
assert.strictEqual(handle.context?.provider.baseUrl, "https://code.example.test");
assert.deepStrictEqual(hosts, ["code.example.test"]);
// Recognition goes through the credential layer; gh is only one of its sources.
assert.notInclude(commands, "gh");
}),
);
it.effect("skips GitHub discovery for the identity resolver's empty base URL", () =>
Effect.gen(function* () {
const hosts: string[] = [];
const remoteUrl = "[email protected]:team/workspace.git";
const registry = yield* makeRegistry({
remotes: [{ name: "origin", url: remoteUrl }],
githubApi: {
credential: (host) => {
hosts.push(host);
return Effect.succeed({
token: Redacted.make("token"),
fingerprint: `${host}:fingerprint`,
});
},
},
});
const context = {
provider: { kind: "unknown" as const, name: "Unknown", baseUrl: "" },
remoteName: "origin",
remoteUrl,
};
const unresolved = yield* registry.resolveHandle({ cwd: "/repo", context });
assert.deepStrictEqual(unresolved.context, context);
assert.deepStrictEqual(hosts, []);
const resolved = yield* registry.resolveHandle({ cwd: "/repo" });
assert.strictEqual(resolved.provider.kind, "github");
assert.strictEqual(
resolved.context?.provider.baseUrl,
"https://githubenterprise.dev.example.com",
);
assert.deepStrictEqual(hosts, ["githubenterprise.dev.example.com"]);
}),
);
@@ -99,7 +99,9 @@ export function resolveGitHubRepository(input: {
// the ones on this host (an SSH alias counts as its API host).
const rank = (name: string) => ["upstream", "github", "origin"].indexOf(name.toLowerCase());
const candidates = fetchRemotes
.filter((remote) => remote.host === host)
.filter(
(remote) => remote.host === host || normalizeGitRemoteUrl(remote.url).split("/")[0] === host,
)
.toSorted((left, right) => {
const l = rank(left.name);
const r = rank(right.name);
+3
View File
@@ -24,6 +24,9 @@ If `gh` is signed in to several accounts or hosts, expand **GitHub** in the same
the account each host uses or turn a host off. A saved token or `GH_TOKEN` takes precedence
over that choice; a host turned off stays off either way.
For GitHub Enterprise, sign in with `gh auth login --hostname YOUR_HOST`. T3 Code treats a
custom server name as GitHub once it has a credential for that host.
### Forgejo and Gitea
Install [Forgejo CLI (`fj`)](https://codeberg.org/forgejo-contrib/forgejo-cli) or