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

main
ts 290 lines 10.8 KB
Raw
1 import * as lf from "@distilled.cloud/aws/lakeformation";
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 {
9 observePrincipalPermissions,
10 retryWhileConcurrentModification,
11 retryWhileInvalidPrincipal,
12 } from "./internal.ts";
13 import { type LakeFormationResourceSpec, toWireResource } from "./ResourceSpec.ts";
14
15 export interface PermissionsProps {
16 /**
17 * The principal receiving the permissions — an IAM user/role ARN, an
18 * external account id, or the `IAM_ALLOWED_PRINCIPALS` group. Changing it
19 * replaces the grant.
20 */
21 principal: string;
22 /**
23 * The Lake Formation resource the permissions apply to (exactly one
24 * variant set). Changing it replaces the grant.
25 */
26 resource: LakeFormationResourceSpec;
27 /**
28 * The permissions to grant (e.g. `["DESCRIBE"]`, `["SELECT"]`, `["ALL"]`).
29 */
30 permissions: lf.Permission[];
31 /**
32 * The subset of permissions the principal may also grant to others.
33 */
34 permissionsWithGrantOption?: lf.Permission[];
35 /**
36 * The catalog id (AWS account id). Changing it replaces the grant.
37 * @default the caller's account
38 */
39 catalogId?: string;
40 }
41
42 export interface Permissions extends Resource<
43 "AWS.LakeFormation.Permissions",
44 PermissionsProps,
45 {
46 principal: string;
47 resource: lf.Resource;
48 permissions: lf.Permission[];
49 permissionsWithGrantOption: lf.Permission[];
50 catalogId: string | undefined;
51 },
52 {},
53 Providers
54 > {}
55
56 /**
57 * A Lake Formation permission grant — gives a principal permissions on a
58 * Data Catalog resource (database, table, data location, LF-tag, or LF-tag
59 * policy expression). The resource owns the full permission set for its
60 * principal/resource pair: permissions removed from the props are revoked.
61 *
62 * The caller must be a Lake Formation data lake administrator (or hold the
63 * grant option on the resource) — see
64 * {@link DataLakeSettings | AWS.LakeFormation.DataLakeSettings}.
65 *
66 * ### Granting Permissions
67 * **Example:** Grant Database Permissions to a Role
68 * ```typescript
69 * import * as AWS from "@alchemy.run/aws";
70 *
71 * const database = yield* AWS.Glue.Database("Analytics", {});
72 * const grant = yield* AWS.LakeFormation.Permissions("AnalystDbAccess", {
73 * principal: analystRole.roleArn,
74 * resource: { database: { name: database.databaseName } },
75 * permissions: ["DESCRIBE", "CREATE_TABLE"],
76 * });
77 * ```
78 *
79 * **Example:** Grant Table Select with Grant Option
80 * ```typescript
81 * const grant = yield* AWS.LakeFormation.Permissions("AnalystTableAccess", {
82 * principal: analystRole.roleArn,
83 * resource: {
84 * table: { databaseName: database.databaseName, tableWildcard: true },
85 * },
86 * permissions: ["SELECT", "DESCRIBE"],
87 * permissionsWithGrantOption: ["SELECT"],
88 * });
89 * ```
90 *
91 * **Example:** Grant Data Location Access
92 * ```typescript
93 * const grant = yield* AWS.LakeFormation.Permissions("EtlLocationAccess", {
94 * principal: etlRole.roleArn,
95 * resource: { dataLocation: { resourceArn: location.resourceArn } },
96 * permissions: ["DATA_LOCATION_ACCESS"],
97 * });
98 * ```
99 *
100 * @resource
101 */
102 export const Permissions = Resource<Permissions>("AWS.LakeFormation.Permissions");
103
104 const dedupeSort = (values: lf.Permission[]): lf.Permission[] => [...new Set(values)].sort();
105
106 export const PermissionsProvider = () =>
107 Provider.effect(
108 Permissions,
109 Effect.gen(function* () {
110 return Permissions.Provider.of({
111 stables: ["principal", "resource", "catalogId"],
112
113 list: () =>
114 Effect.gen(function* () {
115 const pages = yield* lf.listPermissions.pages({}).pipe(Stream.runCollect);
116 return Array.from(pages)
117 .flatMap((page) => page.PrincipalResourcePermissions ?? [])
118 .filter(
119 (e) =>
120 e.Principal?.DataLakePrincipalIdentifier !== undefined &&
121 e.Resource !== undefined,
122 )
123 .map((e) => ({
124 principal: e.Principal!.DataLakePrincipalIdentifier!,
125 resource: e.Resource!,
126 permissions: dedupeSort([...(e.Permissions ?? [])]),
127 permissionsWithGrantOption: dedupeSort([...(e.PermissionsWithGrantOption ?? [])]),
128 catalogId: undefined,
129 }));
130 }),
131
132 read: Effect.fn(function* ({ olds, output }) {
133 const principal = output?.principal ?? olds?.principal;
134 const resource =
135 output?.resource ?? (olds !== undefined ? toWireResource(olds.resource) : undefined);
136 if (principal === undefined || resource === undefined) {
137 return undefined;
138 }
139 const catalogId = output?.catalogId ?? olds?.catalogId;
140 const current = yield* observePrincipalPermissions(principal, resource, catalogId).pipe(
141 // a deleted IAM principal surfaces as "Invalid principal" — the
142 // grant is effectively gone.
143 Effect.catchTag("InvalidLakeFormationPrincipal", () =>
144 Effect.succeed({
145 permissions: [],
146 permissionsWithGrantOption: [],
147 }),
148 ),
149 );
150 if (current.permissions.length === 0) return undefined;
151 return {
152 principal,
153 resource,
154 permissions: current.permissions,
155 permissionsWithGrantOption: current.permissionsWithGrantOption,
156 catalogId,
157 };
158 }),
159
160 diff: Effect.fn(function* ({ news, olds }) {
161 if (!isResolved(news)) return undefined;
162 if (news.principal !== olds.principal) {
163 return { action: "replace" } as const;
164 }
165 if (
166 JSON.stringify(toWireResource(news.resource)) !==
167 JSON.stringify(toWireResource(olds.resource))
168 ) {
169 return { action: "replace" } as const;
170 }
171 if ((news.catalogId ?? undefined) !== (olds.catalogId ?? undefined)) {
172 return { action: "replace" } as const;
173 }
174 // permissions / permissionsWithGrantOption → update
175 }),
176
177 reconcile: Effect.fn(function* ({ news, session }) {
178 const resource = toWireResource(news.resource);
179 const principal: lf.DataLakePrincipal = {
180 DataLakePrincipalIdentifier: news.principal,
181 };
182 const desired = dedupeSort(news.permissions);
183 const desiredGrant = dedupeSort(news.permissionsWithGrantOption ?? []);
184
185 // 1. OBSERVE — retry through IAM propagation of a fresh principal.
186 let current = yield* observePrincipalPermissions(
187 news.principal,
188 resource,
189 news.catalogId,
190 ).pipe(retryWhileInvalidPrincipal);
191
192 // 2. SYNC — revoke stale grants, then grant the desired set
193 // (GrantPermissions is an idempotent upsert).
194 const stale = current.permissions.filter((p) => !desired.includes(p));
195 if (stale.length > 0) {
196 yield* lf
197 .revokePermissions({
198 CatalogId: news.catalogId,
199 Principal: principal,
200 Resource: resource,
201 Permissions: stale,
202 PermissionsWithGrantOption: stale.some((p) =>
203 current.permissionsWithGrantOption.includes(p),
204 )
205 ? stale.filter((p) => current.permissionsWithGrantOption.includes(p))
206 : undefined,
207 })
208 .pipe(retryWhileConcurrentModification);
209 }
210
211 // grant-option-only removals (permission kept, option dropped):
212 // revoke the pair, the grant below restores the plain permission.
213 const staleOptionOnly = current.permissionsWithGrantOption.filter(
214 (p) => !desiredGrant.includes(p) && desired.includes(p),
215 );
216 if (staleOptionOnly.length > 0) {
217 yield* lf
218 .revokePermissions({
219 CatalogId: news.catalogId,
220 Principal: principal,
221 Resource: resource,
222 Permissions: staleOptionOnly,
223 PermissionsWithGrantOption: staleOptionOnly,
224 })
225 .pipe(retryWhileConcurrentModification);
226 }
227
228 const missing = desired.filter((p) => !current.permissions.includes(p));
229 const missingGrant = desiredGrant.filter(
230 (p) => !current.permissionsWithGrantOption.includes(p),
231 );
232 if (missing.length > 0 || missingGrant.length > 0 || staleOptionOnly.length > 0) {
233 yield* lf
234 .grantPermissions({
235 CatalogId: news.catalogId,
236 Principal: principal,
237 Resource: resource,
238 Permissions: desired,
239 PermissionsWithGrantOption: desiredGrant.length > 0 ? desiredGrant : undefined,
240 })
241 .pipe(retryWhileInvalidPrincipal, retryWhileConcurrentModification);
242 }
243
244 // 3. RETURN fresh state
245 current = yield* observePrincipalPermissions(news.principal, resource, news.catalogId);
246 yield* session.note(`${news.principal} ← [${current.permissions.join(", ")}]`);
247 return {
248 principal: news.principal,
249 resource,
250 permissions: current.permissions,
251 permissionsWithGrantOption: current.permissionsWithGrantOption,
252 catalogId: news.catalogId,
253 };
254 }),
255
256 delete: Effect.fn(function* ({ output }) {
257 // Observe first so we only revoke what actually exists (revoking a
258 // non-existent grant is an InvalidInputException).
259 const current = yield* observePrincipalPermissions(
260 output.principal,
261 output.resource,
262 output.catalogId,
263 ).pipe(
264 Effect.catchTag("InvalidLakeFormationPrincipal", () =>
265 Effect.succeed({
266 permissions: [] as lf.Permission[],
267 permissionsWithGrantOption: [] as lf.Permission[],
268 }),
269 ),
270 );
271 if (current.permissions.length === 0) return;
272 yield* lf
273 .revokePermissions({
274 CatalogId: output.catalogId,
275 Principal: { DataLakePrincipalIdentifier: output.principal },
276 Resource: output.resource,
277 Permissions: current.permissions,
278 PermissionsWithGrantOption:
279 current.permissionsWithGrantOption.length > 0
280 ? current.permissionsWithGrantOption
281 : undefined,
282 })
283 .pipe(
284 retryWhileConcurrentModification,
285 Effect.catchTag("EntityNotFoundException", () => Effect.void),
286 );
287 }),
288 });
289 }),
290 );