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

main
ts 250 lines 7.97 KB
Raw
1 import * as storage from "@distilled.cloud/gcp/storage_v1";
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 * as Schedule from "effect/Schedule";
8 import { DeleteNotConfirmed } from "../Errors.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 isUserManagedAclEntity,
12 listAlchemyBuckets,
13 normalizeEntity,
14 normalizeRole,
15 } from "./internal.ts";
16
17 export type BucketAccessControlProps = {
18 /**
19 * Name of the bucket this ACL entry is attached to. Immutable —
20 * changing it replaces the entry.
21 */
22 bucketName: string;
23 /**
24 * Principal granted the role. Forms include `user-{email}`,
25 * `group-{email}`, `domain-{domain}`, `allUsers`, and
26 * `allAuthenticatedUsers`. Immutable — changing it replaces the entry.
27 */
28 entity: string;
29 /**
30 * Access permission for the entity (`OWNER`, `WRITER`, or `READER`).
31 */
32 role: string;
33 };
34
35 export type BucketAccessControl = Resource<
36 "GCP.Storage.BucketAccessControl",
37 BucketAccessControlProps,
38 {
39 /** Parent bucket name. */
40 bucketName: string;
41 /** Principal granted the role. */
42 entity: string;
43 /** Access permission (`OWNER`, `WRITER`, or `READER`). */
44 role: string;
45 /** Server-assigned ACL id. */
46 id: string | undefined;
47 /** Domain associated with the entity, if any. */
48 domain: string | undefined;
49 /** Email associated with the entity, if any. */
50 email: string | undefined;
51 /** Numeric entity id, if any. */
52 entityId: string | undefined;
53 /** HTTP etag. */
54 etag: string | undefined;
55 /** GCS self-link. */
56 selfLink: string | undefined;
57 },
58 never,
59 Providers
60 >;
61
62 /**
63 * A Cloud Storage bucket ACL entry.
64 *
65 * Fine-grained ACLs are identity `(bucket, entity)`. Role is mutable;
66 * changing `bucketName` or `entity` replaces the entry. Entries have no
67 * labels field, so `list` / `pnpm nuke:gcp` discover them by enumerating
68 * alchemy-labeled buckets and skipping project-team defaults.
69 *
70 * Uniform bucket-level access buckets do not support bucket ACLs.
71 *
72 * ### Creating a Bucket ACL
73 * **Example:** Grant a service account writer access
74 * ```typescript
75 * const bucket = yield* GCP.Storage.Bucket("assets", {
76 * forceDestroy: true,
77 * });
78 * const acl = yield* GCP.Storage.BucketAccessControl("writer", {
79 * bucketName: bucket.bucketName,
80 * entity: "user-app@project.iam.gserviceaccount.com",
81 * role: "WRITER",
82 * });
83 * ```
84 *
85 * **Example:** Update the role
86 * ```typescript
87 * const acl = yield* GCP.Storage.BucketAccessControl("writer", {
88 * bucketName: bucket.bucketName,
89 * entity: "user-app@project.iam.gserviceaccount.com",
90 * role: "READER",
91 * });
92 * ```
93 *
94 * @resource
95 * @category Storage
96 */
97 export const BucketAccessControl = Resource<BucketAccessControl>("GCP.Storage.BucketAccessControl");
98
99 export class BucketAccessControlNotResolved extends Data.TaggedError(
100 "GCP.Storage.BucketAccessControlNotResolved",
101 )<{
102 bucketName: string;
103 entity: string;
104 }> {}
105
106 const toAttrs = (acl: storage.BucketAccessControl, bucketName: string) => ({
107 bucketName: acl.bucket ?? bucketName,
108 entity: acl.entity ?? "",
109 role: acl.role ?? "",
110 id: acl.id,
111 domain: acl.domain,
112 email: acl.email,
113 entityId: acl.entityId,
114 etag: acl.etag,
115 selfLink: acl.selfLink,
116 });
117
118 const getByEntity = (bucketName: string, entity: string) =>
119 storage
120 .getBucketAccessControls({ bucket: bucketName, entity })
121 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
122
123 const listOnBucket = (bucketName: string) =>
124 storage.listBucketAccessControls({ bucket: bucketName }).pipe(
125 Effect.map((page) => page.items ?? []),
126 Effect.catchTag("NotFound", () => Effect.succeed([] as storage.BucketAccessControl[])),
127 );
128
129 const waitUntilGone = (bucketName: string, entity: string) =>
130 getByEntity(bucketName, entity).pipe(
131 Effect.map((existing) => (existing === undefined ? ("gone" as const) : ("found" as const))),
132 Effect.repeat({
133 schedule: Schedule.spaced("1 second"),
134 until: (status) => status === "gone",
135 times: 30,
136 }),
137 Effect.flatMap((status): Effect.Effect<void, DeleteNotConfirmed> =>
138 status === "gone"
139 ? Effect.void
140 : Effect.fail(new DeleteNotConfirmed({ resource: `${bucketName}/acl/${entity}` })),
141 ),
142 );
143
144 export const BucketAccessControlProvider = () =>
145 Provider.succeed(BucketAccessControl, {
146 stables: ["bucketName", "entity", "id", "selfLink"],
147
148 diff: Effect.fn(function* ({ news, olds, output }) {
149 if (!isResolved(news)) return undefined;
150 const previousBucket = olds?.bucketName ?? output?.bucketName;
151 const previousEntity = olds?.entity ?? output?.entity;
152 if (previousBucket !== undefined && news.bucketName !== previousBucket) {
153 return { action: "replace" as const, deleteFirst: false };
154 }
155 if (
156 previousEntity !== undefined &&
157 normalizeEntity(news.entity) !== normalizeEntity(previousEntity)
158 ) {
159 return { action: "replace" as const, deleteFirst: false };
160 }
161 return undefined;
162 }),
163
164 read: Effect.fn(function* ({ olds, output }) {
165 const bucketName = olds?.bucketName ?? output?.bucketName;
166 const entity = olds?.entity ?? output?.entity;
167 if (!bucketName || !entity) return undefined;
168 const existing = yield* getByEntity(bucketName, entity);
169 if (existing === undefined) return undefined;
170 return toAttrs(existing, bucketName);
171 }),
172
173 list: () =>
174 Effect.gen(function* () {
175 const buckets = yield* listAlchemyBuckets();
176 const pages = yield* Effect.forEach(
177 buckets,
178 (bucket) => {
179 const bucketName = bucket.name;
180 // Legacy ACL APIs reject uniform bucket-level access buckets.
181 if (
182 !bucketName ||
183 bucket.iamConfiguration?.uniformBucketLevelAccess?.enabled === true
184 ) {
185 return Effect.succeed([] as Array<BucketAccessControl["Attributes"]>);
186 }
187 return listOnBucket(bucketName).pipe(
188 Effect.map((items) =>
189 items
190 .filter((item) => isUserManagedAclEntity(item.entity))
191 .map((item) => toAttrs(item, bucketName)),
192 ),
193 );
194 },
195 { concurrency: 8 },
196 );
197 return pages.flat();
198 }),
199
200 reconcile: Effect.fn(function* ({ news, output }) {
201 const bucketName = news.bucketName;
202 const entity = normalizeEntity(news.entity);
203 const role = normalizeRole(news.role);
204
205 let current =
206 output?.entity !== undefined
207 ? yield* getByEntity(output.bucketName ?? bucketName, normalizeEntity(output.entity))
208 : undefined;
209 if (current === undefined) {
210 current = yield* getByEntity(bucketName, entity);
211 }
212
213 if (current === undefined) {
214 const created = yield* storage
215 .insertBucketAccessControls({
216 bucket: bucketName,
217 body: { entity, role },
218 })
219 .pipe(Effect.catchTag("Conflict", () => getByEntity(bucketName, entity)));
220 current = created ?? undefined;
221 }
222
223 if (current === undefined || !current.entity) {
224 return yield* new BucketAccessControlNotResolved({
225 bucketName,
226 entity,
227 });
228 }
229
230 if (normalizeRole(current.role ?? "") !== role) {
231 current = yield* storage.patchBucketAccessControls({
232 bucket: bucketName,
233 entity,
234 body: { entity, role },
235 });
236 }
237
238 return toAttrs(current, bucketName);
239 }),
240
241 delete: Effect.fn(function* ({ output }) {
242 const bucketName = output.bucketName;
243 const entity = output.entity;
244 if (!bucketName || !entity) return;
245 yield* storage
246 .deleteBucketAccessControls({ bucket: bucketName, entity })
247 .pipe(Effect.catchTag("NotFound", () => Effect.void));
248 yield* waitUntilGone(bucketName, entity);
249 }),
250 });