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

main
ts 365 lines 13.1 KB
Raw
1 import * as rolesanywhere from "@distilled.cloud/aws/rolesanywhere";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
7 import { toWireDays } from "alchemy/Util/Duration";
8 import * as Data from "effect/Data";
9 import type * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import * as Stream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13 import { readRolesAnywhereTags, syncRolesAnywhereTags, toWireTags } from "./internal.ts";
14
15 /**
16 * Raised before any AWS call when the trust anchor's source is misconfigured
17 * — exactly one of `certificateBundle` or `acmPcaArn` must be provided.
18 */
19 export class TrustAnchorSourceConflict extends Data.TaggedError("TrustAnchorSourceConflict")<{
20 readonly message: string;
21 }> {}
22
23 /**
24 * A customized expiry notification for the trust anchor. AWS installs
25 * default notifications (45 days before CA and end-entity certificate
26 * expiry); declaring a setting for the same event/channel overrides the
27 * default, and removing it resets the event back to the AWS default.
28 */
29 export interface TrustAnchorNotificationSetting {
30 /**
31 * The expiry event to notify on: `CA_CERTIFICATE_EXPIRY` or
32 * `END_ENTITY_CERTIFICATE_EXPIRY`.
33 */
34 event: string;
35 /**
36 * Whether the notification is enabled.
37 * @default true
38 */
39 enabled?: boolean;
40 /**
41 * How far ahead of the expiry event to notify, e.g. `"30 days"` (a bare
42 * number is milliseconds). Rounded to whole days on the wire.
43 * @default "45 days"
44 */
45 threshold?: Duration.Input;
46 /**
47 * The notification channel. `ALL` (the only channel today) sends through
48 * both AWS Health Dashboard and email.
49 * @default "ALL"
50 */
51 channel?: string;
52 }
53
54 export interface TrustAnchorProps {
55 /**
56 * Name of the trust anchor. If omitted, a unique name is generated from the
57 * app, stage and logical ID. The name is updatable in place.
58 */
59 trustAnchorName?: string;
60 /**
61 * PEM-encoded CA certificate bundle establishing the trust root
62 * (`CERTIFICATE_BUNDLE` source). Exactly one of `certificateBundle` or
63 * `acmPcaArn` must be provided.
64 */
65 certificateBundle?: string;
66 /**
67 * ARN of an AWS Private CA (`AWS_ACM_PCA` source) establishing the trust
68 * root. Exactly one of `certificateBundle` or `acmPcaArn` must be provided.
69 */
70 acmPcaArn?: string;
71 /**
72 * Whether the trust anchor is enabled for trust validation. When disabled,
73 * temporary credential requests specifying this trust anchor are rejected.
74 * @default true
75 */
76 enabled?: boolean;
77 /**
78 * Customized certificate-expiry notifications. Events omitted here keep
79 * their AWS default notification; a setting previously managed by this
80 * resource and later removed is reset to the AWS default.
81 */
82 notificationSettings?: TrustAnchorNotificationSetting[];
83 /**
84 * User-defined tags for the trust anchor.
85 */
86 tags?: Record<string, string>;
87 }
88
89 export interface TrustAnchor extends Resource<
90 "AWS.RolesAnywhere.TrustAnchor",
91 TrustAnchorProps,
92 {
93 /**
94 * Unique ID of the trust anchor.
95 */
96 trustAnchorId: string;
97 /**
98 * ARN of the trust anchor.
99 */
100 trustAnchorArn: string;
101 /**
102 * Name of the trust anchor.
103 */
104 trustAnchorName: string;
105 /**
106 * Whether the trust anchor is enabled.
107 */
108 enabled: boolean;
109 },
110 never,
111 Providers
112 > {}
113
114 /**
115 * An IAM Roles Anywhere trust anchor. A trust anchor establishes trust
116 * between IAM Roles Anywhere and your certificate authority (CA) — either an
117 * uploaded PEM CA certificate bundle or a reference to an AWS Private CA.
118 * Workloads outside AWS authenticate with certificates issued by the CA in
119 * exchange for temporary AWS credentials.
120 * ### Creating a Trust Anchor
121 * **Example:** Certificate Bundle Trust Anchor
122 * ```typescript
123 * const anchor = yield* RolesAnywhere.TrustAnchor("Anchor", {
124 * certificateBundle: CA_CERTIFICATE_PEM,
125 * });
126 * ```
127 *
128 * **Example:** AWS Private CA Trust Anchor
129 * ```typescript
130 * const anchor = yield* RolesAnywhere.TrustAnchor("Anchor", {
131 * acmPcaArn: privateCa.certificateAuthorityArn,
132 * });
133 * ```
134 *
135 * ### Disabling a Trust Anchor
136 * **Example:** Disabled Trust Anchor
137 * ```typescript
138 * const anchor = yield* RolesAnywhere.TrustAnchor("Anchor", {
139 * certificateBundle: CA_CERTIFICATE_PEM,
140 * enabled: false,
141 * });
142 * ```
143 *
144 * ### Expiry Notifications
145 * **Example:** Custom Notification Threshold
146 * ```typescript
147 * const anchor = yield* RolesAnywhere.TrustAnchor("Anchor", {
148 * certificateBundle: CA_CERTIFICATE_PEM,
149 * notificationSettings: [
150 * { event: "CA_CERTIFICATE_EXPIRY", threshold: "30 days" },
151 * ],
152 * });
153 * ```
154 *
155 * @resource
156 */
157 export const TrustAnchor = Resource<TrustAnchor>("AWS.RolesAnywhere.TrustAnchor");
158
159 const toAttrs = (detail: rolesanywhere.TrustAnchorDetail) => ({
160 trustAnchorId: detail.trustAnchorId!,
161 trustAnchorArn: detail.trustAnchorArn!,
162 trustAnchorName: detail.name!,
163 enabled: detail.enabled ?? false,
164 });
165
166 const desiredSource = Effect.fn(function* (props: TrustAnchorProps) {
167 if ((props.certificateBundle === undefined) === (props.acmPcaArn === undefined)) {
168 return yield* new TrustAnchorSourceConflict({
169 message: "exactly one of certificateBundle or acmPcaArn must be provided",
170 });
171 }
172 return props.certificateBundle !== undefined
173 ? {
174 sourceType: "CERTIFICATE_BUNDLE",
175 sourceData: { x509CertificateData: props.certificateBundle.trim() },
176 }
177 : {
178 sourceType: "AWS_ACM_PCA",
179 sourceData: { acmPcaArn: props.acmPcaArn! },
180 };
181 });
182
183 /** The key AWS uses to identify a notification setting. */
184 const notificationKey = (setting: { event: string; channel?: string }) =>
185 `${setting.event}|${setting.channel ?? "ALL"}`;
186
187 const toWireNotificationSettings = (
188 settings: ReadonlyArray<TrustAnchorNotificationSetting>,
189 ): rolesanywhere.NotificationSetting[] =>
190 settings.map((setting) => ({
191 enabled: setting.enabled ?? true,
192 event: setting.event,
193 threshold: toWireDays(setting.threshold),
194 channel: setting.channel,
195 }));
196
197 const sourceDrift = (
198 observed: rolesanywhere.Source | undefined,
199 desired: { sourceType: string; sourceData: rolesanywhere.SourceData },
200 ) => {
201 if (observed === undefined) return true;
202 if (observed.sourceType !== desired.sourceType) return true;
203 const observedData = observed.sourceData;
204 const desiredData = desired.sourceData;
205 if ("x509CertificateData" in desiredData) {
206 return (
207 observedData === undefined ||
208 !("x509CertificateData" in observedData) ||
209 observedData.x509CertificateData?.trim() !== desiredData.x509CertificateData
210 );
211 }
212 return (
213 observedData === undefined ||
214 !("acmPcaArn" in observedData) ||
215 observedData.acmPcaArn !== desiredData.acmPcaArn
216 );
217 };
218
219 export const TrustAnchorProvider = () =>
220 Provider.effect(
221 TrustAnchor,
222 Effect.gen(function* () {
223 const createName = Effect.fn(function* (id: string, props: TrustAnchorProps) {
224 return props.trustAnchorName ?? (yield* createPhysicalName({ id, maxLength: 255 }));
225 });
226
227 /** Find a trust anchor by its user-facing name across all pages. */
228 const findByName = (name: string) =>
229 rolesanywhere.listTrustAnchors.items({}).pipe(
230 Stream.filter((detail) => detail.name === name),
231 Stream.runHead,
232 Effect.map((head) => (head._tag === "Some" ? head.value : undefined)),
233 );
234
235 const getById = (trustAnchorId: string) =>
236 rolesanywhere.getTrustAnchor({ trustAnchorId }).pipe(
237 Effect.map((r) => r.trustAnchor),
238 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
239 );
240
241 return {
242 stables: ["trustAnchorId", "trustAnchorArn"],
243
244 read: Effect.fn(function* ({ id, olds, output }) {
245 const found = output?.trustAnchorId
246 ? yield* getById(output.trustAnchorId)
247 : yield* findByName(yield* createName(id, olds ?? {}));
248 if (found === undefined) return undefined;
249 const attrs = toAttrs(found);
250 const tags = yield* readRolesAnywhereTags(attrs.trustAnchorArn);
251 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
252 }),
253
254 reconcile: Effect.fn(function* ({ id, news, olds, output, session }) {
255 const name = output?.trustAnchorName ?? (yield* createName(id, news));
256 const internalTags = yield* createInternalTags(id);
257 const desiredTags = { ...internalTags, ...news.tags };
258 const source = yield* desiredSource(news);
259 const desiredEnabled = news.enabled ?? true;
260 const desiredNotifications = toWireNotificationSettings(news.notificationSettings ?? []);
261
262 // 1. Observe — cloud state is authoritative; output caches the id.
263 let live = output?.trustAnchorId
264 ? yield* getById(output.trustAnchorId)
265 : yield* findByName(name);
266
267 // 2. Ensure — create if missing.
268 if (live === undefined) {
269 const created = yield* rolesanywhere.createTrustAnchor({
270 name,
271 source,
272 enabled: desiredEnabled,
273 tags: toWireTags(desiredTags),
274 notificationSettings:
275 desiredNotifications.length > 0 ? desiredNotifications : undefined,
276 });
277 live = created.trustAnchor;
278 } else {
279 // 3. Sync — converge name/source, then the enabled flag.
280 const desiredName = news.trustAnchorName ?? live.name!;
281 if (live.name !== desiredName || sourceDrift(live.source, source)) {
282 const updated = yield* rolesanywhere.updateTrustAnchor({
283 trustAnchorId: live.trustAnchorId!,
284 name: desiredName,
285 source,
286 });
287 live = updated.trustAnchor;
288 }
289 }
290
291 // 3a. Sync notification settings — diff the OBSERVED settings
292 // against the desired set. AWS installs default settings that must
293 // not be touched unless the user manages that event/channel, so
294 // resets are driven by the settings previously declared in `olds`
295 // rather than full replacement of observed state.
296 const observedNotifications = new Map(
297 (live.notificationSettings ?? []).map((setting) => [notificationKey(setting), setting]),
298 );
299 const notificationDrift = desiredNotifications.some((desired) => {
300 const observed = observedNotifications.get(notificationKey(desired));
301 return (
302 observed === undefined ||
303 observed.enabled !== desired.enabled ||
304 (desired.threshold !== undefined && observed.threshold !== desired.threshold)
305 );
306 });
307 if (notificationDrift) {
308 const updated = yield* rolesanywhere.putNotificationSettings({
309 trustAnchorId: live.trustAnchorId!,
310 notificationSettings: desiredNotifications,
311 });
312 live = updated.trustAnchor;
313 }
314 const desiredNotificationKeys = new Set(desiredNotifications.map(notificationKey));
315 const resetKeys = (olds?.notificationSettings ?? [])
316 .filter((previous) => !desiredNotificationKeys.has(notificationKey(previous)))
317 .map((previous) => ({
318 event: previous.event,
319 channel: previous.channel,
320 }));
321 if (resetKeys.length > 0) {
322 const reset = yield* rolesanywhere
323 .resetNotificationSettings({
324 trustAnchorId: live.trustAnchorId!,
325 notificationSettingKeys: resetKeys,
326 })
327 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
328 live = reset?.trustAnchor ?? live;
329 }
330
331 if ((live.enabled ?? false) !== desiredEnabled) {
332 // The enable/disable response can echo the pre-toggle state — the
333 // successful call itself is authoritative for the flag.
334 yield* desiredEnabled
335 ? rolesanywhere.enableTrustAnchor({
336 trustAnchorId: live.trustAnchorId!,
337 })
338 : rolesanywhere.disableTrustAnchor({
339 trustAnchorId: live.trustAnchorId!,
340 });
341 live = { ...live, enabled: desiredEnabled };
342 }
343
344 // 3b. Sync tags against observed cloud tags.
345 yield* syncRolesAnywhereTags(live.trustAnchorArn!, desiredTags);
346
347 yield* session.note(live.trustAnchorId!);
348 return toAttrs(live);
349 }),
350
351 delete: Effect.fn(function* ({ output }) {
352 yield* rolesanywhere
353 .deleteTrustAnchor({ trustAnchorId: output.trustAnchorId })
354 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
355 }),
356
357 list: () =>
358 rolesanywhere.listTrustAnchors.items({}).pipe(
359 Stream.map(toAttrs),
360 Stream.runCollect,
361 Effect.map((chunk) => Array.from(chunk)),
362 ),
363 };
364 }),
365 );