sailfork / t3code-github / .repos/ alchemy-effect/ packages/ gcp/ src/ Apigee/ SecurityProfile.ts

import * as apigee from "@distilled.cloud/gcp/apigee_v1";
import { unownedUnlessPrevious } from "alchemy/AdoptPolicy";
import { isResolved } from "alchemy/Diff";
import * as Provider from "alchemy/Provider";
import { Resource } from "alchemy/Resource";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { GcpEnvironment } from "../Environment.ts";
import type { Providers } from "../Providers.ts";
import { lastSegment, orgParent, organizationFromName, sameJson, toResourceId } from "./names.ts";
import {
  createInternalLabels,
  encodeOwnership,
  hasAlchemyLabels,
  hasOwnershipMarker,
  parseOwnership,
} from "./ownership.ts";

const MAX_NAME_LENGTH = 63;

export type ProfileConfigCategory = {
  /** Include mediation scoring. */
  mediation?: boolean;
  /** Include abuse scoring. */
  abuse?: boolean;
  /** Include authorization scoring. */
  authorization?: boolean;
  /** Include mTLS scoring. */
  mtls?: boolean;
  /** Include CORS scoring. */
  cors?: boolean;
  /** Include threat-protection scoring. */
  threat?: boolean;
};

export type ProfileConfig = {
  /** Scoring categories enabled on this profile. */
  categories?: ProfileConfigCategory[];
};

export type ScoringConfig = {
  /** Description of the scoring config. */
  description?: string;
  /** Path of the component config used for scoring. */
  scorePath?: string;
  /** Title of the config. */
  title?: string;
};

