@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 209 lines 8.16 KB
Raw
1 import * as servicecatalog from "@distilled.cloud/aws/service-catalog";
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 import { awaitVisible } from "./internal.ts";
9
10 export type PrincipalType = "IAM" | "IAM_PATTERN";
11
12 export interface PrincipalPortfolioAssociationProps {
13 /**
14 * ID of the portfolio to grant access to. Changing it replaces the
15 * association.
16 */
17 portfolioId: string;
18 /**
19 * ARN of the IAM principal (user, group, or role) — or an ARN pattern
20 * with wildcards when `principalType` is `IAM_PATTERN`. Changing it
21 * replaces the association.
22 */
23 principalArn: string;
24 /**
25 * Whether `principalArn` is a concrete IAM ARN (`IAM`) or a wildcard
26 * pattern (`IAM_PATTERN`). Changing it replaces the association.
27 * @default "IAM"
28 */
29 principalType?: PrincipalType;
30 }
31
32 export interface PrincipalPortfolioAssociation extends Resource<
33 "AWS.ServiceCatalog.PrincipalPortfolioAssociation",
34 PrincipalPortfolioAssociationProps,
35 {
36 /** ID of the portfolio. */
37 portfolioId: string;
38 /** ARN (or pattern) of the associated principal. */
39 principalArn: string;
40 /** The principal type of the association. */
41 principalType: PrincipalType;
42 },
43 never,
44 Providers
45 > {}
46
47 /**
48 * Grants an IAM principal (user, group, or role) access to a Service
49 * Catalog portfolio, allowing it to browse and launch the portfolio's
50 * products.
51 *
52 * ### Granting Access
53 * **Example:** Associate an IAM role
54 * ```typescript
55 * import * as ServiceCatalog from "@alchemy.run/aws/ServiceCatalog";
56 *
57 * yield* ServiceCatalog.PrincipalPortfolioAssociation("DevAccess", {
58 * portfolioId: portfolio.portfolioId,
59 * principalArn: role.roleArn,
60 * });
61 * ```
62 *
63 * **Example:** Associate a wildcard principal pattern
64 * ```typescript
65 * yield* ServiceCatalog.PrincipalPortfolioAssociation("AllDevRoles", {
66 * portfolioId: portfolio.portfolioId,
67 * principalArn: "arn:aws:iam:::role/dev-*",
68 * principalType: "IAM_PATTERN",
69 * });
70 * ```
71 *
72 * @resource
73 */
74 export const PrincipalPortfolioAssociation = Resource<PrincipalPortfolioAssociation>(
75 "AWS.ServiceCatalog.PrincipalPortfolioAssociation",
76 );
77
78 export const PrincipalPortfolioAssociationProvider = () =>
79 Provider.effect(
80 PrincipalPortfolioAssociation,
81 Effect.gen(function* () {
82 // Enumerate the portfolio's principals and check for ours. A missing
83 // portfolio means the association is gone too.
84 const isAssociated = Effect.fn(function* (portfolioId: string, principalArn: string) {
85 return yield* servicecatalog.listPrincipalsForPortfolio
86 .pages({ PortfolioId: portfolioId })
87 .pipe(
88 Stream.runCollect,
89 Effect.map((chunk) =>
90 Array.from(chunk)
91 .flatMap((page) => page.Principals ?? [])
92 .some((p) => p.PrincipalARN === principalArn),
93 ),
94 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(false)),
95 );
96 });
97
98 return PrincipalPortfolioAssociation.Provider.of({
99 stables: ["portfolioId", "principalArn", "principalType"],
100 // Service Catalog has no account-wide principal-association API. Walk
101 // every portfolio so unsafe nuke can remove principals before their
102 // parent portfolios. AWS may replace the ARN of a deleted IAM role
103 // with its stable principal ID (ARO...); preserve that value because
104 // the disassociate API accepts it.
105 list: () =>
106 Effect.gen(function* () {
107 const portfolioIds = yield* servicecatalog.listPortfolios.pages({}).pipe(
108 Stream.runCollect,
109 Effect.map((pages) =>
110 Array.from(pages)
111 .flatMap((page) => page.PortfolioDetails ?? [])
112 .flatMap((portfolio) => (portfolio.Id === undefined ? [] : [portfolio.Id])),
113 ),
114 );
115
116 const associations = yield* Effect.forEach(
117 portfolioIds,
118 (portfolioId) =>
119 servicecatalog.listPrincipalsForPortfolio.pages({ PortfolioId: portfolioId }).pipe(
120 Stream.runCollect,
121 Effect.map((pages) =>
122 Array.from(pages)
123 .flatMap((page) => page.Principals ?? [])
124 .flatMap((principal) => {
125 if (principal.PrincipalARN === undefined) return [];
126 const principalType =
127 principal.PrincipalType === "IAM"
128 ? ("IAM" as const)
129 : principal.PrincipalType === "IAM_PATTERN"
130 ? ("IAM_PATTERN" as const)
131 : undefined;
132 if (principalType === undefined) return [];
133 return [
134 {
135 portfolioId,
136 principalArn: principal.PrincipalARN,
137 principalType,
138 },
139 ];
140 }),
141 ),
142 // A portfolio can disappear between enumeration and
143 // association hydration.
144 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([])),
145 ),
146 { concurrency: 5 },
147 );
148 return associations.flat();
149 }),
150 // Existence-only resource — every property is part of its identity.
151 diff: Effect.fn(function* ({ olds, news }) {
152 if (!isResolved(news)) return undefined;
153 if (
154 olds.portfolioId !== news.portfolioId ||
155 olds.principalArn !== news.principalArn ||
156 (olds.principalType ?? "IAM") !== (news.principalType ?? "IAM")
157 ) {
158 return { action: "replace" } as const;
159 }
160 }),
161 read: Effect.fn(function* ({ olds, output }) {
162 const portfolioId = output?.portfolioId ?? olds?.portfolioId;
163 const principalArn = output?.principalArn ?? olds?.principalArn;
164 if (portfolioId === undefined || principalArn === undefined) {
165 return undefined;
166 }
167 return (yield* isAssociated(portfolioId, principalArn))
168 ? {
169 portfolioId,
170 principalArn,
171 principalType: output?.principalType ?? olds?.principalType ?? "IAM",
172 }
173 : undefined;
174 }),
175 // Existence-only: observe → if missing, associate. No sync step.
176 reconcile: Effect.fn(function* ({ news, session }) {
177 const principalType = news.principalType ?? "IAM";
178 if (!(yield* isAssociated(news.portfolioId, news.principalArn))) {
179 yield* servicecatalog.associatePrincipalWithPortfolio({
180 PortfolioId: news.portfolioId,
181 PrincipalARN: news.principalArn,
182 PrincipalType: principalType,
183 });
184 // The principal list is eventually consistent — wait (bounded)
185 // until the association is visible so a subsequent read converges.
186 yield* awaitVisible(isAssociated(news.portfolioId, news.principalArn));
187 }
188 yield* session.note(`${news.portfolioId}/${news.principalArn}`);
189 return {
190 portfolioId: news.portfolioId,
191 principalArn: news.principalArn,
192 principalType,
193 };
194 }),
195 delete: Effect.fn(function* ({ output }) {
196 // Always disassociate: the association list is eventually
197 // consistent, so a fresh association can be missing from it, and
198 // skipping the call would leave the portfolio undeletable.
199 yield* servicecatalog
200 .disassociatePrincipalFromPortfolio({
201 PortfolioId: output.portfolioId,
202 PrincipalARN: output.principalArn,
203 PrincipalType: output.principalType,
204 })
205 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
206 }),
207 });
208 }),
209 );