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

main
ts 423 lines 13.9 KB
Raw
1 import * as eks from "@distilled.cloud/aws/eks";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import type { Input } from "alchemy/Input";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12
13 export class AccessEntryUnexpectedResponse extends Data.TaggedError(
14 "AccessEntryUnexpectedResponse",
15 )<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 export interface AccessPolicyAssociation {
21 /**
22 * ARN of the AWS-managed EKS access policy.
23 */
24 policyArn: string;
25 /**
26 * Scope the policy applies to.
27 */
28 accessScope: eks.AccessScope;
29 }
30
31 export interface AccessEntryProps {
32 /**
33 * Target cluster name.
34 */
35 clusterName: Input<string>;
36 /**
37 * IAM principal ARN to grant access to.
38 */
39 principalArn: Input<string>;
40 /**
41 * Optional Kubernetes groups for the principal.
42 */
43 kubernetesGroups?: string[];
44 /**
45 * Optional username to map inside Kubernetes. If omitted, EKS generates one,
46 * and removing a username you set resets it to the generated default.
47 */
48 username?: string;
49 /**
50 * Entry type, such as `STANDARD`.
51 */
52 type?: string;
53 /**
54 * Exact set of EKS access policies associated with this entry.
55 */
56 accessPolicies?: AccessPolicyAssociation[];
57 /**
58 * User-defined tags to apply to the access entry.
59 */
60 tags?: Record<string, string>;
61 }
62
63 export interface AccessEntry extends Resource<
64 "AWS.EKS.AccessEntry",
65 AccessEntryProps,
66 {
67 /** The ARN of the access entry. */
68 accessEntryArn: string;
69 /** The name of the EKS cluster the entry grants access to. */
70 clusterName: string;
71 /** The IAM principal ARN the entry maps into the cluster. */
72 principalArn: string;
73 /** The Kubernetes groups the principal is mapped to. */
74 kubernetesGroups: string[];
75 /** The Kubernetes username the principal is mapped to. */
76 username: string | undefined;
77 /** The access entry type (e.g. `STANDARD`, `EC2_LINUX`, `FARGATE_LINUX`). */
78 type: string | undefined;
79 /** The EKS access policies associated with the entry. */
80 accessPolicies: AccessPolicyAssociation[];
81 /** The tags applied to the access entry. */
82 tags: Record<string, string>;
83 },
84 never,
85 Providers
86 > {}
87
88 /**
89 * An Amazon EKS access entry that grants an IAM principal access to a cluster.
90 *
91 * `AccessEntry` owns both the entry itself and the exact set of associated EKS
92 * access policies, making cluster access explicit and updatable after initial
93 * cluster bootstrap.
94 * ### Managing Cluster Access
95 * **Example:** Grant Read Access to a Role
96 * ```typescript
97 * const viewer = yield* AccessEntry("ViewerAccess", {
98 * clusterName: cluster.clusterName,
99 * principalArn: viewerRole.roleArn,
100 * accessPolicies: [
101 * {
102 * policyArn:
103 * "arn:aws:eks::aws:cluster-access-policy/AmazonEKSViewPolicy",
104 * accessScope: {
105 * type: "cluster",
106 * },
107 * },
108 * ],
109 * });
110 * ```
111 *
112 * @resource
113 */
114 export const AccessEntry = Resource<AccessEntry>("AWS.EKS.AccessEntry");
115
116 export const AccessEntryProvider = () =>
117 Provider.succeed(AccessEntry, {
118 stables: ["accessEntryArn"],
119 diff: Effect.fn(function* ({ olds, news }) {
120 if (!isResolved(news)) return;
121 if (olds.clusterName !== news.clusterName) {
122 return { action: "replace" } as const;
123 }
124
125 if (olds.principalArn !== news.principalArn) {
126 return { action: "replace" } as const;
127 }
128
129 if ((olds.type ?? "STANDARD") !== (news.type ?? "STANDARD")) {
130 return { action: "replace" } as const;
131 }
132 }),
133 // Enumerate every access entry across every cluster in the account/region.
134 // `listAccessEntries` requires a cluster name, so enumerate clusters first
135 // (`listClusters`), then list access entry principal ARNs per cluster, then
136 // hydrate each one through `readAccessEntry` (describe + associated policies)
137 // to produce the full `read`-shaped Attributes. All pagination is exhausted.
138 list: Effect.fn(function* () {
139 const clusterNames = yield* eks.listClusters.items({}).pipe(
140 Stream.runCollect,
141 Effect.map((chunk) => Array.from(chunk)),
142 );
143
144 const perCluster = yield* Effect.forEach(
145 clusterNames,
146 (clusterName) =>
147 Effect.gen(function* () {
148 const cluster = yield* eks.describeCluster({ name: clusterName }).pipe(
149 Effect.map((response) => response.cluster),
150 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
151 );
152 // CONFIG_MAP clusters have no access entries, and EKS rejects
153 // ListAccessEntries on them.
154 if (
155 cluster === undefined ||
156 (cluster.accessConfig?.authenticationMode ?? "CONFIG_MAP") === "CONFIG_MAP"
157 ) {
158 return [];
159 }
160 const principalArns = yield* eks.listAccessEntries.items({ clusterName }).pipe(
161 Stream.runCollect,
162 Effect.map((chunk) => Array.from(chunk)),
163 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([] as string[])),
164 );
165 return yield* Effect.forEach(
166 principalArns,
167 (principalArn) => readAccessEntry({ clusterName, principalArn }),
168 { concurrency: 5 },
169 );
170 }),
171 { concurrency: 5 },
172 );
173
174 return perCluster.flat().filter((entry): entry is NonNullable<typeof entry> => entry != null);
175 }),
176 read: Effect.fn(function* ({ id, olds, output }) {
177 const state = yield* readAccessEntry({
178 clusterName: (output?.clusterName ?? olds.clusterName) as string,
179 principalArn: (output?.principalArn ?? olds.principalArn) as string,
180 });
181 if (!state) return undefined;
182 return (yield* hasAlchemyTags(id, state.tags)) ? state : Unowned(state);
183 }),
184 reconcile: Effect.fn(function* ({ id, news, olds, session }) {
185 const clusterName = news.clusterName as string;
186 const principalArn = news.principalArn as string;
187 const desiredTags = {
188 ...(yield* createInternalTags(id)),
189 ...news.tags,
190 };
191
192 // Observe — fetch live cloud state by (clusterName, principalArn).
193 let state = yield* readAccessEntry({
194 clusterName,
195 principalArn,
196 });
197
198 // Ensure — create the entry if missing. Tolerate
199 // `ResourceInUseException` as a race with a peer reconciler.
200 let created = false;
201 if (!state) {
202 created = yield* eks
203 .createAccessEntry({
204 clusterName,
205 principalArn,
206 kubernetesGroups: news.kubernetesGroups,
207 username: news.username,
208 type: news.type,
209 tags: desiredTags,
210 })
211 .pipe(
212 Effect.as(true),
213 Effect.catchTag("ResourceInUseException", () => Effect.succeed(false)),
214 );
215
216 state = yield* readAccessEntry({
217 clusterName,
218 principalArn,
219 });
220
221 if (!state) {
222 return yield* new AccessEntryUnexpectedResponse({
223 message: `AccessEntry '${principalArn}' could not be read after creation`,
224 });
225 }
226 }
227
228 // Sync kubernetesGroups + username — observed ↔ desired. Groups are a
229 // set. An update that omits the username resets it to the EKS-generated
230 // default, which can't be told apart from a custom one by observation.
231 // So an omitted username is only re-sent when one may have been set:
232 // a username in `olds`, or an adopted entry this reconcile did not create.
233 const desiredGroups = news.kubernetesGroups ?? [];
234 const groupsChanged =
235 JSON.stringify([...state.kubernetesGroups].sort()) !==
236 JSON.stringify([...desiredGroups].sort());
237 const usernameChanged =
238 news.username !== undefined
239 ? state.username !== news.username
240 : !created && (olds === undefined || olds.username !== undefined);
241 if (groupsChanged || usernameChanged) {
242 yield* eks.updateAccessEntry({
243 clusterName,
244 principalArn,
245 kubernetesGroups: desiredGroups,
246 username: news.username,
247 });
248 }
249
250 // Sync tags — diff observed cloud tags against desired.
251 const { removed, upsert } = diffTags(state.tags, desiredTags);
252 if (upsert.length > 0) {
253 yield* eks.tagResource({
254 resourceArn: state.accessEntryArn,
255 tags: Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value] as const)),
256 });
257 }
258 if (removed.length > 0) {
259 yield* eks.untagResource({
260 resourceArn: state.accessEntryArn,
261 tagKeys: removed,
262 });
263 }
264
265 // Sync access policy associations — diff observed against desired.
266 const observedPolicies = state.accessPolicies;
267 const desiredPolicies = normalizeAccessPolicies(news.accessPolicies);
268 const observedPolicyMap = new Map(
269 observedPolicies.map((policy) => [policyKey(policy), policy]),
270 );
271 const desiredPolicyMap = new Map(
272 desiredPolicies.map((policy) => [policyKey(policy), policy]),
273 );
274
275 for (const [key, policy] of desiredPolicyMap) {
276 if (!observedPolicyMap.has(key)) {
277 yield* eks.associateAccessPolicy({
278 clusterName,
279 principalArn,
280 policyArn: policy.policyArn,
281 accessScope: policy.accessScope,
282 });
283 }
284 }
285
286 // EKS keeps one association per policy ARN and `associateAccessPolicy`
287 // replaces its scope in place, while `disassociateAccessPolicy` takes no
288 // scope. Disassociating a still-desired ARN would undo the associate
289 // above, so only disassociate ARNs that are no longer desired.
290 const desiredPolicyArns = new Set(desiredPolicies.map((policy) => policy.policyArn));
291 for (const [key, policy] of observedPolicyMap) {
292 if (!desiredPolicyMap.has(key) && !desiredPolicyArns.has(policy.policyArn)) {
293 yield* eks.disassociateAccessPolicy({
294 clusterName,
295 principalArn,
296 policyArn: policy.policyArn,
297 });
298 }
299 }
300
301 yield* session.note(state.accessEntryArn);
302
303 // Re-read final state so returned attributes reflect post-sync.
304 return yield* readAccessEntry({
305 clusterName,
306 principalArn,
307 }).pipe(
308 Effect.flatMap((finalState) =>
309 finalState
310 ? Effect.succeed(finalState)
311 : Effect.fail(
312 new AccessEntryUnexpectedResponse({
313 message: `AccessEntry '${principalArn}' could not be read after reconcile`,
314 }),
315 ),
316 ),
317 );
318 }),
319 delete: Effect.fn(function* ({ output }) {
320 yield* eks
321 .deleteAccessEntry({
322 clusterName: output.clusterName,
323 principalArn: output.principalArn,
324 })
325 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
326 }),
327 });
328
329 const normalizeTags = (tags: Record<string, string | undefined> | undefined) =>
330 Object.fromEntries(
331 Object.entries(tags ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined),
332 );
333
334 // EKS reports a cluster scope as `{ type: "cluster", namespaces: [] }`, so
335 // compare scopes in one canonical shape rather than as raw JSON.
336 const scopeKey = (scope: eks.AccessScope) =>
337 JSON.stringify({ type: scope.type, namespaces: [...(scope.namespaces ?? [])].sort() });
338
339 const comparePolicyAssociation = (a: AccessPolicyAssociation, b: AccessPolicyAssociation) =>
340 a.policyArn.localeCompare(b.policyArn) ||
341 scopeKey(a.accessScope).localeCompare(scopeKey(b.accessScope));
342
343 const normalizeAccessPolicies = (
344 policies: ReadonlyArray<AccessPolicyAssociation | eks.AssociatedAccessPolicy> | undefined,
345 ): AccessPolicyAssociation[] =>
346 (policies ?? [])
347 .flatMap((policy) =>
348 policy.policyArn && policy.accessScope
349 ? [
350 {
351 policyArn: policy.policyArn,
352 accessScope: policy.accessScope,
353 },
354 ]
355 : [],
356 )
357 .sort(comparePolicyAssociation);
358
359 const policyKey = (policy: AccessPolicyAssociation) =>
360 `${policy.policyArn}::${scopeKey(policy.accessScope)}`;
361
362 const listAccessPolicies = Effect.fn(function* ({
363 clusterName,
364 principalArn,
365 }: {
366 clusterName: string;
367 principalArn: string;
368 }) {
369 const policies: AccessPolicyAssociation[] = [];
370 let nextToken: string | undefined;
371
372 while (true) {
373 const response = yield* eks.listAssociatedAccessPolicies({
374 clusterName,
375 principalArn,
376 nextToken,
377 });
378
379 policies.push(...normalizeAccessPolicies(response.associatedAccessPolicies));
380
381 if (!response.nextToken) {
382 break;
383 }
384
385 nextToken = response.nextToken;
386 }
387
388 return policies.sort(comparePolicyAssociation);
389 });
390
391 const readAccessEntry = Effect.fn(function* ({
392 clusterName,
393 principalArn,
394 }: {
395 clusterName: string;
396 principalArn: string;
397 }) {
398 const response = yield* eks
399 .describeAccessEntry({
400 clusterName,
401 principalArn,
402 })
403 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
404
405 const accessEntry = response?.accessEntry;
406 if (!accessEntry?.accessEntryArn || !accessEntry.clusterName || !accessEntry.principalArn) {
407 return undefined;
408 }
409
410 return {
411 accessEntryArn: accessEntry.accessEntryArn,
412 clusterName: accessEntry.clusterName,
413 principalArn: accessEntry.principalArn,
414 kubernetesGroups: accessEntry.kubernetesGroups ?? [],
415 username: accessEntry.username,
416 type: accessEntry.type,
417 accessPolicies: yield* listAccessPolicies({
418 clusterName: accessEntry.clusterName,
419 principalArn: accessEntry.principalArn,
420 }),
421 tags: normalizeTags(accessEntry.tags),
422 };
423 });