export type SecurityProfileProps = {
  /**
   * Apigee organization id. Defaults to the current GCP project id.
   * Immutable — changing it replaces the profile.
   */
  organization?: string;
  /**
   * Profile id (the `{profile}` segment of
   * `organizations/{org}/securityProfiles/{profile}`). If omitted, a
   * unique name is generated from the stack, stage, and logical id.
   * 1–63 characters matching `^[a-z]([a-z0-9-]{0,61}[a-z0-9])?

	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	.repos/alchemy-effect/packages/gcp/src/Apigee/SecurityProfile.ts at main · sailfork/t3code-github · Sailfork
	
		
. * Immutable — changing it replaces the profile. */ securityProfileId?: string; /** * Human-readable description. Alchemy ownership is stored in a * `[alchemy …]` prefix and stripped from attributes. Profiles have no * labels field. */ description?: string; /** * Deprecated display name. */ displayName?: string; /** * Profile configuration used to compute the security score. * @default `{ categories: [{ authorization: true, threat: true }] }` */ profileConfig?: ProfileConfig; /** * Scoring configs in this revision. */ scoringConfigs?: ScoringConfig[]; }; export type SecurityProfile = Resource< "GCP.Apigee.SecurityProfile", SecurityProfileProps, { /** Full resource name `organizations/{org}/securityProfiles/{profile}`. */ name: string; /** Profile id (last path segment). */ securityProfileId: string; /** Apigee organization id. */ organization: string; /** User description with the Alchemy ownership prefix stripped. */ description: string | undefined; /** Deprecated display name. */ displayName: string | undefined; /** Profile configuration. */ profileConfig: ProfileConfig | undefined; /** Scoring configs. */ scoringConfigs: ScoringConfig[]; /** Attached environments. */ environments: Array<{ environment: string | undefined; attachTime: string | undefined; }>; /** Minimum score this profile can generate. */ minScore: number | undefined; /** Maximum score this profile can generate. */ maxScore: number | undefined; /** Revision id. */ revisionId: string | undefined; /** Revision create time. */ revisionCreateTime: string | undefined; /** Revision update time. */ revisionUpdateTime: string | undefined; }, never, Providers >; /** * An Advanced API Security profile (v1). * * Profiles have no labels field, so Alchemy stamps ownership into the * description for `list` / nuke. Name and organization are identity — * changing them replaces the profile. Description and profile config * update in place (each update creates a new revision). * * ### Creating a Profile * **Example:** Generated name with authorization and threat categories * ```typescript * const profile = yield* GCP.Apigee.SecurityProfile("Baseline", { * profileConfig: { * categories: [{ authorization: true, threat: true }], * }, * }); * ``` * * **Example:** Named profile * ```typescript * const profile = yield* GCP.Apigee.SecurityProfile("Baseline", { * securityProfileId: "app-baseline", * description: "default scoring", * profileConfig: { * categories: [{ authorization: true, cors: true, threat: true }], * }, * }); * ``` * * @resource * @category Apigee */ export const SecurityProfile = Resource<SecurityProfile>("GCP.Apigee.SecurityProfile"); export class SecurityProfileNotResolved extends Data.TaggedError( "GCP.Apigee.SecurityProfileNotResolved", )<{ resourceName: string; }> {} const DEFAULT_PROFILE_CONFIG: ProfileConfig = { categories: [{ authorization: true, threat: true }], }; const resourceName = (organization: string, profileId: string) => `${orgParent(organization)}/securityProfiles/${profileId}`; const profileIdOf = (profile: apigee.GoogleCloudApigeeV1SecurityProfile) => lastSegment(profile.name ?? ""); const flag = (value: unknown) => value !== undefined && value !== false; const categoryOf = ( category: apigee.GoogleCloudApigeeV1ProfileConfigCategory | ProfileConfigCategory, ): ProfileConfigCategory => ({ mediation: flag(category.mediation) ? true : undefined, abuse: flag(category.abuse) ? true : undefined, authorization: flag(category.authorization) ? true : undefined, mtls: flag(category.mtls) ? true : undefined, cors: flag(category.cors) ? true : undefined, threat: flag(category.threat) ? true : undefined, }); const profileConfigOf = ( config: apigee.GoogleCloudApigeeV1ProfileConfig | ProfileConfig | undefined, ): ProfileConfig => ({ categories: (config?.categories ?? DEFAULT_PROFILE_CONFIG.categories ?? []).map(categoryOf), }); const toApiCategory = ( category: ProfileConfigCategory, ): apigee.GoogleCloudApigeeV1ProfileConfigCategory => ({ mediation: category.mediation === true ? {} : undefined, abuse: category.abuse === true ? {} : undefined, authorization: category.authorization === true ? {} : undefined, mtls: category.mtls === true ? {} : undefined, cors: category.cors === true ? {} : undefined, threat: category.threat === true ? {} : undefined, }); const toAttrs = (profile: apigee.GoogleCloudApigeeV1SecurityProfile, organization: string) => { const securityProfileId = profileIdOf(profile); const name = profile.name?.includes("/") ? profile.name : resourceName(organization, securityProfileId); const parsed = parseOwnership(profile.description); return { name, securityProfileId, organization: organizationFromName(name) ?? organization, description: parsed.text, displayName: profile.displayName, profileConfig: profile.profileConfig ? profileConfigOf(profile.profileConfig) : undefined, scoringConfigs: (profile.scoringConfigs ?? []).map((config) => ({ description: config.description, scorePath: config.scorePath, title: config.title, })), environments: (profile.environments ?? []).map((environment) => ({ environment: environment.environment, attachTime: environment.attachTime, })), minScore: profile.minScore, maxScore: profile.maxScore, revisionId: profile.revisionId, revisionCreateTime: profile.revisionCreateTime, revisionUpdateTime: profile.revisionUpdateTime, }; }; const getByName = (name: string) => apigee .getOrganizationsSecurityProfiles({ name }) .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined)); const toBody = ( news: SecurityProfileProps, description: string, ): apigee.GoogleCloudApigeeV1SecurityProfile => { const config = profileConfigOf(news.profileConfig ?? DEFAULT_PROFILE_CONFIG); return { description, displayName: news.displayName, profileConfig: { categories: (config.categories ?? []).map(toApiCategory), }, scoringConfigs: news.scoringConfigs, }; }; export const SecurityProfileProvider = () => Provider.succeed(SecurityProfile, { stables: ["name", "securityProfileId", "organization"], diff: Effect.fn(function* ({ news, olds, output }) { if (!isResolved(news)) return undefined; const previousId = olds?.securityProfileId ?? output?.securityProfileId; const previousOrg = olds?.organization ?? output?.organization; if ( (previousId !== undefined && news.securityProfileId !== undefined && news.securityProfileId !== previousId) || (previousOrg !== undefined && news.organization !== undefined && news.organization !== previousOrg) ) { return { action: "replace" as const, deleteFirst: true }; } return undefined; }), read: Effect.fn(function* ({ id, olds, output, previous }) { const env = yield* GcpEnvironment.current; const organization = organizationFromName(output?.name) ?? olds?.organization ?? env.project; const securityProfileId = yield* toResourceId( id, olds?.securityProfileId, output?.securityProfileId, MAX_NAME_LENGTH, ); const name = output?.name ?? resourceName(organization, securityProfileId); const existing = yield* getByName(name); if (existing === undefined) return undefined; const attrs = toAttrs(existing, organization); const { labels } = parseOwnership(existing.description); return (yield* hasAlchemyLabels(id, labels)) ? attrs : unownedUnlessPrevious(attrs, previous, "name"); }), list: () => Effect.gen(function* () { const env = yield* GcpEnvironment.current; return yield* apigee.listOrganizationsSecurityProfiles .pages({ parent: orgParent(env.project), pageSize: 50, }) .pipe( Stream.flatMap((page) => Stream.fromIterable(page.securityProfiles ?? [])), Stream.filter((profile) => hasOwnershipMarker(profile.description)), Stream.map((profile) => toAttrs(profile, env.project)), Stream.runCollect, Effect.map((chunk) => Array.from(chunk)), Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.succeed([] as SecurityProfile["Attributes"][]), ), ); }), reconcile: Effect.fn(function* ({ id, news, output }) { const env = yield* GcpEnvironment.current; const organization = news.organization ?? output?.organization ?? env.project; const securityProfileId = yield* toResourceId( id, news.securityProfileId, output?.securityProfileId, MAX_NAME_LENGTH, ); const name = resourceName(organization, securityProfileId); const ownership = yield* createInternalLabels(id); const desiredDescription = encodeOwnership(ownership, news.description); const desiredConfig = profileConfigOf(news.profileConfig ?? DEFAULT_PROFILE_CONFIG); let current = yield* getByName(output?.name ?? name); if (current === undefined) { const created = yield* apigee .createOrganizationsSecurityProfiles({ parent: orgParent(organization), securityProfileId, body: toBody(news, desiredDescription), }) .pipe(Effect.catchTag("Conflict", () => getByName(name))); current = created ?? undefined; } if (current === undefined) { return yield* new SecurityProfileNotResolved({ resourceName: name }); } const descriptionChanged = (current.description ?? "") !== desiredDescription; const displayChanged = (current.displayName ?? "") !== (news.displayName ?? ""); const configChanged = !sameJson(profileConfigOf(current.profileConfig), desiredConfig); const scoringChanged = !sameJson( current.scoringConfigs ?? [], news.scoringConfigs ?? current.scoringConfigs ?? [], ); const updateMask = [ descriptionChanged ? "description" : undefined, displayChanged ? "displayName" : undefined, configChanged ? "profileConfig" : undefined, scoringChanged ? "scoringConfigs" : undefined, ].filter((field): field is string => field !== undefined); if (updateMask.length > 0) { current = yield* apigee.patchOrganizationsSecurityProfiles({ name: current.name?.includes("/") ? current.name : name, updateMask: updateMask.join(","), body: toBody(news, desiredDescription), }); } return toAttrs(current, organization); }), delete: Effect.fn(function* ({ output }) { yield* apigee .deleteOrganizationsSecurityProfiles({ name: output.name }) .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void)); }), });
.repos/alchemy-effect/packages/gcp/src/Apigee/SecurityProfile.ts at main · sailfork/t3code-github · Sailfork
.\n * Immutable — changing it replaces the profile.\n */\n securityProfileId?: string;\n /**\n * Human-readable description. Alchemy ownership is stored in a\n * `[alchemy …]` prefix and stripped from attributes. Profiles have no\n * labels field.\n */\n description?: string;\n /**\n * Deprecated display name.\n */\n displayName?: string;\n /**\n * Profile configuration used to compute the security score.\n * @default `{ categories: [{ authorization: true, threat: true }] }`\n */\n profileConfig?: ProfileConfig;\n /**\n * Scoring configs in this revision.\n */\n scoringConfigs?: ScoringConfig[];\n};\n\nexport type SecurityProfile = Resource\u003c\n \"GCP.Apigee.SecurityProfile\",\n SecurityProfileProps,\n {\n /** Full resource name `organizations/{org}/securityProfiles/{profile}`. */\n name: string;\n /** Profile id (last path segment). */\n securityProfileId: string;\n /** Apigee organization id. */\n organization: string;\n /** User description with the Alchemy ownership prefix stripped. */\n description: string | undefined;\n /** Deprecated display name. */\n displayName: string | undefined;\n /** Profile configuration. */\n profileConfig: ProfileConfig | undefined;\n /** Scoring configs. */\n scoringConfigs: ScoringConfig[];\n /** Attached environments. */\n environments: Array\u003c{\n environment: string | undefined;\n attachTime: string | undefined;\n }>;\n /** Minimum score this profile can generate. */\n minScore: number | undefined;\n /** Maximum score this profile can generate. */\n maxScore: number | undefined;\n /** Revision id. */\n revisionId: string | undefined;\n /** Revision create time. */\n revisionCreateTime: string | undefined;\n /** Revision update time. */\n revisionUpdateTime: string | undefined;\n },\n never,\n Providers\n>;\n\n/**\n * An Advanced API Security profile (v1).\n *\n * Profiles have no labels field, so Alchemy stamps ownership into the\n * description for `list` / nuke. Name and organization are identity —\n * changing them replaces the profile. Description and profile config\n * update in place (each update creates a new revision).\n *\n * ### Creating a Profile\n * **Example:** Generated name with authorization and threat categories\n * ```typescript\n * const profile = yield* GCP.Apigee.SecurityProfile(\"Baseline\", {\n * profileConfig: {\n * categories: [{ authorization: true, threat: true }],\n * },\n * });\n * ```\n *\n * **Example:** Named profile\n * ```typescript\n * const profile = yield* GCP.Apigee.SecurityProfile(\"Baseline\", {\n * securityProfileId: \"app-baseline\",\n * description: \"default scoring\",\n * profileConfig: {\n * categories: [{ authorization: true, cors: true, threat: true }],\n * },\n * });\n * ```\n *\n * @resource\n * @category Apigee\n */\nexport const SecurityProfile = Resource\u003cSecurityProfile>(\"GCP.Apigee.SecurityProfile\");\n\nexport class SecurityProfileNotResolved extends Data.TaggedError(\n \"GCP.Apigee.SecurityProfileNotResolved\",\n)\u003c{\n resourceName: string;\n}> {}\n\nconst DEFAULT_PROFILE_CONFIG: ProfileConfig = {\n categories: [{ authorization: true, threat: true }],\n};\n\nconst resourceName = (organization: string, profileId: string) =>\n `${orgParent(organization)}/securityProfiles/${profileId}`;\n\nconst profileIdOf = (profile: apigee.GoogleCloudApigeeV1SecurityProfile) =>\n lastSegment(profile.name ?? \"\");\n\nconst flag = (value: unknown) => value !== undefined && value !== false;\n\nconst categoryOf = (\n category: apigee.GoogleCloudApigeeV1ProfileConfigCategory | ProfileConfigCategory,\n): ProfileConfigCategory => ({\n mediation: flag(category.mediation) ? true : undefined,\n abuse: flag(category.abuse) ? true : undefined,\n authorization: flag(category.authorization) ? true : undefined,\n mtls: flag(category.mtls) ? true : undefined,\n cors: flag(category.cors) ? true : undefined,\n threat: flag(category.threat) ? true : undefined,\n});\n\nconst profileConfigOf = (\n config: apigee.GoogleCloudApigeeV1ProfileConfig | ProfileConfig | undefined,\n): ProfileConfig => ({\n categories: (config?.categories ?? DEFAULT_PROFILE_CONFIG.categories ?? []).map(categoryOf),\n});\n\nconst toApiCategory = (\n category: ProfileConfigCategory,\n): apigee.GoogleCloudApigeeV1ProfileConfigCategory => ({\n mediation: category.mediation === true ? {} : undefined,\n abuse: category.abuse === true ? {} : undefined,\n authorization: category.authorization === true ? {} : undefined,\n mtls: category.mtls === true ? {} : undefined,\n cors: category.cors === true ? {} : undefined,\n threat: category.threat === true ? {} : undefined,\n});\n\nconst toAttrs = (profile: apigee.GoogleCloudApigeeV1SecurityProfile, organization: string) => {\n const securityProfileId = profileIdOf(profile);\n const name = profile.name?.includes(\"/\")\n ? profile.name\n : resourceName(organization, securityProfileId);\n const parsed = parseOwnership(profile.description);\n return {\n name,\n securityProfileId,\n organization: organizationFromName(name) ?? organization,\n description: parsed.text,\n displayName: profile.displayName,\n profileConfig: profile.profileConfig ? profileConfigOf(profile.profileConfig) : undefined,\n scoringConfigs: (profile.scoringConfigs ?? []).map((config) => ({\n description: config.description,\n scorePath: config.scorePath,\n title: config.title,\n })),\n environments: (profile.environments ?? []).map((environment) => ({\n environment: environment.environment,\n attachTime: environment.attachTime,\n })),\n minScore: profile.minScore,\n maxScore: profile.maxScore,\n revisionId: profile.revisionId,\n revisionCreateTime: profile.revisionCreateTime,\n revisionUpdateTime: profile.revisionUpdateTime,\n };\n};\n\nconst getByName = (name: string) =>\n apigee\n .getOrganizationsSecurityProfiles({ name })\n .pipe(Effect.catchTag([\"NotFound\", \"ApigeeResourceNotFound\"], () => Effect.undefined));\n\nconst toBody = (\n news: SecurityProfileProps,\n description: string,\n): apigee.GoogleCloudApigeeV1SecurityProfile => {\n const config = profileConfigOf(news.profileConfig ?? DEFAULT_PROFILE_CONFIG);\n return {\n description,\n displayName: news.displayName,\n profileConfig: {\n categories: (config.categories ?? []).map(toApiCategory),\n },\n scoringConfigs: news.scoringConfigs,\n };\n};\n\nexport const SecurityProfileProvider = () =>\n Provider.succeed(SecurityProfile, {\n stables: [\"name\", \"securityProfileId\", \"organization\"],\n\n diff: Effect.fn(function* ({ news, olds, output }) {\n if (!isResolved(news)) return undefined;\n const previousId = olds?.securityProfileId ?? output?.securityProfileId;\n const previousOrg = olds?.organization ?? output?.organization;\n if (\n (previousId !== undefined &&\n news.securityProfileId !== undefined &&\n news.securityProfileId !== previousId) ||\n (previousOrg !== undefined &&\n news.organization !== undefined &&\n news.organization !== previousOrg)\n ) {\n return { action: \"replace\" as const, deleteFirst: true };\n }\n return undefined;\n }),\n\n read: Effect.fn(function* ({ id, olds, output, previous }) {\n const env = yield* GcpEnvironment.current;\n const organization = organizationFromName(output?.name) ?? olds?.organization ?? env.project;\n const securityProfileId = yield* toResourceId(\n id,\n olds?.securityProfileId,\n output?.securityProfileId,\n MAX_NAME_LENGTH,\n );\n const name = output?.name ?? resourceName(organization, securityProfileId);\n const existing = yield* getByName(name);\n if (existing === undefined) return undefined;\n const attrs = toAttrs(existing, organization);\n const { labels } = parseOwnership(existing.description);\n return (yield* hasAlchemyLabels(id, labels))\n ? attrs\n : unownedUnlessPrevious(attrs, previous, \"name\");\n }),\n\n list: () =>\n Effect.gen(function* () {\n const env = yield* GcpEnvironment.current;\n return yield* apigee.listOrganizationsSecurityProfiles\n .pages({\n parent: orgParent(env.project),\n pageSize: 50,\n })\n .pipe(\n Stream.flatMap((page) => Stream.fromIterable(page.securityProfiles ?? [])),\n Stream.filter((profile) => hasOwnershipMarker(profile.description)),\n Stream.map((profile) => toAttrs(profile, env.project)),\n Stream.runCollect,\n Effect.map((chunk) => Array.from(chunk)),\n Effect.catchTag([\"NotFound\", \"ApigeeResourceNotFound\"], () =>\n Effect.succeed([] as SecurityProfile[\"Attributes\"][]),\n ),\n );\n }),\n\n reconcile: Effect.fn(function* ({ id, news, output }) {\n const env = yield* GcpEnvironment.current;\n const organization = news.organization ?? output?.organization ?? env.project;\n const securityProfileId = yield* toResourceId(\n id,\n news.securityProfileId,\n output?.securityProfileId,\n MAX_NAME_LENGTH,\n );\n const name = resourceName(organization, securityProfileId);\n const ownership = yield* createInternalLabels(id);\n const desiredDescription = encodeOwnership(ownership, news.description);\n const desiredConfig = profileConfigOf(news.profileConfig ?? DEFAULT_PROFILE_CONFIG);\n\n let current = yield* getByName(output?.name ?? name);\n\n if (current === undefined) {\n const created = yield* apigee\n .createOrganizationsSecurityProfiles({\n parent: orgParent(organization),\n securityProfileId,\n body: toBody(news, desiredDescription),\n })\n .pipe(Effect.catchTag(\"Conflict\", () => getByName(name)));\n current = created ?? undefined;\n }\n\n if (current === undefined) {\n return yield* new SecurityProfileNotResolved({ resourceName: name });\n }\n\n const descriptionChanged = (current.description ?? \"\") !== desiredDescription;\n const displayChanged = (current.displayName ?? \"\") !== (news.displayName ?? \"\");\n const configChanged = !sameJson(profileConfigOf(current.profileConfig), desiredConfig);\n const scoringChanged = !sameJson(\n current.scoringConfigs ?? [],\n news.scoringConfigs ?? current.scoringConfigs ?? [],\n );\n\n const updateMask = [\n descriptionChanged ? \"description\" : undefined,\n displayChanged ? \"displayName\" : undefined,\n configChanged ? \"profileConfig\" : undefined,\n scoringChanged ? \"scoringConfigs\" : undefined,\n ].filter((field): field is string => field !== undefined);\n\n if (updateMask.length > 0) {\n current = yield* apigee.patchOrganizationsSecurityProfiles({\n name: current.name?.includes(\"/\") ? current.name : name,\n updateMask: updateMask.join(\",\"),\n body: toBody(news, desiredDescription),\n });\n }\n\n return toAttrs(current, organization);\n }),\n\n delete: Effect.fn(function* ({ output }) {\n yield* apigee\n .deleteOrganizationsSecurityProfiles({ name: output.name })\n .pipe(Effect.catchTag([\"NotFound\", \"ApigeeResourceNotFound\"], () => Effect.void));\n }),\n });\n","preview":null,"history":null,"version":"4bf76cdbc5ae7078465007612ea5b9e8baed11bb"},"/_session?shell=1":null}