The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as config from "@distilled.cloud/aws/config-service"; |
| 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, createTagsList, diffTags, hasAlchemyTags } from "alchemy/Tags"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Schedule from "effect/Schedule"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | |
| 14 | /** |
| 15 | * How often AWS Config runs evaluations for a periodic rule. |
| 16 | */ |
| 17 | export type ConfigMaximumExecutionFrequency = |
| 18 | | "One_Hour" |
| 19 | | "Three_Hours" |
| 20 | | "Six_Hours" |
| 21 | | "Twelve_Hours" |
| 22 | | "TwentyFour_Hours"; |
| 23 | |
| 24 | export interface ConfigRuleSourceDetail { |
| 25 | /** |
| 26 | * The source of the event that triggers evaluation. |
| 27 | * @default "aws.config" |
| 28 | */ |
| 29 | eventSource?: string; |
| 30 | /** |
| 31 | * The type of notification that triggers evaluation, e.g. |
| 32 | * `ConfigurationItemChangeNotification` or `ScheduledNotification`. |
| 33 | */ |
| 34 | messageType?: string; |
| 35 | /** |
| 36 | * The frequency at which the rule is evaluated when the message type is |
| 37 | * `ScheduledNotification`. |
| 38 | */ |
| 39 | maximumExecutionFrequency?: ConfigMaximumExecutionFrequency; |
| 40 | } |
| 41 | |
| 42 | export interface ConfigRuleSource { |
| 43 | /** |
| 44 | * Who owns and maintains the rule logic. `AWS` for managed rules, |
| 45 | * `CUSTOM_LAMBDA` for Lambda-backed custom rules, `CUSTOM_POLICY` for |
| 46 | * Guard custom-policy rules. |
| 47 | */ |
| 48 | owner: "AWS" | "CUSTOM_LAMBDA" | "CUSTOM_POLICY"; |
| 49 | /** |
| 50 | * For managed rules, the rule identifier, e.g. |
| 51 | * `S3_BUCKET_VERSIONING_ENABLED`. For custom Lambda rules, the ARN of the |
| 52 | * rule's Lambda function. |
| 53 | */ |
| 54 | sourceIdentifier?: string; |
| 55 | /** |
| 56 | * The source and type of events that trigger evaluation. Required for |
| 57 | * custom Lambda rules; not used for managed rules. |
| 58 | */ |
| 59 | sourceDetails?: ConfigRuleSourceDetail[]; |
| 60 | /** |
| 61 | * Guard policy details for `CUSTOM_POLICY` rules. |
| 62 | */ |
| 63 | customPolicyDetails?: { |
| 64 | /** |
| 65 | * The runtime system for the Guard policy, e.g. `guard-2.x.x`. |
| 66 | */ |
| 67 | policyRuntime: string; |
| 68 | /** |
| 69 | * The Guard policy text. |
| 70 | */ |
| 71 | policyText: string; |
| 72 | /** |
| 73 | * Whether to log Guard debug output. |
| 74 | * @default false |
| 75 | */ |
| 76 | enableDebugLogDelivery?: boolean; |
| 77 | }; |
| 78 | } |
| 79 | |
| 80 | export interface ConfigRuleScope { |
| 81 | /** |
| 82 | * Resource types the rule evaluates, e.g. `AWS::S3::Bucket`. |
| 83 | */ |
| 84 | complianceResourceTypes?: string[]; |
| 85 | /** |
| 86 | * Tag key applied to resources the rule evaluates. |
| 87 | */ |
| 88 | tagKey?: string; |
| 89 | /** |
| 90 | * Tag value applied to resources the rule evaluates. Requires `tagKey`. |
| 91 | */ |
| 92 | tagValue?: string; |
| 93 | /** |
| 94 | * The ID of a single resource the rule evaluates. Requires exactly one |
| 95 | * entry in `complianceResourceTypes`. |
| 96 | */ |
| 97 | complianceResourceId?: string; |
| 98 | } |
| 99 | |
| 100 | export interface ConfigRuleProps { |
| 101 | /** |
| 102 | * Name of the Config rule. Changing the name replaces the rule. |
| 103 | * @default ${app}-${stage}-${id} |
| 104 | */ |
| 105 | configRuleName?: string; |
| 106 | /** |
| 107 | * Description of the rule. |
| 108 | */ |
| 109 | description?: string; |
| 110 | /** |
| 111 | * The rule's source: owner (AWS-managed, custom Lambda, or Guard custom |
| 112 | * policy) plus the identifier of the rule logic. |
| 113 | */ |
| 114 | source: ConfigRuleSource; |
| 115 | /** |
| 116 | * Input parameters passed to the rule's evaluation logic, serialized to |
| 117 | * JSON. |
| 118 | */ |
| 119 | inputParameters?: Record<string, string>; |
| 120 | /** |
| 121 | * The maximum frequency at which AWS Config runs evaluations for a |
| 122 | * periodic rule. |
| 123 | */ |
| 124 | maximumExecutionFrequency?: ConfigMaximumExecutionFrequency; |
| 125 | /** |
| 126 | * Restricts the rule to a subset of resources by type, tag, or ID. When |
| 127 | * omitted, evaluations are triggered for all supported resources. |
| 128 | */ |
| 129 | scope?: ConfigRuleScope; |
| 130 | /** |
| 131 | * The evaluation modes the rule runs in. |
| 132 | * @default ["DETECTIVE"] |
| 133 | */ |
| 134 | evaluationModes?: ("DETECTIVE" | "PROACTIVE")[]; |
| 135 | /** |
| 136 | * Tags to apply to the rule. Merged with internal Alchemy tags. |
| 137 | */ |
| 138 | tags?: Record<string, string>; |
| 139 | } |
| 140 | |
| 141 | export interface ConfigRule extends Resource< |
| 142 | "AWS.Config.ConfigRule", |
| 143 | ConfigRuleProps, |
| 144 | { |
| 145 | /** Physical name of the config rule. */ |
| 146 | configRuleName: string; |
| 147 | /** ARN of the config rule. */ |
| 148 | configRuleArn: string; |
| 149 | /** Unique AWS-assigned rule ID. */ |
| 150 | configRuleId: string; |
| 151 | }, |
| 152 | never, |
| 153 | Providers |
| 154 | > {} |
| 155 | |
| 156 | /** |
| 157 | * An AWS Config rule that evaluates whether your AWS resources comply with |
| 158 | * a desired configuration — either an AWS-managed rule, a custom Lambda |
| 159 | * rule, or a Guard custom-policy rule. |
| 160 | * |
| 161 | * The account/region must have an AWS Config configuration recorder before |
| 162 | * rules can be created (see `AWS.Config.ConfigurationRecorder`). |
| 163 | * ### Creating Rules |
| 164 | * **Example:** AWS-managed rule |
| 165 | * ```typescript |
| 166 | * import * as Config from "@alchemy.run/aws/Config"; |
| 167 | * |
| 168 | * const rule = yield* Config.ConfigRule("BucketVersioning", { |
| 169 | * source: { |
| 170 | * owner: "AWS", |
| 171 | * sourceIdentifier: "S3_BUCKET_VERSIONING_ENABLED", |
| 172 | * }, |
| 173 | * }); |
| 174 | * ``` |
| 175 | * |
| 176 | * **Example:** Managed rule with input parameters and scope |
| 177 | * ```typescript |
| 178 | * const rule = yield* Config.ConfigRule("RequiredTags", { |
| 179 | * description: "All buckets must carry a team tag", |
| 180 | * source: { owner: "AWS", sourceIdentifier: "REQUIRED_TAGS" }, |
| 181 | * inputParameters: { tag1Key: "team" }, |
| 182 | * scope: { complianceResourceTypes: ["AWS::S3::Bucket"] }, |
| 183 | * }); |
| 184 | * ``` |
| 185 | * |
| 186 | * ### Periodic Evaluation |
| 187 | * **Example:** Evaluate on a schedule |
| 188 | * ```typescript |
| 189 | * const rule = yield* Config.ConfigRule("RootMfa", { |
| 190 | * source: { |
| 191 | * owner: "AWS", |
| 192 | * sourceIdentifier: "ROOT_ACCOUNT_MFA_ENABLED", |
| 193 | * }, |
| 194 | * maximumExecutionFrequency: "TwentyFour_Hours", |
| 195 | * }); |
| 196 | * ``` |
| 197 | * |
| 198 | * @resource |
| 199 | */ |
| 200 | export const ConfigRule = Resource<ConfigRule>("AWS.Config.ConfigRule"); |
| 201 | |
| 202 | /** |
| 203 | * Raised when a Config rule that was just written does not become visible |
| 204 | * to `DescribeConfigRules` within the reconciler's bounded wait. |
| 205 | */ |
| 206 | export class ConfigRuleNotVisible extends Data.TaggedError("ConfigRuleNotVisible")<{ |
| 207 | message: string; |
| 208 | }> {} |
| 209 | |
| 210 | /** |
| 211 | * `PutConfigRule`/`DeleteConfigRule` reject with `ResourceInUseException` |
| 212 | * while a rule is in the `DELETING` state (rule deletion is asynchronous). |
| 213 | * Retry it on a bounded schedule (~40s). |
| 214 | * |
| 215 | * Explicitly typed: inlining `Effect.retry` with options in provider |
| 216 | * lifecycle code can widen the provider layer to `unknown` in declaration |
| 217 | * emit. |
| 218 | * |
| 219 | * @internal |
| 220 | */ |
| 221 | const retryWhileRuleInUse = <A, E extends { readonly _tag: string }, R>( |
| 222 | self: Effect.Effect<A, E, R>, |
| 223 | ): Effect.Effect<A, E, R> => |
| 224 | Effect.retry(self, { |
| 225 | while: (e) => e._tag === "ResourceInUseException", |
| 226 | schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(20)]), |
| 227 | }); |
| 228 | |
| 229 | /** |
| 230 | * A freshly-put rule can take a moment to become visible to |
| 231 | * `DescribeConfigRules`. Bounded retry (~10s). |
| 232 | * @internal |
| 233 | */ |
| 234 | const retryWhileNotVisible = <A, E extends { readonly _tag: string }, R>( |
| 235 | self: Effect.Effect<A, E, R>, |
| 236 | ): Effect.Effect<A, E, R> => |
| 237 | Effect.retry(self, { |
| 238 | while: (e) => e._tag === "ConfigRuleNotVisible", |
| 239 | schedule: Schedule.max([Schedule.fixed("1 second"), Schedule.recurs(10)]), |
| 240 | }); |
| 241 | |
| 242 | /** |
| 243 | * Canonical JSON for structural comparison: recursively sorts object keys |
| 244 | * and drops `undefined` members so wire objects with different key orders |
| 245 | * compare equal. |
| 246 | * @internal |
| 247 | */ |
| 248 | const canonical = (value: unknown): string => { |
| 249 | const sortKeys = (v: unknown): unknown => { |
| 250 | if (Array.isArray(v)) return v.map(sortKeys); |
| 251 | if (v !== null && typeof v === "object") { |
| 252 | return Object.fromEntries( |
| 253 | Object.entries(v as Record<string, unknown>) |
| 254 | .filter(([, member]) => member !== undefined) |
| 255 | .sort(([a], [b]) => a.localeCompare(b)) |
| 256 | .map(([k, member]) => [k, sortKeys(member)]), |
| 257 | ); |
| 258 | } |
| 259 | return v ?? null; |
| 260 | }; |
| 261 | return JSON.stringify(sortKeys(value)); |
| 262 | }; |
| 263 | |
| 264 | /** @internal */ |
| 265 | const parseParams = (params: string | undefined): Record<string, string> => |
| 266 | params === undefined || params === "" ? {} : JSON.parse(params); |
| 267 | |
| 268 | export const ConfigRuleProvider = () => |
| 269 | Provider.effect( |
| 270 | ConfigRule, |
| 271 | Effect.gen(function* () { |
| 272 | const createRuleName = Effect.fn(function* ( |
| 273 | id: string, |
| 274 | props: Pick<ConfigRuleProps, "configRuleName">, |
| 275 | ) { |
| 276 | return props.configRuleName ?? (yield* createPhysicalName({ id, maxLength: 128 })); |
| 277 | }); |
| 278 | |
| 279 | const toWireRule = (name: string, props: ConfigRuleProps): config.ConfigRule => ({ |
| 280 | ConfigRuleName: name, |
| 281 | Description: props.description, |
| 282 | Source: { |
| 283 | Owner: props.source.owner, |
| 284 | SourceIdentifier: props.source.sourceIdentifier, |
| 285 | SourceDetails: props.source.sourceDetails?.map((d) => ({ |
| 286 | EventSource: d.eventSource ?? "aws.config", |
| 287 | MessageType: d.messageType, |
| 288 | MaximumExecutionFrequency: d.maximumExecutionFrequency, |
| 289 | })), |
| 290 | CustomPolicyDetails: props.source.customPolicyDetails |
| 291 | ? { |
| 292 | PolicyRuntime: props.source.customPolicyDetails.policyRuntime, |
| 293 | PolicyText: props.source.customPolicyDetails.policyText, |
| 294 | EnableDebugLogDelivery: props.source.customPolicyDetails.enableDebugLogDelivery, |
| 295 | } |
| 296 | : undefined, |
| 297 | }, |
| 298 | InputParameters: props.inputParameters ? JSON.stringify(props.inputParameters) : undefined, |
| 299 | MaximumExecutionFrequency: props.maximumExecutionFrequency, |
| 300 | Scope: props.scope |
| 301 | ? { |
| 302 | ComplianceResourceTypes: props.scope.complianceResourceTypes, |
| 303 | TagKey: props.scope.tagKey, |
| 304 | TagValue: props.scope.tagValue, |
| 305 | ComplianceResourceId: props.scope.complianceResourceId, |
| 306 | } |
| 307 | : undefined, |
| 308 | EvaluationModes: props.evaluationModes?.map((mode) => ({ |
| 309 | Mode: mode, |
| 310 | })), |
| 311 | }); |
| 312 | |
| 313 | // A rule is in sync when every aspect the user controls matches the |
| 314 | // OBSERVED cloud state. Fields AWS defaults when unspecified |
| 315 | // (EvaluationModes, SourceDetails) are only compared when the user |
| 316 | // declared them, so an omitted prop never causes perpetual drift. |
| 317 | const ruleInSync = (observed: config.ConfigRule, desired: config.ConfigRule): boolean => |
| 318 | (observed.Description ?? undefined) === desired.Description && |
| 319 | (observed.MaximumExecutionFrequency ?? undefined) === desired.MaximumExecutionFrequency && |
| 320 | canonical(parseParams(observed.InputParameters)) === |
| 321 | canonical(parseParams(desired.InputParameters)) && |
| 322 | canonical(observed.Scope) === canonical(desired.Scope) && |
| 323 | observed.Source.Owner === desired.Source.Owner && |
| 324 | (observed.Source.SourceIdentifier ?? undefined) === desired.Source.SourceIdentifier && |
| 325 | (desired.Source.SourceDetails === undefined || |
| 326 | canonical(observed.Source.SourceDetails) === canonical(desired.Source.SourceDetails)) && |
| 327 | (desired.Source.CustomPolicyDetails === undefined || |
| 328 | canonical(observed.Source.CustomPolicyDetails) === |
| 329 | canonical(desired.Source.CustomPolicyDetails)) && |
| 330 | (desired.EvaluationModes === undefined || |
| 331 | canonical(observed.EvaluationModes) === canonical(desired.EvaluationModes)); |
| 332 | |
| 333 | const observeRule = Effect.fn(function* (ruleName: string) { |
| 334 | const response = yield* config |
| 335 | .describeConfigRules({ ConfigRuleNames: [ruleName] }) |
| 336 | .pipe( |
| 337 | Effect.catchTag("NoSuchConfigRuleException", () => Effect.succeed({ ConfigRules: [] })), |
| 338 | ); |
| 339 | return (response.ConfigRules ?? []).at(0); |
| 340 | }); |
| 341 | |
| 342 | const observedTags = (arn: string) => |
| 343 | config.listTagsForResource({ ResourceArn: arn }).pipe( |
| 344 | Effect.map((r) => |
| 345 | Object.fromEntries( |
| 346 | (r.Tags ?? []).flatMap((t) => (t.Key !== undefined ? [[t.Key, t.Value ?? ""]] : [])), |
| 347 | ), |
| 348 | ), |
| 349 | Effect.catchTag("ResourceNotFoundException", () => |
| 350 | Effect.succeed({} as Record<string, string>), |
| 351 | ), |
| 352 | ); |
| 353 | |
| 354 | const toAttrs = (rule: config.ConfigRule) => ({ |
| 355 | configRuleName: rule.ConfigRuleName!, |
| 356 | configRuleArn: rule.ConfigRuleArn!, |
| 357 | configRuleId: rule.ConfigRuleId!, |
| 358 | }); |
| 359 | |
| 360 | return ConfigRule.Provider.of({ |
| 361 | stables: ["configRuleName", "configRuleArn", "configRuleId"], |
| 362 | list: () => |
| 363 | config.describeConfigRules.items({}).pipe( |
| 364 | Stream.runCollect, |
| 365 | Effect.map((rules) => |
| 366 | Array.from(rules).flatMap((rule) => |
| 367 | rule.ConfigRuleName && rule.ConfigRuleArn && rule.ConfigRuleId |
| 368 | ? [toAttrs(rule)] |
| 369 | : [], |
| 370 | ), |
| 371 | ), |
| 372 | ), |
| 373 | read: Effect.fn(function* ({ id, olds, output }) { |
| 374 | const ruleName = output?.configRuleName ?? (yield* createRuleName(id, olds ?? {})); |
| 375 | const rule = yield* observeRule(ruleName); |
| 376 | if (rule?.ConfigRuleArn === undefined) return undefined; |
| 377 | const attrs = toAttrs(rule); |
| 378 | const tags = yield* observedTags(rule.ConfigRuleArn); |
| 379 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 380 | }), |
| 381 | diff: Effect.fn(function* ({ id, news, olds }) { |
| 382 | if (!isResolved(news)) return undefined; |
| 383 | const oldName = yield* createRuleName(id, olds ?? {}); |
| 384 | const newName = yield* createRuleName(id, news); |
| 385 | if (oldName !== newName) { |
| 386 | return { action: "replace" } as const; |
| 387 | } |
| 388 | // fall through: engine default update logic for mutable fields |
| 389 | }), |
| 390 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 391 | const ruleName = output?.configRuleName ?? (yield* createRuleName(id, news)); |
| 392 | const internalTags = yield* createInternalTags(id); |
| 393 | const desiredTags = { ...news.tags, ...internalTags }; |
| 394 | const desired = toWireRule(ruleName, news); |
| 395 | |
| 396 | // 1. OBSERVE — cloud state is authoritative. |
| 397 | const observed = yield* observeRule(ruleName); |
| 398 | |
| 399 | // 2+3. ENSURE + SYNC — PutConfigRule is a full upsert, so a single |
| 400 | // call covers both the missing-rule and the drifted-rule case. |
| 401 | // Skip the API entirely on no-op. A rule stuck in `DELETING` |
| 402 | // rejects with the typed ResourceInUseException; bounded retry. |
| 403 | if (observed === undefined || !ruleInSync(observed, desired)) { |
| 404 | yield* retryWhileRuleInUse( |
| 405 | config.putConfigRule({ |
| 406 | ConfigRule: desired, |
| 407 | Tags: createTagsList(desiredTags), |
| 408 | }), |
| 409 | ); |
| 410 | } |
| 411 | |
| 412 | // 4. RETURN fresh attributes — re-observe for the ARN and ID |
| 413 | // (PutConfigRule returns an empty body). |
| 414 | const live = yield* retryWhileNotVisible( |
| 415 | observeRule(ruleName).pipe( |
| 416 | Effect.flatMap((rule) => |
| 417 | rule?.ConfigRuleArn !== undefined && rule.ConfigRuleId !== undefined |
| 418 | ? Effect.succeed(rule) |
| 419 | : Effect.fail( |
| 420 | new ConfigRuleNotVisible({ |
| 421 | message: `Config rule '${ruleName}' was written but is not yet visible to DescribeConfigRules`, |
| 422 | }), |
| 423 | ), |
| 424 | ), |
| 425 | ), |
| 426 | ); |
| 427 | |
| 428 | // 3b. SYNC TAGS — diff against OBSERVED cloud tags so adoption |
| 429 | // converges (Put-time Tags only apply on first create). |
| 430 | const currentTags = yield* observedTags(live.ConfigRuleArn!); |
| 431 | const { upsert, removed } = diffTags(currentTags, desiredTags); |
| 432 | if (upsert.length > 0) { |
| 433 | yield* config.tagResource({ |
| 434 | ResourceArn: live.ConfigRuleArn!, |
| 435 | Tags: upsert, |
| 436 | }); |
| 437 | } |
| 438 | if (removed.length > 0) { |
| 439 | yield* config.untagResource({ |
| 440 | ResourceArn: live.ConfigRuleArn!, |
| 441 | TagKeys: removed, |
| 442 | }); |
| 443 | } |
| 444 | |
| 445 | yield* session.note(ruleName); |
| 446 | return toAttrs(live); |
| 447 | }), |
| 448 | delete: Effect.fn(function* ({ output }) { |
| 449 | // Rule deletion is asynchronous (state DELETING); a concurrent |
| 450 | // put/delete surfaces as ResourceInUseException — bounded retry. |
| 451 | yield* retryWhileRuleInUse( |
| 452 | config.deleteConfigRule({ |
| 453 | ConfigRuleName: output.configRuleName, |
| 454 | }), |
| 455 | ).pipe(Effect.catchTag("NoSuchConfigRuleException", () => Effect.void)); |
| 456 | }), |
| 457 | }); |
| 458 | }), |
| 459 | ); |