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

gitHubDiscovery.test.ts

207 lines7.7 KB

1import { ServerSettings, SourceControlProviderKind } from "@t3tools/contracts";
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import { assert, it } from "@effect/vitest";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Redacted from "effect/Redacted";
8import * as Schema from "effect/Schema";
9import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
10import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
11import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
12​
13import * as GitHubCredentials from "./GitHubCredentials.ts";
14import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
15import * as GitHubRest from "./GitHubRest.ts";
16import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
17​
18const unknownContext = (baseUrl: string) => ({
19 provider: { kind: SourceControlProviderKind.make("unknown"), name: "Unknown", baseUrl },
20 remoteName: "origin",
21 remoteUrl: "git@code.example.test:team/project.git",
22});
23​
24// The default host dies on any command, so refinement never reaches `gh`.
25const makeDiscovery = (credential: GitHubRest.GitHubRest["Service"]["credential"]) =>
26 GitHubSourceControlProvider.makeDiscovery.pipe(
27 Effect.provide(
28 Layer.mergeAll(
29 Layer.mock(GitHubRest.GitHubRest)({ credential }),
30 Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({ enabled: false }),
31 TestSourceControlHost.layer(),
32 ),
33 ),
34 Effect.provideService(HostProcess.Environment, {}),
35 );
36​
37it.effect.each([
38 { name: "a credential", credential: "found", claimed: true },
39 { name: "a host turned off in Settings", credential: "disabled", claimed: true },
40 { name: "no credential", credential: "missing", claimed: false },
41] as const)("claims a custom-host remote with $name", (scenario) =>
42 Effect.gen(function* () {
43 const hosts: Array<string> = [];
44 const discovery = yield* makeDiscovery((host) => {
45 hosts.push(host);
46 return scenario.credential === "found"
47 ? Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:fingerprint` })
48 : scenario.credential === "disabled"
49 ? Effect.fail(new GitHubCredentials.GitHubHostDisabledError({ host }))
50 : Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host }));
51 });
52 if (discovery.type !== "managed-cli") return assert.fail("expected a managed CLI");
53 const provider = yield* discovery.refineUnknownRemote({
54 cwd: "/repo",
55 context: unknownContext("https://code.example.test"),
56 });
57 assert.deepStrictEqual(
58 provider,
59 scenario.claimed
60 ? {
61 kind: SourceControlProviderKind.make("github"),
62 name: "GitHub Self-Hosted",
63 baseUrl: "https://code.example.test",
64 }
65 : null,
66 );
67 assert.deepStrictEqual(hosts, ["code.example.test"]);
68 }),
69);
70​
71it.effect("asks for no credential when the identity resolver left the base URL empty", () =>
72 Effect.gen(function* () {
73 const hosts: Array<string> = [];
74 const discovery = yield* makeDiscovery((host) => {
75 hosts.push(host);
76 return Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:fingerprint` });
77 });
78 if (discovery.type !== "managed-cli") return assert.fail("expected a managed CLI");
79 assert.strictEqual(
80 yield* discovery.refineUnknownRemote({ cwd: "/repo", context: unknownContext("") }),
81 null,
82 );
83 assert.deepStrictEqual(hosts, []);
84 }),
85);
86​
87it.effect.each([
88 ["github-work", "git@github-work:team/project.git"],
89 ["github-ci", "git@github-ci:team/project.git"],
90 ["github-work", "ssh://git@github-work:22/team/project.git"],
91 ["github.com-work", "git@github.com-work:team/project.git"],
92] as const)("recognizes a GitHub SSH alias on %s (%s)", ([host, remoteUrl]) =>
93 Effect.gen(function* () {
94 const discovery = yield* makeDiscovery((host) =>
95 host === "github.com"
96 ? Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:fingerprint` })
97 : Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })),
98 );
99 if (discovery.type !== "managed-cli") return assert.fail("expected a managed CLI");
100 const provider = yield* discovery.refineUnknownRemote({
101 cwd: "/repo",
102 context: { ...unknownContext(`https://${host}`), remoteUrl },
103 });
104 assert.deepStrictEqual(provider, {
105 kind: SourceControlProviderKind.make("github"),
106 name: "GitHub",
107 baseUrl: "https://github.com",
108 });
109 }),
110);
111​
112const decodeSettings = Schema.decodeSync(ServerSettings);
113const referencedTokenSettings = decodeSettings({
114 sourceControlHosts: {
115 github: { tokens: { "github.com": { provider: "vault", reference: "op://v/gh" } } },
116 },
117});
118​
119it.effect.each([
120 {
121 name: "a readable",
122 token: "resolved-token",
123 status: "authenticated",
124 detail: "the token saved in Settings",
125 },
126 {
127 name: "no",
128 token: "",
129 status: "authenticated",
130 detail: "GH_TOKEN from the server environment",
131 },
132 // getWithSecrets leaves a reference its secret provider could not read in place.
133 {
134 name: "an unreadable",
135 token: { provider: "vault", reference: "op://v/gh" },
136 status: "unauthenticated",
137 detail: 'secret provider "vault"',
138 },
139])("reports $name saved GitHub token instead of another credential", (scenario) =>
140 Effect.gen(function* () {
141 const paths: Array<string> = [];
142 const discovery = yield* GitHubSourceControlProvider.makeDiscovery.pipe(
143 Effect.provide(
144 Layer.mergeAll(
145 Layer.mock(GitHubRest.GitHubRest)({
146 rest: (input) => {
147 paths.push(input.path);
148 return Effect.succeed({
149 status: 200,
150 headers: {},
151 body: JSON.stringify({ login: "octocat" }),
152 truncated: false,
153 invalidUtf8: false,
154 });
155 },
156 }),
157 Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({ enabled: false }),
158 Layer.effect(
159 SourceControlHost.SourceControlHost,
160 Effect.gen(function* () {
161 const host = yield* SourceControlHost.SourceControlHost;
162 return {
163 ...host,
164 settings: {
165 ...host.settings,
166 getWithSecrets: () =>
167 Effect.succeed(
168 decodeSettings({
169 sourceControlHosts: {
170 github: { tokens: { "github.com": scenario.token } },
171 },
172 }),
173 ),
174 },
175 };
176 }),
177 ).pipe(
178 Layer.provide(
179 TestSourceControlHost.layer({
180 settings: referencedTokenSettings,
181 process: {
182 run: () =>
183 Effect.succeed(
184 TestSourceControlHost.processOutput("", {
185 exitCode: ChildProcessSpawner.ExitCode(1),
186 }),
187 ),
188 },
189 }),
190 ),
191 ),
192 ),
193 ),
194 Effect.provideService(HostProcess.Environment, { GH_TOKEN: "environment-token" }),
195 );
196 if (discovery.type !== "managed-cli") return assert.fail("expected a managed CLI");
197 const item = yield* discovery.probe("/repo");
198 const authenticated = scenario.status === "authenticated";
199 assert.deepStrictEqual(paths, authenticated ? ["user"] : []);
200 assert.strictEqual(item.auth.status, scenario.status);
201 assert.deepStrictEqual(
202 item.auth.account,
203 authenticated ? Option.some("octocat") : Option.none(),
204 );
205 assert.include(Option.getOrThrow(item.auth.detail), scenario.detail);
206 }),
207);