| 1 | import * as AWS from "@/AWS"; |
| 2 | import { ConfigRule } from "@/AWS/Config"; |
| 3 | import * as Test from "@/Test/Alchemy"; |
| 4 | import * as config from "@distilled.cloud/aws/config-service"; |
| 5 | import * as iam from "@distilled.cloud/aws/iam"; |
| 6 | import { expect } from "alchemy-test"; |
| 7 | import * as Data from "effect/Data"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Schedule from "effect/Schedule"; |
| 10 | import { makeConfigTestLease } from "./TestLease.ts"; |
| 11 | |
| 12 | const { test, beforeAll, afterAll } = Test.make({ providers: AWS.providers() }); |
| 13 | const testLease = makeConfigTestLease(); |
| 14 | |
| 15 | // Acquire outside the individual lifecycle timer. Bindings holds the same |
| 16 | // account/Region recorder lease for its file-long fixture, and queueing behind |
| 17 | // it is scheduling rather than part of this rule's cloud-operation budget. |
| 18 | beforeAll(testLease.acquire, { timeout: 240_000 }); |
| 19 | afterAll(testLease.release); |
| 20 | |
| 21 | // Ungated typed-error probe: prove the distilled error union carries the |
| 22 | // not-found tag this provider's read/delete paths depend on. Runs in every |
| 23 | // CI pass at near-zero cost. |
| 24 | test.provider( |
| 25 | "describeConfigRules on a nonexistent rule fails with NoSuchConfigRuleException", |
| 26 | () => |
| 27 | Effect.gen(function* () { |
| 28 | const error = yield* Effect.flip( |
| 29 | config.describeConfigRules({ |
| 30 | ConfigRuleNames: ["alchemy-nonexistent-config-rule-probe"], |
| 31 | }), |
| 32 | ); |
| 33 | expect(error._tag).toBe("NoSuchConfigRuleException"); |
| 34 | }), |
| 35 | { tags: ["provider:aws", "provider:aws:config", "live"] }, |
| 36 | ); |
| 37 | |
| 38 | const findRule = (ruleName: string) => |
| 39 | config.describeConfigRules({ ConfigRuleNames: [ruleName] }).pipe( |
| 40 | Effect.map((r) => (r.ConfigRules ?? []).at(0)), |
| 41 | Effect.catchTag("NoSuchConfigRuleException", () => |
| 42 | Effect.succeed(undefined), |
| 43 | ), |
| 44 | ); |
| 45 | |
| 46 | class RuleStillExists extends Data.TaggedError("RuleStillExists")<{ |
| 47 | readonly ruleName: string; |
| 48 | readonly state: string; |
| 49 | }> {} |
| 50 | |
| 51 | // Rule deletion is asynchronous — DELETING is an irreversible terminal |
| 52 | // trajectory, so gone-or-DELETING both count as deleted. |
| 53 | const assertRuleDeleting = (ruleName: string) => |
| 54 | findRule(ruleName).pipe( |
| 55 | Effect.flatMap((rule) => |
| 56 | rule === undefined || rule.ConfigRuleState === "DELETING" |
| 57 | ? Effect.void |
| 58 | : Effect.fail( |
| 59 | new RuleStillExists({ |
| 60 | ruleName, |
| 61 | state: rule.ConfigRuleState ?? "unknown", |
| 62 | }), |
| 63 | ), |
| 64 | ), |
| 65 | Effect.retry({ |
| 66 | while: (e) => e._tag === "RuleStillExists", |
| 67 | schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(8)]), |
| 68 | }), |
| 69 | ); |
| 70 | |
| 71 | // PutConfigRule requires a configuration recorder in the account/region |
| 72 | // (NoAvailableConfigurationRecorderException otherwise). Capture-and-restore: |
| 73 | // if the account has none, stand up a minimal recorder on the Config |
| 74 | // service-linked role for the duration of the test and delete it afterwards; |
| 75 | // an existing foreign recorder is left untouched. The recorder name is a |
| 76 | // deterministic constant unique to this test so a leftover from a |
| 77 | // previously-killed run is RECLAIMED (and thus cleaned up at the end) |
| 78 | // instead of orphaning forever. |
| 79 | const TEST_RECORDER_NAME = "alchemy-test-configrule-recorder"; |
| 80 | |
| 81 | const ensureRecorder = Effect.gen(function* () { |
| 82 | const existing = yield* config.describeConfigurationRecorders({}); |
| 83 | const recorders = existing.ConfigurationRecorders ?? []; |
| 84 | if (recorders.some((r) => r.name === TEST_RECORDER_NAME)) { |
| 85 | // Leftover from a previously-killed run — reclaim it so the release |
| 86 | // finalizer deletes it when this run finishes. |
| 87 | return true; |
| 88 | } |
| 89 | if (recorders.length > 0) { |
| 90 | // A foreign recorder already exists (only one per account/region is |
| 91 | // allowed) — use it, never touch it. |
| 92 | return false; |
| 93 | } |
| 94 | yield* iam |
| 95 | .createServiceLinkedRole({ AWSServiceName: "config.amazonaws.com" }) |
| 96 | .pipe( |
| 97 | Effect.catchTag("InvalidInputException", () => Effect.succeed(undefined)), |
| 98 | ); |
| 99 | const role = yield* iam.getRole({ RoleName: "AWSServiceRoleForConfig" }); |
| 100 | // A freshly-created service-linked role can be transiently rejected until |
| 101 | // IAM propagates. |
| 102 | yield* config |
| 103 | .putConfigurationRecorder({ |
| 104 | ConfigurationRecorder: { |
| 105 | name: TEST_RECORDER_NAME, |
| 106 | roleARN: role.Role.Arn, |
| 107 | recordingGroup: { resourceTypes: ["AWS::S3::Bucket"] }, |
| 108 | }, |
| 109 | }) |
| 110 | .pipe( |
| 111 | Effect.retry({ |
| 112 | while: (e) => e._tag === "InvalidRoleException", |
| 113 | schedule: Schedule.max([ |
| 114 | Schedule.fixed("2 seconds"), |
| 115 | Schedule.recurs(15), |
| 116 | ]), |
| 117 | }), |
| 118 | ); |
| 119 | return true; |
| 120 | }); |
| 121 | |
| 122 | // Idempotent: tolerates the recorder already being gone. |
| 123 | const removeRecorderIfCreated = (created: boolean) => |
| 124 | created |
| 125 | ? config |
| 126 | .deleteConfigurationRecorder({ |
| 127 | ConfigurationRecorderName: TEST_RECORDER_NAME, |
| 128 | }) |
| 129 | .pipe( |
| 130 | Effect.catchTag( |
| 131 | "NoSuchConfigurationRecorderException", |
| 132 | () => Effect.void, |
| 133 | ), |
| 134 | Effect.orDie, |
| 135 | ) |
| 136 | : Effect.void; |
| 137 | |
| 138 | test.provider( |
| 139 | "create, update, replace on rename, delete managed config rule", |
| 140 | (stack) => |
| 141 | Effect.gen(function* () { |
| 142 | yield* stack.destroy(); |
| 143 | // acquireRelease guarantees the out-of-band recorder is deleted on |
| 144 | // success, failure, AND interruption; the deterministic name + |
| 145 | // reclaim in ensureRecorder means a re-run converges on any orphan |
| 146 | // from a previously-killed run. |
| 147 | yield* Effect.acquireRelease(ensureRecorder, (created) => |
| 148 | removeRecorderIfCreated(created), |
| 149 | ); |
| 150 | |
| 151 | yield* Effect.gen(function* () { |
| 152 | const rule = yield* stack.deploy( |
| 153 | Effect.gen(function* () { |
| 154 | return yield* ConfigRule("VersioningRule", { |
| 155 | description: "buckets must have versioning enabled", |
| 156 | source: { |
| 157 | owner: "AWS", |
| 158 | sourceIdentifier: "S3_BUCKET_VERSIONING_ENABLED", |
| 159 | }, |
| 160 | scope: { complianceResourceTypes: ["AWS::S3::Bucket"] }, |
| 161 | tags: { Environment: "test" }, |
| 162 | }); |
| 163 | }), |
| 164 | ); |
| 165 | |
| 166 | expect(rule.configRuleName).toBeDefined(); |
| 167 | expect(rule.configRuleArn).toContain(":config-rule/"); |
| 168 | expect(rule.configRuleId).toContain("config-rule-"); |
| 169 | |
| 170 | // Out-of-band verification via distilled. |
| 171 | const created = yield* findRule(rule.configRuleName); |
| 172 | expect(created?.Source.Owner).toBe("AWS"); |
| 173 | expect(created?.Source.SourceIdentifier).toBe( |
| 174 | "S3_BUCKET_VERSIONING_ENABLED", |
| 175 | ); |
| 176 | expect(created?.Description).toBe( |
| 177 | "buckets must have versioning enabled", |
| 178 | ); |
| 179 | expect(created?.Scope?.ComplianceResourceTypes).toEqual([ |
| 180 | "AWS::S3::Bucket", |
| 181 | ]); |
| 182 | const tags = yield* config |
| 183 | .listTagsForResource({ ResourceArn: rule.configRuleArn }) |
| 184 | .pipe( |
| 185 | Effect.map((r) => |
| 186 | Object.fromEntries((r.Tags ?? []).map((t) => [t.Key, t.Value])), |
| 187 | ), |
| 188 | ); |
| 189 | expect(tags.Environment).toBe("test"); |
| 190 | expect(tags["alchemy::id"]).toBe("VersioningRule"); |
| 191 | |
| 192 | // Update the description and tags in place. |
| 193 | const updated = yield* stack.deploy( |
| 194 | Effect.gen(function* () { |
| 195 | return yield* ConfigRule("VersioningRule", { |
| 196 | description: "buckets must have versioning enabled (v2)", |
| 197 | source: { |
| 198 | owner: "AWS", |
| 199 | sourceIdentifier: "S3_BUCKET_VERSIONING_ENABLED", |
| 200 | }, |
| 201 | scope: { complianceResourceTypes: ["AWS::S3::Bucket"] }, |
| 202 | tags: { Environment: "prod" }, |
| 203 | }); |
| 204 | }), |
| 205 | ); |
| 206 | expect(updated.configRuleName).toBe(rule.configRuleName); |
| 207 | expect(updated.configRuleArn).toBe(rule.configRuleArn); |
| 208 | |
| 209 | const afterUpdate = yield* findRule(rule.configRuleName); |
| 210 | expect(afterUpdate?.Description).toBe( |
| 211 | "buckets must have versioning enabled (v2)", |
| 212 | ); |
| 213 | const updatedTags = yield* config |
| 214 | .listTagsForResource({ ResourceArn: rule.configRuleArn }) |
| 215 | .pipe( |
| 216 | Effect.map((r) => |
| 217 | Object.fromEntries((r.Tags ?? []).map((t) => [t.Key, t.Value])), |
| 218 | ), |
| 219 | ); |
| 220 | expect(updatedTags.Environment).toBe("prod"); |
| 221 | |
| 222 | // Renaming replaces the rule. |
| 223 | const renamed = yield* stack.deploy( |
| 224 | Effect.gen(function* () { |
| 225 | return yield* ConfigRule("VersioningRule", { |
| 226 | configRuleName: "alchemy-test-config-rule-renamed", |
| 227 | source: { |
| 228 | owner: "AWS", |
| 229 | sourceIdentifier: "S3_BUCKET_VERSIONING_ENABLED", |
| 230 | }, |
| 231 | scope: { complianceResourceTypes: ["AWS::S3::Bucket"] }, |
| 232 | }); |
| 233 | }), |
| 234 | ); |
| 235 | expect(renamed.configRuleName).toBe("alchemy-test-config-rule-renamed"); |
| 236 | expect(renamed.configRuleArn).not.toBe(rule.configRuleArn); |
| 237 | yield* assertRuleDeleting(rule.configRuleName); |
| 238 | |
| 239 | yield* stack.destroy(); |
| 240 | yield* assertRuleDeleting(renamed.configRuleName); |
| 241 | }); |
| 242 | }), |
| 243 | { |
| 244 | tags: ["provider:aws", "provider:aws:config", "provider:aws:iam", "live"], |
| 245 | timeout: 120_000, |
| 246 | }, |
| 247 | ); |