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 transfer from "@distilled.cloud/aws/transfer";
6import { describe, expect } from "alchemy-test";
7import * as Effect from "effect/Effect";
8import * as Redacted from "effect/Redacted";
9import * as Schedule from "effect/Schedule";
10import * as HttpClient from "effect/http/HttpClient";
11import * as HttpClientRequest from "effect/http/HttpClientRequest";
12import TransferTestFunctionLive, { TransferTestFunction } from "./handler";
13import TransferWorkflowTestFunctionLive, {
14 TransferWorkflowTestFunction,
15} from "./workflow-handler";
16
17const testOptions = { providers: AWS.providers() };
18const { test, beforeAll, afterAll } = Test.make(testOptions);
19
20// Lambda function URL cold-start (DNS, IAM propagation, init) can take well
21// over 60s on a fresh deploy.
22const readinessPolicy = Schedule.max([
23 Schedule.fixed("2 seconds"),
24 Schedule.recurs(75),
25]);
26
27const probeReady = (readinessUrl: string) =>
28 HttpClient.get(readinessUrl).pipe(
29 Effect.flatMap((response) =>
30 response.status === 200
31 ? Effect.succeed(response)
32 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
33 ),
34 Effect.retry({ schedule: readinessPolicy }),
35 );
36
37// Ungated typed-error probes: prove the distilled error unions carry the
38// tags the bindings and providers depend on, at near-zero cost.
39describe(
40 "typed-error probes",
41 { tags: ["provider:aws", "provider:aws:transfer", "live"] },
42 () => {
43 test.provider(
44 "startServer on a nonexistent server fails with ResourceNotFoundException",
45 () =>
46 Effect.gen(function* () {
47 const error = yield* Effect.flip(
48 transfer.startServer({ ServerId: "s-00000000000000000" }),
49 );
50 expect(error._tag).toBe("ResourceNotFoundException");
51 }),
52 );
53
54 test.provider(
55 "importSshPublicKey on a nonexistent server fails with ResourceNotFoundException",
56 () =>
57 Effect.gen(function* () {
58 const error = yield* Effect.flip(
59 transfer.importSshPublicKey({
60 ServerId: "s-00000000000000000",
61 UserName: "nobody",
62 SshPublicKeyBody: "ssh-ed25519 AAAA",
63 }),
64 );
65 expect(error._tag).toBe("ResourceNotFoundException");
66 }),
67 );
68
69 test.provider(
70 "testIdentityProvider on a nonexistent server fails with ResourceNotFoundException",
71 () =>
72 Effect.gen(function* () {
73 const error = yield* Effect.flip(
74 transfer.testIdentityProvider({
75 ServerId: "s-00000000000000000",
76 UserName: "nobody",
77 UserPassword: Redacted.make("not-a-real-password"),
78 }),
79 );
80 expect(error._tag).toBe("ResourceNotFoundException");
81 }),
82 );
83
84 test.provider(
85 "sendWorkflowStepState on a nonexistent workflow fails with a typed tag",
86 () =>
87 Effect.gen(function* () {
88 const error = yield* Effect.flip(
89 transfer.sendWorkflowStepState({
90 WorkflowId: "w-1234567890abcdef0",
91 ExecutionId: "00000000-0000-0000-0000-000000000000",
92 Token: "MA==",
93 Status: "SUCCESS",
94 }),
95 );
96 // Transfer rejects the nonexistent workflow with the typed
97 // ValidationException (from the shared CommonErrors union).
98 expect([
99 "ResourceNotFoundException",
100 "InvalidRequestException",
101 "ValidationException",
102 ]).toContain(error._tag);
103 }),
104 );
105 },
106);
107
108// Ungated Lambda fixture: exercises the account-level binding + the
109// EventBridge event source without provisioning a Transfer server.
110describe.sequential(
111 "Transfer workflow binding",
112 {
113 tags: [
114 "provider:aws",
115 "provider:aws:lambda",
116 "provider:aws:transfer",
117 "live",
118 ],
119 },
120 () => {
121 const workflowStack = Core.scratchStack(
122 testOptions,
123 "TransferWorkflowBindings",
124 );
125
126 let baseUrl: string;
127 let functionArn: string;
128
129 beforeAll(
130 Effect.gen(function* () {
131 yield* workflowStack.destroy();
132
133 const attrs = yield* workflowStack.deploy(
134 Effect.gen(function* () {
135 return yield* TransferWorkflowTestFunction;
136 }).pipe(Effect.provide(TransferWorkflowTestFunctionLive)),
137 );
138
139 expect(attrs.functionUrl).toBeTruthy();
140 baseUrl = attrs.functionUrl!.replace(/\/+$/, "");
141 functionArn = attrs.functionArn;
142
143 yield* probeReady(`${baseUrl}/bindings`);
144 }),
145 { timeout: 300_000 },
146 );
147
148 afterAll(workflowStack.destroy(), { timeout: 180_000 });
149
150 test.provider("the capability initializes in the runtime", (_stack) =>
151 Effect.gen(function* () {
152 const response = yield* HttpClient.get(`${baseUrl}/bindings`).pipe(
153 Effect.flatMap((r) => r.json),
154 );
155 expect((response as { bound: string[] }).bound).toContain(
156 "sendWorkflowStepState",
157 );
158 }),
159 );
160
161 test.provider(
162 "SendWorkflowStepState round-trips and rejects with a typed tag",
163 (_stack) =>
164 Effect.gen(function* () {
165 const response = (yield* HttpClient.execute(
166 HttpClientRequest.post(`${baseUrl}/workflow-step`),
167 ).pipe(Effect.flatMap((r) => r.json))) as {
168 ok: boolean;
169 tag?: string;
170 };
171 // The workflow does not exist — the call must surface the typed
172 // rejection (not an untyped catch-all, not an IAM denial).
173 expect(response.ok).toBe(false);
174 expect([
175 "ResourceNotFoundException",
176 "InvalidRequestException",
177 "ValidationException",
178 ]).toContain(response.tag);
179 }),
180 );
181
182 test.provider(
183 "consumeFileTransferEvents created an EventBridge rule targeting the function",
184 (_stack) =>
185 Effect.gen(function* () {
186 // Out-of-band via distilled: the fixture's consumeFileTransferEvents
187 // must have materialized as a rule on the default bus with the
188 // Lambda as target.
189 const { RuleNames } = yield* eventbridge.listRuleNamesByTarget({
190 TargetArn: functionArn,
191 });
192 expect((RuleNames ?? []).length).toBeGreaterThanOrEqual(1);
193 }),
194 { tags: ["provider:aws:eventbridge"] },
195 );
196 },
197);
198
199// A running Transfer server is billed hourly and takes minutes to reach
200// ONLINE, so the server/user-scoped binding lifecycle is gated behind
201// AWS_TEST_SLOW=1 (same gate as Server.test.ts) and always destroys what it
202// created.
203describe.runIf(!!process.env.AWS_TEST_SLOW)(
204 "Transfer server bindings (slow)",
205 {
206 tags: [
207 "provider:aws",
208 "provider:aws:iam",
209 "provider:aws:lambda",
210 "provider:aws:transfer",
211 "live",
212 ],
213 },
214 () => {
215 const serverStack = Core.scratchStack(testOptions, "TransferBindings");
216
217 let baseUrl: string;
218
219 const getJson = (path: string) =>
220 HttpClient.get(`${baseUrl}${path}`).pipe(Effect.flatMap((r) => r.json));
221
222 const send = (method: "POST" | "DELETE", path: string) =>
223 HttpClient.execute(
224 method === "POST"
225 ? HttpClientRequest.post(`${baseUrl}${path}`)
226 : HttpClientRequest.delete(`${baseUrl}${path}`),
227 ).pipe(Effect.flatMap((r) => r.json));
228
229 beforeAll(
230 Effect.gen(function* () {
231 yield* serverStack.destroy();
232
233 const attrs = yield* serverStack.deploy(
234 Effect.gen(function* () {
235 return yield* TransferTestFunction;
236 }).pipe(Effect.provide(TransferTestFunctionLive)),
237 );
238
239 expect(attrs.functionUrl).toBeTruthy();
240 baseUrl = attrs.functionUrl!.replace(/\/+$/, "");
241
242 yield* probeReady(`${baseUrl}/bindings`);
243 }),
244 { timeout: 210_000 },
245 );
246
247 afterAll(serverStack.destroy(), { timeout: 90_000 });
248
249 test.provider(
250 "all eight capabilities initialize in the runtime",
251 (_stack) =>
252 Effect.gen(function* () {
253 const response = (yield* getJson("/bindings")) as { bound: string[] };
254 expect(response.bound).toHaveLength(8);
255 expect(response.bound).toContain("describeServer");
256 expect(response.bound).toContain("importSshPublicKey");
257 }),
258 );
259
260 test.provider(
261 "reads the bound server and lists its users (injected ServerId)",
262 (_stack) =>
263 Effect.gen(function* () {
264 const server = (yield* getJson("/server")) as {
265 serverId: string;
266 state: string;
267 };
268 expect(server.serverId).toMatch(/^s-/);
269
270 const users = (yield* getJson("/users")) as { userNames: string[] };
271 expect(users.userNames).toContain("alice");
272 }),
273 );
274
275 test.provider(
276 "imports, observes, and deletes an SSH key on the bound user",
277 (_stack) =>
278 Effect.gen(function* () {
279 const imported = (yield* send("POST", "/key")) as {
280 ok: boolean;
281 keyId?: string;
282 tag?: string;
283 };
284 expect(imported.ok).toBe(true);
285 const keyId = imported.keyId!;
286
287 const user = (yield* getJson("/user")) as {
288 userName: string;
289 keyIds: string[];
290 };
291 expect(user.userName).toBe("alice");
292 expect(user.keyIds).toContain(keyId);
293
294 const deleted = (yield* send(
295 "DELETE",
296 `/key?id=${encodeURIComponent(keyId)}`,
297 )) as { ok: boolean };
298 expect(deleted.ok).toBe(true);
299 }),
300 { timeout: 120_000 },
301 );
302
303 test.provider(
304 "TestIdentityProvider on a SERVICE_MANAGED server rejects with the typed tag",
305 (_stack) =>
306 Effect.gen(function* () {
307 const tested = (yield* send("POST", "/test-idp")) as {
308 ok: boolean;
309 tag?: string;
310 };
311 expect(tested.ok).toBe(false);
312 expect(tested.tag).toBe("InvalidRequestException");
313 }),
314 );
315
316 // A stop/offline/start transition adds several minutes beyond the already
317 // slow server provisioning lifecycle. Keep it separately opt-in so the
318 // standard AWS_TEST_SLOW lane remains below the hard 240-second wall.
319 test.provider.skipIf(!process.env.AWS_TEST_TRANSFER_TRANSITIONS)(
320 "stops and restarts the bound server (extra slow)",
321 (_stack) =>
322 Effect.gen(function* () {
323 const stopped = (yield* send("POST", "/stop")) as {
324 ok: boolean;
325 tag?: string;
326 };
327 expect(stopped.ok).toBe(true);
328
329 // The server parks in STOPPING before OFFLINE.
330 const offline = (yield* getJson("/server").pipe(
331 Effect.repeat({
332 schedule: Schedule.spaced("10 seconds"),
333 until: (r): boolean =>
334 (r as { state: string }).state === "OFFLINE",
335 times: 8,
336 }),
337 )) as { state: string };
338 expect(offline.state).toBe("OFFLINE");
339
340 const started = (yield* send("POST", "/start")) as {
341 ok: boolean;
342 tag?: string;
343 };
344 expect(started.ok).toBe(true);
345 }),
346 { timeout: 120_000 },
347 );
348 },
349);