Skip to content
55 changes: 55 additions & 0 deletions apps/server/src/issue/IssueService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,61 @@ describe("IssueService", () => {
}),
);

it.effect("resolves custom-host issue URLs using the binding on the exact authority", () =>
Effect.gen(function* () {
for (const host of ["code.acme.test", "github.acme.test"]) {
const forgejo = IssueTrackerKind.make("forgejo");
const bare = project({ id: "bare", repository: "acme/web", host });
const ported = project({
id: "ported",
repository: "acme/web",
host: `${host}:8443`,
provider: "forgejo",
});
for (const projects of [
[bare, ported],
[ported, bare],
]) {
const service = yield* makeService({
projects,
trackers: [fakeTracker(), fakeTracker({ kind: forgejo })],
});
expect(yield* service.resolveUrl(`https://${host}/acme/web/issues/7`)).toEqual({
projectId: "bare",
tracker: "github",
host,
scope: "acme/web",
key: "7",
writable: true,
});
expect(yield* service.resolveUrl(`https://${host}:8443/acme/web/issues/7`)).toEqual({
projectId: "ported",
tracker: "forgejo",
host: `${host}:8443`,
scope: "acme/web",
key: "7",
writable: true,
});
expect(yield* service.resolveUrl(`https://${host}/other/repo/issues/8`)).toEqual({
projectId: "bare",
tracker: "github",
host,
scope: "other/repo",
key: "8",
writable: false,
});
const unbound = yield* service
.resolveUrl("https://unbound.test/acme/web/issues/7")
.pipe(Effect.result);
expect(unbound).toMatchObject({
_tag: "Failure",
failure: { _tag: "IssueOperationError", reason: "not-found" },
});
}
}
}),
);

