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

main
ts 190 lines 6.68 KB
Raw
1 import * as ci from "@distilled.cloud/aws/cognito-identity";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Schedule from "effect/Schedule";
7 import type { Providers } from "../Providers.ts";
8
9 export interface IdentityPoolRoleAttachmentProps {
10 /**
11 * The ID of the identity pool. Changing this triggers a replacement.
12 */
13 identityPoolId: string;
14 /**
15 * The IAM role ARNs vended for authenticated and unauthenticated
16 * identities. The roles must trust `cognito-identity.amazonaws.com` via
17 * `sts:AssumeRoleWithWebIdentity`.
18 */
19 roles: {
20 /** Role assumed by authenticated identities. */
21 authenticated?: string;
22 /** Role assumed by unauthenticated (guest) identities. */
23 unauthenticated?: string;
24 };
25 }
26
27 export interface IdentityPoolRoleAttachment extends Resource<
28 "AWS.Cognito.IdentityPoolRoleAttachment",
29 IdentityPoolRoleAttachmentProps,
30 {
31 /** The ID of the identity pool the roles are attached to. */
32 identityPoolId: string;
33 /** The attached role ARNs by identity type. */
34 roles: { authenticated?: string; unauthenticated?: string };
35 },
36 never,
37 Providers
38 > {}
39
40 /**
41 * Attaches the authenticated/unauthenticated IAM roles to an Amazon Cognito
42 * identity pool. A singleton child of the pool — one attachment manages the
43 * pool's role configuration.
44 * ### Attaching Roles
45 * **Example:** Authenticated Role
46 * ```typescript
47 * import * as Cognito from "@alchemy.run/aws/Cognito";
48 *
49 * const identities = yield* Cognito.IdentityPool("Identities", {});
50 * const role = yield* IAM.Role("AuthenticatedRole", {
51 * assumeRolePolicyDocument: {
52 * Version: "2012-10-17",
53 * Statement: [
54 * {
55 * Effect: "Allow",
56 * Principal: { Federated: "cognito-identity.amazonaws.com" },
57 * Action: "sts:AssumeRoleWithWebIdentity",
58 * Condition: {
59 * StringEquals: {
60 * "cognito-identity.amazonaws.com:aud": identities.identityPoolId,
61 * },
62 * },
63 * },
64 * ],
65 * },
66 * });
67 * yield* Cognito.IdentityPoolRoleAttachment("Roles", {
68 * identityPoolId: identities.identityPoolId,
69 * roles: { authenticated: role.roleArn },
70 * });
71 * ```
72 *
73 * @resource
74 */
75 export const IdentityPoolRoleAttachment = Resource<IdentityPoolRoleAttachment>(
76 "AWS.Cognito.IdentityPoolRoleAttachment",
77 );
78
79 /**
80 * Bounded retry over IAM eventual consistency: a freshly-created role's
81 * trust policy can take a few seconds to become visible to Cognito, which
82 * rejects the attachment with InvalidParameterException ("Cannot assume
83 * role"). Explicitly typed so `Retry.Return` never leaks into declaration
84 * emit.
85 */
86 const retryThroughIamPropagation = <A, E extends { _tag: string }, R>(
87 self: Effect.Effect<A, E, R>,
88 ): Effect.Effect<A, E, R> =>
89 Effect.retry(self, {
90 while: (e) =>
91 e._tag === "InvalidParameterException" || e._tag === "ConcurrentModificationException",
92 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]),
93 });
94
95 const desiredRoles = (props: IdentityPoolRoleAttachmentProps) => {
96 const roles: Record<string, string> = {};
97 if (props.roles.authenticated !== undefined) {
98 roles.authenticated = props.roles.authenticated;
99 }
100 if (props.roles.unauthenticated !== undefined) {
101 roles.unauthenticated = props.roles.unauthenticated;
102 }
103 return roles;
104 };
105
106 export const IdentityPoolRoleAttachmentProvider = () =>
107 Provider.effect(
108 IdentityPoolRoleAttachment,
109 Effect.gen(function* () {
110 const getRoles = Effect.fn(function* (identityPoolId: string) {
111 return yield* ci
112 .getIdentityPoolRoles({ IdentityPoolId: identityPoolId })
113 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
114 });
115
116 return IdentityPoolRoleAttachment.Provider.of({
117 stables: ["identityPoolId"],
118
119 // Sub-resource keyed entirely by its identity pool (identityPoolId) with no global
120 // enumeration API of its own — nuke reaches it through the parent's
121 // deletion, so enumeration returns empty per the ProviderService
122 // doctrine.
123 list: () => Effect.succeed([]),
124
125 read: Effect.fn(function* ({ olds, output }) {
126 const identityPoolId = output?.identityPoolId ?? olds?.identityPoolId;
127 if (identityPoolId === undefined) return undefined;
128 const observed = yield* getRoles(identityPoolId);
129 const roles = observed?.Roles ?? {};
130 if (Object.keys(roles).length === 0) return undefined;
131 return {
132 identityPoolId,
133 roles: {
134 authenticated: roles.authenticated,
135 unauthenticated: roles.unauthenticated,
136 },
137 };
138 }),
139
140 diff: Effect.fn(function* ({ news, olds }) {
141 if (!isResolved(news)) return undefined;
142 if (olds?.identityPoolId !== news?.identityPoolId) {
143 return { action: "replace" } as const;
144 }
145 }),
146
147 reconcile: Effect.fn(function* ({ news, session }) {
148 const identityPoolId = news.identityPoolId;
149 const desired = desiredRoles(news);
150
151 // 1. OBSERVE — the attachment is a singleton child; observed state
152 // is the pool's current role map.
153 const observed = yield* getRoles(identityPoolId);
154 const observedRoles = Object.fromEntries(
155 Object.entries(observed?.Roles ?? {}).filter(
156 (entry): entry is [string, string] => entry[1] !== undefined,
157 ),
158 );
159
160 // 2/3. ENSURE + SYNC — SetIdentityPoolRoles is a full PUT; skip it
161 // when the observed map already matches.
162 const same =
163 JSON.stringify(Object.entries(observedRoles).sort(([a], [b]) => a.localeCompare(b))) ===
164 JSON.stringify(Object.entries(desired).sort(([a], [b]) => a.localeCompare(b)));
165 if (!same) {
166 yield* retryThroughIamPropagation(
167 ci.setIdentityPoolRoles({
168 IdentityPoolId: identityPoolId,
169 Roles: desired,
170 }),
171 );
172 }
173
174 yield* session.note(identityPoolId);
175 return { identityPoolId, roles: news.roles };
176 }),
177
178 delete: Effect.fn(function* ({ output }) {
179 // Clearing the role map is the closest analogue to deletion for
180 // this singleton child; the pool itself is unaffected.
181 yield* ci
182 .setIdentityPoolRoles({
183 IdentityPoolId: output.identityPoolId,
184 Roles: {},
185 })
186 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
187 }),
188 });
189 }),
190 );