Skip to content
Source
Sign inSign up
Open History to see the last commit

GitLabSourceControlProvider.test.ts

283 lines9.7 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
3import { refineUnknownRemoteProvider } from "@t3tools/source-control-core/server/discovery";
4import { processOutput } from "@t3tools/source-control-testing/TestSourceControlHost";
5import { assert, it } from "@effect/vitest";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import { ChildProcessSpawner } from "effect/process";
10​
11import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
12import * as GitLabCli from "./GitLabCli.ts";
13import { parseGitLabAuthStatusHosts } from "./gitLabAuthStatus.ts";
14import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
15import { definition } from "../shared/definition.ts";
16​
17function makeProvider(gitlab: Partial<GitLabCli.GitLabCli["Service"]>) {
18 return GitLabSourceControlProvider.make.pipe(
19 Effect.provide(
20 Layer.mergeAll(Layer.mock(GitLabCli.GitLabCli)(gitlab), TestSourceControlHost.layer()),
21 ),
22 );
24​
25it("accepts authenticated GitLab hosts when another configured host fails", () => {
26 const auth = GitLabSourceControlProvider.discovery.parseAuth({
27 exitCode: ChildProcessSpawner.ExitCode(1),
28 stdout: `gitlab.com
29 x gitlab.com: API call failed: 401 Unauthorized
30 ! No token found
31self-hosted.example.test
32 ✓ Logged in to self-hosted.example.test as gitlab-user
33 ✓ Token found: ******
34`,
35 stderr: "",
36 });
37​
38 assert.deepStrictEqual(
39 {
40 status: auth.status,
41 account: auth.account,
42 host: auth.host,
43 },
44 {
45 status: "authenticated",
46 account: Option.some("gitlab-user"),
47 host: Option.some("self-hosted.example.test"),
48 },
49 );
50});
51​
52it("refines unknown GitLab remotes with mixed-case provider hosts", () => {
53 const provider = GitLabSourceControlProvider.discovery.refineUnknownRemote?.({
54 cwd: "/repo",
55 context: {
56 provider: {
57 kind: SourceControlProviderKind.make("unknown"),
58 name: "Self-Hosted.Example.Test",
59 baseUrl: "https://Self-Hosted.Example.Test",
60 },
61 remoteName: "origin",
62 remoteUrl: "https://Self-Hosted.Example.Test/group/project.git",
63 },
64 auth: {
65 exitCode: ChildProcessSpawner.ExitCode(0),
66 stdout: `self-hosted.example.test
67 ✓ Logged in to self-hosted.example.test as gitlab-user
68 ✓ Token found: ******
69`,
70 stderr: "",
71 },
72 });
73​
74 assert.deepStrictEqual(provider, {
75 kind: "gitlab",
76 name: "GitLab Self-Hosted",
77 baseUrl: "https://Self-Hosted.Example.Test",
78 });
79});
80​
81it("tells a host glab has no login for apart from output that cannot say", () => {
82 const refine = (stderr: string) =>
83 GitLabSourceControlProvider.discovery.refineUnknownRemote?.({
84 cwd: "/repo",
85 context: {
86 provider: {
87 kind: SourceControlProviderKind.make("unknown"),
88 name: "git.example.test",
89 baseUrl: "https://git.example.test",
90 },
91 remoteName: "origin",
92 remoteUrl: "https://git.example.test/group/project.git",
93 },
94 auth: { exitCode: ChildProcessSpawner.ExitCode(1), stdout: "", stderr },
95 });
96​
97 assert.strictEqual(
98 refine("x git.example.test has not been authenticated with glab. Run `glab auth login`"),
99 null,
100 );
101 assert.strictEqual(
102 refine("No GitLab instances have been authenticated with glab. Run `glab auth login`"),
103 null,
104 );
105 assert.strictEqual(refine("git.example.test\n x API call failed: 503"), undefined);
106});
107​
108// regression: #15395 self-hosted GitLab remotes resolve bare MR numbers once glab is signed in
109it.effect.each([
110 [
111 "https://code.example.test:8443@Code.Example.Test:8443/Team/Repo.git",
112 true,
113 "gitlab",
114 "Code.Example.Test:8443",
115 ],
116 ["git@code.example.test:team/repo.git", true, "gitlab"],
117 ["https://code.example.test/team/repo.git", false, "unknown"],
118 ["https://github.com/team/repo.git", true, "github"],
119] as const)(
120 "resolves MR numbers for %s with authenticated=%s as %s",
121 ([remoteUrl, authenticated, expectedProvider, expectedAuthHost = "code.example.test"]) =>
122 Effect.gen(function* () {
123 const provider = yield* makeProvider({});
124 const identity = {
125 canonicalKey: normalizeGitRemoteUrl(remoteUrl),
126 locator: { source: "git-remote" as const, remoteName: "upstream", remoteUrl },
127 rootPath: "/repo",
128 // Only a remote no host recognised is left for glab to refine.
129 provider: SourceControlProviderKind.make(
130 expectedProvider === "github" ? "github" : "unknown",
131 ),
132 };
133 let authCalls = 0;
134 const refined = yield* (
135 provider.refineRepositoryIdentity?.({
136 identity,
137 resolveContext: (input) =>
138 refineUnknownRemoteProvider({
139 ...input,
140 specs: [GitLabSourceControlProvider.discovery],
141 process: {
142 run: ({ command, args, cwd }) => {
143 authCalls++;
144 assert.deepStrictEqual(
145 { command, args, cwd },
146 {
147 command: "glab",
148 args: ["auth", "status", "--hostname", expectedAuthHost],
149 cwd: "/repo",
150 },
151 );
152 return Effect.succeed(
153 processOutput(
154 authenticated
155 ? `${expectedAuthHost}\n ✓ Logged in to ${expectedAuthHost} as gitlab-user\n`
156 : "x code.example.test has not been authenticated with glab.",
157 { exitCode: ChildProcessSpawner.ExitCode(authenticated ? 0 : 1) },
158 ),
159 );
160 },
161 },
162 }).pipe(
163 Effect.map(({ provider }) =>
164 provider ? { ...input.context, provider } : input.context,
165 ),
166 ),
167 }) ?? Effect.succeed(identity)
168 );
169 if (expectedProvider === "gitlab") {
170 const [host, ...repository] = refined.canonicalKey.split("/");
171 assert.strictEqual(
172 definition.changeRequestUrl({
173 host: host!,
174 repository: repository.join("/"),
175 number: 42,
176 }),
177 "https://code.example.test/team/repo/-/merge_requests/42",
178 );
179 }
180 assert.deepStrictEqual(refined, {
181 ...identity,
182 provider: SourceControlProviderKind.make(expectedProvider),
183 });
184 if (expectedProvider === "github") assert.strictEqual(authCalls, 0);
185 }),
186);
187​
188it("parses authenticated GitLab auth status hosts with ports and single-label names", () => {
189 assert.deepStrictEqual(
190 parseGitLabAuthStatusHosts(`localhost:8080
191 ✓ Logged in to localhost:8080 as local-user
192selfhosted
193 ✓ Logged in to selfhosted as single-label-user
194`),
195 [
196 { host: "localhost:8080", account: "local-user" },
197 { host: "selfhosted", account: "single-label-user" },
198 ],
199 );
200});
201​
202it.effect.each(["merge_requests", "issues"])(
203 "resolves %s subjects on the linked host without using the checkout",
204 (kind) =>
205 Effect.gen(function* () {
206 const provider = yield* makeProvider({
207 execute: (input) => {
208 assert.deepStrictEqual(input.args, [
209 "api",
210 "--hostname",
211 "gitlab.com",
212 `projects/group%2Fsubgroup%2Fproject/${kind}/42`,
213 ]);
214 assert.strictEqual(input.maxOutputBytes, 32_000);
215 assert.strictEqual(input.timeoutMs, 3_000);
216 return Effect.succeed({
217 exitCode: ChildProcessSpawner.ExitCode(0),
218 stdout: JSON.stringify({
219 title: "Pairing expiry",
220 description: "Preserve remote access",
221 }),
222 stderr: "",
223 stdoutTruncated: false,
224 stderrTruncated: false,
225 });
226 },
227 });
228 const lookup = provider.resolveLink?.({
229 cwd: "/unrelated",
230 url: new URL(`https://gitlab.com/group/subgroup/project/-/${kind}/42`),
231 });
232 assert.ok(lookup);
233 assert.deepStrictEqual(yield* lookup, {
234 title: "Pairing expiry",
235 body: "Preserve remote access",
236 });
237 for (const url of [
238 "https://gitlab.com/owner/repo",
239 "https://gitlab.attacker.test/team/project/-/issues/1",
240 ]) {
241 assert.strictEqual(
242 provider.resolveLink?.({ cwd: "/unrelated", url: new URL(url) }),
243 undefined,
244 );
245 }
246 }),
247);
248​
249it.effect.each(["read", "decode"] as const)(
250 "retains the %s failure without exposing its raw contents",
251 (stage) =>
252 Effect.gen(function* () {
253 const cause = new GitLabCli.GitLabCliCommandError({
254 command: "glab",
255 cwd: "/repo",
256 operation: "execute",
257 cause: new Error("private response text"),
258 });
259 const provider = yield* makeProvider({
260 execute: () =>
261 stage === "read"
262 ? Effect.fail(cause)
263 : Effect.succeed({
264 exitCode: ChildProcessSpawner.ExitCode(0),
265 stdout: "private response text",
266 stderr: "",
267 stdoutTruncated: false,
268 stderrTruncated: false,
269 }),
270 });
271 const lookup = provider.resolveLink?.({
272 cwd: "/repo",
273 url: new URL("https://gitlab.com/owner/repo/-/issues/42"),
274 });
275 assert.ok(lookup);
276 const error = yield* Effect.flip(lookup);
277 assert.strictEqual(error.operation, stage === "read" ? "resolveLink" : "resolveLink.decode");
278 assert.strictEqual(error.detail, "The linked subject could not be read.");
279 assert.notInclude(error.message, "private response text");
280 if (stage === "read") assert.strictEqual(error.cause, cause);
281 else assert.propertyVal(error.cause, "_tag", "SchemaError");
282 }),
283);