1import * as AWS from "@/AWS";
2import * as Core from "@/Test/Core";
3import * as Test from "@/Test/Alchemy";
4import * as eventbridge from "@distilled.cloud/aws/eventbridge";
5import * as ssm from "@distilled.cloud/aws/ssm";
6import { describe, expect } from "alchemy-test";
7import * as Data from "effect/Data";
8import * as Effect from "effect/Effect";
9import * as Schedule from "effect/Schedule";
10import * as HttpClient from "effect/http/HttpClient";
11import * as HttpClientRequest from "effect/http/HttpClientRequest";
12import SSMTestFunctionLive, { SSMTestFunction } from "./handler";
13
14const testOptions = { providers: AWS.providers() };
15const { test, beforeAll, afterAll } = Test.make(testOptions);
16const sharedStack = Core.scratchStack(testOptions, "SSMBindings");
17
18// Lambda function URL cold-start (DNS, IAM propagation, init) can take well
19// over 60s on a fresh deploy under parallel-suite load. Budget ~150s of
20// readiness polling.
21const readinessPolicy = Schedule.max([
22 Schedule.fixed("2 seconds"),
23 Schedule.recurs(75),
24]);
25
26let baseUrl: string;
27let functionArn: string;
28
29class ParameterStillExists extends Data.TaggedError("ParameterStillExists")<{
30 readonly name: string;
31}> {}
32
33const assertParameterDeleted = (name: string) =>
34 ssm.getParameter({ Name: name }).pipe(
35 Effect.flatMap(() => Effect.fail(new ParameterStillExists({ name }))),
36 Effect.catchTag("ParameterNotFound", () => Effect.void),
37 Effect.retry({
38 while: (e) => e._tag === "ParameterStillExists",
39 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(8)]),
40 }),
41 );
42
43class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
44 readonly status: number;
45 readonly body: string;
46}> {}
47
48// The shared Lambda fixture occasionally answers a transient 5xx under
49// parallel load (cold re-init, IAM propagation). Retry 5xx only; a genuine
50// 4xx/assertion failure surfaces immediately.
51const send = (request: HttpClientRequest.HttpClientRequest) =>
52 HttpClient.execute(request).pipe(
53 Effect.flatMap((response) =>
54 response.status >= 500
55 ? response.text.pipe(
56 Effect.flatMap((body) =>
57 Effect.fail(
58 new TransientUpstream({ status: response.status, body }),
59 ),
60 ),
61 )
62 : Effect.succeed(response),
63 ),
64 Effect.retry({
65 while: (e) => e._tag === "TransientUpstream",
66 schedule: Schedule.max([
67 Schedule.exponential("500 millis"),
68 Schedule.recurs(6),
69 ]),
70 }),
71 );
72
73const getJson = (path: string) =>
74 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(
75 Effect.flatMap((r) => r.json),
76 );
77
78const postJson = (path: string) =>
79 send(HttpClientRequest.post(`${baseUrl}${path}`)).pipe(
80 Effect.flatMap((r) => r.json),
81 );
82
83describe.sequential(
84 "SSM Bindings",
85 { tags: ["provider:aws", "provider:aws:lambda", "provider:aws:ssm", "live"] },
86 () => {
87 beforeAll(
88 Effect.gen(function* () {
89 yield* Effect.logInfo("SSM test setup: destroying previous resources");
90 yield* sharedStack.destroy();
91
92 yield* Effect.logInfo("SSM test setup: deploying fixture");
93 const attrs = yield* sharedStack.deploy(
94 Effect.gen(function* () {
95 return yield* SSMTestFunction;
96 }).pipe(Effect.provide(SSMTestFunctionLive)),
97 );
98
99 expect(attrs.functionUrl).toBeTruthy();
100 baseUrl = attrs.functionUrl!.replace(/\/+$/, "");
101 functionArn = attrs.functionArn;
102 const readinessUrl = `${baseUrl}/get-string`;
103
104 yield* Effect.logInfo(
105 `SSM test setup: probing readiness at ${readinessUrl}`,
106 );
107 yield* HttpClient.get(readinessUrl).pipe(
108 Effect.flatMap((response) =>
109 response.status === 200
110 ? Effect.succeed(response)
111 : Effect.fail(
112 new Error(`Function not ready: ${response.status}`),
113 ),
114 ),
115 Effect.tapError((error) =>
116 Effect.logWarning(
117 `SSM test setup: fixture not ready yet (${String(error)})`,
118 ),
119 ),
120 Effect.retry({ schedule: readinessPolicy }),
121 );
122 }),
123 { timeout: 240_000 },
124 );
125
126 // Idempotent backstop — the "destroy leaves nothing behind" test below is
127 // the primary teardown; this reclaims resources if that test never ran.
128 afterAll(sharedStack.destroy(), { timeout: 120_000 });
129
130 describe("GetParameter", () => {
131 test.provider("reads a String parameter through the binding", (_stack) =>
132 Effect.gen(function* () {
133 const response = yield* getJson("/get-string");
134
135 expect((response as any).type).toBe("String");
136 expect((response as any).value).toBe("plain-config-value");
137 }),
138 );
139
140 test.provider(
141 "decrypts a SecureString parameter through the binding",
142 (_stack) =>
143 Effect.gen(function* () {
144 const response = yield* getJson("/get-secure");
145
146 expect((response as any).type).toBe("SecureString");
147 expect((response as any).value).toBe("bound-secret-value");
148 }),
149 );
150 });
151
152 describe("GetParameters", () => {
153 test.provider(
154 "reads String and SecureString parameters in one call",
155 (_stack) =>
156 Effect.gen(function* () {
157 const response = yield* getJson("/get-many");
158
159 const parameters = (response as any).parameters as Array<{
160 name: string;
161 type: string;
162 value: string;
163 }>;
164 expect((response as any).invalidParameters).toEqual([]);
165 expect(parameters).toHaveLength(2);
166 const values = parameters.map((p) => p.value).sort();
167 expect(values).toEqual(
168 ["bound-secret-value", "plain-config-value"].sort(),
169 );
170 }),
171 );
172 });
173
174 describe("GetParameterHistory", () => {
175 test.provider(
176 "reads the deployed version from the parameter's history",
177 (_stack) =>
178 Effect.gen(function* () {
179 const response = (yield* getJson("/history")) as {
180 count: number;
181 values: string[];
182 };
183 expect(response.count).toBeGreaterThanOrEqual(1);
184 expect(response.values).toContain("v1");
185 }),
186 );
187 });
188
189 describe("PutParameter", () => {
190 test.provider(
191 "writes a new version of the bound parameter at runtime",
192 (_stack) =>
193 Effect.gen(function* () {
194 const response = (yield* postJson("/put")) as {
195 version: number;
196 latest: string;
197 };
198 expect(response.version).toBeGreaterThanOrEqual(2);
199 expect(response.latest).toBe("v2-runtime");
200 }),
201 );
202 });
203
204 describe("Label/UnlabelParameterVersion", () => {
205 test.provider(
206 "labels the latest version and removes the label again",
207 (_stack) =>
208 Effect.gen(function* () {
209 const response = (yield* postJson("/label-cycle")) as {
210 labeledVersion: number;
211 invalidLabels: string[];
212 removedLabels: string[];
213 };
214 expect(response.labeledVersion).toBeGreaterThanOrEqual(1);
215 expect(response.invalidLabels).toEqual([]);
216 expect(response.removedLabels).toContain("current");
217 }),
218 );
219 });
220
221 describe("GetParametersByPath", () => {
222 test.provider(
223 "reads the subtree under the bound path-root parameter",
224 (_stack) =>
225 Effect.gen(function* () {
226 const response = (yield* getJson("/by-path")) as {
227 parameters: Array<{ name: string; value: string }>;
228 };
229 const child = response.parameters.find(
230 (parameter) =>
231 parameter.name === "/alchemy-test/ssm-bindings/root/child",
232 );
233 expect(child?.value).toBe("child-value");
234 }),
235 );
236 });
237
238 describe(
239 "consumeParameterEvents",
240 { tags: ["provider:aws:eventbridge"] },
241 () => {
242 test.provider(
243 "the deploy created an EventBridge rule targeting the function",
244 (_stack) =>
245 Effect.gen(function* () {
246 // Out-of-band via distilled: the fixture's consumeParameterEvents
247 // must have materialized as a rule on the default bus with the
248 // Lambda as target.
249 const { RuleNames } = yield* eventbridge.listRuleNamesByTarget({
250 TargetArn: functionArn,
251 });
252 expect((RuleNames ?? []).length).toBeGreaterThanOrEqual(1);
253 }),
254 );
255 },
256 );
257
258 // Runs last (describe.sequential): tear the shared stack down and prove
259 // out-of-band that the destroy left nothing behind. The afterAll destroy
260 // stays registered as an idempotent backstop for crashes before this test.
261 describe("teardown", () => {
262 test.provider(
263 "destroy leaves no parameters behind",
264 (_stack) =>
265 Effect.gen(function* () {
266 yield* sharedStack.destroy();
267 yield* assertParameterDeleted("/alchemy-test/ssm-bindings/root");
268 yield* assertParameterDeleted(
269 "/alchemy-test/ssm-bindings/root/child",
270 );
271 }),
272 { timeout: 120_000 },
273 );
274 });
275 },
276);