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, 04:45 UTC
| 1 | import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3"; |
| 2 | import * as compute from "@distilled.cloud/gcp/compute_v1"; |
| 3 | import { unownedUnlessPrevious } from "alchemy/AdoptPolicy"; |
| 4 | import { isResolved } from "alchemy/Diff"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import * as Data from "effect/Data"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Schedule from "effect/Schedule"; |
| 10 | import * as Stream from "effect/Stream"; |
| 11 | import { GcpEnvironment } from "../Environment.ts"; |
| 12 | import { createInternalLabels, hasAlchemyLabels } from "../Labels.ts"; |
| 13 | import type { Providers } from "../Providers.ts"; |
| 14 | import { |
| 15 | encodeDescription, |
| 16 | ignoredCodes, |
| 17 | hasOwnershipMarker, |
| 18 | lastSegment, |
| 19 | parseDescription, |
| 20 | sameJson, |
| 21 | sorted, |
| 22 | toPhysicalName, |
| 23 | } from "./internal.ts"; |
| 24 | import { waitOrganizationOperation } from "./operations.ts"; |
| 25 | import type { |
| 26 | SecurityPolicyAdaptiveProtectionConfig, |
| 27 | SecurityPolicyAdvancedOptionsConfig, |
| 28 | SecurityPolicyDdosProtectionConfig, |
| 29 | SecurityPolicyRecaptchaOptionsConfig, |
| 30 | SecurityPolicyRule, |
| 31 | SecurityPolicyRuleMatcher, |
| 32 | SecurityPolicyType, |
| 33 | SecurityPolicyUserDefinedField, |
| 34 | } from "./SecurityPolicy.ts"; |
| 35 | |
| 36 | const DEFAULT_TYPE = "CLOUD_ARMOR"; |
| 37 | const DEFAULT_RULE_PRIORITY = 2147483647; |
| 38 | |
| 39 | export type OrganizationSecurityPolicyType = SecurityPolicyType; |
| 40 | export type OrganizationSecurityPolicyRule = SecurityPolicyRule; |
| 41 | export type OrganizationSecurityPolicyRuleMatcher = SecurityPolicyRuleMatcher; |
| 42 | |
| 43 | export type OrganizationSecurityPolicyProps = { |
| 44 | /** |
| 45 | * User-provided RFC1035 name (`shortName`). Unique within the parent |
| 46 | * organization. If omitted, a unique name is generated from the stack, |
| 47 | * stage, and logical id. Immutable — changing it replaces the policy. |
| 48 | * After create, GCP also assigns a numeric `name`. |
| 49 | */ |
| 50 | shortName?: string; |
| 51 | /** |
| 52 | * Parent organization or folder. Format `organizations/{organization}` |
| 53 | * or `folders/{folder}`. If omitted, Alchemy uses the project parent |
| 54 | * from Cloud Resource Manager. Immutable — changing it replaces the |
| 55 | * policy. |
| 56 | */ |
| 57 | parent?: string; |
| 58 | /** |
| 59 | * Optional description. Organization security policies have no |
| 60 | * `setLabels` API, so Alchemy ownership is stored in a `[alchemy …]` |
| 61 | * prefix for `list` / nuke. |
| 62 | */ |
| 63 | description?: string; |
| 64 | /** |
| 65 | * Intended use of the policy. Set only at create time — changing it |
| 66 | * replaces the policy. |
| 67 | * @default "CLOUD_ARMOR" |
| 68 | */ |
| 69 | type?: OrganizationSecurityPolicyType; |
| 70 | /** |
| 71 | * Ordered Cloud Armor rules. There must always be a default rule at |
| 72 | * priority `2147483647` matching `*`. If omitted on create, GCP adds |
| 73 | * an `allow` default. When this field is set, Alchemy syncs rules with |
| 74 | * `addRule` / `patchRule` / `removeRule`. When omitted on later |
| 75 | * updates, observed rules are left in place. |
| 76 | */ |
| 77 | rules?: OrganizationSecurityPolicyRule[]; |
| 78 | /** |
| 79 | * JSON parsing, log level, and related WAF options. Only applied when |
| 80 | * set. |
| 81 | */ |
| 82 | advancedOptionsConfig?: SecurityPolicyAdvancedOptionsConfig; |
| 83 | /** |
| 84 | * Cloud Armor Adaptive Protection. Only applied when set. |
| 85 | */ |
| 86 | adaptiveProtectionConfig?: SecurityPolicyAdaptiveProtectionConfig; |
| 87 | /** |
| 88 | * reCAPTCHA site key used by `redirect` rules of type |
| 89 | * `GOOGLE_RECAPTCHA`. Only applied when set. |
| 90 | */ |
| 91 | recaptchaOptionsConfig?: SecurityPolicyRecaptchaOptionsConfig; |
| 92 | /** |
| 93 | * Network DDoS protection (`STANDARD` or `ADVANCED`). Only applied |
| 94 | * when set. |
| 95 | */ |
| 96 | ddosProtectionConfig?: SecurityPolicyDdosProtectionConfig; |
| 97 | /** |
| 98 | * Packet field extractors for `CLOUD_ARMOR_NETWORK` policies. Only |
| 99 | * applied when set. |
| 100 | */ |
| 101 | userDefinedFields?: SecurityPolicyUserDefinedField[]; |
| 102 | }; |
| 103 | |
| 104 | export type OrganizationSecurityPolicy = Resource< |
| 105 | "GCP.Compute.OrganizationSecurityPolicy", |
| 106 | OrganizationSecurityPolicyProps, |
| 107 | { |
| 108 | /** User-provided RFC1035 name. */ |
| 109 | shortName: string; |
| 110 | /** Server-assigned numeric policy id (`name` in the API). */ |
| 111 | securityPolicyId: string; |
| 112 | /** Parent `organizations/{organization}` or `folders/{folder}`. */ |
| 113 | parent: string; |
| 114 | /** Project id of the deploying stack. */ |
| 115 | project: string; |
| 116 | /** Policy type. */ |
| 117 | type: string; |
| 118 | /** User description with the Alchemy ownership prefix stripped. */ |
| 119 | description: string | undefined; |
| 120 | /** Rules currently attached (including the default). */ |
| 121 | rules: OrganizationSecurityPolicyRule[]; |
| 122 | /** Advanced WAF options, if configured. */ |
| 123 | advancedOptionsConfig: SecurityPolicyAdvancedOptionsConfig | undefined; |
| 124 | /** Adaptive Protection config, if configured. */ |
| 125 | adaptiveProtectionConfig: SecurityPolicyAdaptiveProtectionConfig | undefined; |
| 126 | /** reCAPTCHA options, if configured. */ |
| 127 | recaptchaOptionsConfig: SecurityPolicyRecaptchaOptionsConfig | undefined; |
| 128 | /** DDoS protection config, if configured. */ |
| 129 | ddosProtectionConfig: SecurityPolicyDdosProtectionConfig | undefined; |
| 130 | /** User-defined packet fields, if configured. */ |
| 131 | userDefinedFields: SecurityPolicyUserDefinedField[]; |
| 132 | /** Optimistic-locking fingerprint. */ |
| 133 | fingerprint: string | undefined; |
| 134 | /** Server-defined URL. */ |
| 135 | selfLink: string | undefined; |
| 136 | /** Server-assigned numeric id (same as `securityPolicyId` when present). */ |
| 137 | id: string | undefined; |
| 138 | /** RFC3339 creation timestamp. */ |
| 139 | creationTimestamp: string | undefined; |
| 140 | /** Resource kind. */ |
| 141 | kind: string | undefined; |
| 142 | }, |
| 143 | never, |
| 144 | Providers |
| 145 | >; |
| 146 | |
| 147 | /** |
| 148 | * An organization-scoped Cloud Armor security policy. |
| 149 | * |
| 150 | * Organization security policies live under |
| 151 | * `locations/global/securityPolicies` and are identified by a |
| 152 | * server-assigned numeric id. The user-facing name is `shortName`. Parent |
| 153 | * and type are immutable. Description and WAF options update in place via |
| 154 | * `organizationSecurityPolicies.patch`. Rules are synced with `addRule` / |
| 155 | * `patchRule` / `removeRule`. |
| 156 | * |
| 157 | * ### Creating an Organization Security Policy |
| 158 | * **Example:** Generated name with a deny rule |
| 159 | * ```typescript |
| 160 | * const policy = yield* GCP.Compute.OrganizationSecurityPolicy("OrgArmor", { |
| 161 | * description: "deny a scanner", |
| 162 | * rules: [ |
| 163 | * { |
| 164 | * action: "deny(403)", |
| 165 | * priority: 1000, |
| 166 | * match: { |
| 167 | * versionedExpr: "SRC_IPS_V1", |
| 168 | * config: { srcIpRanges: ["9.9.9.0/24"] }, |
| 169 | * }, |
| 170 | * }, |
| 171 | * ], |
| 172 | * }); |
| 173 | * ``` |
| 174 | * |
| 175 | * **Example:** Named policy under an organization |
| 176 | * ```typescript |
| 177 | * const policy = yield* GCP.Compute.OrganizationSecurityPolicy("OrgArmor", { |
| 178 | * shortName: "app-org-armor", |
| 179 | * parent: "organizations/123456789", |
| 180 | * description: "org WAF", |
| 181 | * }); |
| 182 | * ``` |
| 183 | * |
| 184 | * @resource |
| 185 | * @category Compute |
| 186 | */ |
| 187 | export const OrganizationSecurityPolicy = Resource<OrganizationSecurityPolicy>( |
| 188 | "GCP.Compute.OrganizationSecurityPolicy", |
| 189 | ); |
| 190 | |
| 191 | export class OrganizationSecurityPolicyNotResolved extends Data.TaggedError( |
| 192 | "GCP.Compute.OrganizationSecurityPolicyNotResolved", |
| 193 | )<{ |
| 194 | securityPolicyId: string; |
| 195 | shortName: string; |
| 196 | }> {} |
| 197 | |
| 198 | export class OrganizationSecurityPolicyParentRequired extends Data.TaggedError( |
| 199 | "GCP.Compute.OrganizationSecurityPolicyParentRequired", |
| 200 | )<{ |
| 201 | project: string; |
| 202 | }> {} |
| 203 | |
| 204 | const typeOf = (value: string | undefined) => (value ?? DEFAULT_TYPE).toUpperCase(); |
| 205 | |
| 206 | const normalizeParent = (value: string): string => { |
| 207 | const trimmed = value.trim().replace(/\/+$/, ""); |
| 208 | if (trimmed.startsWith("organizations/") || trimmed.startsWith("folders/")) { |
| 209 | return trimmed; |
| 210 | } |
| 211 | if (trimmed.startsWith("organization/")) { |
| 212 | return `organizations/${trimmed.slice("organization/".length)}`; |
| 213 | } |
| 214 | if (trimmed.startsWith("folder/")) { |
| 215 | return `folders/${trimmed.slice("folder/".length)}`; |
| 216 | } |
| 217 | if (/^\d+$/.test(trimmed)) return `organizations/${trimmed}`; |
| 218 | return trimmed; |
| 219 | }; |
| 220 | |
| 221 | const projectParent = (project: string) => |
| 222 | resourcemanager.getProjects({ name: `projects/${project}` }).pipe( |
| 223 | Effect.map((resource) => |
| 224 | resource.parent !== undefined && resource.parent.length > 0 |
| 225 | ? normalizeParent(resource.parent) |
| 226 | : undefined, |
| 227 | ), |
| 228 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 229 | ); |
| 230 | |
| 231 | const resolveParent = (news: { parent?: string }, output: { parent?: string } | undefined) => |
| 232 | Effect.gen(function* () { |
| 233 | const explicit = news.parent ?? output?.parent; |
| 234 | if (explicit !== undefined && explicit.length > 0) { |
| 235 | return normalizeParent(explicit); |
| 236 | } |
| 237 | const env = yield* GcpEnvironment.current; |
| 238 | const fromProject = yield* projectParent(env.project); |
| 239 | if (fromProject !== undefined) return fromProject; |
| 240 | return yield* new OrganizationSecurityPolicyParentRequired({ |
| 241 | project: env.project, |
| 242 | }); |
| 243 | }); |
| 244 | |
| 245 | const listParents = (project: string) => |
| 246 | Effect.gen(function* () { |
| 247 | const parents = new Set<string>(); |
| 248 | const fromProject = yield* projectParent(project); |
| 249 | if (fromProject !== undefined) parents.add(fromProject); |
| 250 | return [...parents]; |
| 251 | }); |
| 252 | |
| 253 | const canonMatch = (match: SecurityPolicyRuleMatcher | undefined) => { |
| 254 | if (match === undefined) return undefined; |
| 255 | return { |
| 256 | versionedExpr: match.versionedExpr, |
| 257 | config: match.config ? { srcIpRanges: sorted(match.config.srcIpRanges) } : undefined, |
| 258 | expr: match.expr, |
| 259 | exprOptions: match.exprOptions, |
| 260 | }; |
| 261 | }; |
| 262 | |
| 263 | const canonRule = (rule: SecurityPolicyRule) => ({ |
| 264 | priority: rule.priority, |
| 265 | action: rule.action, |
| 266 | description: rule.description ?? "", |
| 267 | preview: rule.preview === true, |
| 268 | match: canonMatch(rule.match), |
| 269 | redirectOptions: rule.redirectOptions ?? null, |
| 270 | rateLimitOptions: rule.rateLimitOptions ?? null, |
| 271 | headerAction: rule.headerAction ?? null, |
| 272 | preconfiguredWafConfig: rule.preconfiguredWafConfig ?? null, |
| 273 | networkMatch: rule.networkMatch ?? null, |
| 274 | }); |
| 275 | |
| 276 | const ruleEquals = (left: SecurityPolicyRule, right: SecurityPolicyRule) => |
| 277 | sameJson(canonRule(left), canonRule(right)); |
| 278 | |
| 279 | const toRuleBody = (rule: SecurityPolicyRule): SecurityPolicyRule => ({ |
| 280 | priority: rule.priority, |
| 281 | action: rule.action, |
| 282 | description: rule.description, |
| 283 | preview: rule.preview === true ? true : undefined, |
| 284 | match: rule.match, |
| 285 | redirectOptions: rule.redirectOptions, |
| 286 | rateLimitOptions: rule.rateLimitOptions, |
| 287 | headerAction: rule.headerAction, |
| 288 | preconfiguredWafConfig: rule.preconfiguredWafConfig, |
| 289 | networkMatch: rule.networkMatch, |
| 290 | }); |
| 291 | |
| 292 | const defaultAllowRule = (): SecurityPolicyRule => ({ |
| 293 | action: "allow", |
| 294 | priority: DEFAULT_RULE_PRIORITY, |
| 295 | match: { |
| 296 | versionedExpr: "SRC_IPS_V1", |
| 297 | config: { srcIpRanges: ["*"] }, |
| 298 | }, |
| 299 | }); |
| 300 | |
| 301 | const withDefaultRule = ( |
| 302 | rules: readonly SecurityPolicyRule[] | undefined, |
| 303 | ): SecurityPolicyRule[] | undefined => { |
| 304 | if (rules === undefined) return undefined; |
| 305 | const bodies = rules.map(toRuleBody); |
| 306 | if (bodies.some((rule) => rule.priority === DEFAULT_RULE_PRIORITY)) { |
| 307 | return bodies; |
| 308 | } |
| 309 | return [...bodies, defaultAllowRule()]; |
| 310 | }; |
| 311 | |
| 312 | const desiredRules = ( |
| 313 | news: OrganizationSecurityPolicyProps, |
| 314 | observed: readonly SecurityPolicyRule[], |
| 315 | ): SecurityPolicyRule[] | undefined => { |
| 316 | if (news.rules === undefined) return undefined; |
| 317 | const byPriority = new Map<number, SecurityPolicyRule>(); |
| 318 | for (const rule of news.rules) { |
| 319 | if (rule.priority === undefined) continue; |
| 320 | byPriority.set(rule.priority, rule); |
| 321 | } |
| 322 | if (!byPriority.has(DEFAULT_RULE_PRIORITY)) { |
| 323 | const observedDefault = observed.find((rule) => rule.priority === DEFAULT_RULE_PRIORITY); |
| 324 | byPriority.set(DEFAULT_RULE_PRIORITY, observedDefault ?? defaultAllowRule()); |
| 325 | } |
| 326 | return [...byPriority.values()].sort( |
| 327 | (left, right) => (left.priority ?? 0) - (right.priority ?? 0), |
| 328 | ); |
| 329 | }; |
| 330 | |
| 331 | const subsetEqual = (observed: unknown, desired: unknown): boolean => { |
| 332 | if (desired === undefined) return true; |
| 333 | if (typeof desired !== typeof observed) return false; |
| 334 | if (desired === null || observed === null) return desired === observed; |
| 335 | if (Array.isArray(desired)) { |
| 336 | if (!Array.isArray(observed) || desired.length !== observed.length) { |
| 337 | return false; |
| 338 | } |
| 339 | return desired.every((item, index) => subsetEqual(observed[index], item)); |
| 340 | } |
| 341 | if (typeof desired === "object") { |
| 342 | if (typeof observed !== "object") return false; |
| 343 | const current = observed as Record<string, unknown>; |
| 344 | return Object.entries(desired as Record<string, unknown>).every( |
| 345 | ([key, value]) => value === undefined || subsetEqual(current[key], value), |
| 346 | ); |
| 347 | } |
| 348 | return observed === desired; |
| 349 | }; |
| 350 | |
| 351 | const policyIdOf = (policy: compute.SecurityPolicy) => |
| 352 | policy.name ?? policy.id ?? lastSegment(policy.selfLink); |
| 353 | |
| 354 | const toAttrs = ( |
| 355 | policy: compute.SecurityPolicy, |
| 356 | project: string, |
| 357 | ): OrganizationSecurityPolicy["Attributes"] => { |
| 358 | const parsed = parseDescription(policy.description); |
| 359 | return { |
| 360 | shortName: policy.shortName ?? policy.name ?? "", |
| 361 | securityPolicyId: policyIdOf(policy), |
| 362 | parent: policy.parent ?? "", |
| 363 | project, |
| 364 | type: typeOf(policy.type), |
| 365 | description: parsed.description, |
| 366 | rules: policy.rules ?? [], |
| 367 | advancedOptionsConfig: policy.advancedOptionsConfig, |
| 368 | adaptiveProtectionConfig: policy.adaptiveProtectionConfig, |
| 369 | recaptchaOptionsConfig: policy.recaptchaOptionsConfig, |
| 370 | ddosProtectionConfig: policy.ddosProtectionConfig, |
| 371 | userDefinedFields: policy.userDefinedFields ?? [], |
| 372 | fingerprint: policy.fingerprint, |
| 373 | selfLink: policy.selfLink, |
| 374 | id: policy.id, |
| 375 | creationTimestamp: policy.creationTimestamp, |
| 376 | kind: policy.kind, |
| 377 | }; |
| 378 | }; |
| 379 | |
| 380 | const getById = (securityPolicy: string) => |
| 381 | compute |
| 382 | .getOrganizationSecurityPolicies({ securityPolicy }) |
| 383 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 384 | |
| 385 | const findByShortName = (parentId: string, shortName: string) => |
| 386 | compute.listOrganizationSecurityPolicies |
| 387 | .items({ |
| 388 | parentId, |
| 389 | maxResults: 500, |
| 390 | returnPartialSuccess: true, |
| 391 | }) |
| 392 | .pipe( |
| 393 | Stream.filter((policy) => policy.shortName === shortName), |
| 394 | Stream.runCollect, |
| 395 | Effect.map((chunk) => Array.from(chunk)[0]), |
| 396 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 397 | ); |
| 398 | |
| 399 | const observe = (securityPolicyId: string | undefined, parentId: string, shortName: string) => |
| 400 | Effect.gen(function* () { |
| 401 | if (securityPolicyId !== undefined && securityPolicyId.length > 0) { |
| 402 | const existing = yield* getById(securityPolicyId); |
| 403 | if (existing !== undefined) return existing; |
| 404 | } |
| 405 | return yield* findByShortName(parentId, shortName); |
| 406 | }); |
| 407 | |
| 408 | const runOp = <E extends { readonly _tag: string }, R>( |
| 409 | securityPolicyId: string, |
| 410 | parentId: string, |
| 411 | start: Effect.Effect<compute.Operation, E, R>, |
| 412 | options?: { ignoreAlreadyExists?: boolean; ignoreNotFound?: boolean }, |
| 413 | ) => |
| 414 | start.pipe( |
| 415 | Effect.flatMap((operation) => |
| 416 | waitOrganizationOperation(operation, parentId, { |
| 417 | ignore: ignoredCodes(options), |
| 418 | }), |
| 419 | ), |
| 420 | Effect.retry({ |
| 421 | while: (error) => error._tag === "Conflict", |
| 422 | times: 5, |
| 423 | schedule: Schedule.spaced("1 second"), |
| 424 | }), |
| 425 | ); |
| 426 | |
| 427 | const idFromOperation = (operation: compute.Operation) => { |
| 428 | if (operation.targetId !== undefined && operation.targetId.length > 0) { |
| 429 | return operation.targetId; |
| 430 | } |
| 431 | const fromLink = lastSegment(operation.targetLink); |
| 432 | return fromLink.length > 0 ? fromLink : ""; |
| 433 | }; |
| 434 | |
| 435 | const awaitResource = (securityPolicyId: string, parentId: string, shortName: string) => |
| 436 | observe(securityPolicyId, parentId, shortName).pipe( |
| 437 | Effect.flatMap((policy) => |
| 438 | policy !== undefined |
| 439 | ? Effect.succeed(policy) |
| 440 | : Effect.fail( |
| 441 | new OrganizationSecurityPolicyNotResolved({ |
| 442 | securityPolicyId, |
| 443 | shortName, |
| 444 | }), |
| 445 | ), |
| 446 | ), |
| 447 | Effect.retry({ |
| 448 | while: (error) => error._tag === "GCP.Compute.OrganizationSecurityPolicyNotResolved", |
| 449 | times: 8, |
| 450 | schedule: Schedule.spaced("1 second"), |
| 451 | }), |
| 452 | ); |
| 453 | |
| 454 | const syncRules = ( |
| 455 | securityPolicyId: string, |
| 456 | parentId: string, |
| 457 | observed: readonly SecurityPolicyRule[], |
| 458 | desired: readonly SecurityPolicyRule[], |
| 459 | ) => |
| 460 | Effect.gen(function* () { |
| 461 | const observedByPriority = new Map<number, SecurityPolicyRule>(); |
| 462 | for (const rule of observed) { |
| 463 | if (rule.priority !== undefined) { |
| 464 | observedByPriority.set(rule.priority, rule); |
| 465 | } |
| 466 | } |
| 467 | const desiredByPriority = new Map<number, SecurityPolicyRule>(); |
| 468 | for (const rule of desired) { |
| 469 | if (rule.priority !== undefined) { |
| 470 | desiredByPriority.set(rule.priority, rule); |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | for (const [priority, rule] of desiredByPriority) { |
| 475 | const current = observedByPriority.get(priority); |
| 476 | if (current === undefined) { |
| 477 | yield* runOp( |
| 478 | securityPolicyId, |
| 479 | parentId, |
| 480 | compute.addRuleOrganizationSecurityPolicies({ |
| 481 | securityPolicy: securityPolicyId, |
| 482 | body: toRuleBody(rule), |
| 483 | }), |
| 484 | { ignoreAlreadyExists: true }, |
| 485 | ); |
| 486 | continue; |
| 487 | } |
| 488 | if (!ruleEquals(current, rule)) { |
| 489 | yield* runOp( |
| 490 | securityPolicyId, |
| 491 | parentId, |
| 492 | compute.patchRuleOrganizationSecurityPolicies({ |
| 493 | securityPolicy: securityPolicyId, |
| 494 | priority, |
| 495 | body: toRuleBody(rule), |
| 496 | }), |
| 497 | ); |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | for (const priority of observedByPriority.keys()) { |
| 502 | if (desiredByPriority.has(priority)) continue; |
| 503 | if (priority === DEFAULT_RULE_PRIORITY) continue; |
| 504 | yield* runOp( |
| 505 | securityPolicyId, |
| 506 | parentId, |
| 507 | compute.removeRuleOrganizationSecurityPolicies({ |
| 508 | securityPolicy: securityPolicyId, |
| 509 | priority, |
| 510 | }), |
| 511 | { ignoreNotFound: true }, |
| 512 | ).pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 513 | } |
| 514 | }); |
| 515 | |
| 516 | export const OrganizationSecurityPolicyProvider = () => |
| 517 | Provider.succeed(OrganizationSecurityPolicy, { |
| 518 | stables: [ |
| 519 | "shortName", |
| 520 | "securityPolicyId", |
| 521 | "parent", |
| 522 | "project", |
| 523 | "type", |
| 524 | "id", |
| 525 | "selfLink", |
| 526 | "creationTimestamp", |
| 527 | ], |
| 528 | |
| 529 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 530 | if (!isResolved(news)) return undefined; |
| 531 | const previousName = olds?.shortName ?? output?.shortName; |
| 532 | const nextName = news.shortName ?? previousName; |
| 533 | const nameChanged = |
| 534 | previousName !== undefined && nextName !== undefined && previousName !== nextName; |
| 535 | const previousParent = olds?.parent ?? output?.parent; |
| 536 | const nextParent = news.parent !== undefined ? normalizeParent(news.parent) : previousParent; |
| 537 | const parentChanged = |
| 538 | previousParent !== undefined && |
| 539 | nextParent !== undefined && |
| 540 | normalizeParent(previousParent) !== normalizeParent(nextParent); |
| 541 | const previousType = typeOf(olds?.type ?? output?.type); |
| 542 | const nextType = typeOf(news.type ?? output?.type); |
| 543 | if (nameChanged) { |
| 544 | return { action: "replace" as const, deleteFirst: false }; |
| 545 | } |
| 546 | if (parentChanged || previousType !== nextType) { |
| 547 | return { action: "replace" as const, deleteFirst: true }; |
| 548 | } |
| 549 | return undefined; |
| 550 | }), |
| 551 | |
| 552 | read: Effect.fn(function* ({ id, olds, output, previous }) { |
| 553 | const env = yield* GcpEnvironment.current; |
| 554 | const shortName = yield* toPhysicalName(id, olds?.shortName, output?.shortName, "policy"); |
| 555 | const parent = yield* resolveParent(olds ?? {}, output).pipe( |
| 556 | Effect.catchTag("GCP.Compute.OrganizationSecurityPolicyParentRequired", () => |
| 557 | Effect.succeed(output?.parent ?? olds?.parent ?? ""), |
| 558 | ), |
| 559 | ); |
| 560 | const existing = yield* observe(output?.securityPolicyId, parent, shortName); |
| 561 | if (existing === undefined) return undefined; |
| 562 | const attrs = toAttrs(existing, env.project); |
| 563 | const { labels } = parseDescription(existing.description); |
| 564 | return (yield* hasAlchemyLabels(id, labels)) |
| 565 | ? attrs |
| 566 | : unownedUnlessPrevious(attrs, previous, "shortName"); |
| 567 | }), |
| 568 | |
| 569 | list: () => |
| 570 | Effect.gen(function* () { |
| 571 | const env = yield* GcpEnvironment.current; |
| 572 | const parents = yield* listParents(env.project); |
| 573 | if (parents.length === 0) return []; |
| 574 | const listed: OrganizationSecurityPolicy["Attributes"][] = []; |
| 575 | for (const parentId of parents) { |
| 576 | const chunk = yield* compute.listOrganizationSecurityPolicies |
| 577 | .items({ |
| 578 | parentId, |
| 579 | maxResults: 500, |
| 580 | returnPartialSuccess: true, |
| 581 | }) |
| 582 | .pipe( |
| 583 | Stream.filter((policy) => hasOwnershipMarker(policy.description)), |
| 584 | Stream.map((policy) => toAttrs(policy, env.project)), |
| 585 | Stream.runCollect, |
| 586 | Effect.map((items) => Array.from(items)), |
| 587 | Effect.catchTag("NotFound", () => |
| 588 | Effect.succeed([] as OrganizationSecurityPolicy["Attributes"][]), |
| 589 | ), |
| 590 | ); |
| 591 | listed.push(...chunk); |
| 592 | } |
| 593 | return listed; |
| 594 | }), |
| 595 | |
| 596 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 597 | const env = yield* GcpEnvironment.current; |
| 598 | const shortName = yield* toPhysicalName(id, news.shortName, output?.shortName, "policy"); |
| 599 | const parentId = yield* resolveParent(news, output); |
| 600 | const ownership = yield* createInternalLabels(id); |
| 601 | const desiredDescription = encodeDescription(ownership, news.description); |
| 602 | |
| 603 | let current = yield* observe(output?.securityPolicyId, parentId, shortName); |
| 604 | |
| 605 | if (current === undefined) { |
| 606 | const inserted = yield* runOp( |
| 607 | shortName, |
| 608 | parentId, |
| 609 | compute.insertOrganizationSecurityPolicies({ |
| 610 | parentId, |
| 611 | body: { |
| 612 | shortName, |
| 613 | description: desiredDescription, |
| 614 | type: typeOf(news.type), |
| 615 | rules: withDefaultRule(news.rules), |
| 616 | advancedOptionsConfig: news.advancedOptionsConfig, |
| 617 | adaptiveProtectionConfig: news.adaptiveProtectionConfig, |
| 618 | recaptchaOptionsConfig: news.recaptchaOptionsConfig, |
| 619 | ddosProtectionConfig: news.ddosProtectionConfig, |
| 620 | userDefinedFields: news.userDefinedFields, |
| 621 | }, |
| 622 | }), |
| 623 | { ignoreAlreadyExists: true }, |
| 624 | ).pipe(Effect.catchTag("Conflict", () => Effect.undefined)); |
| 625 | const createdId = inserted !== undefined ? idFromOperation(inserted) : ""; |
| 626 | current = yield* awaitResource( |
| 627 | createdId.length > 0 ? createdId : (output?.securityPolicyId ?? ""), |
| 628 | parentId, |
| 629 | shortName, |
| 630 | ); |
| 631 | } |
| 632 | |
| 633 | if (current === undefined) { |
| 634 | return yield* new OrganizationSecurityPolicyNotResolved({ |
| 635 | securityPolicyId: output?.securityPolicyId ?? "", |
| 636 | shortName, |
| 637 | }); |
| 638 | } |
| 639 | |
| 640 | const securityPolicyId = policyIdOf(current); |
| 641 | const patch: compute.SecurityPolicy = { |
| 642 | fingerprint: current.fingerprint, |
| 643 | }; |
| 644 | let needsPatch = false; |
| 645 | if ((current.description ?? "") !== desiredDescription) { |
| 646 | patch.description = desiredDescription; |
| 647 | needsPatch = true; |
| 648 | } |
| 649 | if ( |
| 650 | news.advancedOptionsConfig !== undefined && |
| 651 | !subsetEqual(current.advancedOptionsConfig, news.advancedOptionsConfig) |
| 652 | ) { |
| 653 | patch.advancedOptionsConfig = news.advancedOptionsConfig; |
| 654 | needsPatch = true; |
| 655 | } |
| 656 | if ( |
| 657 | news.adaptiveProtectionConfig !== undefined && |
| 658 | !subsetEqual(current.adaptiveProtectionConfig, news.adaptiveProtectionConfig) |
| 659 | ) { |
| 660 | patch.adaptiveProtectionConfig = news.adaptiveProtectionConfig; |
| 661 | needsPatch = true; |
| 662 | } |
| 663 | if ( |
| 664 | news.recaptchaOptionsConfig !== undefined && |
| 665 | !subsetEqual(current.recaptchaOptionsConfig, news.recaptchaOptionsConfig) |
| 666 | ) { |
| 667 | patch.recaptchaOptionsConfig = news.recaptchaOptionsConfig; |
| 668 | needsPatch = true; |
| 669 | } |
| 670 | if ( |
| 671 | news.ddosProtectionConfig !== undefined && |
| 672 | !subsetEqual(current.ddosProtectionConfig, news.ddosProtectionConfig) |
| 673 | ) { |
| 674 | patch.ddosProtectionConfig = news.ddosProtectionConfig; |
| 675 | needsPatch = true; |
| 676 | } |
| 677 | if ( |
| 678 | news.userDefinedFields !== undefined && |
| 679 | !sameJson(current.userDefinedFields ?? [], news.userDefinedFields) |
| 680 | ) { |
| 681 | patch.userDefinedFields = news.userDefinedFields; |
| 682 | needsPatch = true; |
| 683 | } |
| 684 | if (needsPatch) { |
| 685 | yield* runOp( |
| 686 | securityPolicyId, |
| 687 | parentId, |
| 688 | compute.patchOrganizationSecurityPolicies({ |
| 689 | securityPolicy: securityPolicyId, |
| 690 | body: patch, |
| 691 | }), |
| 692 | ); |
| 693 | current = (yield* getById(securityPolicyId)) ?? current; |
| 694 | } |
| 695 | |
| 696 | const nextRules = desiredRules(news, current.rules ?? []); |
| 697 | if (nextRules !== undefined) { |
| 698 | yield* syncRules(securityPolicyId, parentId, current.rules ?? [], nextRules); |
| 699 | current = (yield* getById(securityPolicyId)) ?? current; |
| 700 | } |
| 701 | |
| 702 | if (current === undefined) { |
| 703 | return yield* new OrganizationSecurityPolicyNotResolved({ |
| 704 | securityPolicyId, |
| 705 | shortName, |
| 706 | }); |
| 707 | } |
| 708 | |
| 709 | return toAttrs(current, env.project); |
| 710 | }), |
| 711 | |
| 712 | delete: Effect.fn(function* ({ output }) { |
| 713 | const securityPolicyId = output.securityPolicyId; |
| 714 | if (securityPolicyId.length === 0) return; |
| 715 | const parentId = output.parent.length > 0 ? normalizeParent(output.parent) : undefined; |
| 716 | yield* compute |
| 717 | .deleteOrganizationSecurityPolicies({ |
| 718 | securityPolicy: securityPolicyId, |
| 719 | }) |
| 720 | .pipe( |
| 721 | Effect.flatMap((operation) => |
| 722 | waitOrganizationOperation(operation, parentId, { |
| 723 | ignore: ["RESOURCE_NOT_FOUND"], |
| 724 | }), |
| 725 | ), |
| 726 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 727 | Effect.retry({ |
| 728 | while: (error) => error._tag === "Conflict", |
| 729 | times: 8, |
| 730 | schedule: Schedule.spaced("2 seconds"), |
| 731 | }), |
| 732 | ); |
| 733 | }), |
| 734 | }); |