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, 06:00 UTC
| 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 | listOrganizations, |
| 15 | normalizeLocation, |
| 16 | organizationParent, |
| 17 | parseResourceName, |
| 18 | ResourceNotResolved, |
| 19 | resolveOrganization, |
| 20 | sameJson, |
| 21 | toPhysicalId, |
| 22 | userLabels, |
| 23 | waitForOperation, |
| 24 | waitUntilExists, |
| 25 | waitUntilGone, |
| 26 | } from "./operations.ts"; |
| 27 | |
| 28 | const DEFAULT_TYPE = "THREAT_PREVENTION" satisfies networksecurity.SecurityProfileTypeEnum; |
| 29 | |
| 30 | export type OrganizationsSecurityProfileType = |
| 31 | | networksecurity.SecurityProfileTypeEnum |
| 32 | | (string & {}); |
| 33 | |
| 34 | export type OrganizationsAntivirusOverride = { |
| 35 | /** Protocol to match (`HTTP`, `SMTP`, …). */ |
| 36 | protocol?: string; |
| 37 | /** Threat action (`ALLOW`, `ALERT`, `DENY`, `DEFAULT_ACTION`). */ |
| 38 | action?: string; |
| 39 | }; |
| 40 | |
| 41 | export type OrganizationsSeverityOverride = { |
| 42 | /** Severity (`INFORMATIONAL`, `LOW`, `MEDIUM`, `HIGH`, `CRITICAL`). */ |
| 43 | severity?: string; |
| 44 | /** Threat action (`ALLOW`, `ALERT`, `DENY`, `DEFAULT_ACTION`). */ |
| 45 | action?: string; |
| 46 | }; |
| 47 | |
| 48 | export type OrganizationsThreatOverride = { |
| 49 | /** Vendor-specific threat id. */ |
| 50 | threatId?: string; |
| 51 | /** Threat type (output-only on the wire). */ |
| 52 | type?: string; |
| 53 | /** Threat action (`ALLOW`, `ALERT`, `DENY`, `DEFAULT_ACTION`). */ |
| 54 | action?: string; |
| 55 | }; |
| 56 | |
| 57 | export type OrganizationsThreatPreventionProfile = { |
| 58 | /** Antivirus action overrides per protocol. */ |
| 59 | antivirusOverrides?: OrganizationsAntivirusOverride[]; |
| 60 | /** Action overrides by severity. */ |
| 61 | severityOverrides?: OrganizationsSeverityOverride[]; |
| 62 | /** Action overrides by threat id. */ |
| 63 | threatOverrides?: OrganizationsThreatOverride[]; |
| 64 | }; |
| 65 | |
| 66 | export type OrganizationsCustomMirroringProfile = { |
| 67 | /** Target MirroringEndpointGroup resource name. Immutable. */ |
| 68 | mirroringEndpointGroup?: string; |
| 69 | }; |
| 70 | |
| 71 | export type OrganizationsUrlFilter = { |
| 72 | /** Action (`ALLOW` or `DENY`). */ |
| 73 | filteringAction?: string; |
| 74 | /** URL match strings. */ |
| 75 | urls?: string[]; |
| 76 | /** Unique priority within the profile. Lower is higher priority. */ |
| 77 | priority?: number; |
| 78 | }; |
| 79 | |
| 80 | export type OrganizationsUrlFilteringProfile = { |
| 81 | /** URL filters. */ |
| 82 | urlFilters?: OrganizationsUrlFilter[]; |
| 83 | }; |
| 84 | |
| 85 | export type OrganizationsCustomInterceptProfile = { |
| 86 | /** Target InterceptEndpointGroup resource name. Immutable. */ |
| 87 | interceptEndpointGroup?: string; |
| 88 | }; |
| 89 | |
| 90 | export type OrganizationsSecurityProfileProps = { |
| 91 | /** |
| 92 | * Security profile id. If omitted, a unique RFC1035 name is generated |
| 93 | * from the stack, stage, and logical id. Immutable — changing it |
| 94 | * replaces the profile. |
| 95 | */ |
| 96 | securityProfileId?: string; |
| 97 | /** |
| 98 | * Organization id or `organizations/{organization}`. If omitted, |
| 99 | * Alchemy uses `GOOGLE_ORGANIZATION_ID` or the project's Resource |
| 100 | * Manager parent. Immutable — changing it replaces the profile. |
| 101 | */ |
| 102 | organization?: string; |
| 103 | /** |
| 104 | * Location. Security profiles live in `global`. Immutable — changing |
| 105 | * it replaces the profile. |
| 106 | * @default "global" |
| 107 | */ |
| 108 | location?: string; |
| 109 | /** |
| 110 | * Profile type. Immutable — changing it replaces the profile. |
| 111 | * @default "THREAT_PREVENTION" |
| 112 | */ |
| 113 | type?: OrganizationsSecurityProfileType; |
| 114 | /** |
| 115 | * Threat prevention configuration. Used when `type` is |
| 116 | * `THREAT_PREVENTION`. |
| 117 | */ |
| 118 | threatPreventionProfile?: OrganizationsThreatPreventionProfile; |
| 119 | /** |
| 120 | * Packet mirroring configuration. Used when `type` is |
| 121 | * `CUSTOM_MIRRORING`. Immutable. |
| 122 | */ |
| 123 | customMirroringProfile?: OrganizationsCustomMirroringProfile; |
| 124 | /** |
| 125 | * URL filtering configuration. Used when `type` is `URL_FILTERING`. |
| 126 | */ |
| 127 | urlFilteringProfile?: OrganizationsUrlFilteringProfile; |
| 128 | /** |
| 129 | * Packet intercept configuration. Used when `type` is |
| 130 | * `CUSTOM_INTERCEPT`. Immutable. |
| 131 | */ |
| 132 | customInterceptProfile?: OrganizationsCustomInterceptProfile; |
| 133 | /** |
| 134 | * Human-readable description (max 512 characters). |
| 135 | */ |
| 136 | description?: string; |
| 137 | /** |
| 138 | * User labels. Alchemy ownership labels are merged in automatically. |
| 139 | */ |
| 140 | labels?: Record<string, string>; |
| 141 | }; |
| 142 | |
| 143 | export type OrganizationsSecurityProfile = Resource< |
| 144 | "GCP.NetworkSecurity.OrganizationsSecurityProfile", |
| 145 | OrganizationsSecurityProfileProps, |
| 146 | { |
| 147 | /** Full resource name `organizations/{organization}/locations/{location}/securityProfiles/{securityProfile}`. */ |
| 148 | name: string; |
| 149 | /** Security profile id (last path segment). */ |
| 150 | securityProfileId: string; |
| 151 | /** Organization id. */ |
| 152 | organization: string; |
| 153 | /** Location id. */ |
| 154 | location: string; |
| 155 | /** Profile type. */ |
| 156 | type: string; |
| 157 | /** Threat prevention configuration, if set. */ |
| 158 | threatPreventionProfile: OrganizationsThreatPreventionProfile | undefined; |
| 159 | /** Packet mirroring configuration, if set. */ |
| 160 | customMirroringProfile: OrganizationsCustomMirroringProfile | undefined; |
| 161 | /** URL filtering configuration, if set. */ |
| 162 | urlFilteringProfile: OrganizationsUrlFilteringProfile | undefined; |
| 163 | /** Packet intercept configuration, if set. */ |
| 164 | customInterceptProfile: OrganizationsCustomInterceptProfile | undefined; |
| 165 | /** User-provided description. */ |
| 166 | description: string | undefined; |
| 167 | /** User labels (Alchemy ownership labels stripped). */ |
| 168 | labels: Record<string, string>; |
| 169 | /** Server-computed checksum. */ |
| 170 | etag: string | undefined; |
| 171 | /** RFC3339 creation timestamp. */ |
| 172 | createTime: string | undefined; |
| 173 | /** RFC3339 last-update timestamp. */ |
| 174 | updateTime: string | undefined; |
| 175 | }, |
| 176 | never, |
| 177 | Providers |
| 178 | >; |
| 179 | |
| 180 | /** |
| 181 | * An organization-scoped Network Security profile (threat prevention, |
| 182 | * URL filtering, custom mirroring, or custom intercept). |
| 183 | * |
| 184 | * Changing `securityProfileId`, `organization`, `location`, `type`, or |
| 185 | * the immutable nested mirroring/intercept targets replaces the profile. |
| 186 | * Description, labels, and threat-prevention or URL-filter config update |
| 187 | * in place. |
| 188 | * |
| 189 | * ### Creating a Security Profile |
| 190 | * **Example:** Threat prevention |
| 191 | * ```typescript |
| 192 | * const profile = yield* GCP.NetworkSecurity.OrganizationsSecurityProfile( |
| 193 | * "Threats", |
| 194 | * { |
| 195 | * type: "THREAT_PREVENTION", |
| 196 | * threatPreventionProfile: { |
| 197 | * severityOverrides: [{ severity: "INFORMATIONAL", action: "ALERT" }], |
| 198 | * }, |
| 199 | * }, |
| 200 | * ); |
| 201 | * ``` |
| 202 | * |
| 203 | * @resource |
| 204 | * @category NetworkSecurity |
| 205 | */ |
| 206 | export const OrganizationsSecurityProfile = Resource<OrganizationsSecurityProfile>( |
| 207 | "GCP.NetworkSecurity.OrganizationsSecurityProfile", |
| 208 | ); |
| 209 | |
| 210 | const resourceName = (organization: string, location: string, securityProfileId: string) => |
| 211 | `organizations/${organization}/locations/${location}/securityProfiles/${securityProfileId}`; |
| 212 | |
| 213 | const typeOf = (value: string | undefined) => (value ?? DEFAULT_TYPE).toUpperCase(); |
| 214 | |
| 215 | const toThreatPrevention = ( |
| 216 | profile: networksecurity.ThreatPreventionProfile | undefined, |
| 217 | ): OrganizationsThreatPreventionProfile | undefined => { |
| 218 | if (profile === undefined) return undefined; |
| 219 | return { |
| 220 | antivirusOverrides: profile.antivirusOverrides, |
| 221 | severityOverrides: profile.severityOverrides, |
| 222 | threatOverrides: profile.threatOverrides, |
| 223 | }; |
| 224 | }; |
| 225 | |
| 226 | const toAttrs = (profile: networksecurity.SecurityProfile) => { |
| 227 | const name = profile.name ?? ""; |
| 228 | const parsed = parseResourceName(name); |
| 229 | return { |
| 230 | name, |
| 231 | securityProfileId: parsed.id, |
| 232 | organization: parsed.parentId, |
| 233 | location: parsed.location, |
| 234 | type: profile.type ?? DEFAULT_TYPE, |
| 235 | threatPreventionProfile: toThreatPrevention(profile.threatPreventionProfile), |
| 236 | customMirroringProfile: profile.customMirroringProfile, |
| 237 | urlFilteringProfile: profile.urlFilteringProfile, |
| 238 | customInterceptProfile: profile.customInterceptProfile, |
| 239 | description: profile.description, |
| 240 | labels: userLabels(profile.labels), |
| 241 | etag: profile.etag, |
| 242 | createTime: profile.createTime, |
| 243 | updateTime: profile.updateTime, |
| 244 | }; |
| 245 | }; |
| 246 | |
| 247 | const getByName = (name: string) => |
| 248 | networksecurity |
| 249 | .getOrganizationsLocationsSecurityProfiles({ name }) |
| 250 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 251 | |
| 252 | const listOwned = (organization: string) => |
| 253 | networksecurity.listOrganizationsLocationsSecurityProfiles |
| 254 | .pages({ |
| 255 | parent: organizationParent(organization, "-"), |
| 256 | pageSize: 1000, |
| 257 | }) |
| 258 | .pipe( |
| 259 | Stream.flatMap((page) => Stream.fromIterable(page.securityProfiles ?? [])), |
| 260 | Stream.filter((profile) => |
| 261 | Object.keys(profile.labels ?? {}).some((key) => key.startsWith("alchemy-")), |
| 262 | ), |
| 263 | Stream.map(toAttrs), |
| 264 | Stream.runCollect, |
| 265 | Effect.map((chunk) => Array.from(chunk)), |
| 266 | Effect.catchTag("NotFound", () => Effect.succeed([])), |
| 267 | ); |
| 268 | |
| 269 | const desiredThreatPrevention = ( |
| 270 | news: OrganizationsSecurityProfileProps, |
| 271 | type: string, |
| 272 | ): OrganizationsThreatPreventionProfile | undefined => { |
| 273 | if (type !== "THREAT_PREVENTION") return undefined; |
| 274 | return news.threatPreventionProfile ?? {}; |
| 275 | }; |
| 276 | |
| 277 | export const OrganizationsSecurityProfileProvider = () => |
| 278 | Provider.succeed(OrganizationsSecurityProfile, { |
| 279 | stables: ["name", "securityProfileId", "organization", "location", "type", "createTime"], |
| 280 | |
| 281 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 282 | if (!isResolved(news)) return undefined; |
| 283 | const previousId = olds?.securityProfileId ?? output?.securityProfileId; |
| 284 | const nextId = news.securityProfileId ?? previousId; |
| 285 | const previousOrg = olds?.organization ?? output?.organization; |
| 286 | const nextOrg = news.organization ?? previousOrg; |
| 287 | const previousLocation = normalizeLocation(olds?.location ?? output?.location); |
| 288 | const nextLocation = normalizeLocation(news.location ?? olds?.location ?? output?.location); |
| 289 | const previousType = typeOf(olds?.type ?? output?.type); |
| 290 | const nextType = typeOf(news.type ?? olds?.type ?? output?.type); |
| 291 | const previousMirror = |
| 292 | olds?.customMirroringProfile?.mirroringEndpointGroup ?? |
| 293 | output?.customMirroringProfile?.mirroringEndpointGroup; |
| 294 | const nextMirror = news.customMirroringProfile?.mirroringEndpointGroup ?? previousMirror; |
| 295 | const previousIntercept = |
| 296 | olds?.customInterceptProfile?.interceptEndpointGroup ?? |
| 297 | output?.customInterceptProfile?.interceptEndpointGroup; |
| 298 | const nextIntercept = |
| 299 | news.customInterceptProfile?.interceptEndpointGroup ?? previousIntercept; |
| 300 | const replace = |
| 301 | (previousId !== undefined && nextId !== undefined && nextId !== previousId) || |
| 302 | (previousOrg !== undefined && nextOrg !== undefined && nextOrg !== previousOrg) || |
| 303 | previousLocation !== nextLocation || |
| 304 | previousType !== nextType || |
| 305 | previousMirror !== nextMirror || |
| 306 | previousIntercept !== nextIntercept; |
| 307 | if (!replace) return undefined; |
| 308 | return { |
| 309 | action: "replace" as const, |
| 310 | deleteFirst: |
| 311 | previousLocation === nextLocation && |
| 312 | previousOrg === nextOrg && |
| 313 | previousId !== undefined && |
| 314 | nextId === previousId, |
| 315 | }; |
| 316 | }), |
| 317 | |
| 318 | read: Effect.fn(function* ({ id, olds, output }) { |
| 319 | const securityProfileId = yield* toPhysicalId( |
| 320 | id, |
| 321 | olds?.securityProfileId, |
| 322 | output?.securityProfileId, |
| 323 | "secprofile", |
| 324 | ); |
| 325 | const organization = yield* resolveOrganization( |
| 326 | olds?.organization ?? output?.organization, |
| 327 | output?.organization, |
| 328 | ).pipe( |
| 329 | Effect.catchTag("GCP.NetworkSecurity.OrganizationRequired", () => |
| 330 | Effect.succeed(output?.organization ?? ""), |
| 331 | ), |
| 332 | ); |
| 333 | const location = normalizeLocation(olds?.location ?? output?.location); |
| 334 | const name = |
| 335 | output?.name ?? |
| 336 | (organization.length > 0 ? resourceName(organization, location, securityProfileId) : ""); |
| 337 | if (name.length === 0) return undefined; |
| 338 | const existing = yield* getByName(name); |
| 339 | if (existing === undefined) return undefined; |
| 340 | const attrs = toAttrs(existing); |
| 341 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 342 | }), |
| 343 | |
| 344 | list: () => |
| 345 | Effect.gen(function* () { |
| 346 | const env = yield* GcpEnvironment.current; |
| 347 | const orgs = yield* listOrganizations(env.project); |
| 348 | const listed: OrganizationsSecurityProfile["Attributes"][] = []; |
| 349 | for (const organization of orgs) { |
| 350 | listed.push(...(yield* listOwned(organization))); |
| 351 | } |
| 352 | return listed; |
| 353 | }), |
| 354 | |
| 355 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 356 | const securityProfileId = yield* toPhysicalId( |
| 357 | id, |
| 358 | news.securityProfileId, |
| 359 | output?.securityProfileId, |
| 360 | "secprofile", |
| 361 | ); |
| 362 | const organization = yield* resolveOrganization( |
| 363 | news.organization ?? output?.organization, |
| 364 | output?.organization, |
| 365 | ); |
| 366 | const location = normalizeLocation(news.location ?? output?.location); |
| 367 | const name = resourceName(organization, location, securityProfileId); |
| 368 | const type = typeOf(news.type); |
| 369 | const threatPreventionProfile = desiredThreatPrevention(news, type); |
| 370 | const desiredLabels = { |
| 371 | ...toLabels(news.labels), |
| 372 | ...(yield* createInternalLabels(id)), |
| 373 | }; |
| 374 | |
| 375 | let current = yield* getByName(name); |
| 376 | |
| 377 | if (current === undefined) { |
| 378 | const created = yield* networksecurity |
| 379 | .createOrganizationsLocationsSecurityProfiles({ |
| 380 | parent: organizationParent(organization, location), |
| 381 | securityProfileId, |
| 382 | body: { |
| 383 | type, |
| 384 | description: news.description, |
| 385 | labels: desiredLabels, |
| 386 | threatPreventionProfile, |
| 387 | customMirroringProfile: news.customMirroringProfile, |
| 388 | urlFilteringProfile: news.urlFilteringProfile, |
| 389 | customInterceptProfile: news.customInterceptProfile, |
| 390 | }, |
| 391 | }) |
| 392 | .pipe( |
| 393 | Effect.retry({ |
| 394 | while: (error) => error._tag === "Conflict", |
| 395 | times: 5, |
| 396 | schedule: Schedule.spaced("2 seconds"), |
| 397 | }), |
| 398 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 399 | ); |
| 400 | if (created !== undefined) { |
| 401 | yield* waitForOperation(created); |
| 402 | } |
| 403 | current = yield* waitUntilExists(getByName(name), name); |
| 404 | } |
| 405 | |
| 406 | if (current === undefined) { |
| 407 | return yield* new ResourceNotResolved({ resourceName: name }); |
| 408 | } |
| 409 | |
| 410 | const observedLabels = tagRecord(current.labels); |
| 411 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 412 | const labelsChanged = upsert.length > 0 || removed.length > 0; |
| 413 | const descriptionChanged = (current.description ?? "") !== (news.description ?? ""); |
| 414 | const threatChanged = |
| 415 | type === "THREAT_PREVENTION" && |
| 416 | !sameJson( |
| 417 | toThreatPrevention(current.threatPreventionProfile) ?? {}, |
| 418 | threatPreventionProfile ?? {}, |
| 419 | ); |
| 420 | const urlChanged = |
| 421 | type === "URL_FILTERING" && |
| 422 | !sameJson(current.urlFilteringProfile, news.urlFilteringProfile); |
| 423 | |
| 424 | if (labelsChanged || descriptionChanged || threatChanged || urlChanged) { |
| 425 | const updateMask = [ |
| 426 | labelsChanged ? "labels" : undefined, |
| 427 | descriptionChanged ? "description" : undefined, |
| 428 | threatChanged ? "threatPreventionProfile" : undefined, |
| 429 | urlChanged ? "urlFilteringProfile" : undefined, |
| 430 | ].filter((field): field is string => field !== undefined); |
| 431 | |
| 432 | const operation = yield* networksecurity.patchOrganizationsLocationsSecurityProfiles({ |
| 433 | name: current.name ?? name, |
| 434 | updateMask: updateMask.join(","), |
| 435 | body: { |
| 436 | name: current.name ?? name, |
| 437 | labels: desiredLabels, |
| 438 | description: news.description, |
| 439 | threatPreventionProfile, |
| 440 | urlFilteringProfile: news.urlFilteringProfile, |
| 441 | }, |
| 442 | }); |
| 443 | yield* waitForOperation(operation); |
| 444 | current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name); |
| 445 | } |
| 446 | |
| 447 | return toAttrs(current); |
| 448 | }), |
| 449 | |
| 450 | delete: Effect.fn(function* ({ output }) { |
| 451 | const operation = yield* networksecurity |
| 452 | .deleteOrganizationsLocationsSecurityProfiles({ |
| 453 | name: output.name, |
| 454 | etag: output.etag, |
| 455 | }) |
| 456 | .pipe( |
| 457 | Effect.retry({ |
| 458 | while: (error) => error._tag === "Conflict", |
| 459 | times: 8, |
| 460 | schedule: Schedule.spaced("2 seconds"), |
| 461 | }), |
| 462 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 463 | ); |
| 464 | if (operation !== undefined) { |
| 465 | yield* waitForOperation(operation, { notFoundOk: true }); |
| 466 | } |
| 467 | yield* waitUntilGone(getByName(output.name), output.name); |
| 468 | }), |
| 469 | }); |