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

main
ts 265 lines 10.8 KB
Raw
1 import * as iam from "@distilled.cloud/aws/iam";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags, hasTags } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Redacted from "effect/Redacted";
10 import * as Schedule from "effect/Schedule";
11 import { AWSEnvironment } from "../Environment.ts";
12 import type { Providers } from "../Providers.ts";
13 import { toTagRecord, unwrapRedactedString } from "./common.ts";
14
15 export class SAMLProviderConflict extends Data.TaggedError("SAMLProviderConflict")<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 export interface SAMLProviderProps {
21 /**
22 * The friendly SAML provider name. If omitted, a unique name is
23 * generated from the stack, stage, and logical id.
24 */
25 name?: string;
26 /**
27 * The provider metadata document.
28 */
29 samlMetadataDocument: string;
30 /**
31 * Optional assertion encryption mode.
32 */
33 assertionEncryptionMode?: iam.AssertionEncryptionModeType;
34 /**
35 * Optional private key added during creation/update.
36 */
37 addPrivateKey?: Redacted.Redacted<string> | string;
38 /**
39 * User-defined tags.
40 */
41 tags?: Record<string, string>;
42 }
43
44 export interface SAMLProvider extends Resource<
45 "AWS.IAM.SAMLProvider",
46 SAMLProviderProps,
47 {
48 /** The ARN of the SAML provider. */
49 samlProviderArn: string;
50 /** The name of the SAML provider. */
51 name: string;
52 /** The unique ID AWS assigns to the provider. */
53 samlProviderUUID: string | undefined;
54 /** The SAML metadata document from the identity provider. */
55 samlMetadataDocument: string | undefined;
56 /** Whether SAML assertions must be encrypted (`Required` / `Allowed`). */
57 assertionEncryptionMode: iam.AssertionEncryptionModeType | undefined;
58 /** The tags applied to the provider. */
59 tags: Record<string, string>;
60 },
61 never,
62 Providers
63 > {}
64
65 /**
66 * An IAM SAML identity provider.
67 *
68 * `SAMLProvider` registers a SAML metadata document so IAM roles can trust an
69 * external workforce or application identity provider.
70 * ### Federating with SAML
71 * **Example:** Create a SAML Identity Provider
72 * ```typescript
73 * const provider = yield* SAMLProvider("WorkforceSaml", {
74 * samlMetadataDocument: "<EntityDescriptor>...</EntityDescriptor>",
75 * });
76 * ```
77 *
78 * @resource
79 */
80 export const SAMLProvider = Resource<SAMLProvider>("AWS.IAM.SAMLProvider");
81
82 // IAM is eventually consistent. Recreating a SAML provider immediately after a
83 // same-named one was deleted (the destroy-then-deploy test flow) can transiently
84 // surface a content-less `ValidationError` (or `ConcurrentModificationException`)
85 // until the prior delete settles. A bounded retry rides out that window; a
86 // well-formed metadata document never fails persistently, so this never masks a
87 // genuine bad-input error for longer than the small budget.
88 const transientWriteSchedule = Schedule.max([
89 Schedule.exponential(500).pipe(Schedule.jittered),
90 Schedule.recurs(6),
91 ]);
92 const isEmptyUpdateError = (error: { _tag: string; message?: string }) =>
93 error._tag === "ValidationError" && (error.message?.includes("No updates are defined") ?? false);
94
95 const isTransientWriteError = (error: {
96 _tag: "ValidationError" | "ConcurrentModificationException" | (string & {});
97 message?: string;
98 }) =>
99 error._tag === "ConcurrentModificationException" ||
100 (error._tag === "ValidationError" && !isEmptyUpdateError(error));
101
102 const toName = (id: string, props: { name?: string }) =>
103 props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 128 });
104
105 export const SAMLProviderProvider = () =>
106 Provider.succeed(SAMLProvider, {
107 stables: ["samlProviderArn", "name"],
108 diff: Effect.fn(function* ({ id, olds, news }) {
109 if (!isResolved(news)) return;
110 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news))) {
111 return { action: "replace" } as const;
112 }
113 }),
114 read: Effect.fn(function* ({ output }) {
115 if (!output) {
116 return undefined;
117 }
118 const response = yield* iam
119 .getSAMLProvider({ SAMLProviderArn: output.samlProviderArn })
120 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined));
121 if (!response) {
122 return undefined;
123 }
124 const tags = yield* iam.listSAMLProviderTags({ SAMLProviderArn: output.samlProviderArn });
125 return {
126 samlProviderArn: output.samlProviderArn,
127 name: output.name,
128 samlProviderUUID: response.SAMLProviderUUID,
129 samlMetadataDocument: response.SAMLMetadataDocument,
130 assertionEncryptionMode: response.AssertionEncryptionMode,
131 tags: toTagRecord(tags.Tags),
132 };
133 }),
134 list: Effect.fn(function* () {
135 // IAM is global; `listSAMLProviders` enumerates every provider in the
136 // account but only returns the ARN, so hydrate each via
137 // `getSAMLProvider` + `listSAMLProviderTags` for the full Attributes.
138 const { SAMLProviderList } = yield* iam.listSAMLProviders({});
139 const arns = (SAMLProviderList ?? []).flatMap((entry) => (entry.Arn ? [entry.Arn] : []));
140 const rows = yield* Effect.forEach(
141 arns,
142 (samlProviderArn) =>
143 Effect.gen(function* () {
144 const response = yield* iam.getSAMLProvider({ SAMLProviderArn: samlProviderArn });
145 const tags = yield* iam.listSAMLProviderTags({ SAMLProviderArn: samlProviderArn });
146 return {
147 samlProviderArn,
148 name: samlProviderArn.split("saml-provider/").pop() ?? "",
149 samlProviderUUID: response.SAMLProviderUUID,
150 samlMetadataDocument: response.SAMLMetadataDocument,
151 assertionEncryptionMode: response.AssertionEncryptionMode,
152 tags: toTagRecord(tags.Tags),
153 };
154 }).pipe(
155 // A provider can disappear between listing, reading and tag lookup.
156 Effect.catchTag("NoSuchEntityException", () => Effect.undefined),
157 ),
158 { concurrency: 10 },
159 );
160 return rows.filter((row) => row !== undefined);
161 }),
162 reconcile: Effect.fn(function* ({ id, news, output, session }) {
163 const internalTags = yield* createInternalTags(id);
164 const desiredTags = { ...internalTags, ...news.tags };
165 const name = output?.name ?? (yield* toName(id, news));
166 const accountId = (yield* AWSEnvironment.current).accountId;
167 const samlProviderArn =
168 output?.samlProviderArn ?? `arn:aws:iam::${accountId}:saml-provider/${name}`;
169
170 // Observe — `getSAMLProvider` returns the metadata, encryption
171 // mode, and UUID; absence is `NoSuchEntityException`.
172 let observed = yield* iam
173 .getSAMLProvider({ SAMLProviderArn: samlProviderArn })
174 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined));
175
176 // Ensure — create when missing. Race with a peer is recovered by
177 // verifying alchemy ownership tags on the existing provider.
178 if (!observed) {
179 const created = yield* iam
180 .createSAMLProvider({
181 Name: name,
182 SAMLMetadataDocument: news.samlMetadataDocument,
183 AssertionEncryptionMode: news.assertionEncryptionMode,
184 AddPrivateKey: news.addPrivateKey
185 ? unwrapRedactedString(news.addPrivateKey)
186 : undefined,
187 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({ Key, Value })),
188 })
189 .pipe(
190 Effect.retry({ while: isTransientWriteError, schedule: transientWriteSchedule }),
191 Effect.catchTag("EntityAlreadyExistsException", () =>
192 Effect.gen(function* () {
193 const existingTags = yield* iam.listSAMLProviderTags({
194 SAMLProviderArn: samlProviderArn,
195 });
196 if (!hasTags(internalTags, existingTags.Tags)) {
197 return yield* new SAMLProviderConflict({
198 message: `SAML provider '${name}' already exists and is not managed by alchemy`,
199 });
200 }
201 return { SAMLProviderArn: samlProviderArn };
202 }),
203 ),
204 );
205 observed = yield* iam.getSAMLProvider({
206 SAMLProviderArn: created.SAMLProviderArn ?? samlProviderArn,
207 });
208 } else {
209 // Sync metadata / encryption mode — `updateSAMLProvider` rejects
210 // a call with no fields set ("No updates are defined…"). Only
211 // send fields that actually changed; skip the API on a no-op
212 // (greenfield adopt of a leftover provider, or a tags-only
213 // reconcile).
214 const metadataChanged =
215 (observed.SAMLMetadataDocument ?? undefined) !== news.samlMetadataDocument;
216 const encryptionChanged =
217 news.assertionEncryptionMode !== undefined &&
218 observed.AssertionEncryptionMode !== news.assertionEncryptionMode;
219 const addPrivateKey = news.addPrivateKey
220 ? unwrapRedactedString(news.addPrivateKey)
221 : undefined;
222 if (metadataChanged || encryptionChanged || addPrivateKey !== undefined) {
223 yield* iam
224 .updateSAMLProvider({
225 SAMLProviderArn: samlProviderArn,
226 SAMLMetadataDocument: metadataChanged ? news.samlMetadataDocument : undefined,
227 AssertionEncryptionMode: encryptionChanged ? news.assertionEncryptionMode : undefined,
228 AddPrivateKey: addPrivateKey,
229 })
230 .pipe(
231 Effect.retry({ while: isTransientWriteError, schedule: transientWriteSchedule }),
232 Effect.catchIf(isEmptyUpdateError, () => Effect.void),
233 );
234 }
235 }
236
237 // Sync tags against the cloud's actual tags.
238 const observedTagsResp = yield* iam.listSAMLProviderTags({
239 SAMLProviderArn: samlProviderArn,
240 });
241 const observedTags = toTagRecord(observedTagsResp.Tags);
242 const { removed, upsert } = diffTags(observedTags, desiredTags);
243 if (upsert.length > 0) {
244 yield* iam.tagSAMLProvider({ SAMLProviderArn: samlProviderArn, Tags: upsert });
245 }
246 if (removed.length > 0) {
247 yield* iam.untagSAMLProvider({ SAMLProviderArn: samlProviderArn, TagKeys: removed });
248 }
249
250 yield* session.note(samlProviderArn);
251 return {
252 samlProviderArn,
253 name,
254 samlProviderUUID: observed?.SAMLProviderUUID ?? output?.samlProviderUUID,
255 samlMetadataDocument: news.samlMetadataDocument,
256 assertionEncryptionMode: news.assertionEncryptionMode,
257 tags: desiredTags,
258 };
259 }),
260 delete: Effect.fn(function* ({ output }) {
261 yield* iam
262 .deleteSAMLProvider({ SAMLProviderArn: output.samlProviderArn })
263 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
264 }),
265 });