@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, 06:00 UTC

main
ts 446 lines 16.2 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { AWSEnvironment } from "@alchemy.run/aws/Environment";
3 import { Alias, Key } from "@alchemy.run/aws/KMS";
4 import { describe, expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as KMS from "@distilled.cloud/aws/kms";
7 import * as Provider from "alchemy/Provider";
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
13 const { test } = Test.make({ providers: AWS.providers() });
14
15 describe("AWS.KMS.Key", { tags: ["provider:aws", "provider:aws:kms", "live"] }, () => {
16 test.provider(
17 "reconciles mutable key settings across updates without replacement",
18 (stack) =>
19 Effect.gen(function* () {
20 yield* stack.destroy();
21
22 const { accountId } = yield* AWSEnvironment.current;
23
24 const initial = yield* stack.deploy(
25 Effect.gen(function* () {
26 const key = yield* Key("ManagedKey", {
27 description: "alchemy kms smoke v1",
28 // Duration.Input props: the provider converts these to whole
29 // wire days (7 and 90) — asserted out-of-band below.
30 deletionWindow: "7 days",
31 enableKeyRotation: true,
32 rotationPeriod: "90 days",
33 tags: { Environment: "test", Owner: "alice" },
34 });
35 const alias = yield* Alias("ManagedAlias", { targetKeyId: key.keyId });
36 return { alias, key };
37 }),
38 );
39
40 const described = yield* KMS.describeKey({ KeyId: initial.key.keyId });
41 expect(described.KeyMetadata!.KeyUsage).toEqual("ENCRYPT_DECRYPT");
42 expect(described.KeyMetadata!.KeySpec).toEqual("SYMMETRIC_DEFAULT");
43 expect(described.KeyMetadata!.Enabled).toEqual(true);
44
45 const rotation = yield* KMS.getKeyRotationStatus({ KeyId: initial.key.keyId });
46 expect(rotation.KeyRotationEnabled).toEqual(true);
47 // `rotationPeriod: "90 days"` (Duration.Input) must reach the
48 // wire as the whole number 90.
49 expect(rotation.RotationPeriodInDays).toEqual(90);
50 expect(initial.key.rotationPeriodInDays).toEqual(90);
51
52 const initialTags = yield* listTags(initial.key.keyId);
53 expect(initialTags.Environment).toEqual("test");
54 expect(initialTags.Owner).toEqual("alice");
55
56 const aliasState = yield* getAlias(initial.alias.aliasName);
57 expect(aliasState?.TargetKeyId).toEqual(initial.key.keyId);
58
59 const keyProvider = yield* Provider.findProvider(Key);
60 const aliasProvider = yield* Provider.findProvider(Alias);
61 yield* assertProvidersListResources({
62 aliasName: initial.alias.aliasName,
63 aliasProvider,
64 keyId: initial.key.keyId,
65 keyProvider,
66 });
67
68 // Typed PolicyDocument (not a JSON string) — proves the structured
69 // form deploys and, below, re-deploys as a no-op.
70 const policy: AWS.IAM.PolicyDocument = {
71 Version: "2012-10-17",
72 Statement: [
73 {
74 Sid: "EnableRootPermissions",
75 Effect: "Allow",
76 Principal: { AWS: `arn:aws:iam::${accountId}:root` },
77 Action: ["kms:*"],
78 Resource: "*",
79 },
80 ],
81 };
82
83 const updated = yield* stack.deploy(
84 Effect.gen(function* () {
85 const key = yield* Key("ManagedKey", {
86 deletionWindow: "7 days",
87 description: "alchemy kms smoke v2",
88 enableKeyRotation: false,
89 enabled: false,
90 bypassPolicyLockoutSafetyCheck: true,
91 policy,
92 tags: { Environment: "prod", Team: "platform" },
93 });
94 const alias = yield* Alias("ManagedAlias", { targetKeyId: key.keyId });
95 return { alias, key };
96 }),
97 );
98
99 // No replacement: a settings-only update keeps the same physical key.
100 expect(updated.key.keyId).toEqual(initial.key.keyId);
101
102 yield* assertKeyMetadata({
103 description: "alchemy kms smoke v2",
104 enabled: false,
105 keyId: updated.key.keyId,
106 });
107 yield* assertKeyTags({
108 keyId: updated.key.keyId,
109 tags: { Environment: "prod", Team: "platform" },
110 });
111
112 // The removed `Owner` tag must no longer be present (untag path).
113 const updatedTags = yield* listTags(updated.key.keyId);
114 expect(updatedTags.Owner).toBeUndefined();
115
116 // Rotation must be disabled after the update.
117 const updatedRotation = yield* KMS.getKeyRotationStatus({ KeyId: updated.key.keyId });
118 expect(updatedRotation.KeyRotationEnabled).toEqual(false);
119
120 // The inline (PolicyDocument-valued) policy must have been applied.
121 const appliedPolicy = yield* KMS.getKeyPolicy({
122 KeyId: updated.key.keyId,
123 PolicyName: "default",
124 });
125 expect(appliedPolicy.Policy).toContain("EnableRootPermissions");
126
127 // Re-deploying the identical PolicyDocument is a clean no-op: same
128 // physical key, policy still in place (the provider's normalized
129 // drift comparison must treat AWS's pretty-printed policy JSON as
130 // equal to the synthesized document).
131 const noop = yield* stack.deploy(
132 Effect.gen(function* () {
133 const key = yield* Key("ManagedKey", {
134 deletionWindow: "7 days",
135 description: "alchemy kms smoke v2",
136 enableKeyRotation: false,
137 enabled: false,
138 bypassPolicyLockoutSafetyCheck: true,
139 policy,
140 tags: { Environment: "prod", Team: "platform" },
141 });
142 const alias = yield* Alias("ManagedAlias", { targetKeyId: key.keyId });
143 return { alias, key };
144 }),
145 );
146 expect(noop.key.keyId).toEqual(updated.key.keyId);
147 const noopPolicy = yield* KMS.getKeyPolicy({
148 KeyId: noop.key.keyId,
149 PolicyName: "default",
150 });
151 expect(noopPolicy.Policy).toContain("EnableRootPermissions");
152
153 yield* stack.destroy();
154
155 yield* assertAliasDeleted(updated.alias.aliasName);
156 yield* assertKeyPendingDeletion(updated.key.keyId);
157 }),
158 { timeout: 120_000 },
159 );
160
161 test.provider(
162 "replaces the key when keySpec changes",
163 (stack) =>
164 Effect.gen(function* () {
165 yield* stack.destroy();
166
167 // Set keySpec explicitly so the diff against the next deploy is
168 // well-defined. The physical key may be adopted from a prior run's
169 // pending-deletion key (KMS keys can't be hard-deleted), so we don't
170 // assert its keySpec here — only the replacement behavior below.
171 const initial = yield* stack.deploy(
172 Effect.gen(function* () {
173 const key = yield* Key("ReplaceKey", {
174 description: "alchemy kms replace v1",
175 deletionWindow: "7 days",
176 keySpec: "SYMMETRIC_DEFAULT",
177 keyUsage: "ENCRYPT_DECRYPT",
178 });
179 return { key };
180 }),
181 );
182
183 const replaced = yield* stack.deploy(
184 Effect.gen(function* () {
185 const key = yield* Key("ReplaceKey", {
186 description: "alchemy kms replace v2",
187 deletionWindow: "7 days",
188 keySpec: "RSA_2048",
189 keyUsage: "ENCRYPT_DECRYPT",
190 });
191 return { key };
192 }),
193 );
194
195 // A keySpec change forces a replacement: a brand-new physical key.
196 expect(replaced.key.keyId).not.toEqual(initial.key.keyId);
197
198 const replacedDescribe = yield* KMS.describeKey({ KeyId: replaced.key.keyId });
199 expect(replacedDescribe.KeyMetadata!.KeySpec).toEqual("RSA_2048");
200
201 // The old key must have been scheduled for deletion by the replacement.
202 yield* assertKeyPendingDeletion(initial.key.keyId);
203
204 yield* stack.destroy();
205
206 yield* assertKeyPendingDeletion(replaced.key.keyId);
207 }),
208 { timeout: 120_000 },
209 );
210
211 const aliasNameA = "alias/alchemy-test-kms-rename-a" as const;
212 const aliasNameB = "alias/alchemy-test-kms-rename-b" as const;
213
214 test.provider(
215 "retargets an alias in place, then replaces it on rename",
216 (stack) =>
217 Effect.gen(function* () {
218 yield* stack.destroy();
219
220 const initial = yield* stack.deploy(
221 Effect.gen(function* () {
222 const keyA = yield* Key("AliasKeyA", {
223 description: "alchemy kms alias target A",
224 deletionWindow: "7 days",
225 });
226 const keyB = yield* Key("AliasKeyB", {
227 description: "alchemy kms alias target B",
228 deletionWindow: "7 days",
229 });
230 const alias = yield* Alias("RenamableAlias", {
231 aliasName: aliasNameA,
232 targetKeyId: keyA.keyId,
233 });
234 return { alias, keyA, keyB };
235 }),
236 );
237
238 expect(initial.alias.aliasName).toEqual(aliasNameA);
239 yield* assertAliasTarget({ aliasName: aliasNameA, targetKeyId: initial.keyA.keyId });
240
241 // Retarget the alias to key B. Same alias name => updateAlias, no replace.
242 const retargeted = yield* stack.deploy(
243 Effect.gen(function* () {
244 const keyA = yield* Key("AliasKeyA", {
245 description: "alchemy kms alias target A",
246 deletionWindow: "7 days",
247 });
248 const keyB = yield* Key("AliasKeyB", {
249 description: "alchemy kms alias target B",
250 deletionWindow: "7 days",
251 });
252 const alias = yield* Alias("RenamableAlias", {
253 aliasName: aliasNameA,
254 targetKeyId: keyB.keyId,
255 });
256 return { alias, keyA, keyB };
257 }),
258 );
259
260 expect(retargeted.alias.aliasName).toEqual(aliasNameA);
261 yield* assertAliasTarget({ aliasName: aliasNameA, targetKeyId: retargeted.keyB.keyId });
262
263 // Rename the alias. A name change forces a replacement: a new alias is
264 // created and the old one is deleted.
265 const renamed = yield* stack.deploy(
266 Effect.gen(function* () {
267 const keyA = yield* Key("AliasKeyA", {
268 description: "alchemy kms alias target A",
269 deletionWindow: "7 days",
270 });
271 const keyB = yield* Key("AliasKeyB", {
272 description: "alchemy kms alias target B",
273 deletionWindow: "7 days",
274 });
275 const alias = yield* Alias("RenamableAlias", {
276 aliasName: aliasNameB,
277 targetKeyId: keyB.keyId,
278 });
279 return { alias, keyA, keyB };
280 }),
281 );
282
283 expect(renamed.alias.aliasName).toEqual(aliasNameB);
284 yield* assertAliasTarget({ aliasName: aliasNameB, targetKeyId: renamed.keyB.keyId });
285 yield* assertAliasDeleted(aliasNameA);
286
287 yield* stack.destroy();
288
289 yield* assertAliasDeleted(aliasNameB);
290 }),
291 { timeout: 120_000 },
292 );
293
294 class AliasStillExists extends Data.TaggedError("AliasStillExists") {}
295 class KeyNotPendingDeletion extends Data.TaggedError("KeyNotPendingDeletion") {}
296 class ProviderListNotConverged extends Data.TaggedError("ProviderListNotConverged") {}
297 class KeyMetadataNotConverged extends Data.TaggedError("KeyMetadataNotConverged") {}
298 class KeyTagsNotConverged extends Data.TaggedError("KeyTagsNotConverged") {}
299 class AliasTargetNotConverged extends Data.TaggedError("AliasTargetNotConverged") {}
300
301 const assertKeyMetadata = Effect.fn(function* ({
302 description,
303 enabled,
304 keyId,
305 }: {
306 description: string;
307 enabled: boolean;
308 keyId: string;
309 }) {
310 yield* Effect.gen(function* () {
311 const key = yield* KMS.describeKey({ KeyId: keyId });
312 if (key.KeyMetadata!.Description !== description || key.KeyMetadata!.Enabled !== enabled) {
313 return yield* Effect.fail(new KeyMetadataNotConverged());
314 }
315 }).pipe(
316 Effect.retry({
317 while: (error) => error._tag === "KeyMetadataNotConverged",
318 schedule: Schedule.max([Schedule.exponential(100), Schedule.recurs(8)]),
319 }),
320 );
321 });
322
323 const assertKeyTags = Effect.fn(function* ({
324 keyId,
325 tags,
326 }: {
327 keyId: string;
328 tags: Record<string, string>;
329 }) {
330 yield* Effect.gen(function* () {
331 const observed = yield* listTags(keyId);
332 if (!Object.entries(tags).every(([name, value]) => observed[name] === value)) {
333 return yield* Effect.fail(new KeyTagsNotConverged());
334 }
335 }).pipe(
336 Effect.retry({
337 while: (error) => error._tag === "KeyTagsNotConverged",
338 schedule: Schedule.max([Schedule.exponential(100), Schedule.recurs(8)]),
339 }),
340 );
341 });
342
343 const assertAliasTarget = Effect.fn(function* ({
344 aliasName,
345 targetKeyId,
346 }: {
347 aliasName: string;
348 targetKeyId: string;
349 }) {
350 yield* Effect.gen(function* () {
351 const alias = yield* getAlias(aliasName);
352 if (alias?.TargetKeyId !== targetKeyId) {
353 return yield* Effect.fail(new AliasTargetNotConverged());
354 }
355 }).pipe(
356 Effect.retry({
357 while: (error) => error._tag === "AliasTargetNotConverged",
358 schedule: Schedule.max([Schedule.exponential(100), Schedule.recurs(8)]),
359 }),
360 );
361 });
362
363 const assertProvidersListResources = Effect.fn(function* ({
364 aliasName,
365 aliasProvider,
366 keyId,
367 keyProvider,
368 }: {
369 aliasName: string;
370 aliasProvider: Provider.ProviderService<Alias>;
371 keyId: string;
372 keyProvider: Provider.ProviderService<Key>;
373 }) {
374 yield* Effect.gen(function* () {
375 const [listedKeys, listedAliases] = yield* Effect.all(
376 [keyProvider.list(), aliasProvider.list()],
377 { concurrency: "unbounded" },
378 );
379 if (!listedKeys.some((key) => key.keyId === keyId)) {
380 return yield* Effect.fail(new ProviderListNotConverged());
381 }
382 if (!listedAliases.some((alias) => alias.aliasName === aliasName)) {
383 return yield* Effect.fail(new ProviderListNotConverged());
384 }
385 }).pipe(
386 Effect.retry({
387 while: (error) => error._tag === "ProviderListNotConverged",
388 schedule: Schedule.max([Schedule.exponential(100), Schedule.recurs(8)]),
389 }),
390 );
391 });
392
393 const assertAliasDeleted = Effect.fn(function* (aliasName: string) {
394 yield* Effect.gen(function* () {
395 const alias = yield* getAlias(aliasName);
396 if (alias !== undefined) {
397 return yield* Effect.fail(new AliasStillExists());
398 }
399 }).pipe(
400 Effect.retry({
401 while: (error) => error._tag === "AliasStillExists",
402 schedule: Schedule.max([Schedule.exponential(100), Schedule.recurs(8)]),
403 }),
404 );
405 });
406
407 const assertKeyPendingDeletion = Effect.fn(function* (keyId: string) {
408 const metadata = yield* KMS.describeKey({ KeyId: keyId }).pipe(
409 Effect.flatMap((response) =>
410 response.KeyMetadata!.KeyState === "PendingDeletion"
411 ? Effect.succeed(response.KeyMetadata!)
412 : Effect.fail(new KeyNotPendingDeletion()),
413 ),
414 Effect.retry({
415 while: (error) => error._tag === "KeyNotPendingDeletion",
416 schedule: Schedule.max([Schedule.exponential(100), Schedule.recurs(8)]),
417 }),
418 );
419 // Every key in this suite uses `deletionWindow: "7 days"`
420 // (Duration.Input) — the scheduled DeletionDate must land ~7 wire days
421 // out, proving the Duration→days conversion round-trips through
422 // scheduleKeyDeletion.
423 const now = yield* Effect.sync(() => Date.now());
424 const windowDays = (metadata.DeletionDate!.getTime() - now) / (24 * 60 * 60 * 1000);
425 expect(windowDays).toBeGreaterThan(6);
426 expect(windowDays).toBeLessThanOrEqual(7.1);
427 });
428
429 const getAlias = Effect.fn(function* (aliasName: string) {
430 const aliases = yield* KMS.listAliases.pages({}).pipe(
431 Stream.runCollect,
432 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Aliases ?? [])),
433 );
434
435 return aliases.find((alias) => alias.AliasName === aliasName);
436 });
437
438 const listTags = Effect.fn(function* (keyId: string) {
439 const tags = yield* KMS.listResourceTags.pages({ KeyId: keyId }).pipe(
440 Stream.runCollect,
441 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Tags ?? [])),
442 );
443
444 return Object.fromEntries(tags.map((tag) => [tag.TagKey, tag.TagValue]));
445 });
446 });