it.effect("sends writes as interactive requests and reads as background ones", () =>
Effect.gen(function* () {
const interactive: Array<readonly [string, boolean]> = [];
Expand Down
21 changes: 17 additions & 4 deletions apps/server/src/issue/IssueService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -642,7 +642,23 @@ const make = Effect.gen(function* () {

const resolveUrl: IssueService["Service"]["resolveUrl"] = Effect.fn("IssueService.resolveUrl")(
function* (url, preferredProjectId) {
const gitHost = sourceControlDefinitions.parseIssueUrl(url);
const urlHost = parseUrl(url);
const authority = urlHost?.host.toLowerCase();
const { supported } =
urlHost === null
? { supported: [] }
: yield* listProjects({ host: urlHost.hostname.toLowerCase(), authority });
const onUrlAuthority = supported.filter((project) => project.host === authority);
const urlBindings = onUrlAuthority.length > 0 ? onUrlAuthority : supported;
const gitHost =
urlBindings
.map((project) => {
const definition = sourceControlDefinitions.find(project.tracker);
return definition === undefined
? null
: sourceControlDefinitions.parseIssueUrl(url, definition.kind);
})
.find((candidate) => candidate !== null) ?? sourceControlDefinitions.parseIssueUrl(url);
const standalone = gitHost === null ? findStandaloneIssueUrl(registry.standalone, url) : null;
const parsed =
gitHost === null
Expand All @@ -656,9 +672,6 @@ const make = Effect.gen(function* () {
});
}
const { tracker, link } = parsed;
// A link names its server's port; a binding does only when its remote or web URL did.
const authority = new URL(url).host.toLowerCase();
const { supported } = yield* listProjects({ host: link.host, authority });
const onHost = supported.filter((project) => project.tracker === tracker);
const onAuthority = onHost.filter((project) => project.host === authority);
const onTracker = onAuthority.length > 0 ? onAuthority : onHost;
Expand Down
71 changes: 55 additions & 16 deletions packages/client-runtime/src/issueLinks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,28 +35,67 @@ describe("resolveIssueLinkTarget", () => {
expect(target?.ref).toMatchObject({ tracker: "github", host: "github.com", ...expected });
});

it("prefers the project bound to the link's own port over one on the bare hostname", () => {
const enterprise = (id: string, host: string) =>
({
it.each(["github.example.com", "code.acme.test"])(
"prefers the project bound to an issue link's own port on %s",
(host) => {
const enterprise = (id: string, host: string) =>
({
id: ProjectId.make(id),
environmentId: EnvironmentId.make("env"),
repositoryIdentity: {
canonicalKey: `${host}/acme/web`,
provider: SourceControlProviderKind.make("github"),
displayName: "acme/web",
owner: "acme",
name: "web",
},
}) as never;
const target = resolveIssueLinkTarget({
url: `https://${host}:8443/acme/web/issues/7`,
projects: [enterprise("bare", host), enterprise("ported", `${host}:8443`)],
});
expect(target?.ref.projectId).toBe("ported");
},
);

it.each(["code.acme.test", "github.acme.test"])(
"uses the exact authority's tracker on %s regardless of project order",
(host) => {
const binding = (id: string, host: string, provider: string) => ({
id: ProjectId.make(id),
environmentId: EnvironmentId.make("env"),
repositoryIdentity: {
canonicalKey: `${host}/acme/web`,
provider: SourceControlProviderKind.make("github"),
locator: {
source: "git-remote" as const,
remoteName: "origin",
remoteUrl: `https://${host}/acme/web.git`,
},
provider: SourceControlProviderKind.make(provider),
displayName: "acme/web",
owner: "acme",
name: "web",
},
}) as never;
const target = resolveIssueLinkTarget({
url: "https://github.example.com:8443/acme/web/issues/7",
projects: [
enterprise("bare", "github.example.com"),
enterprise("ported", "github.example.com:8443"),
],
});
expect(target?.ref.projectId).toBe("ported");
});
});
const bare = binding("bare", host, "github");
const ported = binding("ported", `${host}:8443`, "forgejo");
for (const projects of [
[bare, ported],
[ported, bare],
]) {
expect(
resolveIssueLinkTarget({
url: `https://${host}:8443/acme/web/issues/7`,
projects,
})?.ref,
).toEqual({
projectId: "ported",
tracker: "forgejo",
host: `${host}:8443`,
scope: "acme/web",
key: "7",
});
}
},
);

it.each([
"https://github.com.evil.example/acme/web/issues/7",
Expand Down
47 changes: 32 additions & 15 deletions packages/client-runtime/src/issueLinks.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import type { IssueRef } from "@t3tools/contracts";
import {
IssueTrackerKind,
type IssueRef,
type SourceControlProviderKind,
} from "@t3tools/contracts";

import { sourceControlClients } from "./sourceControlClients.ts";
import type { EnvironmentProject } from "./state/shell.ts";
Expand All @@ -7,7 +11,7 @@ type LinkProject = Pick<EnvironmentProject, "id" | "environmentId" | "repository

/** The host and scope a project's git-host tracker is bound to, the way the server resolves it. */
function projectIssueBinding(project: LinkProject): {
readonly tracker: string;
readonly tracker: SourceControlProviderKind;
readonly host: string;
readonly scope: string;
} | null {
Expand All @@ -22,9 +26,10 @@ function projectIssueBinding(project: LinkProject): {
};
}

function linkAuthority(url: string): string | null {
function linkHost(url: string): { readonly hostname: string; readonly authority: string } | null {
try {
return new URL(url).host.toLowerCase();
const { hostname, host } = new URL(url);
return { hostname: hostname.toLowerCase(), authority: host.toLowerCase() };
} catch {
return null;
}
Expand All @@ -42,19 +47,31 @@ export function resolveIssueLinkTarget<Project extends LinkProject>(input: {
readonly projects: ReadonlyArray<Project>;
readonly preferredProjectId?: string | undefined;
}): { readonly project: Project; readonly ref: IssueRef } | null {
const parsed = sourceControlClients.parseIssueUrl(input.url);
if (parsed === null) return null;
const { definition, link } = parsed;
// A link names its server's port; a binding does only when its remote or web URL did.
const authority = linkAuthority(input.url);
const onHost = input.projects.flatMap((project) => {
const url = linkHost(input.url);
if (url === null) return null;
const { hostname, authority } = url;
const bindings = input.projects.flatMap((project) => {
const binding = projectIssueBinding(project);
return binding === null ||
binding.tracker !== definition.kind ||
(binding.host !== link.host && binding.host !== authority)
? []
: [{ project, binding }];
return binding === null ? [] : [{ project, binding }];
});
const onUrlHost = bindings.filter(
({ binding }) => binding.host === hostname || binding.host === authority,
);
const onUrlAuthority = onUrlHost.filter(({ binding }) => binding.host === authority);
const urlBindings = onUrlAuthority.length > 0 ? onUrlAuthority : onUrlHost;
// A self-hosted server can have any hostname, so a host a project is bound to names its tracker.
const parsed =
urlBindings
.map(({ binding }) => sourceControlClients.parseIssueUrl(input.url, binding.tracker))
.find((candidate) => candidate !== null) ?? sourceControlClients.parseIssueUrl(input.url);
if (parsed === null) return null;
const { definition, link } = parsed;
const onHost = bindings.filter(
({ binding }) =>
binding.tracker === definition.kind &&
(binding.host === link.host || binding.host === authority),
);
const onAuthority = onHost.filter((candidate) => candidate.binding.host === authority);
const bound = onAuthority.length > 0 ? onAuthority : onHost;
const preferFirst = (candidates: typeof bound) =>
Expand All @@ -67,7 +84,7 @@ export function resolveIssueLinkTarget<Project extends LinkProject>(input: {
project: lender.project,
ref: {
projectId: lender.project.id,
tracker: lender.binding.tracker as IssueRef["tracker"],
tracker: IssueTrackerKind.make(lender.binding.tracker),
host: lender.binding.host,
scope: own === undefined ? link.scope : lender.binding.scope,
key: link.key,
Expand Down
20 changes: 14 additions & 6 deletions packages/source-control-core/src/shared/definition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,8 +274,11 @@ export interface SourceControlDefinition {
readonly parseCommitUrl?: (url: URL, known: boolean) => CommitLink | null;
/** Null when the URL is not one of this host's change requests. */
readonly parseChangeRequestUrl: (url: URL) => ParsedChangeRequestUrl | null;
/** Null when the URL is not one of this host's issues. Absent for a host with none. */
readonly parseIssueUrl?: (url: URL) => IssueLink | null;
/**
* Null when the URL is not one of this host's issues. Absent for a host with none. `known` is
* set when the caller already knows this host serves the URL's repository.
*/
readonly parseIssueUrl?: (url: URL, known: boolean) => IssueLink | null;
/**
* The repository URL when `url` is a page inside one of this host's repositories. `known` is set
* when the caller already knows this host serves the URL's repository. Off a known host, return
Expand Down Expand Up @@ -670,9 +673,13 @@ export interface SourceControlDefinitionRegistry {
readonly findByPublicDomain: (hostname: string) => SourceControlDefinition | undefined;
/** The first host, in registry order, that reads `url` as one of its change requests. */
readonly parseChangeRequestUrl: (url: string) => ParsedChangeRequest | null;
/** The first host, in registry order, that reads `url` as one of its issues. */
/**
* The first host, in registry order, that reads `url` as one of its issues; with `kind`, only
* that host, which the caller knows serves the URL.
*/
readonly parseIssueUrl: (
url: string,
kind?: SourceControlProviderKind,
) => { readonly definition: SourceControlDefinition; readonly link: IssueLink } | null;
readonly parseCommitUrl: (url: string, kind?: SourceControlProviderKind) => ParsedCommit | null;
readonly findByChangeRequestUrl: (url: string) => SourceControlDefinition | undefined;
Expand Down Expand Up @@ -792,11 +799,12 @@ export function makeSourceControlDefinitionRegistry(
);
},
parseChangeRequestUrl,
parseIssueUrl: (value) => {
parseIssueUrl: (value, kind) => {
const url = httpUrl(value);
if (url === null) return null;
for (const definition of claimOrder) {
const link = definition.parseIssueUrl?.(url) ?? null;
const preferred = kind === undefined ? undefined : byKind.get(kind);
for (const definition of kind === undefined ? claimOrder : preferred ? [preferred] : []) {
const link = definition.parseIssueUrl?.(url, preferred !== undefined) ?? null;
if (link !== null) return { definition, link };
}
return null;
Expand Down
4 changes: 3 additions & 1 deletion packages/source-control-forgejo/src/shared/definition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,9 @@ export const definition = defineSourceControl({
return link === null ? null : { ...link, authority: url.host.toLowerCase() };
},
// `/issues/` is too generic a path to believe from a host not named after Forgejo or Gitea.
parseIssueUrl: (url) => (isForgejoHost(url.hostname) ? parseIssuePath(url, ISSUE_PATH) : null),
// A known project's host can be any self-hosted name.
parseIssueUrl: (url, known) =>
known || isForgejoHost(url.hostname) ? parseIssuePath(url, ISSUE_PATH) : null,
changeRequestUrlFromReferenceAutolink: () => null,
commitUrl: (input) => buildCommitUrl(input, "commit"),
parseCommitUrl: (url) => parseCommitPath(url, COMMIT_PATH),
Expand Down
5 changes: 3 additions & 2 deletions packages/source-control-github/src/shared/definition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,9 @@ export const definition = defineSourceControl({
parseCommitUrl: (url, known) =>
known || isGitHubHost(url.hostname) ? parseCommitPath(url, COMMIT_PATH) : null,
parseChangeRequestUrl: (url) => parseChangeRequestPath(url, CHANGE_REQUEST_PATH),
// `/issues/` is too generic a path to believe from a host that is not GitHub's.
parseIssueUrl: (url) => (isGitHubHost(url.hostname) ? parseIssuePath(url, ISSUE_PATH) : null),
// `/issues/` is too generic a path to believe from a host not known to be GitHub's.
parseIssueUrl: (url, known) =>
known || isGitHubHost(url.hostname) ? parseIssuePath(url, ISSUE_PATH) : null,
repositoryUrlFromPage: (url) =>
isGitHubHost(url.hostname) ? repositoryUrlFromPagePath(url, REPOSITORY_PAGE_PATH) : null,
// GitHub writes every bare reference through `/issues/`, including pull requests.
Expand Down
Loading