@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 276 lines 7.8 KB
Raw
1 /**
2 * Internal pod-identity + host-binding machinery behind the `aws-eks`
3 * cluster adapter's workload-identity implementation (see
4 * `../KubernetesAdapter.ts`). Each helper is an independently idempotent
5 * mini-reconciler: observe, ensure, converge.
6 */
7 import * as eks from "@distilled.cloud/aws/eks";
8 import * as iam from "@distilled.cloud/aws/iam";
9 import { createPhysicalName } from "alchemy/PhysicalName";
10 import type { ResourceBinding } from "alchemy/Resource";
11 import { createInternalTags, hasTags } from "alchemy/Tags";
12 import * as Data from "effect/Data";
13 import * as Effect from "effect/Effect";
14 import * as Stream from "effect/Stream";
15 import type { PolicyStatement } from "../../IAM/Policy.ts";
16
17 export class EKSPodIdentityUnexpectedResponse extends Data.TaggedError(
18 "EKSPodIdentityUnexpectedResponse",
19 )<{
20 readonly message: string;
21 readonly cause?: unknown;
22 }> {}
23
24 export class EKSPodIdentityConflict extends Data.TaggedError("EKSPodIdentityConflict")<{
25 readonly message: string;
26 readonly cause?: unknown;
27 }> {}
28
29 export const toClientRequestToken = (id: string, action: string) =>
30 createPhysicalName({
31 id: `${id}-${action}`,
32 maxLength: 64,
33 delimiter: "-",
34 });
35
36 /**
37 * Ensure the pod-identity IAM role exists (trusts `pods.eks.amazonaws.com`).
38 * Idempotent: creates on miss, adopts a role we already own on race.
39 */
40 export const ensurePodRole = Effect.fn(function* ({
41 id,
42 roleName,
43 managedPolicyArns,
44 }: {
45 id: string;
46 roleName: string;
47 managedPolicyArns?: string[];
48 }) {
49 const tags = yield* createInternalTags(id);
50 const role = yield* iam
51 .createRole({
52 RoleName: roleName,
53 AssumeRolePolicyDocument: JSON.stringify({
54 Version: "2012-10-17",
55 Statement: [
56 {
57 Effect: "Allow",
58 Principal: { Service: "pods.eks.amazonaws.com" },
59 Action: ["sts:AssumeRole", "sts:TagSession"],
60 },
61 ],
62 }),
63 Tags: Object.entries(tags).map(([Key, Value]) => ({ Key, Value })),
64 })
65 .pipe(
66 Effect.catchTag("EntityAlreadyExistsException", () =>
67 iam.getRole({ RoleName: roleName }).pipe(
68 Effect.filterOrFail(
69 (existing) => hasTags(tags, existing.Role?.Tags),
70 () =>
71 new EKSPodIdentityConflict({
72 message: `Role '${roleName}' already exists and is not managed by alchemy`,
73 }),
74 ),
75 ),
76 ),
77 );
78 for (const policyArn of managedPolicyArns ?? []) {
79 yield* iam
80 .attachRolePolicy({ RoleName: roleName, PolicyArn: policyArn })
81 .pipe(Effect.catchTag("LimitExceededException", () => Effect.void));
82 }
83 return role.Role!.Arn!;
84 });
85
86 export interface HostBindingContract {
87 env?: Record<string, any>;
88 policyStatements?: PolicyStatement[];
89 }
90
91 /**
92 * Land the IAM policy statements carried by a host's active bindings as
93 * the pod role's inline policy (or delete it when no statements remain).
94 * Binding env collection is generic and lives in the Kubernetes workload
95 * providers.
96 */
97 export const attachPolicyStatements = Effect.fn(function* ({
98 roleName,
99 policyName,
100 bindings,
101 }: {
102 roleName: string;
103 policyName: string;
104 bindings: ResourceBinding<HostBindingContract>[];
105 }) {
106 const activeBindings = bindings.filter(
107 (
108 binding: ResourceBinding<HostBindingContract> & {
109 action?: string;
110 },
111 ) => binding.action !== "delete",
112 );
113
114 const policyStatements = activeBindings.flatMap(
115 (binding) =>
116 binding?.data?.policyStatements?.map((statement) => ({
117 ...statement,
118 Sid: statement.Sid?.replace(/[^A-Za-z0-9]+/gi, ""),
119 })) ?? [],
120 );
121
122 if (policyStatements.length > 0) {
123 yield* iam.putRolePolicy({
124 RoleName: roleName,
125 PolicyName: policyName,
126 PolicyDocument: JSON.stringify({
127 Version: "2012-10-17",
128 Statement: policyStatements,
129 }),
130 });
131 } else {
132 yield* iam
133 .deleteRolePolicy({ RoleName: roleName, PolicyName: policyName })
134 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
135 }
136 });
137
138 /** Observe an existing pod identity association for (cluster, ns, sa). */
139 export const findAssociation = Effect.fn(function* ({
140 clusterName,
141 namespace,
142 serviceAccount,
143 }: {
144 clusterName: string;
145 namespace: string;
146 serviceAccount: string;
147 }) {
148 const listed = yield* eks.listPodIdentityAssociations({
149 clusterName,
150 namespace,
151 serviceAccount,
152 });
153 const summary = listed.associations?.[0];
154 if (!summary?.associationId) return undefined;
155 const described = yield* eks
156 .describePodIdentityAssociation({
157 clusterName,
158 associationId: summary.associationId,
159 })
160 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
161 const association = described?.association;
162 if (!association?.associationArn || !association.associationId) {
163 return undefined;
164 }
165 return {
166 associationArn: association.associationArn,
167 associationId: association.associationId,
168 roleArn: association.roleArn,
169 };
170 });
171
172 /** Ensure the pod identity association exists and points at roleArn. */
173 export const ensureAssociation = Effect.fn(function* ({
174 id,
175 clusterName,
176 namespace,
177 serviceAccount,
178 roleArn,
179 }: {
180 id: string;
181 clusterName: string;
182 namespace: string;
183 serviceAccount: string;
184 roleArn: string;
185 }) {
186 let state = yield* findAssociation({
187 clusterName,
188 namespace,
189 serviceAccount,
190 });
191 if (!state) {
192 yield* eks
193 .createPodIdentityAssociation({
194 clusterName,
195 namespace,
196 serviceAccount,
197 roleArn,
198 tags: yield* createInternalTags(id),
199 clientRequestToken: yield* toClientRequestToken(id, "assoc"),
200 })
201 .pipe(Effect.catchTag("ResourceInUseException", () => Effect.void));
202 state = yield* findAssociation({
203 clusterName,
204 namespace,
205 serviceAccount,
206 });
207 if (!state) {
208 return yield* new EKSPodIdentityUnexpectedResponse({
209 message: `PodIdentityAssociation '${namespace}/${serviceAccount}' could not be read after creation`,
210 });
211 }
212 } else if (state.roleArn !== roleArn) {
213 yield* eks.updatePodIdentityAssociation({
214 clusterName,
215 associationId: state.associationId,
216 roleArn,
217 clientRequestToken: yield* toClientRequestToken(id, "assoc-update"),
218 });
219 }
220 return {
221 associationArn: state.associationArn,
222 associationId: state.associationId,
223 };
224 });
225
226 /** Delete the pod identity association; missing is success. */
227 export const deleteAssociation = Effect.fn(function* ({
228 clusterName,
229 associationId,
230 }: {
231 clusterName: string;
232 associationId: string;
233 }) {
234 yield* eks
235 .deletePodIdentityAssociation({
236 clusterName,
237 associationId,
238 })
239 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
240 });
241
242 /**
243 * Fully delete a pod IAM role: inline policies, managed-policy attachments,
244 * then the role itself. Idempotent throughout.
245 */
246 export const deletePodRole = Effect.fn(function* (roleName: string) {
247 yield* iam.listRolePolicies.items({ RoleName: roleName }).pipe(
248 Stream.mapEffect((policyName) =>
249 iam
250 .deleteRolePolicy({
251 RoleName: roleName,
252 PolicyName: policyName,
253 })
254 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)),
255 ),
256 Stream.runDrain,
257 Effect.catchTag("NoSuchEntityException", () => Effect.void),
258 );
259
260 yield* iam.listAttachedRolePolicies.items({ RoleName: roleName }).pipe(
261 Stream.mapEffect((policy) =>
262 iam
263 .detachRolePolicy({
264 RoleName: roleName,
265 PolicyArn: policy.PolicyArn!,
266 })
267 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)),
268 ),
269 Stream.runDrain,
270 Effect.catchTag("NoSuchEntityException", () => Effect.void),
271 );
272
273 yield* iam
274 .deleteRole({ RoleName: roleName })
275 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
276 });