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

main
ts 874 lines 30.5 KB
Raw
1 import type * as EC2 from "@distilled.cloud/aws/ec2";
2 import * as ec2 from "@distilled.cloud/aws/ec2";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import type { ScopedPlanStatusSession } from "alchemy/Report";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, createTagsList, diffTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import type { AccountID } from "../Environment.ts";
13 import { AWSEnvironment } from "../Environment.ts";
14 import type { Providers } from "../Providers.ts";
15 import type { RegionID } from "../Region.ts";
16 import type { RouteTableId } from "./RouteTable.ts";
17 import type { SecurityGroupId } from "./SecurityGroup.ts";
18 import type { SubnetId } from "./Subnet.ts";
19 import type { VpcId } from "./Vpc.ts";
20
21 export class VpcEndpointUnexpectedResponse extends Data.TaggedError(
22 "VpcEndpointUnexpectedResponse",
23 )<{
24 readonly message: string;
25 readonly cause?: unknown;
26 }> {}
27
28 export type VpcEndpointId<ID extends string = string> = `vpce-${ID}`;
29 export const VpcEndpointId = <ID extends string>(id: ID): ID & VpcEndpointId<ID> =>
30 `vpce-${id}` as ID & VpcEndpointId<ID>;
31
32 export type VpcEndpointArn = `arn:aws:ec2:${RegionID}:${AccountID}:vpc-endpoint/${VpcEndpointId}`;
33
34 export interface VpcEndpointProps {
35 /**
36 * The VPC to create the endpoint in.
37 */
38 vpcId: VpcId;
39
40 /**
41 * The service name.
42 * For AWS services, use the format: com.amazonaws.<region>.<service>
43 * @example "com.amazonaws.us-east-1.s3"
44 */
45 serviceName: string;
46
47 /**
48 * The type of endpoint.
49 * - Gateway: For S3 and DynamoDB (route table based)
50 * - Interface: For most other AWS services (ENI based)
51 * - GatewayLoadBalancer: For Gateway Load Balancer endpoints
52 * @default "Gateway"
53 */
54 vpcEndpointType?: EC2.VpcEndpointType;
55
56 /**
57 * The IDs of route tables for a Gateway endpoint.
58 * Required for Gateway endpoints.
59 */
60 routeTableIds?: RouteTableId[];
61
62 /**
63 * The IDs of subnets for an Interface endpoint.
64 * Required for Interface endpoints.
65 */
66 subnetIds?: SubnetId[];
67
68 /**
69 * The IDs of security groups for an Interface endpoint.
70 * Required for Interface endpoints.
71 */
72 securityGroupIds?: SecurityGroupId[];
73
74 /**
75 * Whether to associate a private hosted zone with the VPC.
76 * Only applicable for Interface endpoints.
77 * @default true
78 */
79 privateDnsEnabled?: boolean;
80
81 /**
82 * A policy to attach to the endpoint that controls access to the service.
83 * The policy document must be in JSON format.
84 */
85 policyDocument?: string;
86
87 /**
88 * The IP address type for the endpoint.
89 */
90 ipAddressType?: EC2.IpAddressType;
91
92 /**
93 * The DNS options for the endpoint.
94 */
95 dnsOptions?: {
96 dnsRecordIpType?: EC2.DnsRecordIpType;
97 privateDnsOnlyForInboundResolverEndpoint?: boolean;
98 };
99
100 /**
101 * Tags to assign to the VPC endpoint.
102 */
103 tags?: Record<string, string>;
104 }
105
106 export interface VpcEndpoint extends Resource<
107 "AWS.EC2.VpcEndpoint",
108 VpcEndpointProps,
109 {
110 /**
111 * The ID of the VPC endpoint.
112 */
113 vpcEndpointId: VpcEndpointId;
114
115 /**
116 * The Amazon Resource Name (ARN) of the VPC endpoint.
117 */
118 vpcEndpointArn: VpcEndpointArn;
119
120 /**
121 * The type of endpoint.
122 */
123 vpcEndpointType: EC2.VpcEndpointType;
124
125 /**
126 * The ID of the VPC.
127 */
128 vpcId: VpcId;
129
130 /**
131 * The service name.
132 */
133 serviceName: string;
134
135 /**
136 * The current state of the VPC endpoint.
137 */
138 state: EC2.State;
139
140 /**
141 * The policy document associated with the endpoint.
142 */
143 policyDocument?: string;
144
145 /**
146 * The IDs of the route tables associated with the endpoint.
147 */
148 routeTableIds?: string[];
149
150 /**
151 * The IDs of the subnets associated with the endpoint.
152 */
153 subnetIds?: string[];
154
155 /**
156 * Information about the security groups associated with the network interfaces.
157 */
158 groups?: Array<{
159 groupId: string;
160 groupName: string;
161 }>;
162
163 /**
164 * Whether private DNS is enabled.
165 */
166 privateDnsEnabled?: boolean;
167
168 /**
169 * Whether the VPC endpoint is being managed by its service.
170 */
171 requesterManaged?: boolean;
172
173 /**
174 * The IDs of the network interfaces for the endpoint.
175 */
176 networkInterfaceIds?: string[];
177
178 /**
179 * The DNS entries for the endpoint.
180 */
181 dnsEntries?: Array<{
182 dnsName?: string;
183 hostedZoneId?: string;
184 }>;
185
186 /**
187 * The date and time the VPC endpoint was created.
188 */
189 creationTimestamp?: string;
190
191 /**
192 * The ID of the AWS account that owns the VPC endpoint.
193 */
194 ownerId?: string;
195
196 /**
197 * The IP address type for the endpoint.
198 */
199 ipAddressType?: EC2.IpAddressType;
200
201 /**
202 * The DNS options for the endpoint.
203 */
204 dnsOptions?: {
205 dnsRecordIpType?: EC2.DnsRecordIpType;
206 privateDnsOnlyForInboundResolverEndpoint?: boolean;
207 };
208
209 /**
210 * The last error that occurred for VPC endpoint.
211 */
212 lastError?: {
213 code?: string;
214 message?: string;
215 };
216 },
217 never,
218 Providers
219 > {}
220 /**
221 * A VPC endpoint that connects your VPC privately to an AWS service (or a
222 * service behind a Gateway Load Balancer) without traversing the public
223 * internet, a NAT gateway, or an internet gateway.
224 *
225 * The `vpcEndpointType` selects how the connection is realized:
226 * - `"Gateway"` — for S3 and DynamoDB; traffic is directed by adding routes to
227 * the route tables in `routeTableIds` (no hourly cost).
228 * - `"Interface"` — for most other AWS services; provisions elastic network
229 * interfaces in `subnetIds`, guarded by `securityGroupIds`, and optionally
230 * resolves the service's public DNS name privately via `privateDnsEnabled`.
231 * - `"GatewayLoadBalancer"` — routes traffic through a third-party appliance
232 * fleet fronted by a Gateway Load Balancer.
233 *
234 * Changing `vpcId`, `serviceName`, or `vpcEndpointType` replaces the endpoint;
235 * route tables, subnets, security groups, DNS, and the policy update in place.
236 *
237 * ### Gateway Endpoints
238 * Gateway endpoints target S3 and DynamoDB and work by injecting a prefix-list
239 * route into each route table you list, so requests to the service stay on the
240 * AWS network.
241 * **Example:** S3 Gateway Endpoint
242 * ```typescript
243 * const s3Endpoint = yield* AWS.EC2.VpcEndpoint("S3Endpoint", {
244 * vpcId: vpc.vpcId,
245 * serviceName: "com.amazonaws.us-east-1.s3",
246 * vpcEndpointType: "Gateway",
247 * routeTableIds: [privateRouteTable.routeTableId],
248 * tags: { Name: "s3-endpoint" },
249 * });
250 * ```
251 * Listing the private subnets' route tables in `routeTableIds` lets those
252 * subnets reach S3 directly, removing NAT data-processing charges for S3 traffic
253 * and keeping it off the public internet.
254 *
255 * ### Interface Endpoints
256 * Interface endpoints place an ENI in each chosen subnet and are reached over
257 * private IPs; enabling private DNS lets existing SDK calls resolve to the
258 * endpoint transparently.
259 * **Example:** Secrets Manager Interface Endpoint
260 * ```typescript
261 * const secretsEndpoint = yield* AWS.EC2.VpcEndpoint("SecretsEndpoint", {
262 * vpcId: vpc.vpcId,
263 * serviceName: "com.amazonaws.us-east-1.secretsmanager",
264 * vpcEndpointType: "Interface",
265 * subnetIds: [privateSubnet.subnetId],
266 * securityGroupIds: [endpointSecurityGroup.groupId],
267 * privateDnsEnabled: true,
268 * ipAddressType: "ipv4",
269 * dnsOptions: {
270 * dnsRecordIpType: "ipv4",
271 * },
272 * });
273 * ```
274 * The endpoint gets an interface in each `subnetIds` entry, `securityGroupIds`
275 * controls who may reach those interfaces, and `privateDnsEnabled: true` makes
276 * the service's default DNS name resolve to the endpoint; `ipAddressType` and
277 * `dnsOptions` tune the IP family used for the interfaces and their DNS records.
278 *
279 * ### Restricting Access with a Policy
280 * **Example:** Endpoint Policy Limiting Access to One Bucket
281 * ```typescript
282 * const s3Endpoint = yield* AWS.EC2.VpcEndpoint("RestrictedS3Endpoint", {
283 * vpcId: vpc.vpcId,
284 * serviceName: "com.amazonaws.us-east-1.s3",
285 * vpcEndpointType: "Gateway",
286 * routeTableIds: [privateRouteTable.routeTableId],
287 * policyDocument: JSON.stringify({
288 * Version: "2012-10-17",
289 * Statement: [
290 * {
291 * Effect: "Allow",
292 * Principal: "*",
293 * Action: ["s3:GetObject"],
294 * Resource: ["arn:aws:s3:::my-bucket/*"],
295 * },
296 * ],
297 * }),
298 * });
299 * ```
300 * `policyDocument` attaches an endpoint policy (JSON) that constrains which
301 * service actions and resources can be reached through the endpoint; omit it to
302 * allow full access to the service.
303 *
304 * @resource
305 */
306 export const VpcEndpoint = Resource<VpcEndpoint>("AWS.EC2.VpcEndpoint");
307
308 export const VpcEndpointProvider = () =>
309 Provider.effect(
310 VpcEndpoint,
311 Effect.gen(function* () {
312 const createTags = Effect.fn(function* (id: string, tags?: Record<string, string>) {
313 return {
314 Name: id,
315 ...(yield* createInternalTags(id)),
316 ...tags,
317 };
318 });
319
320 const describeVpcEndpoint = (vpcEndpointId: string) =>
321 ec2.describeVpcEndpoints({ VpcEndpointIds: [vpcEndpointId] }).pipe(
322 // describe-after-write eventual consistency: an endpoint we just
323 // created (or modified) may not be visible to describe yet. The id
324 // is known-valid at every call site, so a bounded retry converges.
325 Effect.retry({
326 while: (e) => e._tag === "InvalidVpcEndpointId.NotFound",
327 schedule: Schedule.max([Schedule.fixed(2000), Schedule.recurs(10)]),
328 }),
329 Effect.map((r) => r.VpcEndpoints?.[0]),
330 Effect.flatMap((ep) =>
331 ep
332 ? Effect.succeed(ep)
333 : Effect.fail(
334 new VpcEndpointUnexpectedResponse({
335 message: `VPC Endpoint ${vpcEndpointId} not found`,
336 }),
337 ),
338 ),
339 );
340
341 const toAttrs = Effect.fn(function* (ep: ec2.VpcEndpoint) {
342 const { accountId, region } = yield* AWSEnvironment.current;
343 return {
344 vpcEndpointId: ep.VpcEndpointId as VpcEndpointId,
345 vpcEndpointArn:
346 `arn:aws:ec2:${region}:${accountId}:vpc-endpoint/${ep.VpcEndpointId}` as VpcEndpointArn,
347 vpcEndpointType: ep.VpcEndpointType!,
348 vpcId: ep.VpcId as VpcId,
349 serviceName: ep.ServiceName!,
350 state: ep.State!,
351 policyDocument: ep.PolicyDocument,
352 routeTableIds: ep.RouteTableIds,
353 subnetIds: ep.SubnetIds,
354 groups: ep.Groups?.map((g) => ({
355 groupId: g.GroupId!,
356 groupName: g.GroupName!,
357 })),
358 privateDnsEnabled: ep.PrivateDnsEnabled,
359 requesterManaged: ep.RequesterManaged,
360 networkInterfaceIds: ep.NetworkInterfaceIds,
361 dnsEntries: ep.DnsEntries?.map((d) => ({
362 dnsName: d.DnsName,
363 hostedZoneId: d.HostedZoneId,
364 })),
365 creationTimestamp:
366 ep.CreationTimestamp instanceof Date
367 ? ep.CreationTimestamp.toISOString()
368 : (ep.CreationTimestamp as string | undefined),
369 ownerId: ep.OwnerId,
370 ipAddressType: ep.IpAddressType,
371 dnsOptions: ep.DnsOptions
372 ? {
373 dnsRecordIpType: ep.DnsOptions.DnsRecordIpType,
374 privateDnsOnlyForInboundResolverEndpoint:
375 ep.DnsOptions.PrivateDnsOnlyForInboundResolverEndpoint,
376 }
377 : undefined,
378 lastError: ep.LastError
379 ? {
380 code: ep.LastError.Code,
381 message: ep.LastError.Message,
382 }
383 : undefined,
384 } satisfies VpcEndpoint["Attributes"];
385 });
386
387 return {
388 stables: ["vpcEndpointId", "vpcEndpointArn", "ownerId"],
389
390 read: Effect.fn(function* ({ output }) {
391 if (!output) return undefined;
392 // No consistency retry here: an endpoint deleted out-of-band should
393 // read as missing immediately, not after a retry window.
394 const lookup = yield* ec2
395 .describeVpcEndpoints({ VpcEndpointIds: [output.vpcEndpointId] })
396 .pipe(
397 Effect.catchTag("InvalidVpcEndpointId.NotFound", () =>
398 Effect.succeed({ VpcEndpoints: [] }),
399 ),
400 );
401 const ep = lookup.VpcEndpoints?.[0];
402 if (!ep || ep.State === "deleted" || ep.State === "deleting") {
403 return undefined;
404 }
405 return yield* toAttrs(ep);
406 }),
407
408 list: () =>
409 Effect.gen(function* () {
410 const endpoints = yield* ec2.describeVpcEndpoints.pages({}).pipe(
411 Stream.runCollect,
412 Effect.map((chunk) =>
413 Array.from(chunk).flatMap((page) =>
414 (page.VpcEndpoints ?? []).filter(
415 (ep): ep is ec2.VpcEndpoint & { VpcEndpointId: string } =>
416 ep.VpcEndpointId != null,
417 ),
418 ),
419 ),
420 );
421 return yield* Effect.forEach(endpoints, (ep) => toAttrs(ep));
422 }),
423
424 diff: Effect.fn(function* ({ news, olds }) {
425 if (!isResolved(news)) return;
426 // Core properties require replacement
427 if (
428 news.vpcId !== olds.vpcId ||
429 news.serviceName !== olds.serviceName ||
430 news.vpcEndpointType !== olds.vpcEndpointType
431 ) {
432 return { action: "replace" };
433 }
434 // Other properties can be updated in-place
435 }),
436
437 reconcile: Effect.fn(function* ({ id, news, output, session }) {
438 const desiredTags = yield* createTags(id, news.tags);
439
440 // Observe — find the VPC endpoint via cached id, else fall through
441 // to create.
442 let ep: ec2.VpcEndpoint | undefined;
443 if (output?.vpcEndpointId) {
444 const lookup = yield* ec2
445 .describeVpcEndpoints({
446 VpcEndpointIds: [output.vpcEndpointId],
447 })
448 .pipe(
449 Effect.catchTag("InvalidVpcEndpointId.NotFound", () =>
450 Effect.succeed({ VpcEndpoints: [] }),
451 ),
452 );
453 ep = lookup.VpcEndpoints?.[0];
454 if (ep && (ep.State === "deleted" || ep.State === "deleting")) {
455 ep = undefined;
456 }
457 }
458
459 // Ensure — create the endpoint when missing.
460 if (ep === undefined) {
461 yield* session.note(`Creating VPC Endpoint for ${news.serviceName}...`);
462 const result = yield* ec2.createVpcEndpoint({
463 VpcId: news.vpcId as string,
464 ServiceName: news.serviceName,
465 VpcEndpointType: news.vpcEndpointType ?? "Gateway",
466 RouteTableIds: news.routeTableIds as string[] | undefined,
467 SubnetIds: news.subnetIds as string[] | undefined,
468 SecurityGroupIds: news.securityGroupIds as string[] | undefined,
469 PrivateDnsEnabled: news.privateDnsEnabled,
470 PolicyDocument: news.policyDocument,
471 IpAddressType: news.ipAddressType,
472 DnsOptions: news.dnsOptions
473 ? {
474 DnsRecordIpType: news.dnsOptions.dnsRecordIpType,
475 PrivateDnsOnlyForInboundResolverEndpoint:
476 news.dnsOptions.privateDnsOnlyForInboundResolverEndpoint,
477 }
478 : undefined,
479 TagSpecifications: [
480 {
481 ResourceType: "vpc-endpoint",
482 Tags: createTagsList(desiredTags),
483 },
484 ],
485 DryRun: false,
486 });
487 const newEpId = result.VpcEndpoint!.VpcEndpointId!;
488 yield* session.note(`VPC Endpoint created: ${newEpId}`);
489 // Wait for every endpoint type: the wait loop also absorbs the
490 // describe-after-create eventual-consistency window during which
491 // the fresh id is not yet visible (Gateway endpoints go
492 // `available` almost immediately, so this costs nothing there).
493 ep = yield* waitForVpcEndpointAvailable(newEpId, session);
494 }
495
496 const vpcEndpointId = ep.VpcEndpointId!;
497 const observedType = ep.VpcEndpointType ?? news.vpcEndpointType;
498
499 // Sync mutable configuration — diff observed cloud state against
500 // desired, then issue a single modifyVpcEndpoint call carrying only
501 // the deltas.
502 const modifications: Parameters<typeof ec2.modifyVpcEndpoint>[0] = {
503 VpcEndpointId: vpcEndpointId,
504 DryRun: false,
505 };
506 let hasModifications = false;
507
508 if (observedType === "Gateway") {
509 const observedRtIds = new Set(ep.RouteTableIds ?? []);
510 const desiredRtIds = new Set((news.routeTableIds as string[] | undefined) ?? []);
511 const addRouteTableIds = [...desiredRtIds].filter((rt) => !observedRtIds.has(rt));
512 const removeRouteTableIds = [...observedRtIds].filter((rt) => !desiredRtIds.has(rt));
513 if (addRouteTableIds.length > 0) {
514 modifications.AddRouteTableIds = addRouteTableIds;
515 hasModifications = true;
516 }
517 if (removeRouteTableIds.length > 0) {
518 modifications.RemoveRouteTableIds = removeRouteTableIds;
519 hasModifications = true;
520 }
521 }
522
523 if (observedType === "Interface" || observedType === "GatewayLoadBalancer") {
524 const observedSubnetIds = new Set(ep.SubnetIds ?? []);
525 const desiredSubnetIds = new Set((news.subnetIds as string[] | undefined) ?? []);
526 const addSubnetIds = [...desiredSubnetIds].filter((s) => !observedSubnetIds.has(s));
527 const removeSubnetIds = [...observedSubnetIds].filter((s) => !desiredSubnetIds.has(s));
528 if (addSubnetIds.length > 0) {
529 modifications.AddSubnetIds = addSubnetIds;
530 hasModifications = true;
531 }
532 if (removeSubnetIds.length > 0) {
533 modifications.RemoveSubnetIds = removeSubnetIds;
534 hasModifications = true;
535 }
536
537 const observedSgIds = new Set(
538 (ep.Groups ?? []).map((g) => g.GroupId).filter((g): g is string => Boolean(g)),
539 );
540 const desiredSgIds = new Set((news.securityGroupIds as string[] | undefined) ?? []);
541 const addSecurityGroupIds = [...desiredSgIds].filter((g) => !observedSgIds.has(g));
542 const removeSecurityGroupIds = [...observedSgIds].filter((g) => !desiredSgIds.has(g));
543 if (addSecurityGroupIds.length > 0) {
544 modifications.AddSecurityGroupIds = addSecurityGroupIds;
545 hasModifications = true;
546 }
547 if (removeSecurityGroupIds.length > 0) {
548 modifications.RemoveSecurityGroupIds = removeSecurityGroupIds;
549 hasModifications = true;
550 }
551
552 if (
553 news.privateDnsEnabled !== undefined &&
554 ep.PrivateDnsEnabled !== news.privateDnsEnabled
555 ) {
556 modifications.PrivateDnsEnabled = news.privateDnsEnabled;
557 hasModifications = true;
558 }
559 }
560
561 const observedPolicy = ep.PolicyDocument ?? undefined;
562 if (news.policyDocument !== undefined) {
563 if (!policyDocumentEquals(observedPolicy, news.policyDocument)) {
564 // AWS rejects passing both a policy document and the reset flag
565 // in the same call — choose exactly one.
566 modifications.PolicyDocument = news.policyDocument;
567 hasModifications = true;
568 }
569 } else if (!isFullAccessEndpointPolicy(observedPolicy)) {
570 // An absent `policyDocument` means "the default full-access
571 // policy". AWS attaches exactly that default to every fresh
572 // endpoint, so only reset when a custom policy is actually
573 // present — issuing a ResetPolicy no-op immediately after create
574 // races the new endpoint id's propagation and previously failed
575 // the whole reconcile with InvalidVpcEndpointId.NotFound.
576 modifications.ResetPolicy = true;
577 hasModifications = true;
578 }
579
580 // An unspecified `ipAddressType`/`dnsOptions` means "AWS default" —
581 // the observed value on a fresh endpoint (e.g. "not-specified", or
582 // populated DNS defaults) must not be diffed against `undefined`,
583 // which previously caused a spurious modify on every reconcile.
584 if (news.ipAddressType !== undefined && ep.IpAddressType !== news.ipAddressType) {
585 modifications.IpAddressType = news.ipAddressType;
586 hasModifications = true;
587 }
588
589 if (news.dnsOptions !== undefined) {
590 const observedDnsRecordIpType = ep.DnsOptions?.DnsRecordIpType;
591 const observedPrivateDnsOnly = ep.DnsOptions?.PrivateDnsOnlyForInboundResolverEndpoint;
592 if (
593 (news.dnsOptions.dnsRecordIpType !== undefined &&
594 observedDnsRecordIpType !== news.dnsOptions.dnsRecordIpType) ||
595 (news.dnsOptions.privateDnsOnlyForInboundResolverEndpoint !== undefined &&
596 observedPrivateDnsOnly !== news.dnsOptions.privateDnsOnlyForInboundResolverEndpoint)
597 ) {
598 modifications.DnsOptions = {
599 DnsRecordIpType: news.dnsOptions.dnsRecordIpType,
600 PrivateDnsOnlyForInboundResolverEndpoint:
601 news.dnsOptions.privateDnsOnlyForInboundResolverEndpoint,
602 };
603 hasModifications = true;
604 }
605 }
606
607 if (hasModifications) {
608 yield* ec2.modifyVpcEndpoint(modifications).pipe(
609 // The endpoint id is known-valid here (we just observed or
610 // created it) — NotFound is describe/modify-plane propagation
611 // lag, not a missing endpoint.
612 Effect.retry({
613 while: (e) => e._tag === "InvalidVpcEndpointId.NotFound",
614 schedule: Schedule.max([Schedule.fixed(2000), Schedule.recurs(10)]),
615 }),
616 );
617 yield* session.note("Updated VPC Endpoint configuration");
618 if (observedType === "Interface" || observedType === "GatewayLoadBalancer") {
619 yield* waitForVpcEndpointAvailable(vpcEndpointId, session);
620 }
621 }
622
623 // Sync tags — observed cloud tags vs desired.
624 const currentTags = Object.fromEntries(
625 (ep.Tags ?? []).map((t) => [t.Key!, t.Value!]),
626 ) as Record<string, string>;
627 const { removed, upsert } = diffTags(currentTags, desiredTags);
628 if (removed.length > 0) {
629 yield* ec2.deleteTags({
630 Resources: [vpcEndpointId],
631 Tags: removed.map((key) => ({ Key: key })),
632 DryRun: false,
633 });
634 }
635 if (upsert.length > 0) {
636 yield* ec2.createTags({
637 Resources: [vpcEndpointId],
638 Tags: upsert,
639 DryRun: false,
640 });
641 }
642
643 // Re-read final state.
644 const final = yield* describeVpcEndpoint(vpcEndpointId);
645 return yield* toAttrs(final);
646 }),
647
648 delete: Effect.fn(function* ({ output, session }) {
649 const vpcEndpointId = output.vpcEndpointId;
650
651 yield* session.note(`Deleting VPC Endpoint: ${vpcEndpointId}`);
652
653 yield* ec2
654 .deleteVpcEndpoints({
655 VpcEndpointIds: [vpcEndpointId],
656 DryRun: false,
657 })
658 .pipe(Effect.catchTag("InvalidVpcEndpointId.NotFound", () => Effect.void));
659
660 // Wait for deletion
661 yield* waitForVpcEndpointDeleted(vpcEndpointId, session);
662
663 // Interface/GatewayLoadBalancer endpoints release their network
664 // interfaces asynchronously after the endpoint itself reports
665 // deleted. The parent VPC (and subnets/security groups) cannot be
666 // deleted while those ENIs linger, so wait until they are gone.
667 const eniIds = output.networkInterfaceIds ?? [];
668 if (eniIds.length > 0) {
669 yield* waitForEndpointEnisReleased(eniIds, session);
670 }
671
672 yield* session.note(`VPC Endpoint ${vpcEndpointId} deleted`);
673 }),
674 };
675 }),
676 );
677
678 // Retryable error: VPC Endpoint is still pending
679 class VpcEndpointPending extends Data.TaggedError("VpcEndpointPending")<{
680 vpcEndpointId: string;
681 state: string;
682 }> {}
683
684 // Terminal error: VPC Endpoint creation failed
685 class VpcEndpointFailed extends Data.TaggedError("VpcEndpointFailed")<{
686 vpcEndpointId: string;
687 errorCode?: string;
688 errorMessage?: string;
689 }> {}
690
691 // Retryable error: VPC Endpoint is still deleting
692 class VpcEndpointDeleting extends Data.TaggedError("VpcEndpointDeleting")<{
693 vpcEndpointId: string;
694 state: string;
695 }> {}
696
697 // Retryable error: endpoint network interfaces are still being released
698 class VpcEndpointEnisLingering extends Data.TaggedError("VpcEndpointEnisLingering")<{
699 networkInterfaceIds: string[];
700 }> {}
701
702 /**
703 * Wait for VPC Endpoint to be in available state.
704 *
705 * Only ever called with an id we just created or observed, so a NotFound (or
706 * an empty describe result) is describe-after-create eventual consistency and
707 * is retried as "pending" rather than treated as terminal.
708 */
709 const waitForVpcEndpointAvailable = (vpcEndpointId: string, session: ScopedPlanStatusSession) =>
710 Effect.gen(function* () {
711 const result = yield* ec2
712 .describeVpcEndpoints({ VpcEndpointIds: [vpcEndpointId] })
713 .pipe(
714 Effect.catchTag("InvalidVpcEndpointId.NotFound", () =>
715 Effect.succeed({ VpcEndpoints: [] }),
716 ),
717 );
718 const ep = result.VpcEndpoints?.[0];
719
720 if (!ep) {
721 // Fresh id not visible to describe yet — retry.
722 return yield* new VpcEndpointPending({
723 vpcEndpointId,
724 state: "propagating",
725 });
726 }
727
728 if (ep.State === "available") {
729 return ep;
730 }
731
732 if (ep.State === "failed" || ep.State === "rejected") {
733 return yield* new VpcEndpointFailed({
734 vpcEndpointId,
735 errorCode: ep.LastError?.Code,
736 errorMessage: ep.LastError?.Message,
737 });
738 }
739
740 // Still pending - this is the only retryable case
741 return yield* new VpcEndpointPending({ vpcEndpointId, state: ep.State! });
742 }).pipe(
743 Effect.retry({
744 while: (e) => e._tag === "VpcEndpointPending",
745 schedule: Schedule.max([Schedule.fixed(3000), Schedule.recurs(60)]).pipe(
746 Schedule.tap(({ attempt }) =>
747 session.note(`Waiting for VPC Endpoint to be available... (${attempt * 3}s)`),
748 ),
749 ),
750 }),
751 );
752
753 /**
754 * Wait for VPC Endpoint to be deleted
755 */
756 const waitForVpcEndpointDeleted = (vpcEndpointId: string, session: ScopedPlanStatusSession) =>
757 Effect.gen(function* () {
758 const result = yield* ec2
759 .describeVpcEndpoints({ VpcEndpointIds: [vpcEndpointId] })
760 .pipe(
761 Effect.catchTag("InvalidVpcEndpointId.NotFound", () =>
762 Effect.succeed({ VpcEndpoints: [] }),
763 ),
764 );
765
766 const ep = result.VpcEndpoints?.[0];
767
768 if (!ep || ep.State === "deleted") {
769 return; // Successfully deleted
770 }
771
772 // Still deleting - this is the only retryable case
773 return yield* new VpcEndpointDeleting({ vpcEndpointId, state: ep.State! });
774 }).pipe(
775 Effect.retry({
776 while: (e) => e._tag === "VpcEndpointDeleting",
777 // Interface endpoints sometimes take well over 3 minutes to leave
778 // `deleting`; budget 10.
779 schedule: Schedule.max([Schedule.fixed(5000), Schedule.recurs(120)]).pipe(
780 Schedule.tap(({ attempt }) =>
781 session.note(`Waiting for VPC Endpoint deletion... (${attempt * 5}s)`),
782 ),
783 ),
784 }),
785 );
786
787 /**
788 * Wait for the endpoint's network interfaces to be released after deletion.
789 *
790 * Uses a filter (not `NetworkInterfaceIds`) so already-released interfaces
791 * simply drop out of the result instead of failing the whole describe with
792 * `InvalidNetworkInterfaceID.NotFound`.
793 */
794 const waitForEndpointEnisReleased = (
795 networkInterfaceIds: string[],
796 session: ScopedPlanStatusSession,
797 ) =>
798 Effect.gen(function* () {
799 const remaining = yield* ec2.describeNetworkInterfaces
800 .items({
801 Filters: [{ Name: "network-interface-id", Values: networkInterfaceIds }],
802 })
803 .pipe(
804 Stream.map((eni) => eni.NetworkInterfaceId),
805 Stream.filter((id): id is string => Boolean(id)),
806 Stream.runCollect,
807 Effect.map((chunk) => Array.from(chunk)),
808 );
809 if (remaining.length > 0) {
810 return yield* new VpcEndpointEnisLingering({
811 networkInterfaceIds: remaining,
812 });
813 }
814 }).pipe(
815 Effect.retry({
816 while: (e) => e._tag === "VpcEndpointEnisLingering",
817 schedule: Schedule.max([Schedule.fixed(3000), Schedule.recurs(20)]).pipe(
818 Schedule.tap(({ attempt }) =>
819 session.note(`Waiting for endpoint network interfaces to release... (${attempt * 3}s)`),
820 ),
821 ),
822 }),
823 );
824
825 /**
826 * Structural check for the default full-access endpoint policy that AWS
827 * attaches to every freshly created VPC endpoint. An absent `policyDocument`
828 * prop is equivalent to this default, so observing it must not trigger a
829 * `ResetPolicy` modification.
830 */
831 const isFullAccessEndpointPolicy = (doc: string | undefined): boolean => {
832 if (!doc) return true;
833 try {
834 const parsed = JSON.parse(doc) as {
835 Statement?: Array<{
836 Effect?: unknown;
837 Principal?: unknown;
838 Action?: unknown;
839 Resource?: unknown;
840 Condition?: unknown;
841 }>;
842 };
843 const statements = parsed.Statement ?? [];
844 if (statements.length !== 1) return false;
845 const s = statements[0];
846 const isStar = (value: unknown) =>
847 value === "*" ||
848 (Array.isArray(value) && value.length === 1 && value[0] === "*") ||
849 (typeof value === "object" && value !== null && (value as { AWS?: unknown }).AWS === "*");
850 return (
851 s.Effect === "Allow" &&
852 isStar(s.Principal) &&
853 isStar(s.Action) &&
854 isStar(s.Resource) &&
855 s.Condition === undefined
856 );
857 } catch {
858 return false;
859 }
860 };
861
862 /**
863 * Compare two endpoint policy documents structurally (AWS normalizes the JSON
864 * it stores, so raw string comparison would report a perpetual diff).
865 */
866 const policyDocumentEquals = (a: string | undefined, b: string | undefined): boolean => {
867 if (a === b) return true;
868 if (a === undefined || b === undefined) return false;
869 try {
870 return JSON.stringify(JSON.parse(a)) === JSON.stringify(JSON.parse(b));
871 } catch {
872 return a === b;
873 }
874 };