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

main
ts 298 lines 10.5 KB
Raw
1 import * as organizations from "@distilled.cloud/aws/organizations";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import type { Providers } from "../Providers.ts";
8 import { collectPages, retryOrganizations, unredact } from "./common.ts";
9
10 export class DelegatedAdministratorUnexpectedResponse extends Data.TaggedError(
11 "DelegatedAdministratorUnexpectedResponse",
12 )<{
13 readonly message: string;
14 readonly cause?: unknown;
15 }> {}
16
17 export interface DelegatedAdministratorProps {
18 /**
19 * Member account registered as delegated administrator.
20 */
21 accountId: string;
22 /**
23 * Service principal delegated to the account.
24 */
25 servicePrincipal: string;
26 }
27
28 export interface DelegatedAdministrator extends Resource<
29 "AWS.Organizations.DelegatedAdministrator",
30 DelegatedAdministratorProps,
31 {
32 /**
33 * 12-digit ID of the delegated administrator account.
34 */
35 accountId: string;
36 /**
37 * ARN of the delegated administrator account.
38 */
39 accountArn: string | undefined;
40 /**
41 * Friendly name of the delegated administrator account.
42 */
43 accountName: string | undefined;
44 /**
45 * Email address of the delegated administrator account.
46 */
47 accountEmail: string | undefined;
48 /**
49 * Service principal delegated to the account.
50 */
51 servicePrincipal: string;
52 /**
53 * When the delegation was enabled.
54 */
55 delegationEnabledDate: Date | undefined;
56 },
57 never,
58 Providers
59 > {}
60
61 /**
62 * Registers a member {@link Account} as the delegated administrator for a
63 * trusted AWS service, letting that account manage the service org-wide
64 * instead of the management account.
65 *
66 * Requires trusted access for the same service principal (see
67 * {@link TrustedServiceAccess}). Existence-only resource: changing
68 * `accountId` or `servicePrincipal` replaces the registration.
69 * ### Delegating Administration
70 * **Example:** Delegate GuardDuty to a Security Account
71 * ```typescript
72 * const security = yield* Account("Security", {
73 * name: "security",
74 * email: "aws-security@example.com",
75 * parentId: root.rootId,
76 * });
77 *
78 * const guardDutyAccess = yield* TrustedServiceAccess("GuardDutyAccess", {
79 * servicePrincipal: "guardduty.amazonaws.com",
80 * });
81 *
82 * yield* DelegatedAdministrator("GuardDutyAdmin", {
83 * accountId: security.accountId,
84 * servicePrincipal: guardDutyAccess.servicePrincipal,
85 * });
86 * ```
87 *
88 * @resource
89 */
90 export const DelegatedAdministrator = Resource<DelegatedAdministrator>(
91 "AWS.Organizations.DelegatedAdministrator",
92 );
93
94 export const DelegatedAdministratorProvider = () =>
95 Provider.effect(
96 DelegatedAdministrator,
97 Effect.gen(function* () {
98 return {
99 stables: ["accountId", "servicePrincipal"],
100 diff: Effect.fn(function* ({ olds, news }) {
101 if (!isResolved(news)) return;
102 if (
103 olds?.accountId !== news.accountId ||
104 olds?.servicePrincipal !== news.servicePrincipal
105 ) {
106 return { action: "replace" } as const;
107 }
108 }),
109 read: Effect.fn(function* ({ olds, output }) {
110 const accountId = output?.accountId ?? olds?.accountId;
111 const servicePrincipal = output?.servicePrincipal ?? olds?.servicePrincipal;
112 if (accountId === undefined || servicePrincipal === undefined) {
113 // Output-valued props don't survive a `creating`-state round-trip
114 // (they deserialize as `undefined`) — report "not found" so the
115 // engine re-drives the create.
116 return undefined;
117 }
118 return yield* readDelegatedAdministrator({
119 accountId,
120 servicePrincipal,
121 });
122 }),
123 list: () =>
124 Effect.gen(function* () {
125 // Enumerate every delegated administrator account in the org. If
126 // this account isn't an org management account (or lacks access),
127 // Organizations enumeration isn't available here — return [].
128 const admins = yield* retryOrganizations(
129 collectPages(
130 (NextToken) => organizations.listDelegatedAdministrators({ NextToken }),
131 (page) => page.DelegatedAdministrators,
132 ),
133 ).pipe(
134 Effect.catchTags({
135 AWSOrganizationsNotInUseException: () =>
136 Effect.succeed<organizations.DelegatedAdministrator[]>([]),
137 AccessDeniedException: () =>
138 Effect.succeed<organizations.DelegatedAdministrator[]>([]),
139 UnsupportedAPIEndpointException: () =>
140 Effect.succeed<organizations.DelegatedAdministrator[]>([]),
141 }),
142 );
143
144 // Fan out: each admin account may be delegated for multiple
145 // services. The canonical `read` shape is one item per
146 // (account, servicePrincipal), so expand each account into one
147 // Attributes per delegated service.
148 const rows = yield* Effect.forEach(
149 admins.filter(
150 (
151 admin,
152 ): admin is organizations.DelegatedAdministrator & {
153 Id: string;
154 } => admin.Id != null,
155 ),
156 (admin) =>
157 retryOrganizations(
158 collectPages(
159 (NextToken) =>
160 organizations.listDelegatedServicesForAccount({
161 AccountId: admin.Id,
162 NextToken,
163 }),
164 (page) => page.DelegatedServices,
165 ),
166 ).pipe(
167 // The account may be deregistered between the two calls — skip.
168 Effect.catchTags({
169 AccountNotFoundException: () =>
170 Effect.succeed<organizations.DelegatedService[]>([]),
171 AccountNotRegisteredException: () =>
172 Effect.succeed<organizations.DelegatedService[]>([]),
173 }),
174 Effect.map((services) =>
175 services
176 .filter(
177 (
178 service,
179 ): service is organizations.DelegatedService & {
180 ServicePrincipal: string;
181 } => service.ServicePrincipal != null,
182 )
183 .map(
184 (service) =>
185 ({
186 accountId: admin.Id,
187 accountArn: admin.Arn,
188 accountName: unredact(admin.Name),
189 accountEmail: unredact(admin.Email),
190 servicePrincipal: service.ServicePrincipal,
191 delegationEnabledDate:
192 service.DelegationEnabledDate ?? admin.DelegationEnabledDate,
193 }) satisfies DelegatedAdministrator["Attributes"],
194 ),
195 ),
196 ),
197 { concurrency: 10 },
198 );
199
200 return rows.flat();
201 }),
202 reconcile: Effect.fn(function* ({ news, session }) {
203 // Observe — look up the live delegation. Replacement-only props
204 // (`accountId`, `servicePrincipal`) mean the diff handles identity
205 // changes; we just check whether the registration exists.
206 let state = yield* readDelegatedAdministrator(news);
207
208 // Ensure — register if missing. Tolerate
209 // `AccountAlreadyRegisteredException` for idempotency under races
210 // between observe and register.
211 if (!state) {
212 yield* retryOrganizations(
213 organizations
214 .registerDelegatedAdministrator({
215 AccountId: news.accountId,
216 ServicePrincipal: news.servicePrincipal,
217 })
218 .pipe(Effect.catchTag("AccountAlreadyRegisteredException", () => Effect.void)),
219 );
220 state = yield* readDelegatedAdministrator(news);
221 if (!state) {
222 return yield* new DelegatedAdministratorUnexpectedResponse({
223 message: `delegated administrator '${news.accountId}' for '${news.servicePrincipal}' not found after create`,
224 });
225 }
226 }
227
228 yield* session.note(`${state.accountId}:${state.servicePrincipal}`);
229 return state;
230 }),
231 delete: Effect.fn(function* ({ output }) {
232 if (
233 !(yield* readDelegatedAdministrator({
234 accountId: output.accountId,
235 servicePrincipal: output.servicePrincipal,
236 }))
237 ) {
238 return;
239 }
240
241 yield* retryOrganizations(
242 organizations.deregisterDelegatedAdministrator({
243 AccountId: output.accountId,
244 ServicePrincipal: output.servicePrincipal,
245 }),
246 );
247 }),
248 };
249 }),
250 );
251
252 const readDelegatedAdministrator = Effect.fn(function* ({
253 accountId,
254 servicePrincipal,
255 }: DelegatedAdministratorProps) {
256 const [delegatedServices, delegatedAdmins] = yield* Effect.all([
257 retryOrganizations(
258 collectPages(
259 (NextToken) =>
260 organizations.listDelegatedServicesForAccount({
261 AccountId: accountId,
262 NextToken,
263 }),
264 (page) => page.DelegatedServices,
265 ),
266 ).pipe(
267 Effect.catchTag(["AccountNotFoundException", "AccountNotRegisteredException"], () =>
268 Effect.succeed<organizations.DelegatedService[]>([]),
269 ),
270 ),
271 retryOrganizations(
272 collectPages(
273 (NextToken) =>
274 organizations.listDelegatedAdministrators({
275 ServicePrincipal: servicePrincipal,
276 NextToken,
277 }),
278 (page) => page.DelegatedAdministrators,
279 ),
280 ),
281 ]);
282
283 const service = delegatedServices.find(
284 (candidate) => candidate.ServicePrincipal === servicePrincipal,
285 );
286 const account = delegatedAdmins.find((candidate) => candidate.Id === accountId);
287
288 return service && account
289 ? ({
290 accountId,
291 accountArn: account.Arn,
292 accountName: unredact(account.Name),
293 accountEmail: unredact(account.Email),
294 servicePrincipal,
295 delegationEnabledDate: service.DelegationEnabledDate ?? account.DelegationEnabledDate,
296 } satisfies DelegatedAdministrator["Attributes"])
297 : undefined;
298 });