@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 317 lines 11.9 KB
Raw
1 import type * as lambda from "@distilled.cloud/aws/lambda";
2 import * as Lambda from "@distilled.cloud/aws/lambda";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { plainJson } from "../internal/Observe.ts";
12 import type { Providers } from "../Providers.ts";
13
14 export type { FunctionUrlAuthType } from "@distilled.cloud/aws/lambda";
15
16 export interface PermissionProps {
17 /**
18 * The action that the principal can use on the function.
19 * For example, `lambda:InvokeFunction` or `lambda:GetFunction`.
20 */
21 action: string;
22
23 /**
24 * The name or ARN of the Lambda function, version, or alias.
25 */
26 functionName: string;
27
28 /**
29 * The AWS service, AWS account, IAM user, or IAM role that invokes the function.
30 * If you specify a service, use `sourceArn` or `sourceAccount` to limit who can
31 * invoke the function through that service.
32 */
33 principal: string;
34
35 /**
36 * For Alexa Smart Home functions, a token that the invoker must supply.
37 */
38 eventSourceToken?: string;
39
40 /**
41 * The type of authentication that your function URL uses.
42 * Set to `AWS_IAM` to restrict access to authenticated users only.
43 * Set to `NONE` to bypass IAM authentication to create a public endpoint.
44 */
45 functionUrlAuthType?: lambda.FunctionUrlAuthType;
46
47 /**
48 * Indicates whether the permission applies when the function is invoked
49 * through a function URL.
50 */
51 invokedViaFunctionUrl?: boolean;
52
53 /**
54 * The identifier for your organization in AWS Organizations.
55 * Use this to grant permissions to all the AWS accounts under this organization.
56 */
57 principalOrgID?: string;
58
59 /**
60 * For AWS services, the ID of the AWS account that owns the resource.
61 * Use this together with `sourceArn` to ensure that the specified account owns the resource.
62 */
63 sourceAccount?: string;
64
65 /**
66 * For AWS services, the ARN of the AWS resource that invokes the function.
67 * For example, an Amazon S3 bucket or Amazon SNS topic.
68 */
69 sourceArn?: string;
70 }
71
72 export interface Permission extends Resource<
73 "AWS.Lambda.Permission",
74 PermissionProps,
75 {
76 /** The statement ID of the permission. */
77 statementId: string;
78 /** The function name or ARN the permission is attached to. */
79 functionName: string;
80 /**
81 * The permission's resource-policy statement (principal, action and
82 * conditions), as observed. Lets `alchemy drift` detect out-of-band
83 * changes and removal.
84 */
85 statement?: unknown;
86 },
87 never,
88 Providers
89 > {}
90
91 /**
92 * A Lambda permission that grants an AWS service or another account permission to
93 * invoke a function.
94 * ### Granting Permissions
95 * **Example:** S3 Notification Permission
96 * ```typescript
97 * const perm = yield* Permission("S3Invoke", {
98 * action: "lambda:InvokeFunction",
99 * functionName: yield* fn.functionArn(),
100 * principal: "s3.amazonaws.com",
101 * sourceArn: yield* bucket.bucketArn,
102 * sourceAccount: (yield* AWSEnvironment.current).accountId,
103 * });
104 * ```
105 *
106 * **Example:** Cross Account Invoke
107 * ```typescript
108 * const perm = yield* Permission("CrossAccount", {
109 * action: "lambda:InvokeFunction",
110 * functionName: yield* fn.functionArn(),
111 * principal: "123456789012",
112 * });
113 * ```
114 *
115 * **Example:** Public Function URL
116 * ```typescript
117 * const perm = yield* Permission("PublicUrl", {
118 * action: "lambda:InvokeFunctionUrl",
119 * functionName: yield* fn.functionArn(),
120 * principal: "*",
121 * functionUrlAuthType: "NONE",
122 * });
123 * ```
124 *
125 * @resource
126 */
127 export const Permission = Resource<Permission>("AWS.Lambda.Permission");
128
129 /** A Lambda function's resource policy is not valid JSON. */
130 export class InvalidLambdaResourcePolicy extends Data.TaggedError("InvalidLambdaResourcePolicy")<{
131 message: string;
132 cause?: unknown;
133 }> {}
134
135 export const PermissionProvider = () =>
136 Provider.effect(
137 Permission,
138 Effect.gen(function* () {
139 const createStatementId = (id: string) =>
140 createPhysicalName({
141 id,
142 maxLength: 100,
143 delimiter: "-",
144 });
145
146 type PermissionAttrs = { statementId: string; functionName: string };
147
148 // Lambda serializes resource-policy mutations per function. Parallel
149 // Permission resources (for example several API Gateway routes) can
150 // therefore receive a transient ResourceConflictException even when
151 // their statement ids are distinct. Keep the retry bounded well below
152 // the provider/test timeout.
153 type PolicyMutationError = Lambda.AddPermissionError | Lambda.RemovePermissionError;
154 const retryPolicyMutation = {
155 while: (error: PolicyMutationError) => error._tag === "ResourceConflictException",
156 schedule: Schedule.spaced("500 millis"),
157 times: 8,
158 } as const;
159
160 const addPermission = (request: Lambda.AddPermissionRequest) =>
161 Lambda.addPermission(request).pipe(Effect.retry(retryPolicyMutation));
162
163 const removePermission = (request: Lambda.RemovePermissionRequest) =>
164 Lambda.removePermission(request).pipe(Effect.retry(retryPolicyMutation));
165
166 const findStatement = Effect.fn(function* (functionName: string, statementId: string) {
167 const { Policy } = yield* Lambda.getPolicy({
168 FunctionName: functionName,
169 }).pipe(
170 // A function without a resource policy (or no function at all) is
171 // reported as not found.
172 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed({ Policy: undefined })),
173 );
174 if (!Policy) return undefined;
175 return yield* Effect.try({
176 try: () => {
177 const policy = JSON.parse(Policy) as {
178 Statement?: { Sid?: string } | { Sid?: string }[];
179 };
180 const statements = Array.isArray(policy.Statement)
181 ? policy.Statement
182 : policy.Statement
183 ? [policy.Statement]
184 : [];
185 return statements.find((statement) => statement.Sid === statementId);
186 },
187 catch: (cause) =>
188 new InvalidLambdaResourcePolicy({ message: "invalid Lambda resource policy", cause }),
189 });
190 });
191
192 return {
193 stables: ["statementId", "functionName"],
194 list: () =>
195 Effect.gen(function* () {
196 // Lambda has no list-permissions API. A Permission is a single
197 // statement (Sid) inside a function's resource policy, so we fan
198 // out: enumerate every function in the ambient account/region
199 // (paginated listFunctions), getPolicy per function, parse the
200 // policy JSON, and emit one Attributes per statement Sid.
201 const functionNames = yield* Lambda.listFunctions.pages({}).pipe(
202 Stream.runCollect,
203 Effect.map((chunk) =>
204 Array.from(chunk).flatMap((page) =>
205 (page.Functions ?? [])
206 .map((fn) => fn.FunctionName)
207 .filter((name): name is string => name != null),
208 ),
209 ),
210 );
211
212 const perFunction = yield* Effect.forEach(
213 functionNames,
214 (functionName) =>
215 Effect.gen(function* () {
216 const { Policy } = yield* Lambda.getPolicy({
217 FunctionName: functionName,
218 });
219 if (!Policy) return [] as PermissionAttrs[];
220 const policy = yield* Effect.try({
221 try: () =>
222 JSON.parse(Policy) as {
223 Statement?: { Sid?: string } | { Sid?: string }[];
224 },
225 catch: (cause) =>
226 new InvalidLambdaResourcePolicy({ message: "invalid policy", cause }),
227 }).pipe(
228 // A malformed/non-JSON policy yields no permissions
229 // rather than failing the whole enumeration.
230 Effect.orElseSucceed(() => ({
231 Statement: [] as { Sid?: string }[],
232 })),
233 );
234 const statements = Array.isArray(policy.Statement)
235 ? policy.Statement
236 : policy.Statement
237 ? [policy.Statement]
238 : [];
239 return statements
240 .filter((s): s is { Sid: string } => typeof s.Sid === "string")
241 .map((s): PermissionAttrs => ({
242 statementId: s.Sid,
243 functionName,
244 }));
245 }).pipe(
246 // Functions with no resource policy / removed out of band
247 // between list and getPolicy — skip them.
248 Effect.catchTag("ResourceNotFoundException", () =>
249 Effect.succeed([] as PermissionAttrs[]),
250 ),
251 ),
252 { concurrency: 10 },
253 );
254 return perFunction.flat();
255 }),
256 read: Effect.fn(function* ({ id, olds, output }) {
257 const functionName = output?.functionName ?? olds?.functionName;
258 if (functionName === undefined) return undefined;
259 const statementId = output?.statementId ?? (yield* createStatementId(id));
260 const statement = yield* findStatement(functionName, statementId);
261 if (statement === undefined) return undefined;
262 return { statementId, functionName, statement: plainJson(statement) };
263 }),
264 diff: Effect.fn(function* ({ news, olds }) {
265 if (!isResolved(news)) return;
266 if (news.functionName !== olds.functionName) {
267 return { action: "replace" } as const;
268 }
269 }),
270 reconcile: Effect.fn(function* ({ id, news, output, session }) {
271 // Observe — derive identity. The statementId is deterministic from
272 // the logical id, so we always use it whether this is a first
273 // reconciliation, an adoption, or a re-run after a partial create.
274 const statementId = output?.statementId ?? (yield* createStatementId(id));
275
276 // Observe the deterministic Sid before mutating. An existing Sid is
277 // a true create/update collision and must be replaced; a
278 // ResourceConflictException from an absent Sid is instead Lambda's
279 // transient per-function policy mutation lock and is retried.
280 if ((yield* findStatement(news.functionName, statementId)) !== undefined) {
281 yield* removePermission({
282 FunctionName: news.functionName,
283 StatementId: statementId,
284 }).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
285 }
286
287 yield* addPermission({
288 FunctionName: news.functionName,
289 StatementId: statementId,
290 Action: news.action,
291 Principal: news.principal,
292 SourceArn: news.sourceArn,
293 SourceAccount: news.sourceAccount,
294 EventSourceToken: news.eventSourceToken,
295 FunctionUrlAuthType: news.functionUrlAuthType,
296 InvokedViaFunctionUrl: news.invokedViaFunctionUrl,
297 PrincipalOrgID: news.principalOrgID,
298 });
299
300 yield* session.note(`Permission ${statementId} on ${news.functionName}`);
301
302 const statement = yield* findStatement(news.functionName, statementId);
303 return {
304 statementId,
305 functionName: news.functionName,
306 statement: statement && plainJson(statement),
307 };
308 }),
309 delete: Effect.fn(function* ({ output }) {
310 yield* removePermission({
311 FunctionName: output.functionName,
312 StatementId: output.statementId,
313 }).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
314 }),
315 };
316 }),
317 );