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

main
ts 222 lines 8.36 KB
Raw
1 import * as acmpca from "@distilled.cloud/aws/acm-pca";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Stream from "effect/Stream";
7 import type { Providers } from "../Providers.ts";
8
9 const DEFAULT_PRINCIPAL = "acm.amazonaws.com";
10 const DEFAULT_ACTIONS: acmpca.ActionType[] = [
11 "IssueCertificate",
12 "GetCertificate",
13 "ListPermissions",
14 ];
15
16 export interface PermissionProps {
17 /**
18 * The ARN of the private certificate authority the permission is
19 * granted on. Changing this replaces the permission.
20 */
21 certificateAuthorityArn: string;
22 /**
23 * The Amazon Web Services service principal receiving the permission.
24 * Currently the only supported value is `acm.amazonaws.com`.
25 * Changing this replaces the permission.
26 * @default "acm.amazonaws.com"
27 */
28 principal?: string;
29 /**
30 * The actions the principal may perform against the CA. For the ACM
31 * principal AWS requires all three actions — a subset is rejected with
32 * `ValidationException: Permissions must contain all three actions
33 * [IssueCertificate, GetCertificate, ListPermissions] for ACM to
34 * perform renewals.`
35 * @default ["IssueCertificate", "GetCertificate", "ListPermissions"]
36 */
37 actions?: acmpca.ActionType[];
38 /**
39 * The account that owns the CA (for CAs shared into this account).
40 * Changing this replaces the permission.
41 */
42 sourceAccount?: string;
43 }
44
45 export interface Permission extends Resource<
46 "AWS.ACMPCA.Permission",
47 PermissionProps,
48 {
49 /** The ARN of the CA the permission is granted on. */
50 certificateAuthorityArn: string;
51 /** The service principal the permission is granted to. */
52 principal: string;
53 },
54 never,
55 Providers
56 > {}
57
58 /**
59 * A permission on a private CA granted to the Certificate Manager (ACM)
60 * service principal, allowing ACM to automatically issue and renew ACM
61 * certificates signed by the CA.
62 * ### Granting Permissions
63 * **Example:** Allow ACM to auto-renew certificates
64 * ```typescript
65 * import * as ACMPCA from "@alchemy.run/aws/ACMPCA";
66 *
67 * const permission = yield* ACMPCA.Permission("AcmRenewal", {
68 * certificateAuthorityArn: ca.certificateAuthorityArn,
69 * });
70 * ```
71 *
72 * **Example:** Restrict the granted actions
73 * ```typescript
74 * const permission = yield* ACMPCA.Permission("AcmIssueOnly", {
75 * certificateAuthorityArn: ca.certificateAuthorityArn,
76 * actions: ["IssueCertificate", "GetCertificate"],
77 * });
78 * ```
79 *
80 * @resource
81 */
82 export const Permission = Resource<Permission>("AWS.ACMPCA.Permission");
83
84 const sortedActions = (actions: readonly acmpca.ActionType[] | undefined) =>
85 JSON.stringify([...(actions ?? [])].sort());
86
87 export const PermissionProvider = () =>
88 Provider.effect(
89 Permission,
90 Effect.gen(function* () {
91 // Find the permission entry for a principal on a CA. A missing or
92 // deleted CA yields "no permission" for observation purposes.
93 const findPermission = Effect.fn(function* (
94 certificateAuthorityArn: string,
95 principal: string,
96 ) {
97 return yield* acmpca.listPermissions
98 .items({ CertificateAuthorityArn: certificateAuthorityArn })
99 .pipe(
100 Stream.runCollect,
101 Effect.map((chunk) => Array.from(chunk).find((p) => p.Principal === principal)),
102 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
103 );
104 });
105
106 return {
107 stables: ["certificateAuthorityArn", "principal"],
108 list: () =>
109 Effect.gen(function* () {
110 // Permissions hang off CAs: enumerate every non-deleted CA in
111 // the ambient account/region and collect its permissions.
112 const cas = yield* acmpca.listCertificateAuthorities.items({}).pipe(
113 Stream.runCollect,
114 Effect.map((chunk) =>
115 Array.from(chunk)
116 .filter((ca) => ca.Arn !== undefined && ca.Status !== "DELETED")
117 .map((ca) => ca.Arn!),
118 ),
119 );
120 const perCa = yield* Effect.forEach(
121 cas,
122 (arn) =>
123 acmpca.listPermissions.items({ CertificateAuthorityArn: arn }).pipe(
124 Stream.runCollect,
125 Effect.map((chunk) =>
126 Array.from(chunk)
127 .filter((p) => p.Principal !== undefined)
128 .map((p) => ({
129 certificateAuthorityArn: arn,
130 principal: p.Principal!,
131 })),
132 ),
133 // CA removed (or state-blocked) between enumeration and
134 // listPermissions — it has no listable permissions.
135 Effect.catchTag(["ResourceNotFoundException", "InvalidStateException"], () =>
136 Effect.succeed([] as Permission["Attributes"][]),
137 ),
138 ),
139 { concurrency: 5 },
140 );
141 return perCa.flat();
142 }),
143 read: Effect.fn(function* ({ olds, output }) {
144 const arn = output?.certificateAuthorityArn ?? olds?.certificateAuthorityArn;
145 if (arn === undefined) return undefined;
146 const principal = output?.principal ?? olds?.principal ?? DEFAULT_PRINCIPAL;
147 const found = yield* findPermission(arn, principal);
148 if (found === undefined) return undefined;
149 return { certificateAuthorityArn: arn, principal };
150 }),
151 diff: Effect.fn(function* ({ news, olds }) {
152 if (!isResolved(news)) return;
153 if (
154 news.certificateAuthorityArn !== olds.certificateAuthorityArn ||
155 (news.principal ?? DEFAULT_PRINCIPAL) !== (olds.principal ?? DEFAULT_PRINCIPAL) ||
156 news.sourceAccount !== olds.sourceAccount
157 ) {
158 return { action: "replace" } as const;
159 }
160 // actions changes converge through the default update path.
161 }),
162 reconcile: Effect.fn(function* ({ news, session }) {
163 const principal = news.principal ?? DEFAULT_PRINCIPAL;
164 const actions = news.actions ?? DEFAULT_ACTIONS;
165
166 // OBSERVE — the permission has no update API, so converge by
167 // comparing the observed action set and recreating on drift.
168 const existing = yield* findPermission(news.certificateAuthorityArn, principal);
169
170 const converged =
171 existing !== undefined &&
172 sortedActions(existing.Actions) === sortedActions(actions) &&
173 (news.sourceAccount === undefined || existing.SourceAccount === news.sourceAccount);
174
175 if (!converged) {
176 if (existing !== undefined) {
177 yield* acmpca
178 .deletePermission({
179 CertificateAuthorityArn: news.certificateAuthorityArn,
180 Principal: principal,
181 SourceAccount: news.sourceAccount,
182 })
183 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
184 }
185 yield* acmpca
186 .createPermission({
187 CertificateAuthorityArn: news.certificateAuthorityArn,
188 Principal: principal,
189 SourceAccount: news.sourceAccount,
190 Actions: actions,
191 })
192 .pipe(
193 // A concurrent reconciler won the create race — the
194 // permission exists; treat as converged.
195 Effect.catchTag("PermissionAlreadyExistsException", () => Effect.void),
196 );
197 }
198
199 yield* session.note(`Permission for ${principal} on ${news.certificateAuthorityArn}`);
200 return {
201 certificateAuthorityArn: news.certificateAuthorityArn,
202 principal,
203 };
204 }),
205 delete: Effect.fn(function* ({ output }) {
206 yield* acmpca
207 .deletePermission({
208 CertificateAuthorityArn: output.certificateAuthorityArn,
209 Principal: output.principal,
210 })
211 .pipe(
212 // CA already gone, or in a state (DELETED) where permissions
213 // are no longer addressable — the permission is gone with it.
214 Effect.catchTag(
215 ["ResourceNotFoundException", "InvalidStateException"],
216 () => Effect.void,
217 ),
218 );
219 }),
220 };
221 }),
222 );