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 ProfileConfigCategory = { |
| 23 | /** Include mediation scoring. */ |
| 24 | mediation?: boolean; |
| 25 | /** Include abuse scoring. */ |
| 26 | abuse?: boolean; |
| 27 | /** Include authorization scoring. */ |
| 28 | authorization?: boolean; |
| 29 | /** Include mTLS scoring. */ |
| 30 | mtls?: boolean; |
| 31 | /** Include CORS scoring. */ |
| 32 | cors?: boolean; |
| 33 | /** Include threat-protection scoring. */ |
| 34 | threat?: boolean; |
| 35 | }; |
| 36 | |
| 37 | export type ProfileConfig = { |
| 38 | /** Scoring categories enabled on this profile. */ |
| 39 | categories?: ProfileConfigCategory[]; |
| 40 | }; |
| 41 | |
| 42 | export type ScoringConfig = { |
| 43 | /** Description of the scoring config. */ |
| 44 | description?: string; |
| 45 | /** Path of the component config used for scoring. */ |
| 46 | scorePath?: string; |
| 47 | /** Title of the config. */ |
| 48 | title?: string; |
| 49 | }; |
| 50 | |
| 51 | export type SecurityProfileProps = { |
| 52 | /** |
| 53 | * Apigee organization id. Defaults to the current GCP project id. |
| 54 | * Immutable — changing it replaces the profile. |
| 55 | */ |
| 56 | organization?: string; |
| 57 | /** |
| 58 | * Profile id (the `{profile}` segment of |
| 59 | * `organizations/{org}/securityProfiles/{profile}`). If omitted, a |
| 60 | * unique name is generated from the stack, stage, and logical id. |
| 61 | * 1–63 characters matching `^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$`. |
| 62 | * Immutable — changing it replaces the profile. |
| 63 | */ |
| 64 | securityProfileId?: string; |
| 65 | /** |
| 66 | * Human-readable description. Alchemy ownership is stored in a |
| 67 | * `[alchemy …]` prefix and stripped from attributes. Profiles have no |
| 68 | * labels field. |
| 69 | */ |
| 70 | description?: string; |
| 71 | /** |
| 72 | * Deprecated display name. |
| 73 | */ |
| 74 | displayName?: string; |
| 75 | /** |
| 76 | * Profile configuration used to compute the security score. |
| 77 | * @default `{ categories: [{ authorization: true, threat: true }] }` |
| 78 | */ |
| 79 | profileConfig?: ProfileConfig; |
| 80 | /** |
| 81 | * Scoring configs in this revision. |
| 82 | */ |
| 83 | scoringConfigs?: ScoringConfig[]; |
| 84 | }; |
| 85 | |
| 86 | export type SecurityProfile = Resource< |
| 87 | "GCP.Apigee.SecurityProfile", |
| 88 | SecurityProfileProps, |
| 89 | { |
| 90 | /** Full resource name `organizations/{org}/securityProfiles/{profile}`. */ |
| 91 | name: string; |
| 92 | /** Profile id (last path segment). */ |
| 93 | securityProfileId: string; |
| 94 | /** Apigee organization id. */ |
| 95 | organization: string; |
| 96 | /** User description with the Alchemy ownership prefix stripped. */ |
| 97 | description: string | undefined; |
| 98 | /** Deprecated display name. */ |
| 99 | displayName: string | undefined; |
| 100 | /** Profile configuration. */ |
| 101 | profileConfig: ProfileConfig | undefined; |
| 102 | /** Scoring configs. */ |
| 103 | scoringConfigs: ScoringConfig[]; |
| 104 | /** Attached environments. */ |
| 105 | environments: Array<{ |
| 106 | environment: string | undefined; |
| 107 | attachTime: string | undefined; |
| 108 | }>; |
| 109 | /** Minimum score this profile can generate. */ |
| 110 | minScore: number | undefined; |
| 111 | /** Maximum score this profile can generate. */ |
| 112 | maxScore: number | undefined; |
| 113 | /** Revision id. */ |
| 114 | revisionId: string | undefined; |
| 115 | /** Revision create time. */ |
| 116 | revisionCreateTime: string | undefined; |
| 117 | /** Revision update time. */ |
| 118 | revisionUpdateTime: string | undefined; |
| 119 | }, |
| 120 | never, |
| 121 | Providers |
| 122 | >; |
| 123 | |
| 124 | /** |
| 125 | * An Advanced API Security profile (v1). |
| 126 | * |
| 127 | * Profiles have no labels field, so Alchemy stamps ownership into the |
| 128 | * description for `list` / nuke. Name and organization are identity — |
| 129 | * changing them replaces the profile. Description and profile config |
| 130 | * update in place (each update creates a new revision). |
| 131 | * |
| 132 | * ### Creating a Profile |
| 133 | * **Example:** Generated name with authorization and threat categories |
| 134 | * ```typescript |
| 135 | * const profile = yield* GCP.Apigee.SecurityProfile("Baseline", { |
| 136 | * profileConfig: { |
| 137 | * categories: [{ authorization: true, threat: true }], |
| 138 | * }, |
| 139 | * }); |
| 140 | * ``` |
| 141 | * |
| 142 | * **Example:** Named profile |
| 143 | * ```typescript |
| 144 | * const profile = yield* GCP.Apigee.SecurityProfile("Baseline", { |
| 145 | * securityProfileId: "app-baseline", |
| 146 | * description: "default scoring", |
| 147 | * profileConfig: { |
| 148 | * categories: [{ authorization: true, cors: true, threat: true }], |
| 149 | * }, |
| 150 | * }); |
| 151 | * ``` |
| 152 | * |
| 153 | * @resource |
| 154 | * @category Apigee |
| 155 | */ |
| 156 | export const SecurityProfile = Resource<SecurityProfile>("GCP.Apigee.SecurityProfile"); |
| 157 | |
| 158 | export class SecurityProfileNotResolved extends Data.TaggedError( |
| 159 | "GCP.Apigee.SecurityProfileNotResolved", |
| 160 | )<{ |
| 161 | resourceName: string; |
| 162 | }> {} |
| 163 | |
| 164 | const DEFAULT_PROFILE_CONFIG: ProfileConfig = { |
| 165 | categories: [{ authorization: true, threat: true }], |
| 166 | }; |
| 167 | |
| 168 | const resourceName = (organization: string, profileId: string) => |
| 169 | `${orgParent(organization)}/securityProfiles/${profileId}`; |
| 170 | |
| 171 | const profileIdOf = (profile: apigee.GoogleCloudApigeeV1SecurityProfile) => |
| 172 | lastSegment(profile.name ?? ""); |
| 173 | |
| 174 | const flag = (value: unknown) => value !== undefined && value !== false; |
| 175 | |
| 176 | const categoryOf = ( |
| 177 | category: apigee.GoogleCloudApigeeV1ProfileConfigCategory | ProfileConfigCategory, |
| 178 | ): ProfileConfigCategory => ({ |
| 179 | mediation: flag(category.mediation) ? true : undefined, |
| 180 | abuse: flag(category.abuse) ? true : undefined, |
| 181 | authorization: flag(category.authorization) ? true : undefined, |
| 182 | mtls: flag(category.mtls) ? true : undefined, |
| 183 | cors: flag(category.cors) ? true : undefined, |
| 184 | threat: flag(category.threat) ? true : undefined, |
| 185 | }); |
| 186 | |
| 187 | const profileConfigOf = ( |
| 188 | config: apigee.GoogleCloudApigeeV1ProfileConfig | ProfileConfig | undefined, |
| 189 | ): ProfileConfig => ({ |
| 190 | categories: (config?.categories ?? DEFAULT_PROFILE_CONFIG.categories ?? []).map(categoryOf), |
| 191 | }); |
| 192 | |
| 193 | const toApiCategory = ( |
| 194 | category: ProfileConfigCategory, |
| 195 | ): apigee.GoogleCloudApigeeV1ProfileConfigCategory => ({ |
| 196 | mediation: category.mediation === true ? {} : undefined, |
| 197 | abuse: category.abuse === true ? {} : undefined, |
| 198 | authorization: category.authorization === true ? {} : undefined, |
| 199 | mtls: category.mtls === true ? {} : undefined, |
| 200 | cors: category.cors === true ? {} : undefined, |
| 201 | threat: category.threat === true ? {} : undefined, |
| 202 | }); |
| 203 | |
| 204 | const toAttrs = (profile: apigee.GoogleCloudApigeeV1SecurityProfile, organization: string) => { |
| 205 | const securityProfileId = profileIdOf(profile); |
| 206 | const name = profile.name?.includes("/") |
| 207 | ? profile.name |
| 208 | : resourceName(organization, securityProfileId); |
| 209 | const parsed = parseOwnership(profile.description); |
| 210 | return { |
| 211 | name, |
| 212 | securityProfileId, |
| 213 | organization: organizationFromName(name) ?? organization, |
| 214 | description: parsed.text, |
| 215 | displayName: profile.displayName, |
| 216 | profileConfig: profile.profileConfig ? profileConfigOf(profile.profileConfig) : undefined, |
| 217 | scoringConfigs: (profile.scoringConfigs ?? []).map((config) => ({ |
| 218 | description: config.description, |
| 219 | scorePath: config.scorePath, |
| 220 | title: config.title, |
| 221 | })), |
| 222 | environments: (profile.environments ?? []).map((environment) => ({ |
| 223 | environment: environment.environment, |
| 224 | attachTime: environment.attachTime, |
| 225 | })), |
| 226 | minScore: profile.minScore, |
| 227 | maxScore: profile.maxScore, |
| 228 | revisionId: profile.revisionId, |
| 229 | revisionCreateTime: profile.revisionCreateTime, |
| 230 | revisionUpdateTime: profile.revisionUpdateTime, |
| 231 | }; |
| 232 | }; |
| 233 | |
| 234 | const getByName = (name: string) => |
| 235 | apigee |
| 236 | .getOrganizationsSecurityProfiles({ name }) |
| 237 | .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined)); |
| 238 | |
| 239 | const toBody = ( |
| 240 | news: SecurityProfileProps, |
| 241 | description: string, |
| 242 | ): apigee.GoogleCloudApigeeV1SecurityProfile => { |
| 243 | const config = profileConfigOf(news.profileConfig ?? DEFAULT_PROFILE_CONFIG); |
| 244 | return { |
| 245 | description, |
| 246 | displayName: news.displayName, |
| 247 | profileConfig: { |
| 248 | categories: (config.categories ?? []).map(toApiCategory), |
| 249 | }, |
| 250 | scoringConfigs: news.scoringConfigs, |
| 251 | }; |
| 252 | }; |
| 253 | |
| 254 | export const SecurityProfileProvider = () => |
| 255 | Provider.succeed(SecurityProfile, { |
| 256 | stables: ["name", "securityProfileId", "organization"], |
| 257 | |
| 258 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 259 | if (!isResolved(news)) return undefined; |
| 260 | const previousId = olds?.securityProfileId ?? output?.securityProfileId; |
| 261 | const previousOrg = olds?.organization ?? output?.organization; |
| 262 | if ( |
| 263 | (previousId !== undefined && |
| 264 | news.securityProfileId !== undefined && |
| 265 | news.securityProfileId !== previousId) || |
| 266 | (previousOrg !== undefined && |
| 267 | news.organization !== undefined && |
| 268 | news.organization !== previousOrg) |
| 269 | ) { |
| 270 | return { action: "replace" as const, deleteFirst: true }; |
| 271 | } |
| 272 | return undefined; |
| 273 | }), |
| 274 | |
| 275 | read: Effect.fn(function* ({ id, olds, output, previous }) { |
| 276 | const env = yield* GcpEnvironment.current; |
| 277 | const organization = organizationFromName(output?.name) ?? olds?.organization ?? env.project; |
| 278 | const securityProfileId = yield* toResourceId( |
| 279 | id, |
| 280 | olds?.securityProfileId, |
| 281 | output?.securityProfileId, |
| 282 | MAX_NAME_LENGTH, |
| 283 | ); |
| 284 | const name = output?.name ?? resourceName(organization, securityProfileId); |
| 285 | const existing = yield* getByName(name); |
| 286 | if (existing === undefined) return undefined; |
| 287 | const attrs = toAttrs(existing, organization); |
| 288 | const { labels } = parseOwnership(existing.description); |
| 289 | return (yield* hasAlchemyLabels(id, labels)) |
| 290 | ? attrs |
| 291 | : unownedUnlessPrevious(attrs, previous, "name"); |
| 292 | }), |
| 293 | |
| 294 | list: () => |
| 295 | Effect.gen(function* () { |
| 296 | const env = yield* GcpEnvironment.current; |
| 297 | return yield* apigee.listOrganizationsSecurityProfiles |
| 298 | .pages({ |
| 299 | parent: orgParent(env.project), |
| 300 | pageSize: 50, |
| 301 | }) |
| 302 | .pipe( |
| 303 | Stream.flatMap((page) => Stream.fromIterable(page.securityProfiles ?? [])), |
| 304 | Stream.filter((profile) => hasOwnershipMarker(profile.description)), |
| 305 | Stream.map((profile) => toAttrs(profile, env.project)), |
| 306 | Stream.runCollect, |
| 307 | Effect.map((chunk) => Array.from(chunk)), |
| 308 | Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => |
| 309 | Effect.succeed([] as SecurityProfile["Attributes"][]), |
| 310 | ), |
| 311 | ); |
| 312 | }), |
| 313 | |
| 314 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 315 | const env = yield* GcpEnvironment.current; |
| 316 | const organization = news.organization ?? output?.organization ?? env.project; |
| 317 | const securityProfileId = yield* toResourceId( |
| 318 | id, |
| 319 | news.securityProfileId, |
| 320 | output?.securityProfileId, |
| 321 | MAX_NAME_LENGTH, |
| 322 | ); |
| 323 | const name = resourceName(organization, securityProfileId); |
| 324 | const ownership = yield* createInternalLabels(id); |
| 325 | const desiredDescription = encodeOwnership(ownership, news.description); |
| 326 | const desiredConfig = profileConfigOf(news.profileConfig ?? DEFAULT_PROFILE_CONFIG); |
| 327 | |
| 328 | let current = yield* getByName(output?.name ?? name); |
| 329 | |
| 330 | if (current === undefined) { |
| 331 | const created = yield* apigee |
| 332 | .createOrganizationsSecurityProfiles({ |
| 333 | parent: orgParent(organization), |
| 334 | securityProfileId, |
| 335 | body: toBody(news, desiredDescription), |
| 336 | }) |
| 337 | .pipe(Effect.catchTag("Conflict", () => getByName(name))); |
| 338 | current = created ?? undefined; |
| 339 | } |
| 340 | |
| 341 | if (current === undefined) { |
| 342 | return yield* new SecurityProfileNotResolved({ resourceName: name }); |
| 343 | } |
| 344 | |
| 345 | const descriptionChanged = (current.description ?? "") !== desiredDescription; |
| 346 | const displayChanged = (current.displayName ?? "") !== (news.displayName ?? ""); |
| 347 | const configChanged = !sameJson(profileConfigOf(current.profileConfig), desiredConfig); |
| 348 | const scoringChanged = !sameJson( |
| 349 | current.scoringConfigs ?? [], |
| 350 | news.scoringConfigs ?? current.scoringConfigs ?? [], |
| 351 | ); |
| 352 | |
| 353 | const updateMask = [ |
| 354 | descriptionChanged ? "description" : undefined, |
| 355 | displayChanged ? "displayName" : undefined, |
| 356 | configChanged ? "profileConfig" : undefined, |
| 357 | scoringChanged ? "scoringConfigs" : undefined, |
| 358 | ].filter((field): field is string => field !== undefined); |
| 359 | |
| 360 | if (updateMask.length > 0) { |
| 361 | current = yield* apigee.patchOrganizationsSecurityProfiles({ |
| 362 | name: current.name?.includes("/") ? current.name : name, |
| 363 | updateMask: updateMask.join(","), |
| 364 | body: toBody(news, desiredDescription), |
| 365 | }); |
| 366 | } |
| 367 | |
| 368 | return toAttrs(current, organization); |
| 369 | }), |
| 370 | |
| 371 | delete: Effect.fn(function* ({ output }) { |
| 372 | yield* apigee |
| 373 | .deleteOrganizationsSecurityProfiles({ name: output.name }) |
| 374 | .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void)); |
| 375 | }), |
| 376 | }); |