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

main
ts 334 lines 11 KB
Raw
1 import * as acm from "@distilled.cloud/gcp/accesscontextmanager_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { createInternalLabels } from "../Labels.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 collectPages,
12 encodeOwnership,
13 encodeOwnershipLine,
14 jsonEqual,
15 listOwnedPolicies,
16 MAX_DESCRIPTION_LENGTH,
17 MAX_TITLE_LENGTH,
18 ownedByAlchemy,
19 parseName,
20 parseOwnership,
21 policyNameOf,
22 replaceOnIdentity,
23 resourceNameOf,
24 toAcmId,
25 waitForOperation,
26 waitUntilExists,
27 waitUntilGone,
28 } from "./internal.ts";
29
30 export type AccessLevelOsConstraint = acm.OsConstraint;
31 export type AccessLevelDevicePolicy = acm.DevicePolicy;
32 export type AccessLevelVpcNetworkSource = acm.VpcNetworkSource;
33 export type AccessLevelCondition = acm.Condition;
34 export type AccessLevelBasic = acm.BasicLevel;
35 export type AccessLevelCustom = acm.CustomLevel;
36
37 export type AccessPoliciesAccessLevelProps = {
38 /**
39 * Parent access policy (`accessPolicies/{policy}` or the policy id).
40 * Immutable — changing it replaces the access level.
41 */
42 policy: string;
43 /**
44 * Access level id (the `{access_level}` segment). If omitted, a unique
45 * name is generated from the stack, stage, and logical id. Must begin
46 * with a letter, then alphanumeric or `_`, max 50 characters.
47 * Immutable — changing it replaces the access level.
48 */
49 accessLevelId?: string;
50 /**
51 * Human-readable title. Must be unique within the policy.
52 */
53 title?: string;
54 /**
55 * Description of the access level. Access levels have no labels, so
56 * Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
57 * from attributes.
58 */
59 description?: string;
60 /**
61 * Basic level composed of conditions. Mutually exclusive with
62 * `custom`.
63 */
64 basic?: AccessLevelBasic;
65 /**
66 * Custom CEL level. Mutually exclusive with `basic`.
67 */
68 custom?: AccessLevelCustom;
69 };
70
71 export type AccessPoliciesAccessLevel = Resource<
72 "GCP.AccessContextManager.AccessPoliciesAccessLevel",
73 AccessPoliciesAccessLevelProps,
74 {
75 /** Resource name `accessPolicies/{policy}/accessLevels/{accessLevel}`. */
76 name: string;
77 /** Access level id (last path segment). */
78 accessLevelId: string;
79 /** Parent policy name `accessPolicies/{policy}`. */
80 policy: string;
81 /** User title with the Alchemy ownership prefix stripped. */
82 title: string | undefined;
83 /** User description with the Alchemy ownership prefix stripped. */
84 description: string | undefined;
85 /** Basic level, if set. */
86 basic: AccessLevelBasic | undefined;
87 /** Custom CEL level, if set. */
88 custom: AccessLevelCustom | undefined;
89 },
90 never,
91 Providers
92 >;
93
94 /**
95 * An Access Context Manager access level.
96 *
97 * Access levels label requests to Google Cloud services with a set of
98 * requirements (IP ranges, device policy, members, regions, or a custom
99 * CEL expression). They live under an {@link AccessPolicy}.
100 *
101 * Access levels have no labels. Alchemy stamps ownership into
102 * `description` so `list` / `pnpm nuke:gcp` can find them. `policy` and
103 * `accessLevelId` are immutable — changing them replaces the level.
104 * Title, description, `basic`, and `custom` update in place.
105 *
106 * ### Creating an Access Level
107 * **Example:** Basic level that allows the US
108 * ```typescript
109 * const policy = yield* GCP.AccessContextManager.AccessPolicy("Corp", {
110 * scopes: ["projects/123456789"],
111 * });
112 * const level = yield* GCP.AccessContextManager.AccessPoliciesAccessLevel(
113 * "CorpUsers",
114 * {
115 * policy: policy.name,
116 * title: "corp users",
117 * basic: { conditions: [{ regions: ["US"] }] },
118 * },
119 * );
120 * ```
121 *
122 * **Example:** Custom CEL level
123 * ```typescript
124 * const level = yield* GCP.AccessContextManager.AccessPoliciesAccessLevel(
125 * "Employees",
126 * {
127 * policy: policy.name,
128 * title: "employees",
129 * custom: {
130 * expr: { expression: "request.time.getHours() >= 9" },
131 * },
132 * },
133 * );
134 * ```
135 *
136 * ### Updating an Access Level
137 * **Example:** Add an IP condition
138 * ```typescript
139 * const level = yield* GCP.AccessContextManager.AccessPoliciesAccessLevel(
140 * "CorpUsers",
141 * {
142 * policy: policy.name,
143 * title: "corp users",
144 * basic: {
145 * conditions: [{ ipSubnetworks: ["203.0.113.0/24"] }],
146 * },
147 * },
148 * );
149 * ```
150 *
151 * @resource
152 * @category AccessContextManager
153 */
154 export const AccessPoliciesAccessLevel = Resource<AccessPoliciesAccessLevel>(
155 "GCP.AccessContextManager.AccessPoliciesAccessLevel",
156 );
157
158 export class AccessPoliciesAccessLevelNotResolved extends Data.TaggedError(
159 "GCP.AccessContextManager.AccessPoliciesAccessLevelNotResolved",
160 )<{
161 resourceName: string;
162 }> {}
163
164 const toAttrs = (level: acm.AccessLevel): AccessPoliciesAccessLevel["Attributes"] => {
165 const name = level.name ?? "";
166 const parsed = parseName(name, "accessLevels");
167 const title = parseOwnership(level.title);
168 const description = parseOwnership(level.description);
169 return {
170 name,
171 accessLevelId: parsed.id,
172 policy: parsed.parent,
173 title: title.text,
174 description: description.text,
175 basic: level.basic,
176 custom: level.custom,
177 };
178 };
179
180 const getByName = (name: string) =>
181 acm
182 .getAccessPoliciesAccessLevels({ name })
183 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
184
185 const listLevels = (policy: string) =>
186 collectPages(
187 acm.listAccessPoliciesAccessLevels.pages({
188 parent: policyNameOf(policy),
189 pageSize: 100,
190 }),
191 (page) => page.accessLevels,
192 ).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as acm.AccessLevel[])));
193
194 export const AccessPoliciesAccessLevelProvider = () =>
195 Provider.succeed(AccessPoliciesAccessLevel, {
196 stables: ["name", "accessLevelId", "policy"],
197
198 diff: Effect.fn(function* ({ news, olds, output }) {
199 if (!isResolved(news)) return undefined;
200 const previousId = olds?.accessLevelId ?? output?.accessLevelId;
201 const idChanged =
202 previousId !== undefined &&
203 news.accessLevelId !== undefined &&
204 news.accessLevelId !== previousId;
205 const previousPolicy = olds?.policy ?? output?.policy;
206 const policyChanged =
207 previousPolicy !== undefined && policyNameOf(news.policy) !== policyNameOf(previousPolicy);
208 return replaceOnIdentity(idChanged || policyChanged);
209 }),
210
211 read: Effect.fn(function* ({ id, olds, output }) {
212 const accessLevelId = yield* toAcmId(id, olds?.accessLevelId, output?.accessLevelId);
213 const policy = olds?.policy ?? output?.policy;
214 if (policy === undefined) return undefined;
215 const name = output?.name ?? resourceNameOf(policy, "accessLevels", accessLevelId);
216 const existing = yield* getByName(name);
217 if (existing === undefined) return undefined;
218 const attrs = toAttrs(existing);
219 return (yield* ownedByAlchemy(id, existing.description ?? existing.title))
220 ? attrs
221 : Unowned(attrs);
222 }),
223
224 list: () =>
225 Effect.gen(function* () {
226 const policies = yield* listOwnedPolicies();
227 const levels = yield* Effect.forEach(
228 policies,
229 (policy) =>
230 policy.name ? listLevels(policy.name) : Effect.succeed([] as acm.AccessLevel[]),
231 { concurrency: 4 },
232 );
233 return levels
234 .flat()
235 .filter((level) => parseOwnership(level.description ?? level.title).labels["alchemy-id"])
236 .map(toAttrs);
237 }),
238
239 reconcile: Effect.fn(function* ({ id, news, output }) {
240 const policy = policyNameOf(news.policy);
241 const accessLevelId = yield* toAcmId(id, news.accessLevelId, output?.accessLevelId);
242 const name = resourceNameOf(policy, "accessLevels", accessLevelId);
243 const ownership = yield* createInternalLabels(id);
244 const desiredTitle = encodeOwnershipLine(
245 ownership,
246 news.title ?? accessLevelId,
247 MAX_TITLE_LENGTH,
248 );
249 const desiredDescription = encodeOwnership(
250 ownership,
251 news.description,
252 MAX_DESCRIPTION_LENGTH,
253 );
254
255 let current = yield* getByName(output?.name ?? name);
256
257 if (current === undefined) {
258 const created = yield* acm
259 .createAccessPoliciesAccessLevels({
260 parent: policy,
261 body: {
262 name,
263 title: desiredTitle,
264 description: desiredDescription,
265 basic: news.basic,
266 custom: news.custom,
267 },
268 })
269 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
270 if (created !== undefined) {
271 // ALREADY_EXISTS (6): a concurrent create won the race.
272 yield* waitForOperation(created).pipe(
273 Effect.catchTag("GCP.OperationFailed", (error) =>
274 error.code === 6 ? Effect.void : Effect.fail(error),
275 ),
276 );
277 }
278 current = yield* waitUntilExists(getByName(name), name);
279 }
280
281 if (current === undefined) {
282 return yield* new AccessPoliciesAccessLevelNotResolved({ resourceName: name });
283 }
284
285 const titleChanged = (current.title ?? "") !== desiredTitle;
286 const descriptionChanged = (current.description ?? "") !== desiredDescription;
287 const basicChanged = !jsonEqual(current.basic, news.basic);
288 const customChanged = !jsonEqual(current.custom, news.custom);
289
290 const updateMask = [
291 titleChanged ? "title" : undefined,
292 descriptionChanged ? "description" : undefined,
293 news.basic !== undefined && basicChanged ? "basic" : undefined,
294 news.custom !== undefined && customChanged ? "custom" : undefined,
295 ].filter((field): field is string => field !== undefined);
296
297 if (updateMask.length > 0) {
298 const operation = yield* acm.patchAccessPoliciesAccessLevels({
299 name: current.name ?? name,
300 updateMask: updateMask.join(","),
301 body: {
302 name: current.name ?? name,
303 title: desiredTitle,
304 description: desiredDescription,
305 basic: news.basic,
306 custom: news.custom,
307 },
308 });
309 yield* waitForOperation(operation);
310 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
311 }
312
313 if (current === undefined) {
314 return yield* new AccessPoliciesAccessLevelNotResolved({ resourceName: name });
315 }
316
317 return toAttrs(current);
318 }),
319
320 delete: Effect.fn(function* ({ output }) {
321 const operation = yield* acm
322 .deleteAccessPoliciesAccessLevels({ name: output.name })
323 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
324 if (operation !== undefined) {
325 // NOT_FOUND (5): already gone.
326 yield* waitForOperation(operation).pipe(
327 Effect.catchTag("GCP.OperationFailed", (error) =>
328 error.code === 5 ? Effect.void : Effect.fail(error),
329 ),
330 );
331 }
332 yield* waitUntilGone(getByName(output.name), output.name);
333 }),
334 });