@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

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