The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as networksecurity from "@distilled.cloud/gcp/networksecurity_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 { tagRecord } from "alchemy/Tags"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Schedule from "effect/Schedule"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import { GcpEnvironment } from "../Environment.ts"; |
| 11 | import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | import { |
| 14 | parseResourceName, |
| 15 | projectParent, |
| 16 | ResourceNotResolved, |
| 17 | sameJson, |
| 18 | toPhysicalId, |
| 19 | userLabels, |
| 20 | waitForOperation, |
| 21 | waitUntilExists, |
| 22 | waitUntilGone, |
| 23 | } from "./operations.ts"; |
| 24 | |
| 25 | const DEFAULT_ACTION = "ALLOW" satisfies networksecurity.AuthzPolicyActionEnum; |
| 26 | const DEFAULT_PROFILE = "REQUEST_AUTHZ" satisfies networksecurity.AuthzPolicyPolicyProfileEnum; |
| 27 | |
| 28 | export type AuthzPolicyAction = networksecurity.AuthzPolicyActionEnum | (string & {}); |
| 29 | |
| 30 | export type AuthzPolicyProfile = networksecurity.AuthzPolicyPolicyProfileEnum | (string & {}); |
| 31 | |
| 32 | export type AuthzPolicyLoadBalancingScheme = |
| 33 | | networksecurity.AuthzPolicyTargetLoadBalancingSchemeEnum |
| 34 | | (string & {}); |
| 35 | |
| 36 | export type AuthzPolicyStringMatch = { |
| 37 | exact?: string; |
| 38 | prefix?: string; |
| 39 | suffix?: string; |
| 40 | contains?: string; |
| 41 | ignoreCase?: boolean; |
| 42 | }; |
| 43 | |
| 44 | export type AuthzPolicyHeaderMatch = { |
| 45 | name?: string; |
| 46 | value?: AuthzPolicyStringMatch; |
| 47 | }; |
| 48 | |
| 49 | export type AuthzPolicyRequestOperation = { |
| 50 | methods?: string[]; |
| 51 | hosts?: AuthzPolicyStringMatch[]; |
| 52 | paths?: AuthzPolicyStringMatch[]; |
| 53 | snis?: AuthzPolicyStringMatch[]; |
| 54 | headerSet?: { headers?: AuthzPolicyHeaderMatch[] }; |
| 55 | mcp?: networksecurity.AuthzPolicyAuthzRuleToRequestOperationMCP; |
| 56 | }; |
| 57 | |
| 58 | export type AuthzPolicyRuleTo = { |
| 59 | operations?: AuthzPolicyRequestOperation[]; |
| 60 | notOperations?: AuthzPolicyRequestOperation[]; |
| 61 | }; |
| 62 | |
| 63 | export type AuthzPolicyPrincipal = { |
| 64 | principal?: AuthzPolicyStringMatch; |
| 65 | principalSelector?: string; |
| 66 | }; |
| 67 | |
| 68 | export type AuthzPolicyIpBlock = { |
| 69 | prefix?: string; |
| 70 | length?: number; |
| 71 | }; |
| 72 | |
| 73 | export type AuthzPolicyRequestResource = { |
| 74 | tagValueIdSet?: { ids?: string[] }; |
| 75 | iamServiceAccount?: AuthzPolicyStringMatch; |
| 76 | }; |
| 77 | |
| 78 | export type AuthzPolicyRequestSource = { |
| 79 | principals?: AuthzPolicyPrincipal[]; |
| 80 | ipBlocks?: AuthzPolicyIpBlock[]; |
| 81 | resources?: AuthzPolicyRequestResource[]; |
| 82 | }; |
| 83 | |
| 84 | export type AuthzPolicyRuleFrom = { |
| 85 | sources?: AuthzPolicyRequestSource[]; |
| 86 | notSources?: AuthzPolicyRequestSource[]; |
| 87 | }; |
| 88 | |
| 89 | export type AuthzPolicyRule = { |
| 90 | from?: AuthzPolicyRuleFrom; |
| 91 | to?: AuthzPolicyRuleTo; |
| 92 | when?: string; |
| 93 | }; |
| 94 | |
| 95 | export type AuthzPolicyTarget = { |
| 96 | /** |
| 97 | * Forwarding rules, Secure Web Proxy gateways, or Agent Gateways. |
| 98 | */ |
| 99 | resources?: string[]; |
| 100 | /** |
| 101 | * Load balancing scheme shared by every targeted forwarding rule. |
| 102 | */ |
| 103 | loadBalancingScheme?: AuthzPolicyLoadBalancingScheme; |
| 104 | }; |
| 105 | |
| 106 | export type AuthzPolicyCustomProvider = { |
| 107 | /** Empty object enables Cloud IAP. Mutually exclusive with `authzExtension`. */ |
| 108 | cloudIap?: Record<string, never>; |
| 109 | /** Service-extension resources (limited to 1). */ |
| 110 | authzExtension?: { resources?: string[] }; |
| 111 | }; |
| 112 | |
| 113 | export type AuthzPolicyProps = { |
| 114 | /** |
| 115 | * Authz policy id. If omitted, a unique RFC1035 name is generated from |
| 116 | * the stack, stage, and logical id. Immutable — changing it replaces |
| 117 | * the policy. |
| 118 | */ |
| 119 | authzPolicyId?: string; |
| 120 | /** |
| 121 | * Location (`us-central1`, `global`, …). Must match the targeted |
| 122 | * forwarding rules. Immutable — changing it replaces the policy. |
| 123 | * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`) |
| 124 | */ |
| 125 | location?: string; |
| 126 | /** |
| 127 | * Action (`ALLOW`, `DENY`, `CUSTOM`). `CUSTOM` requires |
| 128 | * `customProvider`. |
| 129 | * @default "ALLOW" |
| 130 | */ |
| 131 | action?: AuthzPolicyAction; |
| 132 | /** |
| 133 | * Resources this policy applies to. Required. |
| 134 | */ |
| 135 | target: AuthzPolicyTarget; |
| 136 | /** |
| 137 | * Authorization HTTP rules. At least one rule is required for ALLOW or |
| 138 | * DENY unless `networkRules` is set. Limited to 5. |
| 139 | */ |
| 140 | httpRules?: AuthzPolicyRule[]; |
| 141 | /** |
| 142 | * Authorization network rules. Mutually exclusive with `httpRules`. |
| 143 | * Limited to 5. |
| 144 | */ |
| 145 | networkRules?: AuthzPolicyRule[]; |
| 146 | /** |
| 147 | * Authorization profile. Immutable — changing it replaces the policy. |
| 148 | * @default "REQUEST_AUTHZ" |
| 149 | */ |
| 150 | policyProfile?: AuthzPolicyProfile; |
| 151 | /** |
| 152 | * Custom authorization provider. Required when `action` is `CUSTOM`. |
| 153 | */ |
| 154 | customProvider?: AuthzPolicyCustomProvider; |
| 155 | /** |
| 156 | * Human-readable description. |
| 157 | */ |
| 158 | description?: string; |
| 159 | /** |
| 160 | * User labels. Alchemy ownership labels are merged in automatically. |
| 161 | */ |
| 162 | labels?: Record<string, string>; |
| 163 | }; |
| 164 | |
| 165 | export type AuthzPolicy = Resource< |
| 166 | "GCP.NetworkSecurity.AuthzPolicy", |
| 167 | AuthzPolicyProps, |
| 168 | { |
| 169 | /** Full resource name `projects/{project}/locations/{location}/authzPolicies/{authzPolicy}`. */ |
| 170 | name: string; |
| 171 | /** Authz policy id (last path segment). */ |
| 172 | authzPolicyId: string; |
| 173 | /** Project id. */ |
| 174 | project: string; |
| 175 | /** Location id. */ |
| 176 | location: string; |
| 177 | /** Action (`ALLOW`, `DENY`, `CUSTOM`). */ |
| 178 | action: string; |
| 179 | /** Targeted forwarding rules / gateways. */ |
| 180 | target: AuthzPolicyTarget | undefined; |
| 181 | /** HTTP match rules. */ |
| 182 | httpRules: AuthzPolicyRule[]; |
| 183 | /** Network match rules. */ |
| 184 | networkRules: AuthzPolicyRule[]; |
| 185 | /** Authorization profile. */ |
| 186 | policyProfile: string | undefined; |
| 187 | /** Custom provider, if `action` is `CUSTOM`. */ |
| 188 | customProvider: AuthzPolicyCustomProvider | undefined; |
| 189 | /** User-provided description. */ |
| 190 | description: string | undefined; |
| 191 | /** User labels (Alchemy ownership labels stripped). */ |
| 192 | labels: Record<string, string>; |
| 193 | /** RFC3339 creation timestamp. */ |
| 194 | createTime: string | undefined; |
| 195 | /** RFC3339 last-update timestamp. */ |
| 196 | updateTime: string | undefined; |
| 197 | }, |
| 198 | never, |
| 199 | Providers |
| 200 | >; |
| 201 | |
| 202 | /** |
| 203 | * A Network Security AuthzPolicy for Application Load Balancers, Secure |
| 204 | * Web Proxy, and Agent Gateway. |
| 205 | * |
| 206 | * Changing `authzPolicyId`, `location`, or `policyProfile` replaces the |
| 207 | * policy. Action, target, rules, custom provider, description, and |
| 208 | * labels update in place. `target.resources` must reference forwarding |
| 209 | * rules or gateways that share `loadBalancingScheme`. |
| 210 | * |
| 211 | * ### Creating an Authz Policy |
| 212 | * **Example:** Allow matching HTTP paths |
| 213 | * ```typescript |
| 214 | * const policy = yield* GCP.NetworkSecurity.AuthzPolicy("AllowAdmin", { |
| 215 | * location: "us-central1", |
| 216 | * action: "ALLOW", |
| 217 | * target: { |
| 218 | * loadBalancingScheme: "INTERNAL_MANAGED", |
| 219 | * resources: [forwardingRule.selfLink], |
| 220 | * }, |
| 221 | * httpRules: [ |
| 222 | * { |
| 223 | * to: { |
| 224 | * operations: [ |
| 225 | * { methods: ["GET"], paths: [{ prefix: "/admin" }] }, |
| 226 | * ], |
| 227 | * }, |
| 228 | * }, |
| 229 | * ], |
| 230 | * }); |
| 231 | * ``` |
| 232 | * |
| 233 | * @resource |
| 234 | * @category NetworkSecurity |
| 235 | */ |
| 236 | export const AuthzPolicy = Resource<AuthzPolicy>("GCP.NetworkSecurity.AuthzPolicy"); |
| 237 | |
| 238 | const resourceName = (project: string, location: string, authzPolicyId: string) => |
| 239 | `projects/${project}/locations/${location}/authzPolicies/${authzPolicyId}`; |
| 240 | |
| 241 | const actionOf = (value: string | undefined) => (value ?? DEFAULT_ACTION).toUpperCase(); |
| 242 | |
| 243 | const profileOf = (value: string | undefined) => (value ?? DEFAULT_PROFILE).toUpperCase(); |
| 244 | |
| 245 | const locationOf = (value: string | undefined, fallback: string) => |
| 246 | (value ?? fallback).toLowerCase(); |
| 247 | |
| 248 | const toCustomProvider = ( |
| 249 | provider: networksecurity.AuthzPolicyCustomProvider | undefined, |
| 250 | ): AuthzPolicyCustomProvider | undefined => { |
| 251 | if (provider === undefined) return undefined; |
| 252 | return { |
| 253 | cloudIap: provider.cloudIap !== undefined ? {} : undefined, |
| 254 | authzExtension: provider.authzExtension, |
| 255 | }; |
| 256 | }; |
| 257 | |
| 258 | const toAttrs = (policy: networksecurity.AuthzPolicy, project: string) => { |
| 259 | const name = policy.name ?? ""; |
| 260 | const parsed = parseResourceName(name); |
| 261 | return { |
| 262 | name, |
| 263 | authzPolicyId: parsed.id, |
| 264 | project: parsed.parentId || project, |
| 265 | location: parsed.location, |
| 266 | action: policy.action ?? DEFAULT_ACTION, |
| 267 | target: policy.target, |
| 268 | httpRules: (policy.httpRules ?? []) as AuthzPolicyRule[], |
| 269 | networkRules: (policy.networkRules ?? []) as AuthzPolicyRule[], |
| 270 | policyProfile: policy.policyProfile, |
| 271 | customProvider: toCustomProvider(policy.customProvider), |
| 272 | description: policy.description, |
| 273 | labels: userLabels(policy.labels), |
| 274 | createTime: policy.createTime, |
| 275 | updateTime: policy.updateTime, |
| 276 | }; |
| 277 | }; |
| 278 | |
| 279 | const getByName = (name: string) => |
| 280 | networksecurity |
| 281 | .getProjectsLocationsAuthzPolicies({ name }) |
| 282 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 283 | |
| 284 | const listOwned = (project: string) => |
| 285 | networksecurity.listProjectsLocationsAuthzPolicies |
| 286 | .pages({ |
| 287 | parent: projectParent(project, "-"), |
| 288 | pageSize: 1000, |
| 289 | }) |
| 290 | .pipe( |
| 291 | Stream.flatMap((page) => Stream.fromIterable(page.authzPolicies ?? [])), |
| 292 | Stream.filter((policy) => |
| 293 | Object.keys(policy.labels ?? {}).some((key) => key.startsWith("alchemy-")), |
| 294 | ), |
| 295 | Stream.map((policy) => toAttrs(policy, project)), |
| 296 | Stream.runCollect, |
| 297 | Effect.map((chunk) => Array.from(chunk)), |
| 298 | Effect.catchTag("NotFound", () => Effect.succeed([])), |
| 299 | ); |
| 300 | |
| 301 | const toCustomProviderBody = ( |
| 302 | provider: AuthzPolicyCustomProvider | undefined, |
| 303 | ): networksecurity.AuthzPolicyCustomProvider | undefined => { |
| 304 | if (provider === undefined) return undefined; |
| 305 | return { |
| 306 | cloudIap: provider.cloudIap !== undefined ? {} : undefined, |
| 307 | authzExtension: provider.authzExtension, |
| 308 | }; |
| 309 | }; |
| 310 | |
| 311 | export const AuthzPolicyProvider = () => |
| 312 | Provider.succeed(AuthzPolicy, { |
| 313 | stables: ["name", "authzPolicyId", "project", "location", "policyProfile", "createTime"], |
| 314 | |
| 315 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 316 | if (!isResolved(news)) return undefined; |
| 317 | const env = yield* GcpEnvironment.current; |
| 318 | const previousId = olds?.authzPolicyId ?? output?.authzPolicyId; |
| 319 | const nextId = news.authzPolicyId ?? previousId; |
| 320 | const previousLocation = locationOf(olds?.location ?? output?.location, env.region); |
| 321 | const nextLocation = locationOf( |
| 322 | news.location ?? olds?.location ?? output?.location, |
| 323 | env.region, |
| 324 | ); |
| 325 | const previousProfile = profileOf(olds?.policyProfile ?? output?.policyProfile); |
| 326 | const nextProfile = profileOf( |
| 327 | news.policyProfile ?? olds?.policyProfile ?? output?.policyProfile, |
| 328 | ); |
| 329 | const replace = |
| 330 | (previousId !== undefined && nextId !== undefined && nextId !== previousId) || |
| 331 | previousLocation !== nextLocation || |
| 332 | previousProfile !== nextProfile; |
| 333 | if (!replace) return undefined; |
| 334 | return { |
| 335 | action: "replace" as const, |
| 336 | deleteFirst: |
| 337 | previousLocation === nextLocation && previousId !== undefined && nextId === previousId, |
| 338 | }; |
| 339 | }), |
| 340 | |
| 341 | read: Effect.fn(function* ({ id, olds, output }) { |
| 342 | const env = yield* GcpEnvironment.current; |
| 343 | const authzPolicyId = yield* toPhysicalId( |
| 344 | id, |
| 345 | olds?.authzPolicyId, |
| 346 | output?.authzPolicyId, |
| 347 | "authzpolicy", |
| 348 | ); |
| 349 | const location = locationOf(olds?.location ?? output?.location, env.region); |
| 350 | const name = output?.name ?? resourceName(env.project, location, authzPolicyId); |
| 351 | const existing = yield* getByName(name); |
| 352 | if (existing === undefined) return undefined; |
| 353 | const attrs = toAttrs(existing, env.project); |
| 354 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 355 | }), |
| 356 | |
| 357 | list: () => |
| 358 | Effect.gen(function* () { |
| 359 | const env = yield* GcpEnvironment.current; |
| 360 | return yield* listOwned(env.project); |
| 361 | }), |
| 362 | |
| 363 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 364 | const env = yield* GcpEnvironment.current; |
| 365 | const authzPolicyId = yield* toPhysicalId( |
| 366 | id, |
| 367 | news.authzPolicyId, |
| 368 | output?.authzPolicyId, |
| 369 | "authzpolicy", |
| 370 | ); |
| 371 | const location = locationOf(news.location ?? output?.location, env.region); |
| 372 | const name = resourceName(env.project, location, authzPolicyId); |
| 373 | const action = actionOf(news.action); |
| 374 | const policyProfile = profileOf(news.policyProfile); |
| 375 | const customProvider = toCustomProviderBody(news.customProvider); |
| 376 | const desiredLabels = { |
| 377 | ...toLabels(news.labels), |
| 378 | ...(yield* createInternalLabels(id)), |
| 379 | }; |
| 380 | |
| 381 | let current = yield* getByName(name); |
| 382 | |
| 383 | if (current === undefined) { |
| 384 | const created = yield* networksecurity |
| 385 | .createProjectsLocationsAuthzPolicies({ |
| 386 | parent: projectParent(env.project, location), |
| 387 | authzPolicyId, |
| 388 | body: { |
| 389 | action, |
| 390 | target: news.target, |
| 391 | httpRules: news.httpRules, |
| 392 | networkRules: news.networkRules, |
| 393 | policyProfile, |
| 394 | customProvider, |
| 395 | description: news.description, |
| 396 | labels: desiredLabels, |
| 397 | }, |
| 398 | }) |
| 399 | .pipe( |
| 400 | Effect.retry({ |
| 401 | while: (error) => error._tag === "Conflict", |
| 402 | times: 5, |
| 403 | schedule: Schedule.spaced("2 seconds"), |
| 404 | }), |
| 405 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 406 | ); |
| 407 | if (created !== undefined) { |
| 408 | yield* waitForOperation(created); |
| 409 | } |
| 410 | current = yield* waitUntilExists(getByName(name), name); |
| 411 | } |
| 412 | |
| 413 | if (current === undefined) { |
| 414 | return yield* new ResourceNotResolved({ resourceName: name }); |
| 415 | } |
| 416 | |
| 417 | const observedLabels = tagRecord(current.labels); |
| 418 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 419 | const labelsChanged = upsert.length > 0 || removed.length > 0; |
| 420 | const descriptionChanged = (current.description ?? "") !== (news.description ?? ""); |
| 421 | const actionChanged = actionOf(current.action) !== action; |
| 422 | const targetChanged = !sameJson(current.target, news.target); |
| 423 | const httpChanged = !sameJson(current.httpRules ?? [], news.httpRules ?? []); |
| 424 | const networkChanged = !sameJson(current.networkRules ?? [], news.networkRules ?? []); |
| 425 | const providerChanged = !sameJson( |
| 426 | toCustomProvider(current.customProvider), |
| 427 | news.customProvider, |
| 428 | ); |
| 429 | |
| 430 | if ( |
| 431 | labelsChanged || |
| 432 | descriptionChanged || |
| 433 | actionChanged || |
| 434 | targetChanged || |
| 435 | httpChanged || |
| 436 | networkChanged || |
| 437 | providerChanged |
| 438 | ) { |
| 439 | const updateMask = [ |
| 440 | labelsChanged ? "labels" : undefined, |
| 441 | descriptionChanged ? "description" : undefined, |
| 442 | actionChanged ? "action" : undefined, |
| 443 | targetChanged ? "target" : undefined, |
| 444 | httpChanged ? "httpRules" : undefined, |
| 445 | networkChanged ? "networkRules" : undefined, |
| 446 | providerChanged ? "customProvider" : undefined, |
| 447 | ].filter((field): field is string => field !== undefined); |
| 448 | |
| 449 | const operation = yield* networksecurity.patchProjectsLocationsAuthzPolicies({ |
| 450 | name: current.name ?? name, |
| 451 | updateMask: updateMask.join(","), |
| 452 | body: { |
| 453 | name: current.name ?? name, |
| 454 | labels: desiredLabels, |
| 455 | description: news.description, |
| 456 | action, |
| 457 | target: news.target, |
| 458 | httpRules: news.httpRules, |
| 459 | networkRules: news.networkRules, |
| 460 | customProvider, |
| 461 | }, |
| 462 | }); |
| 463 | yield* waitForOperation(operation); |
| 464 | current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name); |
| 465 | } |
| 466 | |
| 467 | return toAttrs(current, env.project); |
| 468 | }), |
| 469 | |
| 470 | delete: Effect.fn(function* ({ output }) { |
| 471 | const operation = yield* networksecurity |
| 472 | .deleteProjectsLocationsAuthzPolicies({ name: output.name }) |
| 473 | .pipe( |
| 474 | Effect.retry({ |
| 475 | while: (error) => error._tag === "Conflict", |
| 476 | times: 8, |
| 477 | schedule: Schedule.spaced("2 seconds"), |
| 478 | }), |
| 479 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 480 | ); |
| 481 | if (operation !== undefined) { |
| 482 | yield* waitForOperation(operation, { notFoundOk: true }); |
| 483 | } |
| 484 | yield* waitUntilGone(getByName(output.name), output.name); |
| 485 | }), |
| 486 | }); |