@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 320 lines 13 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { Network } from "@alchemy.run/aws/EC2/Network";
3 import { AccessEntry, Cluster } from "@alchemy.run/aws/EKS";
4 import { Role } from "@alchemy.run/aws/IAM";
5 import { expect } from "@alchemy.run/test";
6 import * as Test from "@alchemy.run/test/Alchemy";
7 import * as eks from "@distilled.cloud/aws/eks";
8 import * as iam from "@distilled.cloud/aws/iam";
9 import * as Provider from "alchemy/Provider";
10 import * as Effect from "effect/Effect";
11
12 const { test } = Test.make({ providers: AWS.providers() });
13
14 // Ungated live probe: `list()` enumerates every EKS access entry across every
15 // cluster in the account/region. It walks `listClusters` (paginated), then
16 // `listAccessEntries` per cluster (paginated), and hydrates each via
17 // `describeAccessEntry` + `listAssociatedAccessPolicies` into the same
18 // Attributes shape `read` returns. We don't deploy here because a fresh EKS
19 // cluster takes 10+ minutes to provision (see the gated test below) — but this
20 // still verifies the cluster-fan-out + pagination + mapping against the live
21 // API and asserts every returned row is well-formed (the array is empty when
22 // the account has no clusters).
23 test.provider(
24 "list returns the account/region access entries",
25 () =>
26 Effect.gen(function* () {
27 const provider = yield* Provider.findProvider(AccessEntry);
28 const all = yield* provider.list();
29
30 expect(Array.isArray(all)).toBe(true);
31 for (const entry of all) {
32 expect(typeof entry.accessEntryArn).toBe("string");
33 expect(typeof entry.clusterName).toBe("string");
34 expect(typeof entry.principalArn).toBe("string");
35 expect(Array.isArray(entry.kubernetesGroups)).toBe(true);
36 expect(Array.isArray(entry.accessPolicies)).toBe(true);
37 expect(entry.tags).toBeDefined();
38 }
39 }),
40 { tags: ["provider:aws", "provider:aws:eks", "live"] },
41 );
42
43 // Full deploy-then-list assertion. SKIPPED by default because an EKS cluster
44 // takes 10+ minutes to create (and requires a VPC + subnets + cluster IAM
45 // role), which exceeds the CI budget. Set AWS_TEST_EKS_CLUSTER to the name of a
46 // pre-provisioned cluster to run it on an entitled account unchanged. A
47 // throwaway IAM role is created out-of-band to serve as the access entry's
48 // principal.
49 const clusterName = process.env.AWS_TEST_EKS_CLUSTER;
50
51 const principalRoleName = "alchemy-test-eks-accessentry-list-principal";
52
53 test.provider.skipIf(!clusterName)(
54 "list enumerates the deployed access entry",
55 (stack) =>
56 Effect.gen(function* () {
57 // Idempotent delete: safe when the role never existed (pre-clean) or was
58 // already removed (post-clean after a partial prior run).
59 const deletePrincipalRole = iam
60 .deleteRole({ RoleName: principalRoleName })
61 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
62
63 yield* stack.destroy();
64
65 // acquireRelease guarantees the out-of-band role is deleted on success,
66 // failure, AND interruption; the deterministic name + pre-clean above
67 // means a re-run reclaims any orphan from a previously-killed run.
68 yield* Effect.gen(function* () {
69 const role = yield* Effect.acquireRelease(
70 // Pre-clean a leftover from a killed run, then create.
71 deletePrincipalRole.pipe(
72 Effect.andThen(
73 iam.createRole({
74 RoleName: principalRoleName,
75 AssumeRolePolicyDocument: JSON.stringify({
76 Version: "2012-10-17",
77 Statement: [
78 {
79 Effect: "Allow",
80 Principal: { Service: "ec2.amazonaws.com" },
81 Action: ["sts:AssumeRole"],
82 },
83 ],
84 }),
85 }),
86 ),
87 ),
88 () => deletePrincipalRole.pipe(Effect.catch(() => Effect.void)),
89 );
90
91 const deployed = yield* stack.deploy(
92 Effect.gen(function* () {
93 return yield* AccessEntry("ListAccessEntry", {
94 clusterName: clusterName!,
95 principalArn: role.Role.Arn,
96 });
97 }),
98 );
99
100 const provider = yield* Provider.findProvider(AccessEntry);
101 const all = yield* provider.list();
102
103 expect(all.some((entry) => entry.accessEntryArn === deployed.accessEntryArn)).toBe(true);
104
105 yield* stack.destroy();
106 }).pipe(Effect.scoped);
107 }),
108 {
109 tags: ["provider:aws", "provider:aws:eks", "provider:aws:iam", "live"],
110 timeout: 240_000,
111 },
112 );
113
114 const viewPolicyArn = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSViewPolicy";
115 const editPolicyArn = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy";
116 const adminPolicyArn = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSAdminPolicy";
117
118 const principalTrustPolicy = {
119 Version: "2012-10-17" as const,
120 Statement: [
121 {
122 Effect: "Allow" as const,
123 Principal: { Service: "ec2.amazonaws.com" },
124 Action: ["sts:AssumeRole"],
125 },
126 ],
127 };
128
129 // Regression for #2192: EKS reports a cluster scope as
130 // `{ type: "cluster", namespaces: [] }`, which never matched the desired
131 // `{ type: "cluster" }`, so every reconcile re-associated and then
132 // disassociated the policy — leaving the principal with no access. A scope
133 // change took the same associate-then-disassociate path. Every step bumps the
134 // `revision` tag so the entry is reconciled even when its policies are
135 // unchanged. Provisions its own Auto Mode cluster (~10 min create, ~5 min
136 // delete), so it skips under `--fast`.
137 test.provider.skipIf(!!process.env.FAST)(
138 "reconcile converges policies, groups, and username without spurious updates",
139 (stack) =>
140 Effect.gen(function* () {
141 yield* stack.destroy();
142
143 const deployEntry = (
144 revision: string,
145 accessPolicies?: { policyArn: string; accessScope: eks.AccessScope }[],
146 identity: { kubernetesGroups?: string[]; username?: string } = {},
147 ) =>
148 stack.deploy(
149 Effect.gen(function* () {
150 const network = yield* Network("AccessEntryNetwork", {
151 cidrBlock: "10.85.0.0/16",
152 availabilityZones: 2,
153 });
154 const cluster = yield* Cluster("AccessEntryCluster", {
155 compute: "auto",
156 resourcesVpcConfig: {
157 subnetIds: network.publicSubnetIds,
158 endpointPublicAccess: true,
159 },
160 });
161 const principal = yield* Role("AccessEntryPrincipal", {
162 assumeRolePolicyDocument: principalTrustPolicy,
163 });
164 return yield* AccessEntry("PolicyAccessEntry", {
165 clusterName: cluster.clusterName,
166 principalArn: principal.roleArn,
167 accessPolicies,
168 kubernetesGroups: identity.kubernetesGroups,
169 username: identity.username,
170 tags: { revision },
171 });
172 }),
173 );
174
175 const associated = (entry: AccessEntry["Attributes"]) =>
176 eks
177 .listAssociatedAccessPolicies({
178 clusterName: entry.clusterName,
179 principalArn: entry.principalArn,
180 })
181 .pipe(
182 Effect.map((response) =>
183 Object.fromEntries(
184 (response.associatedAccessPolicies ?? []).map((policy) => [
185 policy.policyArn!,
186 {
187 type: policy.accessScope?.type,
188 namespaces: [...(policy.accessScope?.namespaces ?? [])].sort(),
189 },
190 ]),
191 ),
192 ),
193 );
194
195 const described = (entry: AccessEntry["Attributes"]) =>
196 eks
197 .describeAccessEntry({
198 clusterName: entry.clusterName,
199 principalArn: entry.principalArn,
200 })
201 .pipe(Effect.map((response) => response.accessEntry!));
202
203 const clusterScope = { type: "cluster", namespaces: [] };
204
205 // Create with a cluster-scoped and a namespace-scoped policy.
206 const created = yield* deployEntry("1", [
207 { policyArn: viewPolicyArn, accessScope: { type: "cluster" } },
208 { policyArn: editPolicyArn, accessScope: { type: "namespace", namespaces: ["a"] } },
209 ]);
210 expect(yield* associated(created)).toEqual({
211 [viewPolicyArn]: clusterScope,
212 [editPolicyArn]: { type: "namespace", namespaces: ["a"] },
213 });
214
215 // Unchanged policies survive a reconcile.
216 const retagged = yield* deployEntry("2", [
217 { policyArn: viewPolicyArn, accessScope: { type: "cluster" } },
218 { policyArn: editPolicyArn, accessScope: { type: "namespace", namespaces: ["a"] } },
219 ]);
220 expect(yield* associated(retagged)).toEqual({
221 [viewPolicyArn]: clusterScope,
222 [editPolicyArn]: { type: "namespace", namespaces: ["a"] },
223 });
224
225 // A namespace change updates the association in place, and a policy
226 // added to an existing entry is associated.
227 const rescoped = yield* deployEntry("3", [
228 { policyArn: viewPolicyArn, accessScope: { type: "cluster" } },
229 { policyArn: editPolicyArn, accessScope: { type: "namespace", namespaces: ["b", "a"] } },
230 { policyArn: adminPolicyArn, accessScope: { type: "namespace", namespaces: ["a"] } },
231 ]);
232 expect(yield* associated(rescoped)).toEqual({
233 [viewPolicyArn]: clusterScope,
234 [editPolicyArn]: { type: "namespace", namespaces: ["a", "b"] },
235 [adminPolicyArn]: { type: "namespace", namespaces: ["a"] },
236 });
237
238 // A scope type change updates the association in place, and the same
239 // namespaces in a different order are unchanged.
240 const retyped = yield* deployEntry("4", [
241 { policyArn: viewPolicyArn, accessScope: { type: "cluster" } },
242 { policyArn: editPolicyArn, accessScope: { type: "namespace", namespaces: ["a", "b"] } },
243 { policyArn: adminPolicyArn, accessScope: { type: "cluster" } },
244 ]);
245 expect(yield* associated(retyped)).toEqual({
246 [viewPolicyArn]: clusterScope,
247 [editPolicyArn]: { type: "namespace", namespaces: ["a", "b"] },
248 [adminPolicyArn]: clusterScope,
249 });
250
251 // A policy disassociated out of band is restored on the next reconcile.
252 yield* eks.disassociateAccessPolicy({
253 clusterName: retyped.clusterName,
254 principalArn: retyped.principalArn,
255 policyArn: viewPolicyArn,
256 });
257 const restored = yield* deployEntry("5", [
258 { policyArn: viewPolicyArn, accessScope: { type: "cluster" } },
259 { policyArn: editPolicyArn, accessScope: { type: "namespace", namespaces: ["a", "b"] } },
260 { policyArn: adminPolicyArn, accessScope: { type: "cluster" } },
261 ]);
262 expect(yield* associated(restored)).toEqual({
263 [viewPolicyArn]: clusterScope,
264 [editPolicyArn]: { type: "namespace", namespaces: ["a", "b"] },
265 [adminPolicyArn]: clusterScope,
266 });
267
268 // Removing policies disassociates only those policies.
269 const trimmed = yield* deployEntry("6", [
270 { policyArn: viewPolicyArn, accessScope: { type: "cluster" } },
271 ]);
272 expect(yield* associated(trimmed)).toEqual({ [viewPolicyArn]: clusterScope });
273
274 // Omitting `accessPolicies` disassociates every policy.
275 const emptied = yield* deployEntry("7");
276 expect(yield* associated(emptied)).toEqual({});
277 expect(emptied.accessPolicies).toEqual([]);
278
279 // Groups and a username set in props are applied.
280 const named = yield* deployEntry("8", [], {
281 kubernetesGroups: ["group-b", "group-a"],
282 username: "deployer",
283 });
284 const namedEntry = yield* described(named);
285 expect([...(namedEntry.kubernetesGroups ?? [])].sort()).toEqual(["group-a", "group-b"]);
286 expect(namedEntry.username).toBe("deployer");
287
288 // Groups are a set: the same groups in another order are not rewritten.
289 // EKS stores groups in the order given and bumps `modifiedAt` only when
290 // an update changes the entry.
291 const reordered = yield* deployEntry("9", [], {
292 kubernetesGroups: ["group-a", "group-b"],
293 username: "deployer",
294 });
295 expect((yield* described(reordered)).modifiedAt).toEqual(namedEntry.modifiedAt);
296
297 // Removing the username resets it to the EKS-generated default.
298 const unnamed = yield* deployEntry("10", [], {
299 kubernetesGroups: ["group-a", "group-b"],
300 });
301 expect((yield* described(unnamed)).username).toContain(":assumed-role/");
302
303 // A group change still applies.
304 const regrouped = yield* deployEntry("11", [], { kubernetesGroups: ["group-a"] });
305 expect((yield* described(regrouped)).kubernetesGroups).toEqual(["group-a"]);
306
307 yield* stack.destroy();
308
309 const gone = yield* eks.describeCluster({ name: emptied.clusterName }).pipe(
310 Effect.map(() => false),
311 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(true)),
312 );
313 expect(gone).toBe(true);
314 }),
315 {
316 tags: ["provider:aws", "provider:aws:eks", "provider:aws:ec2", "provider:aws:iam", "live"],
317 // Auto Mode cluster create (~10 min) + eleven reconciles + delete (~5 min).
318 timeout: 2_700_000,
319 },
320 );