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, 04:45 UTC
| 1 | import * as LambdaWeb from "@distilled.cloud/aws/lambda-web"; |
| 2 | import { deepEqual, isResolved } from "alchemy/Diff"; |
| 3 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import * as Data from "effect/Data"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Schedule from "effect/Schedule"; |
| 9 | import * as Semaphore from "effect/Semaphore"; |
| 10 | import { plainJson } from "../internal/Observe.ts"; |
| 11 | import type { Providers } from "../Providers.ts"; |
| 12 | import type { WebFunctionAuthType } from "./WebFunctionEndpointSync.ts"; |
| 13 | |
| 14 | export const WebFunctionPermissionTypeId = "AWS.Lambda.WebFunctionPermission" as const; |
| 15 | export type WebFunctionPermissionTypeId = typeof WebFunctionPermissionTypeId; |
| 16 | |
| 17 | /** The parts of an endpoint a permission grants access to. */ |
| 18 | export interface WebFunctionEndpointRef { |
| 19 | functionArn: string; |
| 20 | endpointArn: string; |
| 21 | authType: WebFunctionAuthType; |
| 22 | } |
| 23 | |
| 24 | /** |
| 25 | * A resource or its declaration (e.g. a `WebFunction` class), which is |
| 26 | * yielded for you. |
| 27 | */ |
| 28 | type Ref<T> = T | Effect.Effect<T, never, Providers>; |
| 29 | |
| 30 | export interface WebFunctionPermissionProps { |
| 31 | /** |
| 32 | * The endpoint callers may invoke: an `AWS.Lambda.WebFunction` (its |
| 33 | * built-in endpoint), an `AWS.Lambda.WebFunctionEndpoint`, or a class |
| 34 | * declaration of either. The endpoint must use `authType: "IamAuth"`; |
| 35 | * an `ApplicationManaged` endpoint is public and ignores grants. |
| 36 | */ |
| 37 | endpoint: Ref<WebFunctionEndpointRef>; |
| 38 | /** |
| 39 | * Who may invoke the endpoint: an AWS service principal (e.g. |
| 40 | * `"cloudfront.amazonaws.com"`), an account ID, or an IAM role or user |
| 41 | * ARN. Lambda rejects grants to an unspecified set of principals, so a |
| 42 | * service principal needs `sourceArn`. |
| 43 | */ |
| 44 | principal: string; |
| 45 | /** |
| 46 | * Restrict a service principal to one source, e.g. a CloudFront |
| 47 | * distribution ARN. |
| 48 | */ |
| 49 | sourceArn?: string; |
| 50 | } |
| 51 | |
| 52 | export interface WebFunctionPermission extends Resource< |
| 53 | WebFunctionPermissionTypeId, |
| 54 | WebFunctionPermissionProps, |
| 55 | { |
| 56 | /** ARN of the Web Function whose resource policy holds the grant. */ |
| 57 | functionArn: string; |
| 58 | /** ARN of the endpoint the grant applies to. */ |
| 59 | endpointArn: string; |
| 60 | /** Statement ID of the grant in the function's resource policy. */ |
| 61 | statementId: string; |
| 62 | /** |
| 63 | * The grant's policy statement (principal, effect, action, resource and |
| 64 | * conditions), as observed. Lets `alchemy drift` detect out-of-band |
| 65 | * changes. |
| 66 | */ |
| 67 | statement?: unknown; |
| 68 | }, |
| 69 | never, |
| 70 | Providers |
| 71 | > {} |
| 72 | |
| 73 | /** Invoke grants only mean something on an `IamAuth` endpoint. */ |
| 74 | export class WebFunctionEndpointNotIamAuth extends Data.TaggedError( |
| 75 | "WebFunctionEndpointNotIamAuth", |
| 76 | )<{ endpointArn: string; message: string }> {} |
| 77 | |
| 78 | export class WebFunctionPolicyInvalid extends Data.TaggedError("WebFunctionPolicyInvalid")<{ |
| 79 | functionArn: string; |
| 80 | message: string; |
| 81 | }> {} |
| 82 | |
| 83 | const WebFunctionPermissionResource = Resource<WebFunctionPermission>(WebFunctionPermissionTypeId); |
| 84 | |
| 85 | const resolvePermissionProps = ( |
| 86 | props: WebFunctionPermissionProps | Effect.Effect<WebFunctionPermissionProps, never, Providers>, |
| 87 | ): Effect.Effect<WebFunctionPermissionProps, never, Providers> => |
| 88 | Effect.gen(function* () { |
| 89 | const resolved = Effect.isEffect(props) ? yield* props : props; |
| 90 | if (globalThis.__ALCHEMY_RUNTIME__) return resolved; |
| 91 | const endpoint = Effect.isEffect(resolved.endpoint) |
| 92 | ? yield* resolved.endpoint |
| 93 | : resolved.endpoint; |
| 94 | return { ...resolved, endpoint }; |
| 95 | }); |
| 96 | |
| 97 | /** |
| 98 | * Grants a principal `lambda:InvokeWebFunctionEndpoint` on one endpoint of |
| 99 | * an `AWS.Lambda.WebFunction`. |
| 100 | * |
| 101 | * Use it for callers that sign requests with IAM: another AWS account's |
| 102 | * role, or a service such as CloudFront scoped to one distribution. A |
| 103 | * `CloudFront.Distribution` origin with `webFunction` creates this grant |
| 104 | * for you. Each permission owns one statement in the function's resource |
| 105 | * policy, so several permissions on one function coexist. |
| 106 | * |
| 107 | * ### Granting invoke access |
| 108 | * **Example:** Let a role in another account call the endpoint |
| 109 | * ```typescript |
| 110 | * const api = yield* AWS.Lambda.WebFunction("Api", { |
| 111 | * main: "./src/server.ts", |
| 112 | * authType: "IamAuth", |
| 113 | * }); |
| 114 | * |
| 115 | * yield* AWS.Lambda.WebFunctionPermission("PartnerInvoke", { |
| 116 | * endpoint: api, |
| 117 | * principal: "arn:aws:iam::444455556666:role/partner-caller", |
| 118 | * }); |
| 119 | * ``` |
| 120 | * |
| 121 | * **Example:** Let one CloudFront distribution call the endpoint |
| 122 | * ```typescript |
| 123 | * yield* AWS.Lambda.WebFunctionPermission("CdnInvoke", { |
| 124 | * endpoint: api, |
| 125 | * principal: "cloudfront.amazonaws.com", |
| 126 | * sourceArn: distribution.distributionArn, |
| 127 | * }); |
| 128 | * ``` |
| 129 | * |
| 130 | * @resource |
| 131 | */ |
| 132 | export const WebFunctionPermission: typeof WebFunctionPermissionResource = Object.assign( |
| 133 | ( |
| 134 | id: string, |
| 135 | props: WebFunctionPermissionProps | Effect.Effect<WebFunctionPermissionProps, never, Providers>, |
| 136 | ) => WebFunctionPermissionResource(id, resolvePermissionProps(props)), |
| 137 | WebFunctionPermissionResource, |
| 138 | ); |
| 139 | |
| 140 | /** A declared `endpoint` resolves to the resource before the provider runs. */ |
| 141 | const endpointOf = (props: WebFunctionPermissionProps): WebFunctionEndpointRef => |
| 142 | props.endpoint as WebFunctionEndpointRef; |
| 143 | |
| 144 | interface PolicyStatement { |
| 145 | Sid?: string; |
| 146 | [key: string]: unknown; |
| 147 | } |
| 148 | |
| 149 | interface PolicyDocument { |
| 150 | Version?: string; |
| 151 | Statement?: PolicyStatement[]; |
| 152 | } |
| 153 | |
| 154 | const isServicePrincipal = (principal: string) => principal.endsWith(".amazonaws.com"); |
| 155 | |
| 156 | const statementFor = (sid: string, props: WebFunctionPermissionProps): PolicyStatement => ({ |
| 157 | Sid: sid, |
| 158 | Effect: "Allow", |
| 159 | Principal: isServicePrincipal(props.principal) |
| 160 | ? { Service: props.principal } |
| 161 | : { AWS: props.principal }, |
| 162 | Action: "lambda:InvokeWebFunctionEndpoint", |
| 163 | Resource: endpointOf(props).endpointArn, |
| 164 | ...(props.sourceArn === undefined |
| 165 | ? {} |
| 166 | : { Condition: { StringEquals: { "aws:SourceArn": props.sourceArn } } }), |
| 167 | }); |
| 168 | |
| 169 | export const WebFunctionPermissionProvider = () => |
| 170 | Provider.effect( |
| 171 | WebFunctionPermission, |
| 172 | Effect.gen(function* () { |
| 173 | /** Statement IDs allow letters and digits only. */ |
| 174 | const statementIdOf = (id: string) => |
| 175 | createPhysicalName({ id, maxLength: 100 }).pipe( |
| 176 | Effect.map((name) => name.replaceAll(/[^A-Za-z0-9]/g, "")), |
| 177 | ); |
| 178 | |
| 179 | const getPolicy = Effect.fn(function* (functionArn: string) { |
| 180 | const observed = yield* LambdaWeb.getResourcePolicy({ resourceArn: functionArn }).pipe( |
| 181 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 182 | ); |
| 183 | if (observed === undefined) return undefined; |
| 184 | const document = yield* Effect.try({ |
| 185 | try: () => JSON.parse(observed.policy) as PolicyDocument, |
| 186 | catch: (cause) => new WebFunctionPolicyInvalid({ functionArn, message: String(cause) }), |
| 187 | }); |
| 188 | return { document, revisionId: observed.revisionId }; |
| 189 | }); |
| 190 | |
| 191 | /** |
| 192 | * One lock per function: permissions in the same deploy reconcile |
| 193 | * concurrently, and the first write to a function with no policy yet |
| 194 | * has no `revisionId` to detect a conflict with. |
| 195 | */ |
| 196 | const locks = new Map<string, Semaphore.Semaphore>(); |
| 197 | const lockFor = (functionArn: string) => |
| 198 | Effect.sync(() => { |
| 199 | let lock = locks.get(functionArn); |
| 200 | if (lock === undefined) { |
| 201 | lock = Semaphore.makeUnsafe(1); |
| 202 | locks.set(functionArn, lock); |
| 203 | } |
| 204 | return lock; |
| 205 | }); |
| 206 | |
| 207 | /** |
| 208 | * Read-modify-write the function's single policy document, replacing |
| 209 | * only this permission's statement. Writes to one function are |
| 210 | * serialized; `revisionId` additionally makes a writer outside this |
| 211 | * deploy fail with a conflict instead of being overwritten, and the |
| 212 | * retry re-reads. |
| 213 | */ |
| 214 | const updateStatement = ( |
| 215 | functionArn: string, |
| 216 | sid: string, |
| 217 | statement: PolicyStatement | undefined, |
| 218 | ) => |
| 219 | Effect.flatMap(lockFor(functionArn), (lock) => |
| 220 | lock.withPermits(1)(writeStatement(functionArn, sid, statement)), |
| 221 | ); |
| 222 | |
| 223 | const writeStatement = ( |
| 224 | functionArn: string, |
| 225 | sid: string, |
| 226 | statement: PolicyStatement | undefined, |
| 227 | ) => |
| 228 | Effect.gen(function* () { |
| 229 | const current = yield* getPolicy(functionArn); |
| 230 | const others = (current?.document.Statement ?? []).filter((s) => s.Sid !== sid); |
| 231 | const existing = current?.document.Statement?.find((s) => s.Sid === sid); |
| 232 | if (statement !== undefined && deepEqual(existing, statement)) return; |
| 233 | if (statement === undefined && existing === undefined) return; |
| 234 | const statements = statement === undefined ? others : [...others, statement]; |
| 235 | if (statements.length === 0) { |
| 236 | yield* LambdaWeb.deleteResourcePolicy({ |
| 237 | resourceArn: functionArn, |
| 238 | revisionId: current?.revisionId, |
| 239 | }); |
| 240 | return; |
| 241 | } |
| 242 | yield* LambdaWeb.putResourcePolicy({ |
| 243 | resourceArn: functionArn, |
| 244 | policy: JSON.stringify({ |
| 245 | Version: current?.document.Version ?? "2012-10-17", |
| 246 | Statement: statements, |
| 247 | }), |
| 248 | ...(current ? { revisionId: current.revisionId } : {}), |
| 249 | }); |
| 250 | }).pipe( |
| 251 | Effect.retry({ |
| 252 | while: (e) => e._tag === "ConflictException", |
| 253 | schedule: Schedule.spaced("1 second"), |
| 254 | times: 10, |
| 255 | }), |
| 256 | ); |
| 257 | |
| 258 | return { |
| 259 | stables: ["functionArn", "statementId"], |
| 260 | diff: Effect.fn(function* ({ olds, news, output }) { |
| 261 | if (!isResolved(news)) return; |
| 262 | if (!output || !olds) return undefined; |
| 263 | // The policy lives on the function: a different function is a new |
| 264 | // grant. |
| 265 | if (endpointOf(news).functionArn !== output.functionArn) { |
| 266 | return { action: "replace" }; |
| 267 | } |
| 268 | if (deepEqual(olds, news)) return { action: "noop" }; |
| 269 | }), |
| 270 | read: Effect.fn(function* ({ id, olds, output }) { |
| 271 | const functionArn = |
| 272 | output?.functionArn ?? (olds ? endpointOf(olds).functionArn : undefined); |
| 273 | if (functionArn === undefined) return undefined; |
| 274 | const sid = output?.statementId ?? (yield* statementIdOf(id)); |
| 275 | const policy = yield* getPolicy(functionArn); |
| 276 | const statement = policy?.document.Statement?.find((s) => s.Sid === sid); |
| 277 | if (statement === undefined) return undefined; |
| 278 | return { |
| 279 | functionArn, |
| 280 | endpointArn: (statement.Resource as string) ?? output?.endpointArn ?? "", |
| 281 | statementId: sid, |
| 282 | statement: plainJson(statement), |
| 283 | }; |
| 284 | }), |
| 285 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 286 | const endpoint = endpointOf(news); |
| 287 | if (endpoint.authType !== "IamAuth") { |
| 288 | return yield* new WebFunctionEndpointNotIamAuth({ |
| 289 | endpointArn: endpoint.endpointArn, |
| 290 | message: `AWS.Lambda.WebFunctionPermission "${id}": the endpoint uses authType "${endpoint.authType}", which is public and ignores invoke grants. Set authType: "IamAuth" on it.`, |
| 291 | }); |
| 292 | } |
| 293 | const sid = output?.statementId ?? (yield* statementIdOf(id)); |
| 294 | yield* updateStatement(endpoint.functionArn, sid, statementFor(sid, news)); |
| 295 | const policy = yield* getPolicy(endpoint.functionArn); |
| 296 | const statement = policy?.document.Statement?.find((s) => s.Sid === sid); |
| 297 | return { |
| 298 | functionArn: endpoint.functionArn, |
| 299 | endpointArn: endpoint.endpointArn, |
| 300 | statementId: sid, |
| 301 | statement: plainJson(statement ?? statementFor(sid, news)), |
| 302 | }; |
| 303 | }), |
| 304 | delete: Effect.fn(function* ({ output }) { |
| 305 | // A deleted function takes its policy with it. |
| 306 | yield* updateStatement(output.functionArn, output.statementId, undefined).pipe( |
| 307 | Effect.catchTag("ResourceNotFoundException", () => Effect.void), |
| 308 | ); |
| 309 | }), |
| 310 | }; |
| 311 | }), |
| 312 | ); |