@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 679 lines 24.5 KB
Raw
1 import * as acmpca from "@distilled.cloud/aws/acm-pca";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
7 import { toWireDays } from "alchemy/Util/Duration";
8 import * as Data from "effect/Data";
9 import * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import * as Schedule from "effect/Schedule";
12 import * as Stream from "effect/Stream";
13 import type { Providers } from "../Providers.ts";
14
15 /**
16 * X.500 distinguished name of the certificate authority. At least one
17 * field must be set (typically `commonName`).
18 */
19 export interface CertificateAuthoritySubject {
20 /**
21 * Fully qualified domain name (FQDN) associated with the certificate
22 * subject, e.g. `corp.example.com`.
23 */
24 commonName?: string;
25 /**
26 * Legal name of the organization with which the certificate subject is
27 * affiliated.
28 */
29 organization?: string;
30 /**
31 * A subdivision or unit of the organization with which the certificate
32 * subject is affiliated.
33 */
34 organizationalUnit?: string;
35 /**
36 * Two-digit ISO 3166-1 country code, e.g. `US`.
37 */
38 country?: string;
39 /**
40 * State in which the subject of the certificate is located.
41 */
42 state?: string;
43 /**
44 * The locality (city) in which the certificate subject is located.
45 */
46 locality?: string;
47 /**
48 * The certificate serial number.
49 */
50 serialNumber?: string;
51 /**
52 * A title such as Mr. or Ms., assigned to the certificate subject.
53 */
54 title?: string;
55 /**
56 * Family name of the certificate subject.
57 */
58 surname?: string;
59 /**
60 * First name of the certificate subject.
61 */
62 givenName?: string;
63 /**
64 * Concatenation of first letters of the subject's first name, middle
65 * name(s) and last name.
66 */
67 initials?: string;
68 /**
69 * Shortened version of a longer given name.
70 */
71 pseudonym?: string;
72 /**
73 * Disambiguating information for the certificate subject.
74 */
75 distinguishedNameQualifier?: string;
76 /**
77 * A qualifier appended to the subject's name, e.g. `Jr.` or `III`.
78 */
79 generationQualifier?: string;
80 }
81
82 /**
83 * Certificate revocation list (CRL) configuration.
84 */
85 export interface CrlConfigurationProps {
86 /**
87 * Whether Amazon Web Services Private CA maintains a CRL for the CA.
88 */
89 enabled: boolean;
90 /**
91 * Validity period of the CRL (e.g. `"7 days"` or `Duration.days(7)`).
92 * Rounded to whole days on the wire (`ExpirationInDays`).
93 * @default 7 days (service default when enabled)
94 */
95 expiration?: Duration.Input;
96 /**
97 * Alias to conceal the S3 bucket name inside issued certificates.
98 */
99 customCname?: string;
100 /**
101 * Name of the S3 bucket that receives the CRL. The bucket policy must
102 * grant write access to Amazon Web Services Private CA.
103 */
104 s3BucketName?: string;
105 /**
106 * ACL applied to the CRL objects written to S3.
107 */
108 s3ObjectAcl?: "PUBLIC_READ" | "BUCKET_OWNER_FULL_CONTROL";
109 /**
110 * Whether to generate a complete or partitioned CRL.
111 */
112 crlType?: "COMPLETE" | "PARTITIONED";
113 /**
114 * Custom path inside the S3 bucket under which the CRL is stored.
115 */
116 customPath?: string;
117 }
118
119 /**
120 * Online Certificate Status Protocol (OCSP) configuration.
121 */
122 export interface OcspConfigurationProps {
123 /**
124 * Whether OCSP is enabled for the CA.
125 */
126 enabled: boolean;
127 /**
128 * Custom CNAME for the OCSP responder endpoint.
129 */
130 ocspCustomCname?: string;
131 }
132
133 export interface CertificateAuthorityProps {
134 /**
135 * The type of the certificate authority.
136 * Changing this replaces the CA.
137 * @default "ROOT"
138 */
139 type?: acmpca.CertificateAuthorityType;
140 /**
141 * The key algorithm used to generate the CA's private key.
142 * Changing this replaces the CA.
143 * @default "RSA_2048"
144 */
145 keyAlgorithm?: acmpca.KeyAlgorithm;
146 /**
147 * The signing algorithm the CA uses to sign certificate requests. Must
148 * match the key algorithm family (RSA vs ECDSA).
149 * Changing this replaces the CA.
150 * @default "SHA256WITHRSA"
151 */
152 signingAlgorithm?: acmpca.SigningAlgorithm;
153 /**
154 * X.500 distinguished name of the CA. Changing this replaces the CA.
155 */
156 subject: CertificateAuthoritySubject;
157 /**
158 * Whether the CA issues general-purpose or short-lived (7 days or less)
159 * certificates. Short-lived mode has a lower monthly price.
160 * Changing this replaces the CA.
161 * @default "GENERAL_PURPOSE"
162 */
163 usageMode?: acmpca.CertificateAuthorityUsageMode;
164 /**
165 * Security standard of the HSM that stores the CA key.
166 * Changing this replaces the CA.
167 * @default "FIPS_140_2_LEVEL_3_OR_HIGHER" (varies by region)
168 */
169 keyStorageSecurityStandard?: acmpca.KeyStorageSecurityStandard;
170 /**
171 * Certificate revocation configuration (CRL and/or OCSP). Applied at
172 * create time; subsequent changes are applied via
173 * `UpdateCertificateAuthority`, which AWS only permits while the CA is in
174 * the `ACTIVE` or `DISABLED` state. When omitted the existing revocation
175 * configuration is left unchanged.
176 */
177 revocationConfiguration?: {
178 /**
179 * Certificate revocation list (CRL) settings.
180 */
181 crlConfiguration?: CrlConfigurationProps;
182 /**
183 * Online Certificate Status Protocol (OCSP) settings.
184 */
185 ocspConfiguration?: OcspConfigurationProps;
186 };
187 /**
188 * How long (7-30 days, e.g. `"7 days"`) the CA remains restorable after
189 * deletion. Used when the CA is destroyed while in the
190 * `PENDING_CERTIFICATE` or `DISABLED` state. Rounded to whole days on the
191 * wire (`PermanentDeletionTimeInDays`).
192 * @default 7 days
193 */
194 permanentDeletionTime?: Duration.Input;
195 /**
196 * Tags to apply to the CA. Merged with internal Alchemy tags.
197 */
198 tags?: Record<string, string>;
199 }
200
201 export interface CertificateAuthority extends Resource<
202 "AWS.ACMPCA.CertificateAuthority",
203 CertificateAuthorityProps,
204 {
205 /** The ARN of the certificate authority. */
206 certificateAuthorityArn: string;
207 /** The status of the CA (e.g. `PENDING_CERTIFICATE`, `ACTIVE`). */
208 status: acmpca.CertificateAuthorityStatus;
209 },
210 never,
211 Providers
212 > {}
213
214 /**
215 * An Amazon Web Services Private CA certificate authority.
216 *
217 * A newly created CA starts in the `PENDING_CERTIFICATE` state — to
218 * activate it you must retrieve its CSR, sign it (self-sign for a root
219 * CA), and import the signed certificate. Private CAs bill a monthly fee
220 * for as long as they exist, so destroy test CAs promptly. Deletion
221 * places the CA in the `DELETED` state for a configurable 7-30 day
222 * restoration window.
223 * ### Creating a Certificate Authority
224 * **Example:** Root CA
225 * ```typescript
226 * import * as ACMPCA from "@alchemy.run/aws/ACMPCA";
227 *
228 * const ca = yield* ACMPCA.CertificateAuthority("RootCA", {
229 * subject: { commonName: "corp.example.com" },
230 * });
231 * ```
232 *
233 * **Example:** ECDSA Subordinate CA
234 * ```typescript
235 * const ca = yield* ACMPCA.CertificateAuthority("IssuingCA", {
236 * type: "SUBORDINATE",
237 * keyAlgorithm: "EC_prime256v1",
238 * signingAlgorithm: "SHA256WITHECDSA",
239 * subject: {
240 * commonName: "issuing.corp.example.com",
241 * organization: "Example Corp",
242 * country: "US",
243 * },
244 * });
245 * ```
246 *
247 * **Example:** Short-Lived Certificate Mode
248 * ```typescript
249 * const ca = yield* ACMPCA.CertificateAuthority("ShortLivedCA", {
250 * subject: { commonName: "ephemeral.example.com" },
251 * usageMode: "SHORT_LIVED_CERTIFICATE",
252 * });
253 * ```
254 *
255 * ### Revocation
256 * **Example:** CA with CRL published to S3
257 * ```typescript
258 * const ca = yield* ACMPCA.CertificateAuthority("RootCA", {
259 * subject: { commonName: "corp.example.com" },
260 * revocationConfiguration: {
261 * crlConfiguration: {
262 * enabled: true,
263 * expiration: "7 days",
264 * s3BucketName: bucket.bucketName,
265 * },
266 * },
267 * });
268 * ```
269 *
270 * ### Granting ACM Access
271 * **Example:** Allow ACM to auto-renew certificates issued by this CA
272 * ```typescript
273 * const permission = yield* ACMPCA.Permission("AcmRenewal", {
274 * certificateAuthorityArn: ca.certificateAuthorityArn,
275 * });
276 * ```
277 *
278 * ### Reacting to CA Events
279 * **Example:** Consume ACM PCA Events from EventBridge
280 * ```typescript
281 * // ACM PCA emits lifecycle events (certificate issuance, expiry, CRL and
282 * // audit-report generation) on the default EventBridge bus under the
283 * // `aws.acm-pca` source — consume them with the generic EventBridge
284 * // event source; there is no ACM PCA-specific notification config.
285 * yield* AWS.EventBridge.consumeBusEvents(
286 * {
287 * source: ["aws.acm-pca"],
288 * "detail-type": ["ACM Private CA Certificate Issuance"],
289 * },
290 * (events) =>
291 * Stream.runForEach(events, (event) => Effect.log(event.detail)),
292 * );
293 * ```
294 *
295 * @resource
296 */
297 export const CertificateAuthority = Resource<CertificateAuthority>(
298 "AWS.ACMPCA.CertificateAuthority",
299 );
300
301 /**
302 * Internal signal used to poll a freshly created CA out of the
303 * `CREATING` state on a bounded schedule.
304 */
305 class CertificateAuthorityStillCreating extends Data.TaggedError(
306 "CertificateAuthorityStillCreating",
307 )<{ arn: string }> {}
308
309 // Bounded retry helpers with explicit signatures. Inlining Effect.retry in
310 // lifecycle ops leaks Retry.Return's conditional type into declaration emit
311 // and widens the provider layer to `unknown` for every consumer.
312 const retryWhileCreating = <A, E extends { readonly _tag: string }, R>(
313 self: Effect.Effect<A, E, R>,
314 ): Effect.Effect<A, E, R> =>
315 Effect.retry(self, {
316 while: (e) => e._tag === "CertificateAuthorityStillCreating",
317 schedule: Schedule.max([Schedule.fixed(2000), Schedule.recurs(30)]),
318 });
319
320 const retryWhileConcurrentlyModified = <A, E extends { readonly _tag: string }, R>(
321 self: Effect.Effect<A, E, R>,
322 ): Effect.Effect<A, E, R> =>
323 Effect.retry(self, {
324 while: (e) => e._tag === "ConcurrentModificationException",
325 schedule: Schedule.max([Schedule.fixed(2000), Schedule.recurs(10)]),
326 });
327
328 const buildSubject = (subject: CertificateAuthoritySubject): acmpca.ASN1Subject => ({
329 CommonName: subject.commonName,
330 Organization: subject.organization,
331 OrganizationalUnit: subject.organizationalUnit,
332 Country: subject.country,
333 State: subject.state,
334 Locality: subject.locality,
335 SerialNumber: subject.serialNumber,
336 Title: subject.title,
337 Surname: subject.surname,
338 GivenName: subject.givenName,
339 Initials: subject.initials,
340 Pseudonym: subject.pseudonym,
341 DistinguishedNameQualifier: subject.distinguishedNameQualifier,
342 GenerationQualifier: subject.generationQualifier,
343 });
344
345 const buildRevocationConfiguration = (
346 props: CertificateAuthorityProps["revocationConfiguration"],
347 ): acmpca.RevocationConfiguration | undefined => {
348 if (props === undefined) return undefined;
349 const crl = props.crlConfiguration;
350 const ocsp = props.ocspConfiguration;
351 return {
352 CrlConfiguration: crl
353 ? {
354 Enabled: crl.enabled,
355 ExpirationInDays: toWireDays(crl.expiration),
356 CustomCname: crl.customCname,
357 S3BucketName: crl.s3BucketName,
358 S3ObjectAcl: crl.s3ObjectAcl,
359 CrlType: crl.crlType,
360 CustomPath: crl.customPath,
361 }
362 : undefined,
363 OcspConfiguration: ocsp
364 ? {
365 Enabled: ocsp.enabled,
366 OcspCustomCname: ocsp.ocspCustomCname,
367 }
368 : undefined,
369 };
370 };
371
372 export const CertificateAuthorityProvider = () =>
373 Provider.effect(
374 CertificateAuthority,
375 Effect.gen(function* () {
376 // Describe a CA by ARN; typed not-found → undefined. A CA in the
377 // DELETED state is inside its restoration window — for lifecycle
378 // purposes it is gone (we never restore automatically).
379 const describeCa = Effect.fn(function* (arn: string) {
380 return yield* acmpca.describeCertificateAuthority({ CertificateAuthorityArn: arn }).pipe(
381 Effect.map((r) => r.CertificateAuthority),
382 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
383 );
384 });
385
386 const listCaTags = Effect.fn(function* (arn: string) {
387 const tags = yield* acmpca.listTags.items({ CertificateAuthorityArn: arn }).pipe(
388 Stream.runCollect,
389 Effect.map((chunk) =>
390 Object.fromEntries(
391 Array.from(chunk)
392 .filter((t) => t.Value !== undefined)
393 .map((t) => [t.Key, t.Value!] as const),
394 ),
395 ),
396 Effect.orElseSucceed(() => ({}) as Record<string, string>),
397 );
398 return tags;
399 });
400
401 const subjectFromAsn1 = (s: acmpca.ASN1Subject | undefined): CertificateAuthoritySubject => ({
402 commonName: s?.CommonName,
403 organization: s?.Organization,
404 organizationalUnit: s?.OrganizationalUnit,
405 country: s?.Country,
406 state: s?.State,
407 locality: s?.Locality,
408 serialNumber: s?.SerialNumber,
409 title: s?.Title,
410 surname: s?.Surname,
411 givenName: s?.GivenName,
412 initials: s?.Initials,
413 pseudonym: s?.Pseudonym,
414 distinguishedNameQualifier: s?.DistinguishedNameQualifier,
415 generationQualifier: s?.GenerationQualifier,
416 });
417
418 // Does the live CA's immutable configuration match the desired props?
419 // The tag-search fallback below must NOT match a CA whose immutable
420 // config differs — during a replacement the new instance reconciles
421 // with `output === undefined` and the same logical id, and matching
422 // the old CA by tags alone would silently re-adopt it instead of
423 // creating the replacement.
424 const matchesImmutableConfig = (
425 ca: acmpca.CertificateAuthority,
426 props: CertificateAuthorityProps,
427 ) => {
428 const config = ca.CertificateAuthorityConfiguration;
429 return (
430 (ca.Type ?? "ROOT") === (props.type ?? "ROOT") &&
431 config?.KeyAlgorithm === (props.keyAlgorithm ?? "RSA_2048") &&
432 config?.SigningAlgorithm === (props.signingAlgorithm ?? "SHA256WITHRSA") &&
433 (ca.UsageMode ?? "GENERAL_PURPOSE") === (props.usageMode ?? "GENERAL_PURPOSE") &&
434 (props.keyStorageSecurityStandard === undefined ||
435 ca.KeyStorageSecurityStandard === props.keyStorageSecurityStandard) &&
436 JSON.stringify(buildSubject(subjectFromAsn1(config?.Subject))) ===
437 JSON.stringify(buildSubject(props.subject ?? {}))
438 );
439 };
440
441 // ARNs are auto-assigned, so after a state persistence failure the
442 // only way back to an orphaned CA is its Alchemy ownership tags.
443 // Leaking a CA would keep billing, so reconcile searches by tags
444 // (plus matching immutable configuration) before creating.
445 const findManagedCa = Effect.fn(function* (id: string, props: CertificateAuthorityProps) {
446 const cas = yield* acmpca.listCertificateAuthorities.items({}).pipe(
447 Stream.runCollect,
448 Effect.map((chunk) =>
449 Array.from(chunk).filter((ca) => ca.Arn !== undefined && ca.Status !== "DELETED"),
450 ),
451 );
452 for (const ca of cas) {
453 if (!matchesImmutableConfig(ca, props)) continue;
454 const tags = yield* listCaTags(ca.Arn!);
455 if (yield* hasAlchemyTags(id, tags)) {
456 return ca;
457 }
458 }
459 return undefined;
460 });
461
462 // Poll a freshly created CA out of CREATING (bounded ~60s; the
463 // transition to PENDING_CERTIFICATE is normally fast).
464 const waitUntilCreated = Effect.fn(function* (arn: string) {
465 return yield* describeCa(arn).pipe(
466 Effect.flatMap((ca) =>
467 ca?.Status === "CREATING"
468 ? Effect.fail(new CertificateAuthorityStillCreating({ arn }))
469 : Effect.succeed(ca),
470 ),
471 retryWhileCreating,
472 );
473 });
474
475 const toAttrs = (
476 arn: string,
477 status: acmpca.CertificateAuthorityStatus | undefined,
478 ): CertificateAuthority["Attributes"] => ({
479 certificateAuthorityArn: arn,
480 status: status ?? "PENDING_CERTIFICATE",
481 });
482
483 return {
484 stables: ["certificateAuthorityArn"],
485 list: () =>
486 acmpca.listCertificateAuthorities.items({}).pipe(
487 Stream.runCollect,
488 Effect.map((chunk) =>
489 Array.from(chunk)
490 // DELETED CAs are already inside their restoration window
491 // and cannot be deleted again.
492 .filter((ca) => ca.Arn !== undefined && ca.Status !== "DELETED")
493 .map((ca) => toAttrs(ca.Arn!, ca.Status)),
494 ),
495 ),
496 read: Effect.fn(function* ({ id, olds, output }) {
497 // The ARN is auto-assigned: prefer the cached output, fall back
498 // to searching by ownership tags (state persistence failure).
499 let ca =
500 output?.certificateAuthorityArn !== undefined
501 ? yield* describeCa(output.certificateAuthorityArn)
502 : undefined;
503 if ((ca === undefined || ca.Status === "DELETED") && olds) {
504 ca = yield* findManagedCa(id, olds);
505 }
506 if (ca?.Arn === undefined || ca.Status === "DELETED") {
507 return undefined;
508 }
509 const attrs = toAttrs(ca.Arn, ca.Status);
510 const tags = yield* listCaTags(ca.Arn);
511 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
512 }),
513 diff: Effect.fn(function* ({ news, olds }) {
514 if (!isResolved(news)) return;
515 const immutableChanged =
516 (news.type ?? "ROOT") !== (olds.type ?? "ROOT") ||
517 (news.keyAlgorithm ?? "RSA_2048") !== (olds.keyAlgorithm ?? "RSA_2048") ||
518 (news.signingAlgorithm ?? "SHA256WITHRSA") !==
519 (olds.signingAlgorithm ?? "SHA256WITHRSA") ||
520 (news.usageMode ?? "GENERAL_PURPOSE") !== (olds.usageMode ?? "GENERAL_PURPOSE") ||
521 news.keyStorageSecurityStandard !== olds.keyStorageSecurityStandard ||
522 JSON.stringify(buildSubject(news.subject)) !==
523 JSON.stringify(buildSubject(olds.subject));
524 if (immutableChanged) {
525 return { action: "replace" } as const;
526 }
527 }),
528 reconcile: Effect.fn(function* ({ id, news, output, session }) {
529 const internalTags = yield* createInternalTags(id);
530 const desiredRevocation = buildRevocationConfiguration(news.revocationConfiguration);
531
532 // 1. OBSERVE — output is only an ARN cache; cloud state is
533 // authoritative. Fall back to a tag search so a persistence
534 // failure never leaks (and double-bills) a CA.
535 let ca =
536 output?.certificateAuthorityArn !== undefined
537 ? yield* describeCa(output.certificateAuthorityArn)
538 : undefined;
539 if (ca === undefined || ca.Status === "DELETED") {
540 ca = yield* findManagedCa(id, news);
541 }
542
543 // 2. ENSURE — create if missing and wait out the CREATING state.
544 if (ca?.Arn === undefined || ca.Status === "DELETED") {
545 const created = yield* acmpca.createCertificateAuthority({
546 CertificateAuthorityConfiguration: {
547 KeyAlgorithm: news.keyAlgorithm ?? "RSA_2048",
548 SigningAlgorithm: news.signingAlgorithm ?? "SHA256WITHRSA",
549 Subject: buildSubject(news.subject),
550 },
551 CertificateAuthorityType: news.type ?? "ROOT",
552 RevocationConfiguration: desiredRevocation,
553 KeyStorageSecurityStandard: news.keyStorageSecurityStandard,
554 UsageMode: news.usageMode,
555 Tags: Object.entries({
556 ...news.tags,
557 ...internalTags,
558 }).map(([Key, Value]) => ({ Key, Value })),
559 });
560 const arn = created.CertificateAuthorityArn!;
561 yield* session.note(`Created certificate authority ${arn}`);
562 ca = (yield* waitUntilCreated(arn)) ?? { Arn: arn };
563 }
564 const arn = ca.Arn!;
565
566 // 3. SYNC revocation configuration — AWS only allows
567 // UpdateCertificateAuthority while the CA is ACTIVE or DISABLED,
568 // so a PENDING_CERTIFICATE CA keeps its create-time settings.
569 if (
570 desiredRevocation !== undefined &&
571 (ca.Status === "ACTIVE" || ca.Status === "DISABLED")
572 ) {
573 const observed = JSON.stringify(
574 buildRevocationConfiguration({
575 crlConfiguration: ca.RevocationConfiguration?.CrlConfiguration
576 ? {
577 enabled: ca.RevocationConfiguration.CrlConfiguration.Enabled,
578 expiration:
579 ca.RevocationConfiguration.CrlConfiguration.ExpirationInDays === undefined
580 ? undefined
581 : Duration.days(
582 ca.RevocationConfiguration.CrlConfiguration.ExpirationInDays,
583 ),
584 customCname: ca.RevocationConfiguration.CrlConfiguration.CustomCname,
585 s3BucketName: ca.RevocationConfiguration.CrlConfiguration.S3BucketName,
586 s3ObjectAcl: ca.RevocationConfiguration.CrlConfiguration.S3ObjectAcl as
587 | "PUBLIC_READ"
588 | undefined,
589 crlType: ca.RevocationConfiguration.CrlConfiguration.CrlType as
590 | "COMPLETE"
591 | undefined,
592 customPath: ca.RevocationConfiguration.CrlConfiguration.CustomPath,
593 }
594 : undefined,
595 ocspConfiguration: ca.RevocationConfiguration?.OcspConfiguration
596 ? {
597 enabled: ca.RevocationConfiguration.OcspConfiguration.Enabled,
598 ocspCustomCname: ca.RevocationConfiguration.OcspConfiguration.OcspCustomCname,
599 }
600 : undefined,
601 }),
602 );
603 if (observed !== JSON.stringify(desiredRevocation)) {
604 yield* acmpca
605 .updateCertificateAuthority({
606 CertificateAuthorityArn: arn,
607 RevocationConfiguration: desiredRevocation,
608 })
609 .pipe(retryWhileConcurrentlyModified);
610 }
611 }
612
613 // 3b. SYNC tags — diff against OBSERVED cloud tags so adoption
614 // converges.
615 const currentTags = yield* listCaTags(arn);
616 const desiredTags: Record<string, string> = {
617 ...news.tags,
618 ...internalTags,
619 };
620 const { upsert, removed } = diffTags(currentTags, desiredTags);
621 if (upsert.length > 0) {
622 yield* acmpca.tagCertificateAuthority({
623 CertificateAuthorityArn: arn,
624 Tags: upsert,
625 });
626 }
627 if (removed.length > 0) {
628 yield* acmpca.untagCertificateAuthority({
629 CertificateAuthorityArn: arn,
630 Tags: removed.map((Key) => ({ Key })),
631 });
632 }
633
634 // 4. RETURN fresh attributes.
635 const final = yield* describeCa(arn);
636 yield* session.note(arn);
637 return toAttrs(arn, final?.Status ?? ca.Status);
638 }),
639 delete: Effect.fn(function* ({ olds, output, session }) {
640 const arn = output.certificateAuthorityArn;
641 const ca = yield* describeCa(arn);
642 if (ca === undefined || ca.Status === "DELETED") {
643 return;
644 }
645 // An ACTIVE CA must be DISABLED before it can be deleted.
646 if (ca.Status === "ACTIVE") {
647 yield* acmpca
648 .updateCertificateAuthority({
649 CertificateAuthorityArn: arn,
650 Status: "DISABLED",
651 })
652 .pipe(
653 retryWhileConcurrentlyModified,
654 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
655 );
656 }
657 // The restoration window may only be set while the CA is in the
658 // PENDING_CERTIFICATE or DISABLED state (CREATING/FAILED CAs have
659 // no restoration period).
660 const canSetWindow =
661 ca.Status === "PENDING_CERTIFICATE" ||
662 ca.Status === "DISABLED" ||
663 ca.Status === "ACTIVE"; // just disabled above
664 yield* acmpca
665 .deleteCertificateAuthority({
666 CertificateAuthorityArn: arn,
667 PermanentDeletionTimeInDays: canSetWindow
668 ? (toWireDays(olds?.permanentDeletionTime) ?? 7)
669 : undefined,
670 })
671 .pipe(
672 retryWhileConcurrentlyModified,
673 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
674 );
675 yield* session.note(`Deleted certificate authority ${arn}`);
676 }),
677 };
678 }),
679 );