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

main
ts 370 lines 13.1 KB
Raw
1 import * as aoss from "@distilled.cloud/aws/opensearchserverless";
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 { toWireMinutes } from "alchemy/Util/Duration";
7 import type * as Duration from "effect/Duration";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import { AWSEnvironment } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12 import { retryWhileConflict } from "./internal.ts";
13
14 /**
15 * The kind of security configuration:
16 * - `saml` — SAML federation with an external identity provider.
17 * - `iamidentitycenter` — AWS IAM Identity Center integration.
18 * - `iamfederation` — IAM federation via session attributes.
19 */
20 export type SecurityConfigType = "saml" | "iamidentitycenter" | "iamfederation";
21
22 export interface SamlOptions {
23 /**
24 * The XML IdP metadata document generated by the identity provider.
25 */
26 metadata: string;
27 /**
28 * A user attribute for the SAML assertion.
29 */
30 userAttribute?: string;
31 /**
32 * A group attribute for the SAML assertion.
33 */
34 groupAttribute?: string;
35 /**
36 * Custom entity ID used as the audience restriction of the SAML assertion.
37 */
38 openSearchServerlessEntityId?: string;
39 /**
40 * How long a SAML session remains valid. Accepts any `Duration.Input`
41 * (e.g. `"2 hours"`, `Duration.minutes(90)`; a bare number is milliseconds);
42 * the wire unit is minutes.
43 * @default 60 minutes (maximum 12 hours)
44 */
45 sessionTimeout?: Duration.Input;
46 }
47
48 export interface IamIdentityCenterOptions {
49 /**
50 * ARN of the IAM Identity Center instance.
51 */
52 instanceArn: string;
53 /**
54 * The user attribute to map (e.g. `UserId`, `UserName`, `Email`).
55 */
56 userAttribute?: string;
57 /**
58 * The group attribute to map (e.g. `GroupId`, `GroupName`).
59 */
60 groupAttribute?: string;
61 }
62
63 export interface IamFederationOptions {
64 /**
65 * The session attribute that carries the user identity.
66 */
67 userAttribute?: string;
68 /**
69 * The session attribute that carries the user's groups.
70 */
71 groupAttribute?: string;
72 }
73
74 export interface SecurityConfigProps {
75 /**
76 * Name of the security configuration (3-32 characters, lowercase). Changing
77 * the name replaces the configuration.
78 * @default a generated physical name
79 */
80 configName?: string;
81 /**
82 * The configuration kind (`saml`, `iamidentitycenter`, or `iamfederation`).
83 * Changing the type replaces the configuration.
84 */
85 type: SecurityConfigType;
86 /**
87 * A human-readable description of the configuration.
88 */
89 description?: string;
90 /**
91 * SAML options — required when `type` is `saml`.
92 */
93 samlOptions?: SamlOptions;
94 /**
95 * IAM Identity Center options — required when `type` is
96 * `iamidentitycenter`. `instanceArn` is create-only.
97 */
98 iamIdentityCenterOptions?: IamIdentityCenterOptions;
99 /**
100 * IAM federation options — required when `type` is `iamfederation`.
101 */
102 iamFederationOptions?: IamFederationOptions;
103 }
104
105 export interface SecurityConfig extends Resource<
106 "AWS.OpenSearchServerless.SecurityConfig",
107 SecurityConfigProps,
108 {
109 /**
110 * Unique identifier of the security configuration, in the format
111 * `{type}/{accountId}/{name}`. Use this as the `Principal` in a data
112 * access policy to grant federated identities access.
113 */
114 configId: string;
115 /**
116 * Name of the security configuration.
117 */
118 configName: string;
119 /**
120 * Configuration type (`saml`, `iamidentitycenter`, or `iamfederation`).
121 */
122 type: string;
123 /**
124 * Version of the configuration, used for optimistic-concurrency updates.
125 */
126 configVersion: string;
127 /**
128 * Description of the security configuration.
129 */
130 description?: string;
131 },
132 {},
133 Providers
134 > {}
135
136 /**
137 * An Amazon OpenSearch Serverless security configuration. Security
138 * configurations federate OpenSearch Dashboards sign-in with SAML identity
139 * providers, AWS IAM Identity Center, or IAM federation, so human users can
140 * access collections without IAM credentials.
141 *
142 * The configuration's `configId` (format `saml/{accountId}/{name}`) is what a
143 * data {@link AccessPolicy} references as a `Principal` to grant the federated
144 * identities index- and collection-level permissions.
145 *
146 * ### SAML Authentication
147 * **Example:** Federate Dashboards with a SAML Identity Provider
148 * ```typescript
149 * import * as AWS from "@alchemy.run/aws";
150 *
151 * const saml = yield* AWS.OpenSearchServerless.SecurityConfig("Saml", {
152 * configName: "my-idp",
153 * type: "saml",
154 * samlOptions: {
155 * metadata: idpMetadataXml,
156 * groupAttribute: "groups",
157 * sessionTimeout: "4 hours",
158 * },
159 * });
160 * // Reference saml.configId as a Principal in a data access policy
161 * ```
162 *
163 * ### IAM Federation
164 * **Example:** Map Session Attributes to Identities
165 * ```typescript
166 * const federation = yield* AWS.OpenSearchServerless.SecurityConfig("Federation", {
167 * configName: "my-federation",
168 * type: "iamfederation",
169 * iamFederationOptions: {
170 * userAttribute: "user",
171 * groupAttribute: "groups",
172 * },
173 * });
174 * ```
175 *
176 * @resource
177 */
178 export const SecurityConfig = Resource<SecurityConfig>("AWS.OpenSearchServerless.SecurityConfig");
179
180 export const SecurityConfigProvider = () =>
181 Provider.effect(
182 SecurityConfig,
183 Effect.gen(function* () {
184 const createName = Effect.fn(function* (
185 id: string,
186 props: { configName?: string | undefined },
187 ) {
188 return (
189 props.configName ?? (yield* createPhysicalName({ id, maxLength: 32, lowercase: true }))
190 );
191 });
192
193 // A security config's id is deterministic: {type}/{accountId}/{name}.
194 const computeConfigId = Effect.fn(function* (type: string, name: string) {
195 const { accountId } = yield* AWSEnvironment.current;
196 return `${type}/${accountId}/${name}`;
197 });
198
199 const toName = (configId: string) => configId.split("/").at(-1)!;
200
201 const toAttributes = (detail: aoss.SecurityConfigDetail) => ({
202 configId: detail.id!,
203 configName: toName(detail.id!),
204 type: detail.type!,
205 configVersion: detail.configVersion!,
206 description: detail.description,
207 });
208
209 const toWireSamlOptions = (saml: SamlOptions | undefined) =>
210 saml === undefined
211 ? undefined
212 : {
213 metadata: saml.metadata,
214 userAttribute: saml.userAttribute,
215 groupAttribute: saml.groupAttribute,
216 openSearchServerlessEntityId: saml.openSearchServerlessEntityId,
217 sessionTimeout: toWireMinutes(saml.sessionTimeout),
218 };
219
220 const observe = Effect.fn(function* (configId: string) {
221 return yield* aoss.getSecurityConfig({ id: configId }).pipe(
222 Effect.map((r) => r.securityConfigDetail),
223 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
224 );
225 });
226
227 return SecurityConfig.Provider.of({
228 stables: ["configId", "configName", "type"],
229
230 list: () =>
231 Effect.gen(function* () {
232 const types: SecurityConfigType[] = ["saml", "iamidentitycenter", "iamfederation"];
233 const results: {
234 configId: string;
235 configName: string;
236 type: string;
237 configVersion: string;
238 description?: string;
239 }[] = [];
240 for (const type of types) {
241 const pages = yield* aoss.listSecurityConfigs.pages({ type }).pipe(Stream.runCollect);
242 for (const page of pages) {
243 for (const s of page.securityConfigSummaries ?? []) {
244 if (s.id !== undefined && s.type !== undefined && s.configVersion !== undefined) {
245 results.push({
246 configId: s.id,
247 configName: toName(s.id),
248 type: s.type,
249 configVersion: s.configVersion,
250 description: s.description,
251 });
252 }
253 }
254 }
255 }
256 return results;
257 }),
258
259 read: Effect.fn(function* ({ id, olds, output }) {
260 const type = output?.type ?? olds?.type;
261 if (type === undefined) {
262 return undefined;
263 }
264 const configId =
265 output?.configId ?? (yield* computeConfigId(type, yield* createName(id, olds ?? {})));
266 const detail = yield* observe(configId);
267 if (detail?.id === undefined) {
268 return undefined;
269 }
270 // Security configs carry no tags, so an existing same-name config is
271 // adopted.
272 return toAttributes(detail);
273 }),
274
275 diff: Effect.fn(function* ({ id, news, olds }) {
276 if (!isResolved(news)) return undefined;
277 if (olds.type !== news.type) {
278 return { action: "replace" } as const;
279 }
280 const oldName = yield* createName(id, olds);
281 const newName = yield* createName(id, news);
282 if (oldName !== newName) {
283 return { action: "replace" } as const;
284 }
285 // description/options fall through to the default update path
286 }),
287
288 reconcile: Effect.fn(function* ({ id, news, output, session }) {
289 const type = news.type;
290 const name = output?.configName ?? (yield* createName(id, news));
291 const configId = output?.configId ?? (yield* computeConfigId(type, name));
292 const desiredSaml = toWireSamlOptions(news.samlOptions);
293
294 // 1. OBSERVE
295 let detail = yield* observe(configId);
296
297 // 2. ENSURE — create if missing; tolerate a concurrent create race
298 if (detail?.id === undefined) {
299 detail = yield* aoss
300 .createSecurityConfig({
301 type,
302 name,
303 description: news.description,
304 samlOptions: desiredSaml,
305 iamIdentityCenterOptions: news.iamIdentityCenterOptions,
306 iamFederationOptions: news.iamFederationOptions,
307 })
308 .pipe(
309 Effect.map((r) => r.securityConfigDetail),
310 Effect.catchTag("ConflictException", () => observe(configId)),
311 );
312 } else {
313 // 3. SYNC — update when observed drifts from desired
314 const samlDrift =
315 desiredSaml !== undefined &&
316 (desiredSaml.metadata !== detail.samlOptions?.metadata ||
317 desiredSaml.userAttribute !== detail.samlOptions?.userAttribute ||
318 desiredSaml.groupAttribute !== detail.samlOptions?.groupAttribute ||
319 (desiredSaml.sessionTimeout !== undefined &&
320 desiredSaml.sessionTimeout !== detail.samlOptions?.sessionTimeout));
321 const federationDrift =
322 news.iamFederationOptions !== undefined &&
323 (news.iamFederationOptions.userAttribute !==
324 detail.iamFederationOptions?.userAttribute ||
325 news.iamFederationOptions.groupAttribute !==
326 detail.iamFederationOptions?.groupAttribute);
327 const identityCenterDrift =
328 news.iamIdentityCenterOptions !== undefined &&
329 (news.iamIdentityCenterOptions.userAttribute !==
330 detail.iamIdentityCenterOptions?.userAttribute ||
331 news.iamIdentityCenterOptions.groupAttribute !==
332 detail.iamIdentityCenterOptions?.groupAttribute);
333 const descriptionDrift =
334 news.description !== undefined && news.description !== detail.description;
335 if (samlDrift || federationDrift || identityCenterDrift || descriptionDrift) {
336 detail = yield* aoss
337 .updateSecurityConfig({
338 id: detail.id,
339 configVersion: detail.configVersion!,
340 description: descriptionDrift ? news.description : undefined,
341 samlOptions: samlDrift ? desiredSaml : undefined,
342 iamIdentityCenterOptionsUpdates: identityCenterDrift
343 ? {
344 userAttribute: news.iamIdentityCenterOptions?.userAttribute,
345 groupAttribute: news.iamIdentityCenterOptions?.groupAttribute,
346 }
347 : undefined,
348 iamFederationOptions: federationDrift ? news.iamFederationOptions : undefined,
349 })
350 .pipe(Effect.map((r) => r.securityConfigDetail));
351 }
352 }
353
354 if (detail?.id === undefined) {
355 return yield* aoss.ResourceNotFoundException.make({
356 message: `security config ${configId} not visible after reconcile`,
357 });
358 }
359 yield* session.note(detail.id);
360 return toAttributes(detail);
361 }),
362
363 delete: Effect.fn(function* ({ output }) {
364 yield* retryWhileConflict(aoss.deleteSecurityConfig({ id: output.configId })).pipe(
365 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
366 );
367 }),
368 });
369 }),
370 );