The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as apigee from "@distilled.cloud/gcp/apigee_v1"; |
| 2 | import { unownedUnlessPrevious } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import * as Data from "effect/Data"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Stream from "effect/Stream"; |
| 9 | import { GcpEnvironment } from "../Environment.ts"; |
| 10 | import type { Providers } from "../Providers.ts"; |
| 11 | import { lastSegment, orgParent, organizationFromName, sameJson, toResourceId } from "./names.ts"; |
| 12 | import { |
| 13 | createInternalLabels, |
| 14 | encodeOwnership, |
| 15 | hasAlchemyLabels, |
| 16 | hasOwnershipMarker, |
| 17 | parseOwnership, |
| 18 | } from "./ownership.ts"; |
| 19 | |
| 20 | const MAX_NAME_LENGTH = 63; |
| 21 | |
| 22 | export type ProfileAssessmentConfig = { |
| 23 | /** |
| 24 | * Weight of this assessment. |
| 25 | */ |
| 26 | weight?: |
| 27 | | apigee.GoogleCloudApigeeV1SecurityProfileV2ProfileAssessmentConfigWeightEnum |
| 28 | | (string & {}); |
| 29 | /** |
| 30 | * API Hub gateway types to include. |
| 31 | */ |
| 32 | include?: Array< |
| 33 | | apigee.GoogleCloudApigeeV1SecurityProfileV2ProfileAssessmentConfigApiHubGatewayTypeArrayGatewayTypesItemEnum |
| 34 | | (string & {}) |
| 35 | >; |
| 36 | }; |
| 37 | |
| 38 | export type SecurityProfilesV2Props = { |
| 39 | /** |
| 40 | * Apigee organization id. Defaults to the current GCP project id. |
| 41 | * Immutable — changing it replaces the profile. |
| 42 | */ |
| 43 | organization?: string; |
| 44 | /** |
| 45 | * Profile id (the `{profile}` segment of |
| 46 | * `organizations/{org}/securityProfilesV2/{profile}`). If omitted, a |
| 47 | * unique name is generated from the stack, stage, and logical id. |
| 48 | * Immutable — changing it replaces the profile. |
| 49 | */ |
| 50 | securityProfileV2Id?: string; |
| 51 | /** |
| 52 | * Human-readable description. Alchemy ownership is stored in a |
| 53 | * `[alchemy …]` prefix and stripped from attributes. Profiles have no |
| 54 | * labels field. |
| 55 | */ |
| 56 | description?: string; |
| 57 | /** |
| 58 | * Risk assessment type. |
| 59 | * @default "APIGEE" |
| 60 | */ |
| 61 | riskAssessmentType?: |
| 62 | | apigee.GoogleCloudApigeeV1SecurityProfileV2RiskAssessmentTypeEnum |
| 63 | | (string & {}); |
| 64 | /** |
| 65 | * Configuration for each assessment, keyed by assessment id. |
| 66 | * @default `{ authorization: { weight: "MODERATE" }, threat: { weight: "MODERATE" } }` |
| 67 | */ |
| 68 | profileAssessmentConfigs?: Record<string, ProfileAssessmentConfig>; |
| 69 | }; |
| 70 | |
| 71 | export type SecurityProfilesV2 = Resource< |
| 72 | "GCP.Apigee.SecurityProfilesV2", |
| 73 | SecurityProfilesV2Props, |
| 74 | { |
| 75 | /** Full resource name `organizations/{org}/securityProfilesV2/{profile}`. */ |
| 76 | name: string; |
| 77 | /** Profile id (last path segment). */ |
| 78 | securityProfileV2Id: string; |
| 79 | /** Apigee organization id. */ |
| 80 | organization: string; |
| 81 | /** User description with the Alchemy ownership prefix stripped. */ |
| 82 | description: string | undefined; |
| 83 | /** Risk assessment type. */ |
| 84 | riskAssessmentType: string | undefined; |
| 85 | /** Assessment configuration map. */ |
| 86 | profileAssessmentConfigs: Record<string, ProfileAssessmentConfig>; |
| 87 | /** Whether this profile is Google-defined. */ |
| 88 | googleDefined: boolean | undefined; |
| 89 | /** RFC3339 creation timestamp. */ |
| 90 | createTime: string | undefined; |
| 91 | /** RFC3339 last-update timestamp. */ |
| 92 | updateTime: string | undefined; |
| 93 | }, |
| 94 | never, |
| 95 | Providers |
| 96 | >; |
| 97 | |
| 98 | /** |
| 99 | * An Advanced API Security profile (risk assessment v2). |
| 100 | * |
| 101 | * Profiles have no labels field, so Alchemy stamps ownership into the |
| 102 | * description for `list` / nuke. Google-defined profiles are ignored by |
| 103 | * `list`. Name and organization are identity — changing them replaces |
| 104 | * the profile. Description and assessment configs update in place. |
| 105 | * |
| 106 | * ### Creating a Profile |
| 107 | * **Example:** Generated name with default assessments |
| 108 | * ```typescript |
| 109 | * const profile = yield* GCP.Apigee.SecurityProfilesV2("Baseline", {}); |
| 110 | * ``` |
| 111 | * |
| 112 | * **Example:** Named profile with explicit weights |
| 113 | * ```typescript |
| 114 | * const profile = yield* GCP.Apigee.SecurityProfilesV2("Baseline", { |
| 115 | * securityProfileV2Id: "app-baseline", |
| 116 | * description: "production scoring", |
| 117 | * profileAssessmentConfigs: { |
| 118 | * authorization: { weight: "MAJOR" }, |
| 119 | * threat: { weight: "MODERATE" }, |
| 120 | * cors: { weight: "MINOR" }, |
| 121 | * }, |
| 122 | * }); |
| 123 | * ``` |
| 124 | * |
| 125 | * @resource |
| 126 | * @category Apigee |
| 127 | */ |
| 128 | export const SecurityProfilesV2 = Resource<SecurityProfilesV2>("GCP.Apigee.SecurityProfilesV2"); |
| 129 | |
| 130 | export class SecurityProfilesV2NotResolved extends Data.TaggedError( |
| 131 | "GCP.Apigee.SecurityProfilesV2NotResolved", |
| 132 | )<{ |
| 133 | resourceName: string; |
| 134 | }> {} |
| 135 | |
| 136 | const DEFAULT_ASSESSMENTS: Record<string, ProfileAssessmentConfig> = { |
| 137 | authorization: { weight: "MODERATE" }, |
| 138 | threat: { weight: "MODERATE" }, |
| 139 | }; |
| 140 | |
| 141 | const resourceName = (organization: string, profileId: string) => |
| 142 | `${orgParent(organization)}/securityProfilesV2/${profileId}`; |
| 143 | |
| 144 | const profileIdOf = (profile: apigee.GoogleCloudApigeeV1SecurityProfileV2) => |
| 145 | lastSegment(profile.name ?? ""); |
| 146 | |
| 147 | const configsOf = ( |
| 148 | configs: |
| 149 | | apigee.GoogleCloudApigeeV1SecurityProfileV2ProfileAssessmentConfigMap |
| 150 | | Record<string, ProfileAssessmentConfig> |
| 151 | | undefined, |
| 152 | ): Record<string, ProfileAssessmentConfig> => { |
| 153 | const result: Record<string, ProfileAssessmentConfig> = {}; |
| 154 | for (const [key, value] of Object.entries(configs ?? {})) { |
| 155 | if (value === undefined) continue; |
| 156 | result[key] = { |
| 157 | weight: value.weight, |
| 158 | include: value.include?.gatewayTypes |
| 159 | ? [...value.include.gatewayTypes] |
| 160 | : "include" in value && Array.isArray(value.include) |
| 161 | ? [...value.include] |
| 162 | : undefined, |
| 163 | }; |
| 164 | } |
| 165 | return result; |
| 166 | }; |
| 167 | |
| 168 | const toApiConfigs = ( |
| 169 | configs: Record<string, ProfileAssessmentConfig>, |
| 170 | ): apigee.GoogleCloudApigeeV1SecurityProfileV2ProfileAssessmentConfigMap => { |
| 171 | const result: apigee.GoogleCloudApigeeV1SecurityProfileV2ProfileAssessmentConfigMap = {}; |
| 172 | for (const [key, value] of Object.entries(configs)) { |
| 173 | result[key] = { |
| 174 | weight: value.weight, |
| 175 | include: value.include !== undefined ? { gatewayTypes: value.include } : undefined, |
| 176 | }; |
| 177 | } |
| 178 | return result; |
| 179 | }; |
| 180 | |
| 181 | const toAttrs = (profile: apigee.GoogleCloudApigeeV1SecurityProfileV2, organization: string) => { |
| 182 | const securityProfileV2Id = profileIdOf(profile); |
| 183 | const name = profile.name?.includes("/") |
| 184 | ? profile.name |
| 185 | : resourceName(organization, securityProfileV2Id); |
| 186 | const parsed = parseOwnership(profile.description); |
| 187 | return { |
| 188 | name, |
| 189 | securityProfileV2Id, |
| 190 | organization: organizationFromName(name) ?? organization, |
| 191 | description: parsed.text, |
| 192 | riskAssessmentType: profile.riskAssessmentType, |
| 193 | profileAssessmentConfigs: configsOf(profile.profileAssessmentConfigs), |
| 194 | googleDefined: profile.googleDefined, |
| 195 | createTime: profile.createTime, |
| 196 | updateTime: profile.updateTime, |
| 197 | }; |
| 198 | }; |
| 199 | |
| 200 | const getByName = (name: string) => |
| 201 | apigee |
| 202 | .getOrganizationsSecurityProfilesV2({ name }) |
| 203 | .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined)); |
| 204 | |
| 205 | const toBody = ( |
| 206 | news: SecurityProfilesV2Props, |
| 207 | description: string, |
| 208 | ): apigee.GoogleCloudApigeeV1SecurityProfileV2 => ({ |
| 209 | description, |
| 210 | riskAssessmentType: news.riskAssessmentType, |
| 211 | profileAssessmentConfigs: toApiConfigs(news.profileAssessmentConfigs ?? DEFAULT_ASSESSMENTS), |
| 212 | }); |
| 213 | |
| 214 | export const SecurityProfilesV2Provider = () => |
| 215 | Provider.succeed(SecurityProfilesV2, { |
| 216 | stables: ["name", "securityProfileV2Id", "organization", "createTime"], |
| 217 | |
| 218 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 219 | if (!isResolved(news)) return undefined; |
| 220 | const previousId = olds?.securityProfileV2Id ?? output?.securityProfileV2Id; |
| 221 | const previousOrg = olds?.organization ?? output?.organization; |
| 222 | if ( |
| 223 | (previousId !== undefined && |
| 224 | news.securityProfileV2Id !== undefined && |
| 225 | news.securityProfileV2Id !== previousId) || |
| 226 | (previousOrg !== undefined && |
| 227 | news.organization !== undefined && |
| 228 | news.organization !== previousOrg) |
| 229 | ) { |
| 230 | return { action: "replace" as const, deleteFirst: true }; |
| 231 | } |
| 232 | return undefined; |
| 233 | }), |
| 234 | |
| 235 | read: Effect.fn(function* ({ id, olds, output, previous }) { |
| 236 | const env = yield* GcpEnvironment.current; |
| 237 | const organization = organizationFromName(output?.name) ?? olds?.organization ?? env.project; |
| 238 | const securityProfileV2Id = yield* toResourceId( |
| 239 | id, |
| 240 | olds?.securityProfileV2Id, |
| 241 | output?.securityProfileV2Id, |
| 242 | MAX_NAME_LENGTH, |
| 243 | ); |
| 244 | const name = output?.name ?? resourceName(organization, securityProfileV2Id); |
| 245 | const existing = yield* getByName(name); |
| 246 | if (existing === undefined) return undefined; |
| 247 | const attrs = toAttrs(existing, organization); |
| 248 | const { labels } = parseOwnership(existing.description); |
| 249 | return (yield* hasAlchemyLabels(id, labels)) |
| 250 | ? attrs |
| 251 | : unownedUnlessPrevious(attrs, previous, "name"); |
| 252 | }), |
| 253 | |
| 254 | list: () => |
| 255 | Effect.gen(function* () { |
| 256 | const env = yield* GcpEnvironment.current; |
| 257 | return yield* apigee.listOrganizationsSecurityProfilesV2 |
| 258 | .pages({ |
| 259 | parent: orgParent(env.project), |
| 260 | pageSize: 1000, |
| 261 | }) |
| 262 | .pipe( |
| 263 | Stream.flatMap((page) => Stream.fromIterable(page.securityProfilesV2 ?? [])), |
| 264 | Stream.filter( |
| 265 | (profile) => |
| 266 | profile.googleDefined !== true && hasOwnershipMarker(profile.description), |
| 267 | ), |
| 268 | Stream.map((profile) => toAttrs(profile, env.project)), |
| 269 | Stream.runCollect, |
| 270 | Effect.map((chunk) => Array.from(chunk)), |
| 271 | Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => |
| 272 | Effect.succeed([] as SecurityProfilesV2["Attributes"][]), |
| 273 | ), |
| 274 | ); |
| 275 | }), |
| 276 | |
| 277 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 278 | const env = yield* GcpEnvironment.current; |
| 279 | const organization = news.organization ?? output?.organization ?? env.project; |
| 280 | const securityProfileV2Id = yield* toResourceId( |
| 281 | id, |
| 282 | news.securityProfileV2Id, |
| 283 | output?.securityProfileV2Id, |
| 284 | MAX_NAME_LENGTH, |
| 285 | ); |
| 286 | const name = resourceName(organization, securityProfileV2Id); |
| 287 | const ownership = yield* createInternalLabels(id); |
| 288 | const desiredDescription = encodeOwnership(ownership, news.description); |
| 289 | const desiredConfigs = configsOf(news.profileAssessmentConfigs ?? DEFAULT_ASSESSMENTS); |
| 290 | |
| 291 | let current = yield* getByName(output?.name ?? name); |
| 292 | |
| 293 | if (current === undefined) { |
| 294 | const created = yield* apigee |
| 295 | .createOrganizationsSecurityProfilesV2({ |
| 296 | parent: orgParent(organization), |
| 297 | securityProfileV2Id, |
| 298 | body: toBody(news, desiredDescription), |
| 299 | }) |
| 300 | .pipe(Effect.catchTag("Conflict", () => getByName(name))); |
| 301 | current = created ?? undefined; |
| 302 | } |
| 303 | |
| 304 | if (current === undefined) { |
| 305 | return yield* new SecurityProfilesV2NotResolved({ resourceName: name }); |
| 306 | } |
| 307 | |
| 308 | const descriptionChanged = (current.description ?? "") !== desiredDescription; |
| 309 | const configsChanged = !sameJson(configsOf(current.profileAssessmentConfigs), desiredConfigs); |
| 310 | const typeChanged = |
| 311 | news.riskAssessmentType !== undefined && |
| 312 | (current.riskAssessmentType ?? "") !== news.riskAssessmentType; |
| 313 | |
| 314 | const updateMask = [ |
| 315 | descriptionChanged ? "description" : undefined, |
| 316 | configsChanged ? "profileAssessmentConfigs" : undefined, |
| 317 | typeChanged ? "riskAssessmentType" : undefined, |
| 318 | ].filter((field): field is string => field !== undefined); |
| 319 | |
| 320 | if (updateMask.length > 0) { |
| 321 | current = yield* apigee.patchOrganizationsSecurityProfilesV2({ |
| 322 | name: current.name?.includes("/") ? current.name : name, |
| 323 | updateMask: updateMask.join(","), |
| 324 | body: toBody(news, desiredDescription), |
| 325 | }); |
| 326 | } |
| 327 | |
| 328 | return toAttrs(current, organization); |
| 329 | }), |
| 330 | |
| 331 | delete: Effect.fn(function* ({ output }) { |
| 332 | yield* apigee |
| 333 | .deleteOrganizationsSecurityProfilesV2({ name: output.name }) |
| 334 | .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void)); |
| 335 | }), |
| 336 | }); |