@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 232 lines 7.97 KB
Raw
1 import type * as WAFV2 from "@distilled.cloud/aws/wafv2";
2 import * as wafv2 from "@distilled.cloud/aws/wafv2";
3 import { deepEqual, isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import type { Providers } from "../Providers.ts";
9 import { type WafScope, withWafScope } from "./internal.ts";
10
11 export interface LoggingConfigurationProps {
12 /**
13 * ARN of the {@link WebACL} to enable logging for. Changing the web ACL
14 * replaces the logging configuration.
15 */
16 resourceArn: string;
17 /**
18 * ARNs of the log destinations — an Amazon Kinesis Data Firehose delivery
19 * stream, a CloudWatch Logs log group, or an S3 bucket. The destination
20 * name must begin with `aws-waf-logs-`. A trailing `:*` on a CloudWatch
21 * Logs log group ARN is stripped automatically (WAF rejects it).
22 */
23 logDestinationConfigs: string[];
24 /**
25 * Parts of each logged request to redact (e.g. a specific header or the
26 * query string). Only `SingleHeader`, `UriPath`, `QueryString`, and
27 * `Method` are supported by WAF. Raw WAFv2 API shapes.
28 */
29 redactedFields?: WAFV2.FieldToMatch[];
30 /**
31 * Filter which requests are logged based on rule action and labels.
32 */
33 loggingFilter?: WAFV2.LoggingFilter;
34 }
35
36 export interface LoggingConfiguration extends Resource<
37 "AWS.WAFv2.LoggingConfiguration",
38 LoggingConfigurationProps,
39 {
40 /**
41 * ARN of the web ACL the logging configuration applies to.
42 */
43 resourceArn: string;
44 /**
45 * Scope of the web ACL (derived from its ARN).
46 */
47 scope: WafScope;
48 /**
49 * ARNs of the configured log destinations.
50 */
51 logDestinationConfigs: string[];
52 },
53 never,
54 Providers
55 > {}
56
57 /**
58 * The logging configuration of an AWS WAFv2 {@link WebACL} — streams full
59 * web request logs to a Kinesis Data Firehose delivery stream, a CloudWatch
60 * Logs log group, or an S3 bucket.
61 *
62 * The destination must be named with the `aws-waf-logs-` prefix. A web ACL
63 * has at most one logging configuration; deleting this resource disables
64 * logging.
65 *
66 * ### Configuring Logging
67 * **Example:** Log to CloudWatch Logs
68 * ```typescript
69 * const logGroup = yield* AWS.Logs.LogGroup("WafLogs", {
70 * logGroupName: "aws-waf-logs-my-firewall",
71 * });
72 *
73 * yield* AWS.WAFv2.LoggingConfiguration("Logging", {
74 * resourceArn: acl.webAclArn,
75 * logDestinationConfigs: [logGroup.logGroupArn],
76 * });
77 * ```
78 *
79 * **Example:** Redact Headers and Filter to Blocked Requests
80 * ```typescript
81 * yield* AWS.WAFv2.LoggingConfiguration("Logging", {
82 * resourceArn: acl.webAclArn,
83 * logDestinationConfigs: [logGroup.logGroupArn],
84 * redactedFields: [{ SingleHeader: { Name: "authorization" } }],
85 * loggingFilter: {
86 * DefaultBehavior: "DROP",
87 * Filters: [
88 * {
89 * Behavior: "KEEP",
90 * Requirement: "MEETS_ANY",
91 * Conditions: [{ ActionCondition: { Action: "BLOCK" } }],
92 * },
93 * ],
94 * },
95 * });
96 * ```
97 *
98 * @resource
99 */
100 export const LoggingConfiguration = Resource<LoggingConfiguration>(
101 "AWS.WAFv2.LoggingConfiguration",
102 );
103
104 /**
105 * Derive the scope from a WAFv2 entity ARN. CLOUDFRONT-scoped ARNs carry a
106 * `global/` resource prefix (`arn:aws:wafv2:us-east-1:acct:global/webacl/…`);
107 * REGIONAL ARNs carry `regional/`.
108 */
109 const scopeOfArn = (arn: string): WafScope =>
110 arn.split(":")[5]?.startsWith("global/") ? "CLOUDFRONT" : "REGIONAL";
111
112 /**
113 * WAF rejects CloudWatch Logs log group ARNs with the `:*` suffix that IAM
114 * policies (and the Logs API) use — strip it.
115 */
116 const normalizeDestination = (arn: string): string => (arn.endsWith(":*") ? arn.slice(0, -2) : arn);
117
118 /**
119 * The first PutLoggingConfiguration in an account creates the WAF
120 * service-linked role; until that completes the API surfaces
121 * `WAFServiceLinkedRoleErrorException` ("Retry your request"). Bounded
122 * retry (~30s).
123 */
124 const retryServiceLinkedRole = <A, E extends { _tag: string }, R>(
125 self: Effect.Effect<A, E, R>,
126 ): Effect.Effect<A, E, R> =>
127 Effect.retry(self, {
128 while: (e) => e._tag === "WAFServiceLinkedRoleErrorException",
129 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
130 });
131
132 export const LoggingConfigurationProvider = () =>
133 Provider.effect(
134 LoggingConfiguration,
135 Effect.gen(function* () {
136 const readConfig = Effect.fn(function* (resourceArn: string) {
137 const scope = scopeOfArn(resourceArn);
138 return yield* withWafScope(
139 scope,
140 wafv2
141 .getLoggingConfiguration({ ResourceArn: resourceArn })
142 .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)),
143 );
144 });
145
146 const toAttrs = (resourceArn: string, destinations: readonly string[]) => ({
147 resourceArn,
148 scope: scopeOfArn(resourceArn),
149 logDestinationConfigs: [...destinations],
150 });
151
152 return LoggingConfiguration.Provider.of({
153 stables: ["resourceArn", "scope"],
154
155 // A logging configuration is a singleton setting keyed by its web
156 // ACL; enumerating them standalone is not useful for orphan scans
157 // (the web ACL itself is the discoverable resource).
158 list: () => Effect.succeed([]),
159
160 diff: Effect.fn(function* ({ news, olds }) {
161 if (!isResolved(news)) return undefined;
162 if (olds.resourceArn !== news.resourceArn) {
163 return { action: "replace" } as const;
164 }
165 }),
166
167 read: Effect.fn(function* ({ olds, output }) {
168 const resourceArn = output?.resourceArn ?? olds?.resourceArn;
169 if (resourceArn === undefined) return undefined;
170 const found = yield* readConfig(resourceArn);
171 const config = found?.LoggingConfiguration;
172 if (!config) return undefined;
173 return toAttrs(resourceArn, config.LogDestinationConfigs ?? []);
174 }),
175
176 reconcile: Effect.fn(function* ({ news, session }) {
177 const scope = scopeOfArn(news.resourceArn);
178 const desired: WAFV2.LoggingConfiguration = {
179 ResourceArn: news.resourceArn,
180 LogDestinationConfigs: news.logDestinationConfigs.map(normalizeDestination),
181 RedactedFields: news.redactedFields,
182 LoggingFilter: news.loggingFilter,
183 };
184
185 // Observe — PutLoggingConfiguration is a true upsert, so only
186 // call it when the observed configuration drifts from desired.
187 const observed = yield* readConfig(news.resourceArn);
188 const current = observed?.LoggingConfiguration;
189 const drifted = !deepEqual(
190 {
191 LogDestinationConfigs: current?.LogDestinationConfigs ?? [],
192 RedactedFields: current?.RedactedFields,
193 LoggingFilter: current?.LoggingFilter,
194 },
195 {
196 LogDestinationConfigs: desired.LogDestinationConfigs,
197 RedactedFields: desired.RedactedFields,
198 LoggingFilter: desired.LoggingFilter,
199 },
200 { stripNullish: true },
201 );
202 if (current === undefined || drifted) {
203 yield* retryServiceLinkedRole(
204 withWafScope(
205 scope,
206 wafv2.putLoggingConfiguration({
207 LoggingConfiguration: desired,
208 }),
209 ),
210 );
211 }
212
213 yield* session.note(news.resourceArn);
214 return toAttrs(news.resourceArn, desired.LogDestinationConfigs);
215 }),
216
217 delete: Effect.fn(function* ({ output }) {
218 const scope = scopeOfArn(output.resourceArn);
219 // Idempotent — the configuration (or the web ACL itself) may
220 // already be gone.
221 yield* withWafScope(
222 scope,
223 wafv2
224 .deleteLoggingConfiguration({
225 ResourceArn: output.resourceArn,
226 })
227 .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.void)),
228 );
229 }),
230 });
231 }),
232 );