The best way to control Claude Code, Codex and more from any computer or phone

main
ts 224 lines 8 KB
Raw
1 import * as Budgets from "@alchemy.run/aws/Budgets";
2 import * as IAM from "@alchemy.run/aws/IAM";
3 import * as Lambda from "@alchemy.run/aws/Lambda";
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 path from "pathe";
9
10 const main = path.resolve(import.meta.dirname, "handler.ts");
11
12 export const fixtureBudgetName = "alchemy-test-budgets-bindings";
13
14 export class BudgetsTestFunction extends Lambda.Function<Lambda.Function>()(
15 "BudgetsTestFunction",
16 ) {}
17
18 export default BudgetsTestFunction.make(
19 {
20 main,
21 functionUrl: true,
22 },
23 Effect.gen(function* () {
24 const execRole = yield* IAM.Role("BindingsExecRole", {
25 roleName: "alchemy-test-budgets-bind-exec",
26 assumeRolePolicyDocument: {
27 Version: "2012-10-17",
28 Statement: [
29 {
30 Effect: "Allow",
31 Principal: { Service: "budgets.amazonaws.com" },
32 Action: ["sts:AssumeRole"],
33 },
34 ],
35 },
36 managedPolicyArns: ["arn:aws:iam::aws:policy/AWSBudgetsActionsWithAWSResourceControlAccess"],
37 });
38
39 const targetRole = yield* IAM.Role("BindingsTargetRole", {
40 roleName: "alchemy-test-budgets-bind-target",
41 assumeRolePolicyDocument: {
42 Version: "2012-10-17",
43 Statement: [
44 {
45 Effect: "Allow",
46 Principal: { Service: "ec2.amazonaws.com" },
47 Action: ["sts:AssumeRole"],
48 },
49 ],
50 },
51 });
52
53 const budget = yield* Budgets.Budget("BindingsBudget", {
54 budgetName: fixtureBudgetName,
55 budgetType: "COST",
56 timeUnit: "MONTHLY",
57 // Large limit so the action's 100% threshold is never crossed by real
58 // account spend — the fixture action must stay in STANDBY.
59 budgetLimit: { amount: "1000000", unit: "USD" },
60 notifications: [
61 {
62 notificationType: "ACTUAL",
63 comparisonOperator: "GREATER_THAN",
64 threshold: 80,
65 thresholdType: "PERCENTAGE",
66 subscribers: [{ subscriptionType: "EMAIL", address: "budget-test@example.com" }],
67 },
68 ],
69 });
70
71 const action = yield* Budgets.BudgetAction("BindingsAction", {
72 budgetName: budget.budgetName,
73 notificationType: "ACTUAL",
74 actionType: "APPLY_IAM_POLICY",
75 actionThreshold: {
76 actionThresholdValue: 100,
77 actionThresholdType: "PERCENTAGE",
78 },
79 definition: {
80 iamActionDefinition: {
81 policyArn: "arn:aws:iam::aws:policy/AWSDenyAll",
82 roles: [targetRole.roleName],
83 },
84 },
85 executionRoleArn: execRole.roleArn,
86 approvalModel: "MANUAL",
87 subscribers: [{ subscriptionType: "EMAIL", address: "budget-test@example.com" }],
88 });
89
90 // --- budget-scoped bindings ---
91 const describeBudget = yield* Budgets.DescribeBudget(budget);
92 const performanceHistory = yield* Budgets.DescribeBudgetPerformanceHistory(budget);
93 const notifications = yield* Budgets.DescribeNotificationsForBudget(budget);
94 const subscribers = yield* Budgets.DescribeSubscribersForNotification(budget);
95 const listActions = yield* Budgets.DescribeBudgetActionsForBudget(budget);
96
97 // --- action-scoped bindings ---
98 const executeAction = yield* Budgets.ExecuteBudgetAction(action);
99 const actionHistories = yield* Budgets.DescribeBudgetActionHistories(action);
100
101 const bound = {
102 describeBudget,
103 performanceHistory,
104 notifications,
105 subscribers,
106 listActions,
107 executeAction,
108 actionHistories,
109 };
110
111 return {
112 fetch: Effect.gen(function* () {
113 const request = yield* HttpServerRequest;
114 const url = new URL(request.originalUrl);
115 const pathname = url.pathname;
116
117 if (request.method === "GET" && pathname === "/bindings") {
118 return yield* HttpServerResponse.json({
119 bound: Object.keys(bound),
120 });
121 }
122
123 if (request.method === "GET" && pathname === "/budget") {
124 const result = yield* describeBudget();
125 return yield* HttpServerResponse.json({
126 name: result.Budget?.BudgetName ?? null,
127 limitAmount: result.Budget?.BudgetLimit?.Amount ?? null,
128 limitUnit: result.Budget?.BudgetLimit?.Unit ?? null,
129 timeUnit: result.Budget?.TimeUnit ?? null,
130 });
131 }
132
133 if (request.method === "GET" && pathname === "/history") {
134 const result = yield* performanceHistory();
135 return yield* HttpServerResponse.json({
136 budgetName: result.BudgetPerformanceHistory?.BudgetName ?? null,
137 periods: (result.BudgetPerformanceHistory?.BudgetedAndActualAmountsList ?? []).length,
138 });
139 }
140
141 if (request.method === "GET" && pathname === "/notifications") {
142 const result = yield* notifications();
143 return yield* HttpServerResponse.json({
144 thresholds: (result.Notifications ?? []).map((n) => n.Threshold),
145 });
146 }
147
148 if (request.method === "GET" && pathname === "/subscribers") {
149 // Enumerate notifications, then list each one's subscribers — the
150 // round trip proves the ViewBudget grant and identifier injection.
151 const notifs = yield* notifications();
152 const first = (notifs.Notifications ?? [])[0];
153 if (!first) {
154 return yield* HttpServerResponse.json({
155 count: 0,
156 subscriptionTypes: [],
157 });
158 }
159 const result = yield* subscribers({ Notification: first });
160 return yield* HttpServerResponse.json({
161 count: (result.Subscribers ?? []).length,
162 subscriptionTypes: (result.Subscribers ?? []).map((s) => s.SubscriptionType),
163 });
164 }
165
166 if (request.method === "GET" && pathname === "/actions") {
167 const result = yield* listActions();
168 return yield* HttpServerResponse.json({
169 actions: (result.Actions ?? []).map((a) => ({
170 actionId: a.ActionId,
171 status: a.Status,
172 actionType: a.ActionType,
173 })),
174 });
175 }
176
177 if (request.method === "GET" && pathname === "/action-histories") {
178 const result = yield* actionHistories({});
179 return yield* HttpServerResponse.json({
180 count: result.ActionHistories.length,
181 eventTypes: result.ActionHistories.map((h) => h.EventType),
182 });
183 }
184
185 if (request.method === "GET" && pathname === "/execute-reset") {
186 // A STANDBY action can't meaningfully be reset — the point is to
187 // prove the `budgets:ExecuteBudgetAction` grant and identifier
188 // injection: any typed budgets-service outcome (success or a
189 // business error) proves the call was authorized. An IAM gap would
190 // surface AccessDeniedException and fail the route with a 500.
191 const outcome = yield* executeAction({
192 ExecutionType: "RESET_BUDGET_ACTION",
193 }).pipe(
194 Effect.map((r) => ({
195 outcome: "ok",
196 executionType: r.ExecutionType,
197 })),
198 Effect.catchTag(["ResourceLockedException", "InvalidParameterException"], (e) =>
199 Effect.succeed({ outcome: e._tag, executionType: null }),
200 ),
201 );
202 return yield* HttpServerResponse.json(outcome);
203 }
204
205 return yield* HttpServerResponse.json(
206 { error: "Not found", method: request.method, pathname },
207 { status: 404 },
208 );
209 }).pipe(Effect.orDie),
210 };
211 }).pipe(
212 Effect.provide(
213 Layer.mergeAll(
214 Budgets.DescribeBudgetHttp,
215 Budgets.DescribeBudgetPerformanceHistoryHttp,
216 Budgets.DescribeNotificationsForBudgetHttp,
217 Budgets.DescribeSubscribersForNotificationHttp,
218 Budgets.DescribeBudgetActionsForBudgetHttp,
219 Budgets.ExecuteBudgetActionHttp,
220 Budgets.DescribeBudgetActionHistoriesHttp,
221 ),
222 ),
223 ),
224 );