@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 354 lines 13.1 KB
Raw
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 ProtectionUnexpectedResponse extends Data.TaggedError("ProtectionUnexpectedResponse")<{
14 readonly message: string;
15 readonly cause?: unknown;
16 }> {}
17
18 /** Route 53 health check ARNs look like `arn:aws:route53:::healthcheck/{id}`. */
19 const healthCheckIdFromArn = (arn: string) => arn.split("/").pop() ?? arn;
20 const healthCheckArnFromId = (id: string) => `arn:aws:route53:::healthcheck/${id}`;
21
22 /**
23 * How Shield Advanced responds automatically to application-layer (layer 7)
24 * DDoS attacks against the protected resource: `BLOCK` the attacking traffic
25 * with the associated AWS WAF web ACL, or `COUNT` it for visibility only.
26 */
27 export type ApplicationLayerAutomaticResponseAction = "BLOCK" | "COUNT";
28
29 export interface ProtectionProps {
30 /**
31 * Friendly name for the protection. Immutable — changing it replaces the
32 * protection. If omitted, a unique name is generated.
33 */
34 name?: string;
35 /**
36 * ARN of the resource to protect (CloudFront distribution, Route 53 hosted
37 * zone, Global Accelerator, ALB, CLB, or Elastic IP allocation). Immutable —
38 * changing it replaces the protection.
39 */
40 resourceArn: string;
41 /**
42 * Route 53 health check ARNs to associate with the protection for
43 * health-based DDoS detection. Mutable.
44 */
45 healthCheckArns?: string[];
46 /**
47 * Shield Advanced automatic application-layer DDoS mitigation: `BLOCK`
48 * attacking traffic with the associated AWS WAF web ACL, or `COUNT` it for
49 * visibility only. Omit to leave the feature disabled. Only supported for
50 * CloudFront distributions and Application Load Balancers that have an
51 * associated web ACL. Mutable.
52 */
53 applicationLayerAutomaticResponse?: ApplicationLayerAutomaticResponseAction;
54 /**
55 * User-defined tags. Alchemy ownership tags are merged in automatically.
56 */
57 tags?: Record<string, string>;
58 }
59
60 export interface Protection extends Resource<
61 "AWS.Shield.Protection",
62 ProtectionProps,
63 {
64 /** Unique identifier of the protection. */
65 protectionId: string;
66 /** ARN of the protection. */
67 protectionArn: string;
68 /** Name of the protection. */
69 name: string;
70 /** ARN of the protected resource. */
71 resourceArn: string;
72 /** IDs of the associated Route 53 health checks. */
73 healthCheckIds: string[];
74 /**
75 * The automatic application-layer DDoS mitigation action, or `undefined`
76 * when the feature is disabled.
77 */
78 applicationLayerAutomaticResponse: ApplicationLayerAutomaticResponseAction | undefined;
79 /** Tags on the protection (including Alchemy ownership tags). */
80 tags: Record<string, string>;
81 },
82 never,
83 Providers
84 > {}
85
86 /**
87 * An AWS Shield Advanced Protection for a single resource (CloudFront
88 * distribution, Route 53 hosted zone, Global Accelerator, Application/Classic
89 * Load Balancer, or Elastic IP).
90 *
91 * Requires an active Shield Advanced subscription ($3,000/month with a 1-year
92 * commitment); without one every call fails with the typed
93 * `SubscriptionNotFound` error.
94 *
95 * ### Protecting Resources
96 * **Example:** Protect a CloudFront Distribution
97 * ```typescript
98 * const protection = yield* Shield.Protection("SiteProtection", {
99 * resourceArn: distribution.distributionArn,
100 * });
101 * ```
102 *
103 * **Example:** Protection with Health-Based Detection
104 * ```typescript
105 * const protection = yield* Shield.Protection("ApiProtection", {
106 * name: "api-protection",
107 * resourceArn: loadBalancer.loadBalancerArn,
108 * healthCheckArns: ["arn:aws:route53:::healthcheck/11111111-2222-3333-4444-555555555555"],
109 * tags: { team: "platform" },
110 * });
111 * ```
112 *
113 * ### Automatic Application-Layer Mitigation
114 * **Example:** Block Layer-7 Attacks Automatically
115 * ```typescript
116 * // Requires an AWS WAF web ACL associated with the CloudFront distribution
117 * // or Application Load Balancer.
118 * const protection = yield* Shield.Protection("SiteProtection", {
119 * resourceArn: distribution.distributionArn,
120 * applicationLayerAutomaticResponse: "BLOCK",
121 * });
122 * ```
123 */
124 export const Protection = Resource<Protection>("AWS.Shield.Protection");
125
126 const observeByResourceArn = (resourceArn: string) =>
127 shield.describeProtection({ ResourceArn: resourceArn }).pipe(
128 Effect.map((r) => r.Protection),
129 Effect.catchTag(["ResourceNotFoundException", "SubscriptionNotFound"], () => Effect.undefined),
130 );
131
132 const toTagRecord = (tags: shield.Tag[] | undefined): Record<string, string> =>
133 tagRecord(
134 (tags ?? []).flatMap((t) =>
135 t.Key !== undefined && t.Value !== undefined ? [{ Key: t.Key, Value: t.Value }] : [],
136 ),
137 );
138
139 const readProtectionTags = (protectionArn: string) =>
140 shield.listTagsForResource({ ResourceARN: protectionArn }).pipe(
141 Effect.map((r) => toTagRecord(r.Tags)),
142 Effect.orElseSucceed(() => ({})),
143 );
144
145 /**
146 * Collapse the observed ALAR configuration to the prop shape: the action when
147 * enabled, `undefined` when disabled or never configured.
148 */
149 const observedAlarAction = (
150 protection: shield.Protection,
151 ): ApplicationLayerAutomaticResponseAction | undefined => {
152 const config = protection.ApplicationLayerAutomaticResponseConfiguration;
153 if (config?.Status !== "ENABLED") return undefined;
154 return config.Action.Block !== undefined ? "BLOCK" : "COUNT";
155 };
156
157 const buildAttrs = (protection: shield.Protection, tags: Record<string, string>) => ({
158 protectionId: protection.Id!,
159 protectionArn: protection.ProtectionArn!,
160 name: protection.Name!,
161 resourceArn: protection.ResourceArn!,
162 healthCheckIds: [...(protection.HealthCheckIds ?? [])],
163 applicationLayerAutomaticResponse: observedAlarAction(protection),
164 tags,
165 });
166
167 export const ProtectionProvider = () =>
168 Provider.effect(
169 Protection,
170 Effect.gen(function* () {
171 const toName = (id: string, props: { name?: string }) =>
172 props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 128 });
173
174 const syncTags = Effect.fn(function* (
175 protectionArn: string,
176 desiredTags: Record<string, string>,
177 ) {
178 const observedTags = yield* readProtectionTags(protectionArn);
179 const { upsert, removed } = diffTags(observedTags, desiredTags);
180 if (upsert.length > 0) {
181 yield* shield.tagResource({
182 ResourceARN: protectionArn,
183 Tags: upsert,
184 });
185 }
186 if (removed.length > 0) {
187 yield* shield.untagResource({
188 ResourceARN: protectionArn,
189 TagKeys: removed,
190 });
191 }
192 });
193
194 // Automatic application-layer DDoS mitigation: enable, update, or
195 // disable based on the delta between OBSERVED and desired state.
196 const syncApplicationLayerAutomaticResponse = Effect.fn(function* (
197 resourceArn: string,
198 observed: ApplicationLayerAutomaticResponseAction | undefined,
199 desired: ApplicationLayerAutomaticResponseAction | undefined,
200 ) {
201 if (observed === desired) return;
202 if (desired === undefined) {
203 yield* shield.disableApplicationLayerAutomaticResponse({
204 ResourceArn: resourceArn,
205 });
206 return;
207 }
208 const Action = desired === "BLOCK" ? { Block: {} } : { Count: {} };
209 if (observed === undefined) {
210 yield* shield.enableApplicationLayerAutomaticResponse({
211 ResourceArn: resourceArn,
212 Action,
213 });
214 } else {
215 yield* shield.updateApplicationLayerAutomaticResponse({
216 ResourceArn: resourceArn,
217 Action,
218 });
219 }
220 });
221
222 const syncHealthChecks = Effect.fn(function* (
223 protectionId: string,
224 observedIds: readonly string[],
225 desiredArns: readonly string[],
226 ) {
227 const desiredIds = desiredArns.map(healthCheckIdFromArn);
228 for (const arn of desiredArns) {
229 if (!observedIds.includes(healthCheckIdFromArn(arn))) {
230 yield* shield.associateHealthCheck({
231 ProtectionId: protectionId,
232 HealthCheckArn: arn,
233 });
234 }
235 }
236 for (const observedId of observedIds) {
237 if (!desiredIds.includes(observedId)) {
238 yield* shield.disassociateHealthCheck({
239 ProtectionId: protectionId,
240 HealthCheckArn: healthCheckArnFromId(observedId),
241 });
242 }
243 }
244 });
245
246 return {
247 stables: ["protectionId", "protectionArn", "name", "resourceArn"],
248
249 diff: Effect.fn(function* ({ id, olds, news }) {
250 if (!isResolved(news)) return;
251 if (olds === undefined) return;
252 if (olds.resourceArn !== news.resourceArn) {
253 return { action: "replace" } as const;
254 }
255 if ((yield* toName(id, olds)) !== (yield* toName(id, news))) {
256 return { action: "replace" } as const;
257 }
258 }),
259
260 read: Effect.fn(function* ({ id, olds, output }) {
261 const resourceArn = output?.resourceArn ?? olds?.resourceArn;
262 if (resourceArn === undefined) return undefined;
263 const protection = yield* observeByResourceArn(resourceArn);
264 if (!protection?.Id || !protection.ProtectionArn) return undefined;
265 const tags = yield* readProtectionTags(protection.ProtectionArn);
266 const attrs = buildAttrs(protection, tags);
267 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
268 }),
269
270 reconcile: Effect.fn(function* ({ id, news, session }) {
271 const name = yield* toName(id, news);
272 const internalTags = yield* createInternalTags(id);
273 const desiredTags = { ...news.tags, ...internalTags };
274
275 // 1. OBSERVE — cloud state is authoritative; a protection is keyed
276 // by the resource it protects.
277 let protection = yield* observeByResourceArn(news.resourceArn);
278
279 // 2. ENSURE — create if missing; tolerate the AlreadyExists race.
280 if (!protection?.Id) {
281 yield* shield
282 .createProtection({
283 Name: name,
284 ResourceArn: news.resourceArn,
285 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
286 Key,
287 Value,
288 })),
289 })
290 .pipe(Effect.catchTag("ResourceAlreadyExistsException", () => Effect.void));
291 protection = yield* observeByResourceArn(news.resourceArn);
292 if (!protection?.Id || !protection.ProtectionArn) {
293 return yield* new ProtectionUnexpectedResponse({
294 message: `Failed to create or read Shield protection for ${news.resourceArn}`,
295 });
296 }
297 }
298
299 // 3. SYNC health check associations — diff observed against desired.
300 yield* syncHealthChecks(
301 protection.Id,
302 protection.HealthCheckIds ?? [],
303 news.healthCheckArns ?? [],
304 );
305
306 // 3b. SYNC automatic application-layer DDoS mitigation.
307 yield* syncApplicationLayerAutomaticResponse(
308 news.resourceArn,
309 observedAlarAction(protection),
310 news.applicationLayerAutomaticResponse,
311 );
312
313 // 3c. SYNC tags — diff against OBSERVED cloud tags.
314 yield* syncTags(protection.ProtectionArn!, desiredTags);
315
316 // 4. RETURN fresh attributes.
317 const final = yield* observeByResourceArn(news.resourceArn);
318 yield* session.note(protection.ProtectionArn!);
319 return buildAttrs(final ?? protection, desiredTags);
320 }),
321
322 // Enumerate every protection in the account. Without a Shield Advanced
323 // subscription the account cannot have any protections.
324 list: () =>
325 Effect.gen(function* () {
326 const protections = yield* shield.listProtections.pages({}).pipe(
327 Stream.runCollect,
328 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Protections ?? [])),
329 Effect.catchTag("SubscriptionNotFound", () => Effect.succeed([])),
330 );
331 return yield* Effect.forEach(
332 protections.filter((p) => p.Id != null && p.ProtectionArn != null),
333 (protection) =>
334 Effect.gen(function* () {
335 const tags = yield* readProtectionTags(protection.ProtectionArn!);
336 return buildAttrs(protection, tags);
337 }),
338 { concurrency: 5 },
339 );
340 }),
341
342 delete: Effect.fn(function* ({ output }) {
343 yield* shield
344 .deleteProtection({ ProtectionId: output.protectionId })
345 .pipe(
346 Effect.catchTag(
347 ["ResourceNotFoundException", "SubscriptionNotFound"],
348 () => Effect.void,
349 ),
350 );
351 }),
352 };
353 }),
354 );