The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as shield from "@distilled.cloud/aws/shield"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import { createInternalTags, diffTags, hasAlchemyTags, tagRecord } from "alchemy/Tags"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Stream from "effect/Stream"; |
| 11 | import type { Providers } from "../Providers.ts"; |
| 12 | |
| 13 | export class ProtectionGroupUnexpectedResponse extends Data.TaggedError( |
| 14 | "ProtectionGroupUnexpectedResponse", |
| 15 | )<{ |
| 16 | readonly message: string; |
| 17 | readonly cause?: unknown; |
| 18 | }> {} |
| 19 | |
| 20 | /** How Shield Advanced aggregates traffic across a protection group. */ |
| 21 | export type ProtectionGroupAggregation = "SUM" | "MEAN" | "MAX"; |
| 22 | |
| 23 | /** Which protected resources are members of the group. */ |
| 24 | export type ProtectionGroupPattern = "ALL" | "ARBITRARY" | "BY_RESOURCE_TYPE"; |
| 25 | |
| 26 | /** Resource type selector for `BY_RESOURCE_TYPE` groups. */ |
| 27 | export type ProtectedResourceType = |
| 28 | | "CLOUDFRONT_DISTRIBUTION" |
| 29 | | "ROUTE_53_HOSTED_ZONE" |
| 30 | | "ELASTIC_IP_ALLOCATION" |
| 31 | | "CLASSIC_LOAD_BALANCER" |
| 32 | | "APPLICATION_LOAD_BALANCER" |
| 33 | | "GLOBAL_ACCELERATOR"; |
| 34 | |
| 35 | export interface ProtectionGroupProps { |
| 36 | /** |
| 37 | * Identifier of the protection group (alphanumeric and `-`, max 36 chars). |
| 38 | * Immutable — changing it replaces the group. If omitted, a unique id is |
| 39 | * generated. |
| 40 | */ |
| 41 | protectionGroupId?: string; |
| 42 | /** |
| 43 | * How Shield Advanced aggregates traffic across the group: `SUM` for |
| 44 | * combined volume, `MEAN` for per-resource average, `MAX` for the highest |
| 45 | * single-resource volume. Mutable. |
| 46 | */ |
| 47 | aggregation: ProtectionGroupAggregation; |
| 48 | /** |
| 49 | * Which protected resources are members: `ALL` protected resources, |
| 50 | * an `ARBITRARY` list (set `members`), or all of one `BY_RESOURCE_TYPE` |
| 51 | * (set `resourceType`). Mutable. |
| 52 | */ |
| 53 | pattern: ProtectionGroupPattern; |
| 54 | /** |
| 55 | * Resource type included in the group. Required when `pattern` is |
| 56 | * `BY_RESOURCE_TYPE`; omit otherwise. |
| 57 | */ |
| 58 | resourceType?: ProtectedResourceType; |
| 59 | /** |
| 60 | * ARNs of the protected resources in the group. Required when `pattern` is |
| 61 | * `ARBITRARY`; omit otherwise. |
| 62 | */ |
| 63 | members?: string[]; |
| 64 | /** |
| 65 | * User-defined tags. Alchemy ownership tags are merged in automatically. |
| 66 | */ |
| 67 | tags?: Record<string, string>; |
| 68 | } |
| 69 | |
| 70 | export interface ProtectionGroup extends Resource< |
| 71 | "AWS.Shield.ProtectionGroup", |
| 72 | ProtectionGroupProps, |
| 73 | { |
| 74 | /** Identifier of the protection group. */ |
| 75 | protectionGroupId: string; |
| 76 | /** ARN of the protection group. */ |
| 77 | protectionGroupArn: string; |
| 78 | /** Traffic aggregation mode. */ |
| 79 | aggregation: string; |
| 80 | /** Membership pattern. */ |
| 81 | pattern: string; |
| 82 | /** Resource type for `BY_RESOURCE_TYPE` groups. */ |
| 83 | resourceType: string | undefined; |
| 84 | /** Member resource ARNs for `ARBITRARY` groups. */ |
| 85 | members: string[]; |
| 86 | /** Tags on the protection group (including Alchemy ownership tags). */ |
| 87 | tags: Record<string, string>; |
| 88 | }, |
| 89 | never, |
| 90 | Providers |
| 91 | > {} |
| 92 | |
| 93 | /** |
| 94 | * An AWS Shield Advanced Protection Group — a collective of protected |
| 95 | * resources whose traffic Shield Advanced monitors as a unit, improving |
| 96 | * detection accuracy and reducing false positives. |
| 97 | * |
| 98 | * Requires an active Shield Advanced subscription ($3,000/month with a 1-year |
| 99 | * commitment); without one every call fails with the typed |
| 100 | * `SubscriptionNotFound` error. |
| 101 | * |
| 102 | * ### Grouping Protections |
| 103 | * **Example:** Group All Protected Resources |
| 104 | * ```typescript |
| 105 | * const group = yield* Shield.ProtectionGroup("AllResources", { |
| 106 | * aggregation: "SUM", |
| 107 | * pattern: "ALL", |
| 108 | * }); |
| 109 | * ``` |
| 110 | * |
| 111 | * **Example:** Group by Resource Type |
| 112 | * ```typescript |
| 113 | * const group = yield* Shield.ProtectionGroup("Distributions", { |
| 114 | * aggregation: "MAX", |
| 115 | * pattern: "BY_RESOURCE_TYPE", |
| 116 | * resourceType: "CLOUDFRONT_DISTRIBUTION", |
| 117 | * }); |
| 118 | * ``` |
| 119 | * |
| 120 | * **Example:** Arbitrary Member List |
| 121 | * ```typescript |
| 122 | * const group = yield* Shield.ProtectionGroup("Fleet", { |
| 123 | * aggregation: "MEAN", |
| 124 | * pattern: "ARBITRARY", |
| 125 | * members: [distribution.distributionArn], |
| 126 | * tags: { team: "platform" }, |
| 127 | * }); |
| 128 | * ``` |
| 129 | */ |
| 130 | export const ProtectionGroup = Resource<ProtectionGroup>("AWS.Shield.ProtectionGroup"); |
| 131 | |
| 132 | const observeGroup = (protectionGroupId: string) => |
| 133 | shield.describeProtectionGroup({ ProtectionGroupId: protectionGroupId }).pipe( |
| 134 | Effect.map((r) => r.ProtectionGroup), |
| 135 | Effect.catchTag(["ResourceNotFoundException", "SubscriptionNotFound"], () => Effect.undefined), |
| 136 | ); |
| 137 | |
| 138 | const toTagRecord = (tags: shield.Tag[] | undefined): Record<string, string> => |
| 139 | tagRecord( |
| 140 | (tags ?? []).flatMap((t) => |
| 141 | t.Key !== undefined && t.Value !== undefined ? [{ Key: t.Key, Value: t.Value }] : [], |
| 142 | ), |
| 143 | ); |
| 144 | |
| 145 | const readGroupTags = (protectionGroupArn: string) => |
| 146 | shield.listTagsForResource({ ResourceARN: protectionGroupArn }).pipe( |
| 147 | Effect.map((r) => toTagRecord(r.Tags)), |
| 148 | Effect.orElseSucceed(() => ({})), |
| 149 | ); |
| 150 | |
| 151 | const buildAttrs = (group: shield.ProtectionGroup, tags: Record<string, string>) => ({ |
| 152 | protectionGroupId: group.ProtectionGroupId, |
| 153 | protectionGroupArn: group.ProtectionGroupArn!, |
| 154 | aggregation: group.Aggregation, |
| 155 | pattern: group.Pattern, |
| 156 | resourceType: group.ResourceType, |
| 157 | members: [...group.Members], |
| 158 | tags, |
| 159 | }); |
| 160 | |
| 161 | const sameMembers = (a: readonly string[], b: readonly string[]) => |
| 162 | a.length === b.length && [...a].sort().join(",") === [...b].sort().join(","); |
| 163 | |
| 164 | export const ProtectionGroupProvider = () => |
| 165 | Provider.effect( |
| 166 | ProtectionGroup, |
| 167 | Effect.gen(function* () { |
| 168 | const toGroupId = (id: string, props: { protectionGroupId?: string }) => |
| 169 | props.protectionGroupId |
| 170 | ? Effect.succeed(props.protectionGroupId) |
| 171 | : createPhysicalName({ id, maxLength: 36 }); |
| 172 | |
| 173 | const syncTags = Effect.fn(function* ( |
| 174 | protectionGroupArn: string, |
| 175 | desiredTags: Record<string, string>, |
| 176 | ) { |
| 177 | const observedTags = yield* readGroupTags(protectionGroupArn); |
| 178 | const { upsert, removed } = diffTags(observedTags, desiredTags); |
| 179 | if (upsert.length > 0) { |
| 180 | yield* shield.tagResource({ |
| 181 | ResourceARN: protectionGroupArn, |
| 182 | Tags: upsert, |
| 183 | }); |
| 184 | } |
| 185 | if (removed.length > 0) { |
| 186 | yield* shield.untagResource({ |
| 187 | ResourceARN: protectionGroupArn, |
| 188 | TagKeys: removed, |
| 189 | }); |
| 190 | } |
| 191 | }); |
| 192 | |
| 193 | return { |
| 194 | stables: ["protectionGroupId", "protectionGroupArn"], |
| 195 | |
| 196 | diff: Effect.fn(function* ({ id, olds, news }) { |
| 197 | if (!isResolved(news)) return; |
| 198 | if (olds === undefined) return; |
| 199 | if ((yield* toGroupId(id, olds)) !== (yield* toGroupId(id, news))) { |
| 200 | return { action: "replace" } as const; |
| 201 | } |
| 202 | }), |
| 203 | |
| 204 | read: Effect.fn(function* ({ id, olds, output }) { |
| 205 | const groupId = output?.protectionGroupId ?? (yield* toGroupId(id, olds ?? {})); |
| 206 | const group = yield* observeGroup(groupId); |
| 207 | if (!group?.ProtectionGroupArn) return undefined; |
| 208 | const tags = yield* readGroupTags(group.ProtectionGroupArn); |
| 209 | const attrs = buildAttrs(group, tags); |
| 210 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 211 | }), |
| 212 | |
| 213 | reconcile: Effect.fn(function* ({ id, news, session }) { |
| 214 | const groupId = yield* toGroupId(id, news); |
| 215 | const internalTags = yield* createInternalTags(id); |
| 216 | const desiredTags = { ...news.tags, ...internalTags }; |
| 217 | |
| 218 | // 1. OBSERVE — cloud state is authoritative. |
| 219 | let group = yield* observeGroup(groupId); |
| 220 | |
| 221 | // 2. ENSURE — create if missing; tolerate the AlreadyExists race. |
| 222 | if (!group) { |
| 223 | yield* shield |
| 224 | .createProtectionGroup({ |
| 225 | ProtectionGroupId: groupId, |
| 226 | Aggregation: news.aggregation, |
| 227 | Pattern: news.pattern, |
| 228 | ResourceType: news.resourceType, |
| 229 | Members: news.members, |
| 230 | Tags: Object.entries(desiredTags).map(([Key, Value]) => ({ |
| 231 | Key, |
| 232 | Value, |
| 233 | })), |
| 234 | }) |
| 235 | .pipe(Effect.catchTag("ResourceAlreadyExistsException", () => Effect.void)); |
| 236 | group = yield* observeGroup(groupId); |
| 237 | if (!group?.ProtectionGroupArn) { |
| 238 | return yield* new ProtectionGroupUnexpectedResponse({ |
| 239 | message: `Failed to create or read Shield protection group ${groupId}`, |
| 240 | }); |
| 241 | } |
| 242 | } else { |
| 243 | // 3. SYNC settings — diff observed against desired; update only |
| 244 | // on an actual delta. |
| 245 | const changed = |
| 246 | group.Aggregation !== news.aggregation || |
| 247 | group.Pattern !== news.pattern || |
| 248 | (group.ResourceType ?? undefined) !== (news.resourceType ?? undefined) || |
| 249 | !sameMembers(group.Members ?? [], news.members ?? []); |
| 250 | if (changed) { |
| 251 | yield* shield.updateProtectionGroup({ |
| 252 | ProtectionGroupId: groupId, |
| 253 | Aggregation: news.aggregation, |
| 254 | Pattern: news.pattern, |
| 255 | ResourceType: news.resourceType, |
| 256 | Members: news.members, |
| 257 | }); |
| 258 | group = yield* observeGroup(groupId); |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | // 3b. SYNC tags — diff against OBSERVED cloud tags. |
| 263 | yield* syncTags(group!.ProtectionGroupArn!, desiredTags); |
| 264 | |
| 265 | // 4. RETURN fresh attributes. |
| 266 | yield* session.note(group!.ProtectionGroupArn!); |
| 267 | return buildAttrs(group!, desiredTags); |
| 268 | }), |
| 269 | |
| 270 | // Enumerate every protection group in the account. Without a Shield |
| 271 | // Advanced subscription the account cannot have any groups. |
| 272 | list: () => |
| 273 | Effect.gen(function* () { |
| 274 | const groups = yield* shield.listProtectionGroups.pages({}).pipe( |
| 275 | Stream.runCollect, |
| 276 | Effect.map((chunk) => |
| 277 | Array.from(chunk).flatMap((page) => page.ProtectionGroups ?? []), |
| 278 | ), |
| 279 | Effect.catchTag("SubscriptionNotFound", () => Effect.succeed([])), |
| 280 | ); |
| 281 | return yield* Effect.forEach( |
| 282 | groups.filter((g) => g.ProtectionGroupArn != null), |
| 283 | (group) => |
| 284 | Effect.gen(function* () { |
| 285 | const tags = yield* readGroupTags(group.ProtectionGroupArn!); |
| 286 | return buildAttrs(group, tags); |
| 287 | }), |
| 288 | { concurrency: 5 }, |
| 289 | ); |
| 290 | }), |
| 291 | |
| 292 | delete: Effect.fn(function* ({ output }) { |
| 293 | yield* shield |
| 294 | .deleteProtectionGroup({ |
| 295 | ProtectionGroupId: output.protectionGroupId, |
| 296 | }) |
| 297 | .pipe( |
| 298 | Effect.catchTag( |
| 299 | ["ResourceNotFoundException", "SubscriptionNotFound"], |
| 300 | () => Effect.void, |
| 301 | ), |
| 302 | ); |
| 303 | }), |
| 304 | }; |
| 305 | }), |
| 306 | ); |