@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 183 lines 6.95 KB
Raw
1 import * as Lambda from "@alchemy.run/aws/Lambda";
2 import * as Shield from "@alchemy.run/aws/Shield";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import { HttpServerRequest } from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Layer from "effect/Layer";
8 import * as Stream from "effect/Stream";
9 import path from "pathe";
10
11 const main = path.resolve(import.meta.dirname, "handler.ts");
12
13 export class ShieldTestFunction extends Lambda.Function<Lambda.Function>()("ShieldTestFunction") {}
14
15 /**
16 * Routes answer `{ …fields }` on success or `{ errorTag }` when the operation
17 * fails with a TYPED error — the test asserts the tag is in a route-specific
18 * allowlist, which proves both the binding wiring and the IAM grant. An
19 * untyped error crashes into a 500 instead.
20 */
21 const errorTagged = <A, E extends { _tag: string }, R>(
22 effect: Effect.Effect<A, E, R>,
23 ): Effect.Effect<A | { errorTag: string; errorMessage?: string }, never, R> =>
24 effect.pipe(
25 Effect.map((a): A | { errorTag: string; errorMessage?: string } => a),
26 Effect.catch((e) =>
27 Effect.succeed({
28 errorTag: e._tag,
29 errorMessage: (e as { Message?: string }).Message ?? (e as { message?: string }).message,
30 }),
31 ),
32 );
33
34 // The testing account is NOT (and must never be) subscribed to Shield
35 // Advanced ($3,000/month, 1-year commitment). GetSubscriptionState and
36 // DescribeAttackStatistics succeed on any account; the subscription-gated
37 // operations answer with their typed entitlement/not-found tags, which the
38 // test asserts — proving the binding + IAM wiring end-to-end either way.
39 export default ShieldTestFunction.make(
40 {
41 main,
42 functionUrl: true,
43 timeout: Duration.seconds(30),
44 },
45 Effect.gen(function* () {
46 // Event source: subscribe the host to Shield Advanced attack events
47 // (AWS Health, source `aws.health`, service SHIELD). The deploy proves
48 // the EventBridge rule + invoke permission wiring; events only fire on
49 // subscribed accounts under active attack.
50 yield* Shield.consumeAttackEvents({}, (events) =>
51 Stream.runForEach(events, (event) =>
52 Effect.log(`shield attack event: ${event.detail.eventTypeCode}`),
53 ),
54 );
55
56 const getSubscriptionState = yield* Shield.GetSubscriptionState();
57 const describeAttackStatistics = yield* Shield.DescribeAttackStatistics();
58 const listAttacks = yield* Shield.ListAttacks();
59 const describeAttack = yield* Shield.DescribeAttack();
60 const describeDRTAccess = yield* Shield.DescribeDRTAccess();
61 const listResourcesInProtectionGroup = yield* Shield.ListResourcesInProtectionGroup();
62
63 const bound = {
64 getSubscriptionState,
65 describeAttackStatistics,
66 listAttacks,
67 describeAttack,
68 describeDRTAccess,
69 listResourcesInProtectionGroup,
70 };
71
72 return {
73 fetch: Effect.gen(function* () {
74 const request = yield* HttpServerRequest;
75 const url = new URL(request.originalUrl);
76 const pathname = url.pathname;
77
78 if (request.method === "GET" && pathname === "/bindings") {
79 return yield* HttpServerResponse.json({ bound: Object.keys(bound) });
80 }
81
82 // Available to every account, subscribed or not.
83 if (request.method === "GET" && pathname === "/subscription-state") {
84 const { SubscriptionState } = yield* getSubscriptionState();
85 return yield* HttpServerResponse.json({ state: SubscriptionState });
86 }
87
88 // Available to Standard and Advanced customers alike.
89 if (request.method === "GET" && pathname === "/attack-stats") {
90 const result = yield* errorTagged(
91 describeAttackStatistics().pipe(Effect.map((r) => ({ dataItems: r.DataItems.length }))),
92 );
93 return yield* HttpServerResponse.json(result);
94 }
95
96 // Subscription-gated — a non-subscribed account answers with a typed
97 // error tag.
98 if (request.method === "GET" && pathname === "/attacks") {
99 const result = yield* errorTagged(
100 listAttacks().pipe(
101 Effect.map((r) => ({
102 count: (r.AttackSummaries ?? []).length,
103 })),
104 ),
105 );
106 return yield* HttpServerResponse.json(result);
107 }
108
109 // A nonexistent attack id answers with an empty document (observed
110 // live) or the documented typed AccessDeniedException.
111 if (request.method === "GET" && pathname === "/attack-detail") {
112 const result = yield* errorTagged(
113 describeAttack({
114 AttackId: "00000000-0000-0000-0000-000000000000",
115 }).pipe(Effect.map((r) => ({ attackId: r.Attack?.AttackId }))),
116 );
117 return yield* HttpServerResponse.json(result);
118 }
119
120 // Subscription-gated — a non-subscribed account answers with the
121 // typed ResourceNotFoundException.
122 if (request.method === "GET" && pathname === "/drt-access") {
123 const result = yield* errorTagged(
124 describeDRTAccess().pipe(
125 Effect.map((r) => ({
126 roleArn: r.RoleArn ?? null,
127 logBuckets: (r.LogBucketList ?? []).length,
128 })),
129 ),
130 );
131 return yield* HttpServerResponse.json(result);
132 }
133
134 // A nonexistent group answers with the typed
135 // ResourceNotFoundException (even without a subscription).
136 if (request.method === "GET" && pathname === "/group-members") {
137 const result = yield* errorTagged(
138 listResourcesInProtectionGroup({
139 ProtectionGroupId: "alchemy-shield-bindings-nonexistent",
140 }).pipe(
141 Effect.map((r) => ({
142 count: (r.ResourceArns ?? []).length,
143 })),
144 ),
145 );
146 return yield* HttpServerResponse.json(result);
147 }
148
149 return yield* HttpServerResponse.json(
150 { error: "Not found", method: request.method, pathname },
151 { status: 404 },
152 );
153 }).pipe(
154 // Surface typed operation errors as JSON so live-test failures carry
155 // the tag + message instead of an opaque 500 (routes that expect a
156 // typed error use `errorTagged` above and never reach this).
157 Effect.catch((e) =>
158 HttpServerResponse.json(
159 {
160 errorTag: (e as { _tag?: string })._tag ?? "UnknownError",
161 errorMessage:
162 (e as { message?: string }).message ?? (e as { Message?: string }).Message,
163 },
164 { status: 500 },
165 ),
166 ),
167 Effect.orDie,
168 ),
169 };
170 }).pipe(
171 Effect.provide(
172 Layer.mergeAll(
173 Lambda.EventSource,
174 Shield.GetSubscriptionStateHttp,
175 Shield.DescribeAttackStatisticsHttp,
176 Shield.ListAttacksHttp,
177 Shield.DescribeAttackHttp,
178 Shield.DescribeDRTAccessHttp,
179 Shield.ListResourcesInProtectionGroupHttp,
180 ),
181 ),
182 ),
183 );