The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3"; |
| 2 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 3 | import * as Data from "effect/Data"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as Stream from "effect/Stream"; |
| 6 | import { GcpEnvironment } from "../Environment.ts"; |
| 7 | import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts"; |
| 8 | |
| 9 | export const MAX_ID_LENGTH = 63; |
| 10 | export const MAX_DESCRIPTION_LENGTH = 1024; |
| 11 | export const MAX_DISPLAY_NAME_LENGTH = 128; |
| 12 | |
| 13 | export class SecuritycenterNotResolved extends Data.TaggedError("GCP.SecurityCenter.NotResolved")<{ |
| 14 | resourceName: string; |
| 15 | }> {} |
| 16 | |
| 17 | export class OrganizationNotResolved extends Data.TaggedError( |
| 18 | "GCP.SecurityCenter.OrganizationNotResolved", |
| 19 | )<{ |
| 20 | project: string; |
| 21 | }> {} |
| 22 | |
| 23 | export class FolderNotResolved extends Data.TaggedError("GCP.SecurityCenter.FolderNotResolved")<{ |
| 24 | project: string; |
| 25 | }> {} |
| 26 | |
| 27 | export const lastSegment = (value: string) => { |
| 28 | const trimmed = value.replace(/\/+$/, ""); |
| 29 | const parts = trimmed.split("/"); |
| 30 | return parts[parts.length - 1] || trimmed; |
| 31 | }; |
| 32 | |
| 33 | export const projectOf = (name: string) => { |
| 34 | const parts = name.split("/"); |
| 35 | const index = parts.indexOf("projects"); |
| 36 | return index >= 0 ? (parts[index + 1] ?? "") : ""; |
| 37 | }; |
| 38 | |
| 39 | export const organizationOf = (name: string) => { |
| 40 | const parts = name.split("/"); |
| 41 | const index = parts.indexOf("organizations"); |
| 42 | return index >= 0 ? (parts[index + 1] ?? "") : ""; |
| 43 | }; |
| 44 | |
| 45 | export const organizationParent = (value: string) => |
| 46 | value.startsWith("organizations/") ? value : `organizations/${lastSegment(value)}`; |
| 47 | |
| 48 | export const organizationIdOf = (value: string) => lastSegment(value); |
| 49 | |
| 50 | export const folderParent = (value: string) => |
| 51 | value.startsWith("folders/") ? value : `folders/${lastSegment(value)}`; |
| 52 | |
| 53 | export const folderIdOf = (value: string) => lastSegment(value); |
| 54 | |
| 55 | export const parseName = (name: string, collection: string) => { |
| 56 | const parts = name.split("/").filter((part) => part.length > 0); |
| 57 | const collectionAt = parts.lastIndexOf(collection); |
| 58 | const locationsAt = parts.lastIndexOf("locations"); |
| 59 | const projectsAt = parts.lastIndexOf("projects"); |
| 60 | const orgsAt = parts.lastIndexOf("organizations"); |
| 61 | const foldersAt = parts.lastIndexOf("folders"); |
| 62 | return { |
| 63 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 64 | organization: orgsAt >= 0 && parts[orgsAt + 1] ? parts[orgsAt + 1]! : "", |
| 65 | folder: foldersAt >= 0 && parts[foldersAt + 1] ? parts[foldersAt + 1]! : "", |
| 66 | location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "", |
| 67 | id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name), |
| 68 | parent: |
| 69 | collectionAt > 0 |
| 70 | ? parts.slice(0, collectionAt).join("/") |
| 71 | : parts.slice(0, Math.max(0, parts.length - 1)).join("/"), |
| 72 | }; |
| 73 | }; |
| 74 | |
| 75 | export const DEFAULT_MUTE_TYPE = "STATIC"; |
| 76 | export const DEFAULT_ENABLEMENT = "ENABLED"; |
| 77 | export const DEFAULT_CLOUD_PROVIDER = "GOOGLE_CLOUD_PLATFORM"; |
| 78 | export const DEFAULT_ETD_TYPE = "CONFIGURABLE_BAD_IP"; |
| 79 | |
| 80 | export const defaultEtdConfig = { |
| 81 | metadata: { |
| 82 | severity: "LOW", |
| 83 | description: "alchemy custom module", |
| 84 | recommendation: "n/a", |
| 85 | }, |
| 86 | ips: ["192.0.2.1"], |
| 87 | }; |
| 88 | |
| 89 | export const defaultShaCustomConfig = { |
| 90 | predicate: { expression: 'resource.name == "alchemy-nonexistent"' }, |
| 91 | resourceSelector: { |
| 92 | resourceTypes: ["compute.googleapis.com/Instance"], |
| 93 | }, |
| 94 | severity: "LOW", |
| 95 | description: "alchemy custom module", |
| 96 | recommendation: "n/a", |
| 97 | }; |
| 98 | |
| 99 | export const shaSettingsParent = (parent: string) => `${parent}/securityHealthAnalyticsSettings`; |
| 100 | |
| 101 | export const etdSettingsParent = (parent: string) => `${parent}/eventThreatDetectionSettings`; |
| 102 | |
| 103 | export const sameText = (left: string | undefined, right: string | undefined) => |
| 104 | (left ?? "") === (right ?? ""); |
| 105 | |
| 106 | export const jsonEqual = (left: unknown, right: unknown) => |
| 107 | JSON.stringify(canonical(left) ?? null) === JSON.stringify(canonical(right) ?? null); |
| 108 | |
| 109 | export const updateMaskOf = (...fields: Array<string | undefined>) => |
| 110 | fields.filter((field): field is string => field !== undefined).join(","); |
| 111 | |
| 112 | export const toResourceId = ( |
| 113 | id: string, |
| 114 | requested: string | undefined, |
| 115 | existing: string | undefined, |
| 116 | prefix = "s", |
| 117 | maxLength = MAX_ID_LENGTH, |
| 118 | ) => |
| 119 | Effect.gen(function* () { |
| 120 | if (requested !== undefined) return requested; |
| 121 | if (existing !== undefined) return existing; |
| 122 | const generated = yield* createPhysicalName({ |
| 123 | id, |
| 124 | maxLength, |
| 125 | lowercase: true, |
| 126 | }); |
| 127 | const next = /^[a-z]/.test(generated) ? generated : `${prefix}${generated}`; |
| 128 | return next.replace(/[^a-z0-9-]/g, "-").slice(0, maxLength); |
| 129 | }); |
| 130 | |
| 131 | export const toPhysicalId = ( |
| 132 | id: string, |
| 133 | explicit: string | undefined, |
| 134 | existing: string | undefined, |
| 135 | ) => toResourceId(id, explicit, existing); |
| 136 | |
| 137 | export const shaDisplayNameOf = (physical: string) => { |
| 138 | const cleaned = physical |
| 139 | .replace(/[^a-zA-Z0-9_]/g, "_") |
| 140 | .replace(/_+/g, "_") |
| 141 | .replace(/^_+|_+$/g, ""); |
| 142 | const withLetter = /^[A-Z]/.test(cleaned) ? cleaned : `A${cleaned}`.replace(/_+/g, "_"); |
| 143 | return withLetter.slice(0, MAX_DISPLAY_NAME_LENGTH); |
| 144 | }; |
| 145 | |
| 146 | export const etdDisplayNameOf = (physical: string) => { |
| 147 | const cleaned = physical |
| 148 | .replace(/[^a-zA-Z0-9_]/g, "_") |
| 149 | .replace(/_+/g, "_") |
| 150 | .replace(/^_+|_+$/g, ""); |
| 151 | const withLetter = /^[A-Za-z]/.test(cleaned) ? cleaned : `e${cleaned}`; |
| 152 | return withLetter.slice(0, MAX_DISPLAY_NAME_LENGTH); |
| 153 | }; |
| 154 | |
| 155 | export const toShaDisplayName = ( |
| 156 | id: string, |
| 157 | requested: string | undefined, |
| 158 | existing: string | undefined, |
| 159 | ) => |
| 160 | Effect.gen(function* () { |
| 161 | if (requested !== undefined) return requested; |
| 162 | if (existing !== undefined) return existing; |
| 163 | const physical = yield* createPhysicalName({ |
| 164 | id, |
| 165 | maxLength: 63, |
| 166 | lowercase: true, |
| 167 | }); |
| 168 | return shaDisplayNameOf(physical); |
| 169 | }); |
| 170 | |
| 171 | const markerOf = (stack: string, stage: string, id: string) => |
| 172 | `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`; |
| 173 | |
| 174 | const fitMarker = (labels: Record<string, string>, maxLength: number) => { |
| 175 | let stack = labels[alchemyLabelKeys.stack] ?? "x"; |
| 176 | let stage = labels[alchemyLabelKeys.stage] ?? "x"; |
| 177 | let id = labels[alchemyLabelKeys.id] ?? "x"; |
| 178 | let marker = markerOf(stack, stage, id); |
| 179 | while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) { |
| 180 | if (stack.length >= stage.length && stack.length >= id.length) { |
| 181 | stack = stack.slice(0, -1); |
| 182 | } else if (stage.length >= id.length) { |
| 183 | stage = stage.slice(0, -1); |
| 184 | } else { |
| 185 | id = id.slice(0, -1); |
| 186 | } |
| 187 | marker = markerOf(stack, stage, id); |
| 188 | } |
| 189 | return marker.slice(0, maxLength); |
| 190 | }; |
| 191 | |
| 192 | export const encodeOwnership = ( |
| 193 | labels: Record<string, string>, |
| 194 | text: string | undefined, |
| 195 | maxLength = MAX_DESCRIPTION_LENGTH, |
| 196 | ): string => { |
| 197 | const marker = fitMarker(labels, maxLength); |
| 198 | const trimmed = text?.trim(); |
| 199 | if (!trimmed) return marker.slice(0, maxLength); |
| 200 | return `${marker}\n${trimmed}`.slice(0, maxLength); |
| 201 | }; |
| 202 | |
| 203 | export const encodeDescription = encodeOwnership; |
| 204 | |
| 205 | export const parseOwnership = ( |
| 206 | text: string | undefined, |
| 207 | ): { |
| 208 | labels: Record<string, string>; |
| 209 | text: string | undefined; |
| 210 | } => { |
| 211 | if (!text?.startsWith("[alchemy ")) { |
| 212 | return { labels: {}, text }; |
| 213 | } |
| 214 | const end = text.indexOf("]"); |
| 215 | if (end < 0) return { labels: {}, text }; |
| 216 | const labels: Record<string, string> = {}; |
| 217 | for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) { |
| 218 | const eq = part.indexOf("="); |
| 219 | if (eq > 0) { |
| 220 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 221 | } |
| 222 | } |
| 223 | const rest = text.slice(end + 1).replace(/^[\s\n]+/, ""); |
| 224 | return { labels, text: rest.length > 0 ? rest : undefined }; |
| 225 | }; |
| 226 | |
| 227 | export const hasOwnershipMarker = (text: string | undefined) => |
| 228 | Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-")); |
| 229 | |
| 230 | const prefixMatch = (expected: string, observed: string) => |
| 231 | expected === observed || expected.startsWith(observed) || observed.startsWith(expected); |
| 232 | |
| 233 | export const ownedByAlchemy = (id: string, text: string | undefined) => |
| 234 | Effect.gen(function* () { |
| 235 | const expected = yield* createInternalLabels(id); |
| 236 | const { labels } = parseOwnership(text); |
| 237 | if (!hasOwnershipMarker(text)) return false; |
| 238 | const exact = yield* hasAlchemyLabels(id, labels); |
| 239 | if (exact) return true; |
| 240 | return ( |
| 241 | prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") && |
| 242 | prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") && |
| 243 | prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "") |
| 244 | ); |
| 245 | }); |
| 246 | |
| 247 | export const collectPages = <Page, A, E, R>( |
| 248 | pages: Stream.Stream<Page, E, R>, |
| 249 | items: (page: Page) => readonly A[] | undefined, |
| 250 | ) => |
| 251 | pages.pipe( |
| 252 | Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])), |
| 253 | Stream.runCollect, |
| 254 | Effect.map((chunk) => Array.from(chunk)), |
| 255 | ); |
| 256 | |
| 257 | export const findOwned = <A>( |
| 258 | items: readonly A[], |
| 259 | textOf: (item: A) => string | undefined, |
| 260 | id: string, |
| 261 | ) => |
| 262 | Effect.gen(function* () { |
| 263 | for (const item of items) { |
| 264 | if (yield* ownedByAlchemy(id, textOf(item))) return item; |
| 265 | } |
| 266 | return undefined; |
| 267 | }); |
| 268 | |
| 269 | export const canonical = (value: unknown): unknown => { |
| 270 | if (value === undefined || value === null) return undefined; |
| 271 | if (typeof value === "boolean" || typeof value === "number") return value; |
| 272 | if (typeof value === "string") { |
| 273 | return value.length === 0 ? undefined : value; |
| 274 | } |
| 275 | if (Array.isArray(value)) { |
| 276 | const items = value.map(canonical).filter((item) => item !== undefined); |
| 277 | return items.length === 0 ? undefined : items; |
| 278 | } |
| 279 | if (typeof value === "object") { |
| 280 | const entries = Object.entries(value as Record<string, unknown>) |
| 281 | .map(([key, item]) => [key, canonical(item)] as const) |
| 282 | .filter(([, item]) => item !== undefined) |
| 283 | .sort(([left], [right]) => left.localeCompare(right)); |
| 284 | if (entries.length === 0) return undefined; |
| 285 | return Object.fromEntries(entries); |
| 286 | } |
| 287 | return undefined; |
| 288 | }; |
| 289 | |
| 290 | export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null); |
| 291 | |
| 292 | const parentOf = (name: string) => |
| 293 | name.startsWith("projects/") |
| 294 | ? resourcemanager.getProjects({ name }).pipe( |
| 295 | Effect.map((resource) => resource.parent), |
| 296 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 297 | ) |
| 298 | : name.startsWith("folders/") |
| 299 | ? resourcemanager.getFolders({ name }).pipe( |
| 300 | Effect.map((folder) => folder.parent), |
| 301 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 302 | ) |
| 303 | : Effect.undefined; |
| 304 | |
| 305 | export const tryResolveOrganization = () => |
| 306 | Effect.gen(function* () { |
| 307 | const env = yield* GcpEnvironment.current; |
| 308 | let current: string | undefined = `projects/${env.project}`; |
| 309 | for (let i = 0; i < 8; i++) { |
| 310 | if (current === undefined) return undefined; |
| 311 | if (current.startsWith("organizations/")) return current; |
| 312 | current = yield* parentOf(current); |
| 313 | } |
| 314 | return undefined; |
| 315 | }); |
| 316 | |
| 317 | export const resolveOrganization = (explicit: string | undefined, existing: string | undefined) => |
| 318 | Effect.gen(function* () { |
| 319 | if (explicit !== undefined) return organizationParent(explicit); |
| 320 | if (existing !== undefined) return organizationParent(existing); |
| 321 | const resolved = yield* tryResolveOrganization(); |
| 322 | if (resolved === undefined) { |
| 323 | const env = yield* GcpEnvironment.current; |
| 324 | return yield* new OrganizationNotResolved({ project: env.project }); |
| 325 | } |
| 326 | return resolved; |
| 327 | }); |
| 328 | |
| 329 | export const tryResolveFolder = () => |
| 330 | Effect.gen(function* () { |
| 331 | const env = yield* GcpEnvironment.current; |
| 332 | let current: string | undefined = `projects/${env.project}`; |
| 333 | for (let i = 0; i < 8; i++) { |
| 334 | if (current === undefined) return undefined; |
| 335 | if (current.startsWith("folders/")) return current; |
| 336 | if (current.startsWith("organizations/")) return undefined; |
| 337 | current = yield* parentOf(current); |
| 338 | } |
| 339 | return undefined; |
| 340 | }); |
| 341 | |
| 342 | export const resolveFolder = (explicit: string | undefined, existing: string | undefined) => |
| 343 | Effect.gen(function* () { |
| 344 | if (explicit !== undefined) return folderParent(explicit); |
| 345 | if (existing !== undefined) return folderParent(existing); |
| 346 | const resolved = yield* tryResolveFolder(); |
| 347 | if (resolved === undefined) { |
| 348 | const env = yield* GcpEnvironment.current; |
| 349 | return yield* new FolderNotResolved({ project: env.project }); |
| 350 | } |
| 351 | return resolved; |
| 352 | }); |
| 353 | |
| 354 | export const replaceOnIdentity = (changed: boolean) => |
| 355 | changed ? ({ action: "replace" as const, deleteFirst: false } as const) : undefined; |
| 356 | |
| 357 | export const replaceOn = (previous: string | undefined, next: string | undefined) => |
| 358 | replaceOnIdentity(previous !== undefined && next !== undefined && previous !== next); |