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

main
ts 285 lines 10.8 KB
Raw
1 import * as iam from "@distilled.cloud/aws/iam";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import { diffTags } from "alchemy/Tags";
6 import * as Effect from "effect/Effect";
7 import { AWSEnvironment } from "../Environment.ts";
8 import type { Providers } from "../Providers.ts";
9 import { toTagRecord } from "./common.ts";
10
11 export interface OpenIDConnectProviderProps {
12 /**
13 * The identity provider URL.
14 */
15 url: string;
16 /**
17 * Client IDs allowed for the provider. AWS rejects requests with an
18 * empty list, so the prop is typed as a non-empty tuple.
19 */
20 clientIDList?: [string, ...string[]];
21 /**
22 * Certificate thumbprints for the provider. AWS auto-manages thumbprints
23 * for well-known IdPs (e.g. GitHub Actions), so this is optional — but
24 * `iam.updateOpenIDConnectProviderThumbprint` rejects an empty list, so
25 * the prop is typed as a non-empty tuple when supplied.
26 */
27 thumbprintList?: [string, ...string[]];
28 /**
29 * User-defined tags to apply to the provider.
30 */
31 tags?: Record<string, string>;
32 }
33
34 export interface OpenIDConnectProvider extends Resource<
35 "AWS.IAM.OpenIDConnectProvider",
36 OpenIDConnectProviderProps,
37 {
38 /** The ARN of the OIDC provider. */
39 openIDConnectProviderArn: string;
40 /** The URL of the identity provider. */
41 url: string;
42 /** The client IDs (audiences) registered with the provider. */
43 clientIDList: string[];
44 /**
45 * Reflects the desired state — `undefined` when the user opted out of
46 * managing thumbprints (AWS auto-manages them for well-known IdPs).
47 */
48 thumbprintList: string[] | undefined;
49 /** The tags applied to the provider. */
50 tags: Record<string, string>;
51 },
52 never,
53 Providers
54 > {}
55
56 /**
57 * An IAM OpenID Connect provider for web identity federation.
58 *
59 * `OpenIDConnectProvider` registers an external OIDC issuer so IAM roles can be
60 * assumed through web identity federation flows such as GitHub Actions.
61 * ### Federating with OIDC
62 * **Example:** Create a GitHub Actions OIDC Provider
63 * ```typescript
64 * const oidc = yield* OpenIDConnectProvider("GithubOidc", {
65 * url: "https://token.actions.githubusercontent.com",
66 * clientIDList: ["sts.amazonaws.com"],
67 * thumbprintList: ["6938fd4d98bab03faadb97b34396831e3780aea1"],
68 * });
69 * ```
70 *
71 * @resource
72 */
73 export const OpenIDConnectProvider = Resource<OpenIDConnectProvider>(
74 "AWS.IAM.OpenIDConnectProvider",
75 );
76
77 export const OpenIDConnectProviderProvider = () =>
78 Provider.effect(
79 OpenIDConnectProvider,
80 Effect.gen(function* () {
81 const oidcArnFromUrl = (url: string) =>
82 AWSEnvironment.current.pipe(
83 Effect.map(
84 ({ accountId }) =>
85 `arn:aws:iam::${accountId}:oidc-provider/${url.replace(/^https?:\/\//, "")}`,
86 ),
87 );
88
89 const readProvider = Effect.fn(function* (providerArn: string) {
90 const response = yield* iam
91 .getOpenIDConnectProvider({
92 OpenIDConnectProviderArn: providerArn,
93 })
94 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined));
95 return response;
96 });
97
98 const hydrate = (providerArn: string) =>
99 Effect.gen(function* () {
100 const provider = yield* readProvider(providerArn);
101 if (!provider?.Url) {
102 return undefined;
103 }
104 const tags = yield* iam.listOpenIDConnectProviderTags({
105 OpenIDConnectProviderArn: providerArn,
106 });
107 return {
108 openIDConnectProviderArn: providerArn,
109 url: provider.Url,
110 clientIDList: provider.ClientIDList ?? [],
111 thumbprintList: provider.ThumbprintList ?? [],
112 tags: toTagRecord(tags.Tags),
113 };
114 }).pipe(
115 // A peer test may delete a provider between
116 // `listOpenIDConnectProviders` and hydrating its tags — skip the
117 // vanished entry rather than failing the whole enumeration.
118 Effect.catchTag("NoSuchEntityException", () => Effect.undefined),
119 );
120
121 return {
122 stables: ["openIDConnectProviderArn"],
123 // IAM is global; `listOpenIDConnectProviders` returns ARNs only, so
124 // hydrate each into the full Attributes shape `read` produces.
125 list: () =>
126 Effect.gen(function* () {
127 const { OpenIDConnectProviderList } = yield* iam.listOpenIDConnectProviders({});
128 const arns = (OpenIDConnectProviderList ?? [])
129 .map((entry) => entry.Arn)
130 .filter((arn): arn is string => arn != null);
131 const rows = yield* Effect.forEach(arns, hydrate, {
132 concurrency: 10,
133 });
134 const result: OpenIDConnectProvider["Attributes"][] = rows.filter(
135 (row): row is NonNullable<typeof row> => row !== undefined,
136 );
137 return result;
138 }),
139 diff: Effect.fn(function* ({ olds, news }) {
140 if (!isResolved(news)) return;
141 if (olds.url !== news.url) {
142 return { action: "replace" } as const;
143 }
144 }),
145 read: Effect.fn(function* ({ olds, output }) {
146 const providerArn =
147 output?.openIDConnectProviderArn ??
148 (olds?.url !== undefined ? yield* oidcArnFromUrl(olds.url) : undefined);
149 if (providerArn === undefined) {
150 // An Output-valued `url` doesn't survive a `creating`-state
151 // round-trip (it deserializes as `undefined`) — report "not
152 // found" so the engine re-drives the create.
153 return undefined;
154 }
155 const provider = yield* readProvider(providerArn);
156 if (!provider?.Url) {
157 return undefined;
158 }
159 const tags = yield* iam.listOpenIDConnectProviderTags({
160 OpenIDConnectProviderArn: providerArn,
161 });
162 return {
163 openIDConnectProviderArn: providerArn,
164 url: provider.Url,
165 clientIDList: provider.ClientIDList ?? [],
166 thumbprintList: provider.ThumbprintList ?? [],
167 tags: toTagRecord(tags.Tags),
168 };
169 }),
170 reconcile: Effect.fn(function* ({ news, output, session }) {
171 // The OIDC provider's ARN is deterministic from its URL, so we
172 // can observe with or without prior output.
173 const providerArn = output?.openIDConnectProviderArn ?? (yield* oidcArnFromUrl(news.url));
174
175 // Observe — read the live provider; absent when missing.
176 let observed = yield* readProvider(providerArn);
177 let observedClientIds: string[] = [];
178 let observedThumbprints: string[] = [];
179 let observedTags: Record<string, string> = {};
180
181 if (observed?.Url) {
182 observedClientIds = observed.ClientIDList ?? [];
183 observedThumbprints = observed.ThumbprintList ?? [];
184 const tagsResp = yield* iam.listOpenIDConnectProviderTags({
185 OpenIDConnectProviderArn: providerArn,
186 });
187 observedTags = toTagRecord(tagsResp.Tags);
188 }
189
190 // Ensure — create the provider when it is missing. The API does
191 // not return idempotently for OIDC, but the deterministic ARN
192 // means a race manifests as `EntityAlreadyExistsException`.
193 if (!observed?.Url) {
194 yield* iam
195 .createOpenIDConnectProvider({
196 Url: news.url,
197 ClientIDList: news.clientIDList,
198 ThumbprintList: news.thumbprintList,
199 Tags: Object.entries(news.tags ?? {}).map(([Key, Value]) => ({
200 Key,
201 Value,
202 })),
203 })
204 .pipe(Effect.catchTag("EntityAlreadyExistsException", () => Effect.void));
205 observed = yield* readProvider(providerArn);
206 observedClientIds = observed?.ClientIDList ?? [];
207 observedThumbprints = observed?.ThumbprintList ?? [];
208 const tagsResp = yield* iam.listOpenIDConnectProviderTags({
209 OpenIDConnectProviderArn: providerArn,
210 });
211 observedTags = toTagRecord(tagsResp.Tags);
212 }
213
214 // Sync client IDs against the observed list.
215 const desiredClientIds = news.clientIDList ?? [];
216 const observedClientSet = new Set(observedClientIds);
217 const desiredClientSet = new Set(desiredClientIds);
218 for (const clientId of desiredClientIds) {
219 if (!observedClientSet.has(clientId)) {
220 yield* iam.addClientIDToOpenIDConnectProvider({
221 OpenIDConnectProviderArn: providerArn,
222 ClientID: clientId,
223 });
224 }
225 }
226 for (const clientId of observedClientIds) {
227 if (!desiredClientSet.has(clientId)) {
228 yield* iam.removeClientIDFromOpenIDConnectProvider({
229 OpenIDConnectProviderArn: providerArn,
230 ClientID: clientId,
231 });
232 }
233 }
234
235 // Sync thumbprints — `updateOpenIDConnectProviderThumbprint`
236 // replaces the entire list, so call it whenever the set differs.
237 // When the user didn't request a list we leave the cloud-managed
238 // thumbprints alone (AWS auto-manages for well-known IdPs).
239 const desiredThumbprints = news.thumbprintList;
240 if (
241 desiredThumbprints &&
242 JSON.stringify([...observedThumbprints].sort()) !==
243 JSON.stringify([...desiredThumbprints].sort())
244 ) {
245 yield* iam.updateOpenIDConnectProviderThumbprint({
246 OpenIDConnectProviderArn: providerArn,
247 ThumbprintList: desiredThumbprints,
248 });
249 }
250
251 // Sync tags against the observed cloud tags.
252 const desiredTags = news.tags ?? {};
253 const { removed, upsert } = diffTags(observedTags, desiredTags);
254 if (upsert.length > 0) {
255 yield* iam.tagOpenIDConnectProvider({
256 OpenIDConnectProviderArn: providerArn,
257 Tags: upsert,
258 });
259 }
260 if (removed.length > 0) {
261 yield* iam.untagOpenIDConnectProvider({
262 OpenIDConnectProviderArn: providerArn,
263 TagKeys: removed,
264 });
265 }
266
267 yield* session.note(providerArn);
268 return {
269 openIDConnectProviderArn: providerArn,
270 url: news.url,
271 clientIDList: desiredClientIds,
272 thumbprintList: desiredThumbprints,
273 tags: desiredTags,
274 };
275 }),
276 delete: Effect.fn(function* ({ output }) {
277 yield* iam
278 .deleteOpenIDConnectProvider({
279 OpenIDConnectProviderArn: output.openIDConnectProviderArn,
280 })
281 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
282 }),
283 };
284 }),
285 );