The best way to control Claude Code, Codex and more from any computer or phone

main
ts 274 lines 9.65 KB
Raw
1 import * as GitHub from "@alchemy.run/github";
2 import { expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as Repos from "@distilled.cloud/github/repos";
5 import * as Teams from "@distilled.cloud/github/teams";
6 import * as Output from "alchemy/Output";
7 import * as Provider from "alchemy/Provider";
8 import { destroy } from "alchemy/RemovalPolicy";
9 import * as Effect from "effect/Effect";
10 import * as Layer from "effect/Layer";
11 import * as Redacted from "effect/Redacted";
12 import * as Result from "effect/Result";
13 import * as Stream from "effect/Stream";
14 import { gh, mockGitHub, scopedToOwner } from "./scope.ts";
15
16 const testOwner = (value: string) => {
17 if (value !== "alchemy-run-test" && value !== "alchemy-run-test-2") {
18 throw new Error(`Unsafe GITHUB_TEST_OWNER: ${value}`);
19 }
20 return value;
21 };
22 const owner = testOwner(process.env.GITHUB_TEST_OWNER ?? "alchemy-run-test");
23 testOwner(process.env.GITHUB_TEST_OWNER_2 ?? "alchemy-run-test-2");
24 const repositoryName = "alchemy-pr-1572-team-access";
25 const teamName = "alchemy-pr-1572-team-access";
26 const { test } = Test.make({
27 providers: GitHub.providers({ baseUrl: "github.com" }),
28 });
29
30 const getTeams = (repo: string) =>
31 Effect.gen(function* () {
32 return yield* gh(
33 Stream.runCollect(
34 Repos.listTeams.items({
35 owner,
36 repo,
37 per_page: 100,
38 }),
39 ),
40 );
41 });
42
43 const listTestOrgAccess = Effect.gen(function* () {
44 const provider = yield* Provider.findProviderByType<GitHub.TeamAccess>(GitHub.TeamAccess.Type);
45 return yield* provider.list().pipe(scopedToOwner(owner));
46 });
47
48 test.provider(
49 "grant, update, list, and revoke dedicated team access",
50 (stack) =>
51 Effect.gen(function* () {
52 yield* stack.destroy();
53 // Creating a fresh dedicated team requires admin:org; never use an existing team's access.
54 const team = yield* gh(
55 Teams.create({
56 org: owner,
57 name: teamName,
58 privacy: "closed",
59 }),
60 );
61 expect(team.slug).toBe(teamName);
62
63 const deployAccess = (permission?: GitHub.TeamAccessProps["permission"]) =>
64 stack.deploy(
65 Effect.gen(function* () {
66 // Retained intentionally: the default gh token does not have delete_repo.
67 const repo = yield* GitHub.Repository("Repo", {
68 owner,
69 name: repositoryName,
70 visibility: "private",
71 autoInit: true,
72 });
73 return yield* GitHub.TeamAccess("TeamAccess", {
74 owner,
75 repository: Output.map(repo.fullName, (fullName) => fullName.split("/")[1]!),
76 teamSlug: team.slug,
77 permission,
78 }).pipe(destroy());
79 }),
80 );
81
82 yield* Effect.gen(function* () {
83 const created = yield* deployAccess();
84 expect(created).toEqual({ teamSlug: team.slug, permission: "push" });
85 expect(
86 (yield* getTeams(repositoryName)).find((item) => item.slug === team.slug)?.permission,
87 ).toBe("push");
88 expect(yield* listTestOrgAccess).toContainEqual({
89 teamSlug: team.slug,
90 permission: "push",
91 });
92
93 const updated = yield* deployAccess("admin");
94 expect(updated.permission).toBe("admin");
95 expect(
96 (yield* getTeams(repositoryName)).find((item) => item.slug === team.slug)?.permission,
97 ).toBe("admin");
98 }).pipe(
99 Effect.onExit(() =>
100 Effect.gen(function* () {
101 yield* stack.destroy();
102 // Verify access removal while both the repository and team still exist.
103 expect(
104 (yield* getTeams(repositoryName)).find((item) => item.slug === team.slug),
105 ).toBeUndefined();
106 yield* gh(
107 Teams.deleteInOrg({
108 org: owner,
109 team_slug: team.slug,
110 }),
111 );
112 const remaining = yield* gh(
113 Stream.runCollect(
114 Teams.list.items({
115 org: owner,
116 per_page: 100,
117 }),
118 ),
119 );
120 expect(remaining.some((item) => item.slug === team.slug)).toBe(false);
121 }).pipe(Effect.orDie),
122 ),
123 );
124 yield* stack.destroy();
125 }),
126 {
127 tags: ["provider:github", "provider:github:repository", "provider:github:teamaccess", "live"],
128 timeout: 120_000,
129 },
130 );
131
132 test.provider(
133 "list team access only within the authorized test org",
134 (stack) =>
135 Effect.gen(function* () {
136 yield* stack.destroy();
137 expect(Array.isArray(yield* listTestOrgAccess)).toBe(true);
138 yield* stack.destroy();
139 }),
140 { tags: ["provider:github", "provider:github:teamaccess", "live"] },
141 );
142
143 const grants = new Map<string, string>();
144 const requests: { method: string; path: string }[] = [];
145 let rejectWrites = false;
146 const mockedCredentials = mockGitHub((input: string | URL | Request, init?: RequestInit) =>
147 Effect.runPromise(
148 Effect.sync(() => {
149 const url = new URL(
150 typeof input === "string" ? input : input instanceof URL ? input.href : input.url,
151 );
152 const method = init?.method ?? "GET";
153 requests.push({ method, path: url.pathname });
154 const json = (data: unknown, status = 200) =>
155 new Response(JSON.stringify(data), {
156 status,
157 headers: { "content-type": "application/json" },
158 });
159 const match = url.pathname.match(
160 /^\/orgs\/([^/]+)\/teams\/([^/]+)\/repos\/([^/]+)\/([^/]+)$/,
161 );
162 if (match) {
163 expect(match[1]).toBe(owner);
164 expect(match[3]).toBe(owner);
165 const key = `${match[2]}/${match[4]}`;
166 if (method === "PUT") {
167 if (rejectWrites) return json({ message: "Resource not accessible by integration" }, 403);
168 grants.set(key, JSON.parse(String(init?.body)).permission);
169 return new Response(null, { status: 204 });
170 }
171 if (method === "DELETE") {
172 return grants.delete(key)
173 ? new Response(null, { status: 204 })
174 : json({ message: "Not Found" }, 404);
175 }
176 }
177 if (method === "GET" && url.pathname === "/user/repos") {
178 return json([{ owner: { login: owner }, name: repositoryName }]);
179 }
180 if (method === "GET" && url.pathname === `/repos/${owner}/${repositoryName}/teams`) {
181 return json(
182 [...grants].map(([key, permission]) => ({
183 slug: key.split("/")[0],
184 permission,
185 })),
186 );
187 }
188 throw new Error(`Unexpected mocked request: ${method} ${url.pathname}`);
189 }),
190 ),
191 );
192 const { test: unit } = Test.make({
193 providers: Layer.effect(GitHub.Providers, Provider.collection([GitHub.TeamAccess])).pipe(
194 Layer.provide(GitHub.TeamAccessProvider()),
195 Layer.provideMerge(mockedCredentials),
196 ),
197 });
198
199 unit.provider(
200 "unit: defaults, updates, replacement, retention, errors, and idempotent deletion",
201 (stack) =>
202 Effect.gen(function* () {
203 yield* stack.destroy();
204 const deploy = (
205 teamSlug: string,
206 permission?: GitHub.TeamAccessProps["permission"],
207 remove = true,
208 ) =>
209 stack.deploy(
210 Effect.gen(function* () {
211 const access = GitHub.TeamAccess("Access", {
212 owner,
213 repository: repositoryName,
214 teamSlug,
215 permission,
216 });
217 return yield* remove ? access.pipe(destroy()) : access;
218 }),
219 );
220
221 expect((yield* deploy(teamName)).permission).toBe("push");
222 expect(grants.get(`${teamName}/${repositoryName}`)).toBe("push");
223 expect((yield* deploy(teamName, "admin")).permission).toBe("admin");
224 expect(grants.get(`${teamName}/${repositoryName}`)).toBe("admin");
225 const provider = yield* Provider.findProviderByType<GitHub.TeamAccess>(
226 GitHub.TeamAccess.Type,
227 );
228 expect(yield* provider.list()).toEqual([{ teamSlug: teamName, permission: "admin" }]);
229
230 const replacement = `${teamName}-replacement`;
231 yield* deploy(replacement, "pull");
232 expect(grants.has(`${teamName}/${repositoryName}`)).toBe(false);
233 expect(grants.get(`${replacement}/${repositoryName}`)).toBe("pull");
234
235 // An out-of-band revocation must not make stack deletion fail.
236 yield* Effect.sync(() => grants.clear());
237 yield* stack.destroy();
238 expect(requests).toContainEqual({
239 method: "DELETE",
240 path: `/orgs/${owner}/teams/${replacement}/repos/${owner}/${repositoryName}`,
241 });
242
243 yield* deploy(teamName, "triage", false);
244 yield* stack.destroy();
245 expect(grants.get(`${teamName}/${repositoryName}`)).toBe("triage");
246 yield* deploy(teamName, "maintain");
247 yield* stack.destroy();
248 expect(grants.size).toBe(0);
249
250 yield* Effect.sync(() => {
251 rejectWrites = true;
252 });
253 const rejected = yield* deploy(teamName).pipe(Effect.result);
254 expect(Result.isFailure(rejected)).toBe(true);
255 yield* Effect.sync(() => {
256 rejectWrites = false;
257 });
258 yield* stack.destroy();
259 expect(grants.size).toBe(0);
260 }),
261 { tags: ["unit", "provider:github", "provider:github:teamaccess", "local"] },
262 );
263
264 unit(
265 "unit: rejects production and arbitrary fixture owners",
266 Effect.sync(() => {
267 expect(() => testOwner("alchemy-run")).toThrow("Unsafe GITHUB_TEST_OWNER");
268 expect(() => testOwner("personal-account")).toThrow("Unsafe GITHUB_TEST_OWNER");
269 expect(() => testOwner("")).toThrow("Unsafe GITHUB_TEST_OWNER");
270 expect(testOwner("alchemy-run-test")).toBe("alchemy-run-test");
271 expect(testOwner("alchemy-run-test-2")).toBe("alchemy-run-test-2");
272 }),
273 { tags: ["unit", "provider:github", "provider:github:teamaccess", "local"] },
274 );