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

main
ts 549 lines 17.6 KB
Raw
1 import * as organizations from "@distilled.cloud/aws/organizations";
2 import * as Data from "effect/Data";
3 import type * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import type { ServiceControlPolicyDocument } from "../IAM/Policy.ts";
6 import * as IdentityCenter from "../IdentityCenter/index.ts";
7 import type { Account, AccountProps } from "./Account.ts";
8 import { Account as OrganizationAccount } from "./Account.ts";
9 import type { DelegatedAdministrator } from "./DelegatedAdministrator.ts";
10 import { DelegatedAdministrator as OrganizationsDelegatedAdministrator } from "./DelegatedAdministrator.ts";
11 import type { Organization, OrganizationProps } from "./Organization.ts";
12 import { Organization as AwsOrganization } from "./Organization.ts";
13 import type { OrganizationalUnit, OrganizationalUnitProps } from "./OrganizationalUnit.ts";
14 import { OrganizationalUnit as AwsOrganizationalUnit } from "./OrganizationalUnit.ts";
15 import type { Policy } from "./Policy.ts";
16 import { Policy as OrganizationsPolicy } from "./Policy.ts";
17 import type { PolicyAttachment } from "./PolicyAttachment.ts";
18 import { PolicyAttachment as OrganizationsPolicyAttachment } from "./PolicyAttachment.ts";
19 import type { Root, RootProps } from "./Root.ts";
20 import { Root as OrganizationRoot } from "./Root.ts";
21 import type { RootPolicyType } from "./RootPolicyType.ts";
22 import { RootPolicyType as OrganizationsRootPolicyType } from "./RootPolicyType.ts";
23 import type { TrustedServiceAccess } from "./TrustedServiceAccess.ts";
24 import { TrustedServiceAccess as OrganizationsTrustedServiceAccess } from "./TrustedServiceAccess.ts";
25
26 export class TenantRootInvalidProps extends Data.TaggedError("TenantRootInvalidProps")<{
27 readonly message: string;
28 readonly cause?: unknown;
29 }> {}
30
31 export type TenantTargetKey = string;
32
33 export interface TenantAccountSpec extends Omit<AccountProps, "parentId" | "name" | "email"> {
34 /** Stable key identifying the account within the tenant (used in logical IDs and `targetKeys`). */
35 key: string;
36 /** Friendly account name. */
37 name: string;
38 /** Globally unique email address for the account. */
39 email: string;
40 }
41
42 export interface TenantOrganizationalUnitSpec extends Omit<
43 OrganizationalUnitProps,
44 "parentId" | "name"
45 > {
46 /** Stable key identifying the OU within the tenant (used in logical IDs and `targetKeys`). */
47 key: string;
48 /**
49 * OU name.
50 * @default the spec `key`
51 */
52 name?: string;
53 /** Member accounts vended directly under this OU. */
54 accounts?: TenantAccountSpec[];
55 /** Nested child OUs. */
56 children?: TenantOrganizationalUnitSpec[];
57 }
58
59 export interface TenantPolicySpec {
60 /** Stable key identifying the policy within the tenant. */
61 key: string;
62 /** Policy name. If omitted, Alchemy generates one. */
63 name?: string;
64 /** Policy description. */
65 description?: string;
66 /**
67 * Organizations policy type.
68 * @default "SERVICE_CONTROL_POLICY"
69 */
70 type?: organizations.PolicyType;
71 /**
72 * Policy content — a typed {@link ServiceControlPolicyDocument} for
73 * SCP/RCP policies, or a raw JSON `string` for other policy types
74 * (tag, backup, ...) and as the escape hatch.
75 */
76 document: ServiceControlPolicyDocument | string;
77 /** Keys of the roots/OUs/accounts to attach the policy to (`"root"` or a spec key). */
78 targetKeys: TenantTargetKey[];
79 /** Tags applied to the policy, merged with tenant-wide tags. */
80 tags?: Record<string, string>;
81 }
82
83 export interface TenantIdentityCenterGroupSpec {
84 /** Stable key identifying the group within the tenant. */
85 key: string;
86 /** Display name of the Identity Center group. */
87 displayName: string;
88 /** Group description. */
89 description?: string;
90 }
91
92 export interface TenantIdentityCenterPermissionSetSpec {
93 /** Stable key identifying the permission set within the tenant. */
94 key: string;
95 /** Name of the permission set. */
96 name: string;
97 /** Permission set description. */
98 description?: string;
99 /**
100 * Optional session duration, e.g. `"8 hours"` or `Duration.hours(8)`.
101 * Sent to Identity Center as an ISO-8601 string such as `PT8H` (a bare
102 * number is milliseconds).
103 */
104 sessionDuration?: Duration.Input;
105 /** URL the user lands on after federating into the account. */
106 relayState?: string;
107 }
108
109 export interface TenantIdentityCenterAssignmentSpec {
110 /** Stable key for the assignment. Defaults to a key derived from the other fields. */
111 key?: string;
112 /** Key of the permission set to assign. */
113 permissionSetKey: string;
114 /** Key of the account the principal is granted access to. */
115 accountKey: string;
116 /**
117 * Kind of principal being assigned.
118 * @default "GROUP"
119 */
120 principalType?: "USER" | "GROUP";
121 /** Key of the Identity Center group to assign (when `principalType` is `GROUP`). */
122 groupKey?: string;
123 /** Explicit principal ID (e.g. an existing user) instead of a group key. */
124 principalId?: string;
125 }
126
127 export interface TenantIdentityCenterSpec {
128 /**
129 * Whether to adopt the org's existing Identity Center instance
130 * (`existing`) or create an account instance (`account`).
131 * @default "existing"
132 */
133 mode?: "existing" | "account";
134 /** ARN of an existing Identity Center instance to use explicitly. */
135 instanceArn?: string;
136 /** Name for the Identity Center instance. */
137 name?: string;
138 /** Account key to register as the Identity Center delegated administrator. */
139 delegatedAdminAccountKey?: string;
140 /** Identity Center groups to create. */
141 groups?: TenantIdentityCenterGroupSpec[];
142 /** Permission sets to create. */
143 permissionSets?: TenantIdentityCenterPermissionSetSpec[];
144 /** Account assignments binding groups/users to permission sets. */
145 assignments?: TenantIdentityCenterAssignmentSpec[];
146 }
147
148 export interface TenantRootProps {
149 /** Organization settings (feature set). Defaults to `featureSet: "ALL"`. */
150 organization?: OrganizationProps;
151 /** Root import settings (explicit root ID, tags). */
152 root?: RootProps;
153 /**
154 * Policy types to enable on the root.
155 * @default ["SERVICE_CONTROL_POLICY"]
156 */
157 policyTypes?: organizations.PolicyType[];
158 /** Service principals granted trusted access (Identity Center's is added automatically). */
159 trustedServicePrincipals?: string[];
160 /** OU tree to create under the root. Defaults to a security/infrastructure/workloads baseline. */
161 organizationalUnits?: TenantOrganizationalUnitSpec[];
162 /** Organizations policies to create and attach via `targetKeys`. */
163 policies?: TenantPolicySpec[];
164 /** IAM Identity Center groups, permission sets, and assignments. */
165 identityCenter?: TenantIdentityCenterSpec;
166 /** Tags applied to every taggable resource in the tenant. */
167 tags?: Record<string, string>;
168 }
169
170 export interface TenantRootResult {
171 organization: Organization;
172 root: Root;
173 policyTypes: RootPolicyType[];
174 trustedServiceAccess: TrustedServiceAccess[];
175 delegatedAdministrators: DelegatedAdministrator[];
176 organizationalUnits: Record<string, OrganizationalUnit>;
177 accounts: Record<string, Account>;
178 policies: Record<string, Policy>;
179 policyAttachments: PolicyAttachment[];
180 identityCenter?: {
181 instance: IdentityCenter.Instance;
182 groups: Record<string, IdentityCenter.Group>;
183 permissionSets: Record<string, IdentityCenter.PermissionSet>;
184 assignments: Record<string, IdentityCenter.AccountAssignment>;
185 };
186 }
187
188 const defaultTenantOrganizationalUnits = (): TenantOrganizationalUnitSpec[] => [
189 {
190 key: "security",
191 name: "security",
192 accounts: [
193 {
194 key: "security",
195 name: "security",
196 email: "security@example.com",
197 },
198 {
199 key: "log-archive",
200 name: "log-archive",
201 email: "log-archive@example.com",
202 },
203 ],
204 },
205 {
206 key: "infrastructure",
207 name: "infrastructure",
208 accounts: [
209 {
210 key: "shared-services",
211 name: "shared-services",
212 email: "shared-services@example.com",
213 },
214 ],
215 },
216 {
217 key: "workloads",
218 name: "workloads",
219 accounts: [
220 {
221 key: "prod",
222 name: "prod",
223 email: "prod@example.com",
224 },
225 ],
226 },
227 ];
228
229 const toLogicalIdSegment = (value: string) =>
230 value
231 .split(/[^A-Za-z0-9]+/)
232 .filter(Boolean)
233 .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
234 .join("");
235
236 /**
237 * Compose an opinionated single-tenant landing zone inside the current AWS
238 * Organizations management account.
239 *
240 * This helper intentionally stays aligned to native AWS semantics:
241 * one real Organization, one root, nested OUs, and accounts beneath that
242 * tenant root. The broader `RootRoot` concept is an Alchemy control-plane
243 * abstraction over many such tenant roots deployed into separate management
244 * accounts, not a nested AWS Organizations feature.
245 * ### Creating A Tenant Root
246 * **Example:** Tenant With Baseline Accounts
247 * ```typescript
248 * const tenant = yield* TenantRoot("CustomerA", {
249 * identityCenter: {
250 * mode: "existing",
251 * groups: [
252 * { key: "platform", displayName: "platform-engineers" },
253 * ],
254 * permissionSets: [
255 * {
256 * key: "admin",
257 * name: "AdministratorAccess",
258 * sessionDuration: "8 hours",
259 * },
260 * ],
261 * assignments: [
262 * {
263 * permissionSetKey: "admin",
264 * groupKey: "platform",
265 * accountKey: "prod",
266 * },
267 * ],
268 * },
269 * });
270 * ```
271 *
272 * @resource
273 */
274 export const TenantRoot = Effect.fn(function* (id: string, props: TenantRootProps = {}) {
275 const sharedTags = props.tags ?? {};
276 const organization = yield* AwsOrganization(`${id}Organization`, {
277 featureSet: "ALL",
278 ...props.organization,
279 });
280 const root = yield* OrganizationRoot(`${id}Root`, {
281 ...props.root,
282 tags: mergeTags(sharedTags, props.root?.tags),
283 });
284
285 const policyTypes = yield* Effect.forEach(
286 props.policyTypes ?? ["SERVICE_CONTROL_POLICY"],
287 (policyType) =>
288 OrganizationsRootPolicyType(`${id}${toLogicalIdSegment(policyType)}PolicyType`, {
289 rootId: root.rootId,
290 policyType,
291 }),
292 { concurrency: "unbounded" },
293 );
294
295 const trustedServicePrincipals = [
296 ...(props.trustedServicePrincipals ?? []),
297 ...(props.identityCenter ? ["sso.amazonaws.com"] : []),
298 ];
299 const trustedServiceAccess = yield* Effect.forEach(
300 [...new Set(trustedServicePrincipals)],
301 (servicePrincipal) =>
302 OrganizationsTrustedServiceAccess(
303 `${id}${toLogicalIdSegment(servicePrincipal)}TrustedAccess`,
304 { servicePrincipal },
305 ),
306 { concurrency: "unbounded" },
307 );
308
309 const organizationalUnits: Record<string, OrganizationalUnit> = {};
310 const accounts: Record<string, Account> = {};
311 const targets: Record<TenantTargetKey, { targetId: any }> = {
312 root: { targetId: root.rootId as any },
313 };
314
315 yield* createOrganizationalUnits({
316 id,
317 parentId: root.rootId,
318 sharedTags,
319 specs: props.organizationalUnits ?? defaultTenantOrganizationalUnits(),
320 organizationalUnits,
321 accounts,
322 targets,
323 });
324
325 const delegatedAdministrators: DelegatedAdministrator[] = [];
326 const identityCenter = props.identityCenter
327 ? yield* createTenantIdentityCenter({
328 id,
329 spec: props.identityCenter,
330 accounts,
331 sharedTags,
332 delegatedAdministrators,
333 })
334 : undefined;
335
336 const policies: Record<string, Policy> = {};
337 const policyAttachments: PolicyAttachment[] = [];
338 for (const policySpec of props.policies ?? []) {
339 const policy = yield* OrganizationsPolicy(`${id}${toLogicalIdSegment(policySpec.key)}Policy`, {
340 name: policySpec.name,
341 description: policySpec.description,
342 type: policySpec.type ?? "SERVICE_CONTROL_POLICY",
343 document: policySpec.document,
344 tags: mergeTags(sharedTags, policySpec.tags),
345 });
346 policies[policySpec.key] = policy;
347
348 for (const targetKey of policySpec.targetKeys) {
349 const target = targets[targetKey];
350 if (!target) {
351 return yield* new TenantRootInvalidProps({
352 message: `Unknown tenant policy target '${targetKey}' for policy '${policySpec.key}'`,
353 });
354 }
355
356 policyAttachments.push(
357 yield* OrganizationsPolicyAttachment(
358 `${id}${toLogicalIdSegment(policySpec.key)}${toLogicalIdSegment(targetKey)}Attachment`,
359 {
360 policyId: policy.policyId,
361 targetId: target.targetId,
362 },
363 ),
364 );
365 }
366 }
367
368 return {
369 organization,
370 root,
371 policyTypes,
372 trustedServiceAccess,
373 delegatedAdministrators,
374 organizationalUnits,
375 accounts,
376 policies,
377 policyAttachments,
378 identityCenter,
379 } satisfies TenantRootResult;
380 });
381
382 const createOrganizationalUnits = ({
383 id,
384 parentId,
385 sharedTags,
386 specs,
387 organizationalUnits,
388 accounts,
389 targets,
390 }: {
391 id: string;
392 parentId: any;
393 sharedTags: Record<string, string>;
394 specs: TenantOrganizationalUnitSpec[];
395 organizationalUnits: Record<string, OrganizationalUnit>;
396 accounts: Record<string, Account>;
397 targets: Record<TenantTargetKey, { targetId: any }>;
398 }): Effect.Effect<void, unknown, unknown> =>
399 Effect.gen(function* () {
400 for (const spec of specs) {
401 const ou = yield* AwsOrganizationalUnit(`${id}${toLogicalIdSegment(spec.key)}Ou`, {
402 parentId,
403 name: spec.name ?? spec.key,
404 tags: mergeTags(sharedTags, spec.tags),
405 });
406 organizationalUnits[spec.key] = ou;
407 targets[spec.key] = { targetId: ou.ouId as any };
408
409 for (const accountSpec of spec.accounts ?? []) {
410 const account = yield* OrganizationAccount(
411 `${id}${toLogicalIdSegment(accountSpec.key)}Account`,
412 {
413 ...accountSpec,
414 parentId: ou.ouId,
415 tags: mergeTags(sharedTags, accountSpec.tags),
416 },
417 );
418 accounts[accountSpec.key] = account;
419 targets[accountSpec.key] = { targetId: account.accountId as any };
420 }
421
422 if (spec.children?.length) {
423 yield* createOrganizationalUnits({
424 id,
425 parentId: ou.ouId as any,
426 sharedTags,
427 specs: spec.children,
428 organizationalUnits,
429 accounts,
430 targets,
431 });
432 }
433 }
434 });
435
436 const createTenantIdentityCenter = Effect.fn(function* ({
437 id,
438 spec,
439 accounts,
440 delegatedAdministrators,
441 }: {
442 id: string;
443 spec: TenantIdentityCenterSpec;
444 accounts: Record<string, Account>;
445 sharedTags: Record<string, string>;
446 delegatedAdministrators: DelegatedAdministrator[];
447 }) {
448 const instance = yield* IdentityCenter.Instance(`${id}IdentityCenter`, {
449 mode: spec.mode ?? "existing",
450 instanceArn: spec.instanceArn,
451 name: spec.name,
452 });
453
454 if (spec.delegatedAdminAccountKey) {
455 const account = accounts[spec.delegatedAdminAccountKey];
456 if (!account) {
457 return yield* new TenantRootInvalidProps({
458 message: `Unknown delegated admin account '${spec.delegatedAdminAccountKey}'`,
459 });
460 }
461 delegatedAdministrators.push(
462 yield* OrganizationsDelegatedAdministrator(
463 `${id}${toLogicalIdSegment(spec.delegatedAdminAccountKey)}IdentityCenterDelegatedAdmin`,
464 {
465 accountId: account.accountId,
466 servicePrincipal: "sso.amazonaws.com",
467 },
468 ),
469 );
470 }
471
472 const groups: Record<string, IdentityCenter.Group> = {};
473 for (const groupSpec of spec.groups ?? []) {
474 groups[groupSpec.key] = yield* IdentityCenter.Group(
475 `${id}${toLogicalIdSegment(groupSpec.key)}Group`,
476 {
477 identityStoreId: instance.identityStoreId,
478 displayName: groupSpec.displayName,
479 description: groupSpec.description,
480 },
481 );
482 }
483
484 const permissionSets: Record<string, IdentityCenter.PermissionSet> = {};
485 for (const permissionSetSpec of spec.permissionSets ?? []) {
486 permissionSets[permissionSetSpec.key] = yield* IdentityCenter.PermissionSet(
487 `${id}${toLogicalIdSegment(permissionSetSpec.key)}PermissionSet`,
488 {
489 instanceArn: instance.instanceArn,
490 name: permissionSetSpec.name,
491 description: permissionSetSpec.description,
492 sessionDuration: permissionSetSpec.sessionDuration,
493 relayState: permissionSetSpec.relayState,
494 },
495 );
496 }
497
498 const assignments: Record<string, IdentityCenter.AccountAssignment> = {};
499 for (const assignmentSpec of spec.assignments ?? []) {
500 const account = accounts[assignmentSpec.accountKey];
501 if (!account) {
502 return yield* new TenantRootInvalidProps({
503 message: `Unknown assignment account '${assignmentSpec.accountKey}'`,
504 });
505 }
506 const permissionSet = permissionSets[assignmentSpec.permissionSetKey];
507 if (!permissionSet) {
508 return yield* new TenantRootInvalidProps({
509 message: `Unknown assignment permission set '${assignmentSpec.permissionSetKey}'`,
510 });
511 }
512 const principalId =
513 assignmentSpec.groupKey !== undefined
514 ? groups[assignmentSpec.groupKey]?.groupId
515 : assignmentSpec.principalId;
516 if (!principalId) {
517 return yield* new TenantRootInvalidProps({
518 message: `Unable to resolve principal for assignment '${assignmentSpec.key ?? `${assignmentSpec.permissionSetKey}-${assignmentSpec.accountKey}`}'`,
519 });
520 }
521
522 const key =
523 assignmentSpec.key ??
524 `${assignmentSpec.permissionSetKey}-${assignmentSpec.accountKey}-${assignmentSpec.groupKey ?? assignmentSpec.principalId}`;
525
526 assignments[key] = yield* IdentityCenter.AccountAssignment(
527 `${id}${toLogicalIdSegment(key)}Assignment`,
528 {
529 instanceArn: instance.instanceArn,
530 permissionSetArn: permissionSet.permissionSetArn,
531 principalId,
532 principalType: assignmentSpec.groupKey ? "GROUP" : (assignmentSpec.principalType ?? "USER"),
533 targetId: account.accountId,
534 },
535 );
536 }
537
538 return {
539 instance,
540 groups,
541 permissionSets,
542 assignments,
543 };
544 });
545
546 const mergeTags = (shared: Record<string, string>, tags: Record<string, string> | undefined) => ({
547 ...shared,
548 ...tags,
549 });