@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, 04:45 UTC

main
ts 359 lines 13.3 KB
Raw
1 import * as ram from "@distilled.cloud/aws/ram";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Array from "effect/Array";
9 import * as Data from "effect/Data";
10 import * as Effect from "effect/Effect";
11 import * as Schedule from "effect/Schedule";
12 import * as Stream from "effect/Stream";
13 import type { Providers } from "../Providers.ts";
14
15 export class RAMPermissionUnexpectedResponse extends Data.TaggedError(
16 "RAMPermissionUnexpectedResponse",
17 )<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 /**
23 * The policy template of a customer managed permission — the actions a
24 * resource share grants to principals for the permission's resource type.
25 * RAM policy templates only support `Effect: "Allow"` with `Action` and an
26 * optional `Condition`; the `Principal` and `Resource` are supplied by the
27 * resource share at association time.
28 */
29 export interface PermissionPolicyTemplate {
30 /**
31 * Actions granted to principals the resource share is shared with. Must be
32 * a subset of the actions RAM supports for the permission's `resourceType`
33 * (for example `appsync:SourceGraphQL` for `appsync:Apis`).
34 */
35 actions: string[];
36
37 /**
38 * Optional IAM condition block constraining when the actions are granted.
39 */
40 condition?: Record<string, unknown>;
41 }
42
43 export interface PermissionProps {
44 /**
45 * Name of the customer managed permission. Must be unique within your
46 * account and Region. If omitted, Alchemy generates a deterministic name
47 * from the stack, stage, and logical ID. Max 36 characters.
48 * Changing the name replaces the permission.
49 */
50 permissionName?: string;
51
52 /**
53 * The resource type this permission applies to, in `service:Type` format —
54 * for example `appsync:Apis`. Only some resource types support customer
55 * managed permissions (others, like `ec2:Subnet`, only allow the AWS
56 * managed default permission).
57 * Changing the resource type replaces the permission.
58 */
59 resourceType: string;
60
61 /**
62 * The policy template granted by resource shares using this permission.
63 * Changing the template creates a new permission version and promotes it
64 * to the default; the previous default version is deleted when it is no
65 * longer attached to any resource share.
66 */
67 policyTemplate: PermissionPolicyTemplate;
68
69 /**
70 * Tags applied to the permission.
71 */
72 tags?: Record<string, string>;
73 }
74
75 export interface Permission extends Resource<
76 "AWS.RAM.Permission",
77 PermissionProps,
78 {
79 /** ARN of the customer managed permission. */
80 permissionArn: string;
81 /** Name of the permission. */
82 name: string;
83 /** The resource type the permission applies to. */
84 resourceType: string;
85 /** The default version number of the permission. */
86 version: string | undefined;
87 /** Current status (`ATTACHABLE`, `UNATTACHABLE`, `DELETING`, ...). */
88 status: string | undefined;
89 /** Tags applied to the permission. */
90 tags: Record<string, string>;
91 },
92 never,
93 Providers
94 > {}
95
96 /**
97 * An AWS Resource Access Manager (RAM) customer managed permission.
98 *
99 * A customer managed permission precisely controls which actions principals
100 * receive on resources of a given type when you attach the permission to a
101 * {@link ResourceShare} via `permissionArns`.
102 *
103 * ### Creating a Permission
104 * **Example:** Least-privilege AppSync API sharing
105 * ```typescript
106 * const permission = yield* Permission("SourceGraphQLOnly", {
107 * resourceType: "appsync:Apis",
108 * policyTemplate: {
109 * actions: ["appsync:SourceGraphQL"],
110 * },
111 * });
112 * ```
113 *
114 * **Example:** Attach a permission to a resource share
115 * ```typescript
116 * const share = yield* ResourceShare("ApiShare", {
117 * resourceArns: [api.apiArn],
118 * principals: ["123456789012"],
119 * permissionArns: [permission.permissionArn],
120 * });
121 * ```
122 *
123 * ### Updating the Policy
124 * **Example:** Add an action (creates a new default version)
125 * ```typescript
126 * const permission = yield* Permission("SourceGraphQLOnly", {
127 * resourceType: "appsync:Apis",
128 * policyTemplate: {
129 * actions: ["appsync:SourceGraphQL", "appsync:GraphQL"],
130 * },
131 * });
132 * ```
133 *
134 * @resource
135 */
136 export const Permission = Resource<Permission>("AWS.RAM.Permission");
137
138 const toName = (id: string, props: { permissionName?: string } = {}) =>
139 props.permissionName
140 ? Effect.succeed(props.permissionName)
141 : createPhysicalName({ id, maxLength: 36 });
142
143 /** RAM's inline `{ key, value }` tag list → a plain `Record`. */
144 const tagsToRecord = (tags: readonly ram.Tag[] | undefined): Record<string, string> => {
145 const record: Record<string, string> = {};
146 for (const tag of tags ?? []) {
147 if (tag.key !== undefined && tag.value !== undefined) {
148 record[tag.key] = tag.value;
149 }
150 }
151 return record;
152 };
153
154 /** A permission is "live" only while it is not deleting/deleted. */
155 const isLive = (status: string | undefined): boolean =>
156 status !== "DELETING" && status !== "DELETED";
157
158 /** Serialize the declared policy template to RAM's JSON wire format. */
159 const renderPolicyTemplate = (template: PermissionPolicyTemplate): string =>
160 JSON.stringify({
161 Effect: "Allow",
162 Action: [...template.actions].sort(),
163 ...(template.condition ? { Condition: template.condition } : {}),
164 });
165
166 /** Parse an observed policy document into a comparable canonical string. */
167 const canonicalizePolicy = (policy: string | undefined): string => {
168 if (policy === undefined) return "";
169 try {
170 const parsed = JSON.parse(policy) as {
171 Effect?: string;
172 Action?: string | string[];
173 Condition?: Record<string, unknown>;
174 };
175 const actions = typeof parsed.Action === "string" ? [parsed.Action] : (parsed.Action ?? []);
176 return JSON.stringify({
177 Effect: parsed.Effect ?? "Allow",
178 Action: [...actions].sort(),
179 ...(parsed.Condition ? { Condition: parsed.Condition } : {}),
180 });
181 } catch {
182 return policy;
183 }
184 };
185
186 const toAttrs = (
187 permission: ram.ResourceSharePermissionSummary | ram.ResourceSharePermissionDetail,
188 ): Permission["Attributes"] => ({
189 permissionArn: permission.arn!,
190 name: permission.name!,
191 resourceType: permission.resourceType!,
192 version: permission.version,
193 status: permission.status,
194 tags: tagsToRecord(permission.tags),
195 });
196
197 /** Read the default version of a permission by ARN; undefined if missing. */
198 const readDetail = Effect.fn(function* (arn: string) {
199 const detail = yield* ram.getPermission({ permissionArn: arn }).pipe(
200 Effect.map((r) => r.permission),
201 Effect.catchTag("UnknownResourceException", () => Effect.undefined),
202 );
203 return detail && isLive(detail.status) ? detail : undefined;
204 });
205
206 /** Find a live customer managed permission owned by us with the given name. */
207 const readByName = Effect.fn(function* (name: string) {
208 const permissions = yield* ram.listPermissions.pages({ permissionType: "CUSTOMER_MANAGED" }).pipe(
209 Stream.runCollect,
210 Effect.map((chunk) => Array.fromIterable(chunk).flatMap((page) => page.permissions ?? [])),
211 );
212 const summary = permissions.find((p) => p.name === name && isLive(p.status));
213 return summary?.arn ? yield* readDetail(summary.arn) : undefined;
214 });
215
216 export const PermissionProvider = () =>
217 Provider.effect(
218 Permission,
219 Effect.gen(function* () {
220 return {
221 stables: ["permissionArn"],
222 diff: Effect.fn(function* ({ news, olds }) {
223 if (!isResolved(news)) return;
224 // Name and resource type are fixed at creation (RAM has no
225 // rename/retype API for permissions).
226 if (olds !== undefined) {
227 if (news.permissionName !== olds.permissionName) {
228 return { action: "replace" } as const;
229 }
230 if (news.resourceType !== olds.resourceType) {
231 return { action: "replace" } as const;
232 }
233 }
234 }),
235 list: () =>
236 ram.listPermissions.pages({ permissionType: "CUSTOMER_MANAGED" }).pipe(
237 Stream.runCollect,
238 Effect.map((chunk) =>
239 Array.fromIterable(chunk)
240 .flatMap((page) => page.permissions ?? [])
241 .filter((p) => isLive(p.status) && p.arn !== undefined && p.name !== undefined)
242 .map(toAttrs),
243 ),
244 ),
245 read: Effect.fn(function* ({ id, olds, output }) {
246 const detail = output?.permissionArn
247 ? yield* readDetail(output.permissionArn)
248 : yield* readByName(yield* toName(id, olds ?? {}));
249 if (!detail) return undefined;
250 const state = toAttrs(detail);
251 return (yield* hasAlchemyTags(id, state.tags)) ? state : Unowned(state);
252 }),
253 reconcile: Effect.fn(function* ({ id, news, output, session }) {
254 const name = yield* toName(id, news);
255 const internalTags = yield* createInternalTags(id);
256 const desiredTags = { ...news.tags, ...internalTags };
257 const desiredPolicy = renderPolicyTemplate(news.policyTemplate);
258
259 // 1. OBSERVE — output ARN is only a cache; re-read live state.
260 let detail = output?.permissionArn
261 ? yield* readDetail(output.permissionArn)
262 : yield* readByName(name);
263
264 // 2. ENSURE — create if missing. PermissionAlreadyExists is a
265 // race with a concurrent create; fall through to observation.
266 if (!detail) {
267 const created = yield* ram
268 .createPermission({
269 name,
270 resourceType: news.resourceType,
271 policyTemplate: desiredPolicy,
272 tags: Object.entries(desiredTags).map(([key, value]) => ({
273 key,
274 value,
275 })),
276 })
277 .pipe(
278 Effect.map((r) => r.permission),
279 Effect.catchTag("PermissionAlreadyExistsException", () => Effect.undefined),
280 );
281 // Prefer the ARN from the create response; on the AlreadyExists
282 // race fall back to the (briefly eventually consistent) list.
283 detail = created?.arn ? yield* readDetail(created.arn) : yield* readByName(name);
284 if (!detail?.arn) {
285 if (created?.arn) {
286 yield* session.note(created.arn);
287 return { ...toAttrs(created), tags: desiredTags };
288 }
289 return yield* new RAMPermissionUnexpectedResponse({
290 message: `permission '${name}' not found after create`,
291 });
292 }
293 yield* session.note(detail.arn);
294 return toAttrs(detail);
295 }
296
297 const arn = detail.arn!;
298 const previousVersion = detail.version;
299
300 // 3a. SYNC policy — diff the observed default version's policy
301 // against the desired template; publish a new default version
302 // on drift, then drop the superseded version (RAM caps a
303 // permission at 5 versions).
304 if (canonicalizePolicy(detail.permission) !== desiredPolicy) {
305 // createPermissionVersion automatically becomes the default.
306 yield* ram.createPermissionVersion({
307 permissionArn: arn,
308 policyTemplate: desiredPolicy,
309 });
310 if (previousVersion !== undefined) {
311 // The old version may still be attached to an existing share;
312 // that's fine — leave it and converge on a later reconcile.
313 yield* ram
314 .deletePermissionVersion({
315 permissionArn: arn,
316 permissionVersion: Number(previousVersion),
317 })
318 .pipe(
319 Effect.catchTag(
320 ["OperationNotPermittedException", "InvalidParameterException"],
321 () => Effect.void,
322 ),
323 );
324 }
325 }
326
327 // 3b. SYNC tags — diff against observed cloud tags.
328 const { upsert, removed } = diffTags(tagsToRecord(detail.tags), desiredTags);
329 if (upsert.length > 0) {
330 yield* ram.tagResource({
331 resourceArn: arn,
332 tags: upsert.map((t) => ({ key: t.Key, value: t.Value })),
333 });
334 }
335 if (removed.length > 0) {
336 yield* ram.untagResource({ resourceArn: arn, tagKeys: removed });
337 }
338
339 // 4. RETURN fresh state.
340 const updated = yield* readDetail(arn);
341 yield* session.note(arn);
342 return updated ? toAttrs(updated) : { ...toAttrs(detail), tags: desiredTags };
343 }),
344 delete: Effect.fn(function* ({ output }) {
345 // A permission cannot be deleted while attached to a resource
346 // share; shares delete asynchronously, so retry briefly on
347 // OperationNotPermitted before giving up.
348 yield* ram.deletePermission({ permissionArn: output.permissionArn }).pipe(
349 Effect.retry({
350 while: (e): boolean => e._tag === "OperationNotPermittedException",
351 schedule: Schedule.exponential("2 seconds"),
352 times: 8,
353 }),
354 Effect.catchTag("UnknownResourceException", () => Effect.void),
355 );
356 }),
357 };
358 }),
359 );