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

main
ts 798 lines 28 KB
Raw
1 import * as ec2 from "@distilled.cloud/aws/ec2";
2 import { deepEqual, isResolved } from "alchemy/Diff";
3 import * as Output from "alchemy/Output";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { Stack } from "alchemy/Stack";
7 import { State, isActionState } from "alchemy/State/State";
8 import { createInternalTags, createTagsList, diffTags } from "alchemy/Tags";
9 import { canonicalCidr } from "alchemy/Util/ip-address";
10 import * as Data from "effect/Data";
11 import * as Effect from "effect/Effect";
12 import * as Schedule from "effect/Schedule";
13 import * as Stream from "effect/Stream";
14 import type { Providers } from "../Providers.ts";
15 import {
16 getDefaultVpcDefaultSecurityGroupId,
17 getDefaultVpcEmrManagedSecurityGroupIds,
18 getDefaultVpcScope,
19 } from "./defaultVpcScope.ts";
20 import type { SecurityGroupId, SecurityGroupRuleData } from "./SecurityGroup.ts";
21
22 export class SecurityGroupRuleUnexpectedResponse extends Data.TaggedError(
23 "SecurityGroupRuleUnexpectedResponse",
24 )<{
25 readonly message: string;
26 readonly cause?: unknown;
27 }> {}
28
29 export type SecurityGroupRuleId<ID extends string = string> = `sgr-${ID}`;
30 export const SecurityGroupRuleId = <ID extends string>(id: ID): ID & SecurityGroupRuleId<ID> =>
31 `sgr-${id}` as ID & SecurityGroupRuleId<ID>;
32
33 export interface SecurityGroupRuleProps {
34 /**
35 * The SecurityGroup or DefaultSecurityGroup resource, or a { groupId } object.
36 * Pass the whole resource to wait for its inline-rule reconciliation before
37 * creating or updating this rule; an ID-only object does not retain that edge.
38 * Only groupId is consumed; other attributes do not change this rule.
39 * Specify exactly one of group or groupId.
40 */
41 group?: {
42 /** The security group's physical ID. */
43 groupId: SecurityGroupId;
44 };
45
46 /**
47 * The ID of an existing security group. Retained for ID-only callers; use
48 * group with the whole resource when composing inline and standalone rules.
49 * Specify exactly one of group or groupId.
50 */
51 groupId?: SecurityGroupId;
52
53 /**
54 * Whether this is an ingress (inbound) or egress (outbound) rule.
55 */
56 type: "ingress" | "egress";
57
58 /**
59 * The IP protocol name or number.
60 * Use -1 to specify all protocols.
61 */
62 ipProtocol: string;
63
64 /**
65 * The start of the port range.
66 * For ICMP, use the ICMP type number.
67 */
68 fromPort?: number;
69
70 /**
71 * The end of the port range.
72 * For ICMP, use the ICMP code.
73 */
74 toPort?: number;
75
76 /**
77 * IPv4 CIDR range to allow.
78 */
79 cidrIpv4?: string;
80
81 /**
82 * IPv6 CIDR range to allow.
83 */
84 cidrIpv6?: string;
85
86 /**
87 * ID of a security group to allow traffic from/to.
88 */
89 referencedGroupId?: SecurityGroupId;
90
91 /**
92 * ID of a prefix list.
93 */
94 prefixListId?: string;
95
96 /**
97 * Description for the rule.
98 */
99 description?: string;
100
101 /**
102 * Tags to assign to the security group rule.
103 */
104 tags?: Record<string, string>;
105 }
106
107 export interface SecurityGroupRule extends Resource<
108 "AWS.EC2.SecurityGroupRule",
109 SecurityGroupRuleProps,
110 {
111 /**
112 * The ID of the security group rule.
113 */
114 securityGroupRuleId: SecurityGroupRuleId;
115
116 /**
117 * The ID of the security group.
118 */
119 groupId: SecurityGroupId;
120
121 /**
122 * The ID of the AWS account that owns the security group.
123 */
124 groupOwnerId: string;
125
126 /**
127 * Whether this is an egress rule.
128 */
129 isEgress: boolean;
130
131 /**
132 * The IP protocol.
133 */
134 ipProtocol: string;
135
136 /**
137 * The start of the port range.
138 */
139 fromPort?: number;
140
141 /**
142 * The end of the port range.
143 */
144 toPort?: number;
145
146 /**
147 * The IPv4 CIDR range.
148 */
149 cidrIpv4?: string | undefined;
150
151 /**
152 * The IPv6 CIDR range.
153 */
154 cidrIpv6?: string | undefined;
155
156 /**
157 * The ID of the referenced security group.
158 */
159 referencedGroupId?: string;
160
161 /**
162 * The ID of the prefix list.
163 */
164 prefixListId?: string;
165
166 /**
167 * The description.
168 */
169 description?: string | undefined;
170 },
171 never,
172 Providers
173 > {}
174 /**
175 * A single ingress or egress rule attached to an existing security group,
176 * managed as a standalone resource. Use this when you want to manage a
177 * security group's rules independently of its inline rules, or to add rules
178 * to a group not managed by an Alchemy SecurityGroup resource.
179 *
180 * Declare the group and rule in the same stack and stage, passing the whole
181 * resource as `group` to order rule operations after inline reconciliation.
182 * `groupId` remains supported for ID-only callers, but its stable value alone
183 * does not order concurrent inline updates. Specify exactly one input form;
184 * switching forms with the same physical ID does not replace the rule.
185 * The group recognizes the current declaration and its persisted physical
186 * rule ID, not cloud tags. Rules in another stack or stage are not protected
187 * from the group's reconciliation;
188 * cross-stack ownership is unsupported.
189 *
190 * Changes to protocol, ports, source, or `type` props replace the rule.
191 * External edits to protocol, ports, source, description, and tags are repaired
192 * on unchanged deployment. Description and tag prop changes update in place.
193 *
194 * ### Ingress vs Egress
195 * The `type` field decides the direction: `"ingress"` for inbound rules and
196 * `"egress"` for outbound. Everything else (protocol, ports, source) is shared
197 * between the two directions.
198 *
199 * **Example:** Inbound HTTPS from anywhere
200 * ```typescript
201 * const httpsRule = yield* AWS.EC2.SecurityGroupRule("HttpsIngress", {
202 * group: sg,
203 * type: "ingress",
204 * ipProtocol: "tcp",
205 * fromPort: 443,
206 * toPort: 443,
207 * cidrIpv4: "0.0.0.0/0",
208 * description: "Allow HTTPS",
209 * });
210 * ```
211 *
212 * Opens TCP 443 inbound from the entire internet on the target group. A single
213 * port is expressed by setting `fromPort` and `toPort` to the same value.
214 *
215 * **Example:** Outbound to a database port
216 * ```typescript
217 * const egressRule = yield* AWS.EC2.SecurityGroupRule("DbEgress", {
218 * group: sg,
219 * type: "egress",
220 * ipProtocol: "tcp",
221 * fromPort: 5432,
222 * toPort: 5432,
223 * cidrIpv4: "10.0.0.0/16",
224 * description: "Allow PostgreSQL to the VPC",
225 * });
226 * ```
227 *
228 * This rule allows outbound PostgreSQL within the VPC CIDR. Set `egress: []`
229 * on the parent group to remove its default allow-all-outbound rule; adding a
230 * standalone egress rule does not remove other rules.
231 *
232 * ### Rule Sources
233 * A rule's source (for ingress) or destination (for egress) is exactly one of:
234 * an IPv4 CIDR (`cidrIpv4`), an IPv6 CIDR (`cidrIpv6`), another security group
235 * (`referencedGroupId`), or a managed prefix list (`prefixListId`).
236 *
237 * **Example:** Allow traffic from another security group
238 * ```typescript
239 * const dbFromWeb = yield* AWS.EC2.SecurityGroupRule("DbFromWeb", {
240 * group: dbSg,
241 * type: "ingress",
242 * ipProtocol: "tcp",
243 * fromPort: 5432,
244 * toPort: 5432,
245 * referencedGroupId: webSg.groupId,
246 * description: "Allow PostgreSQL from web tier",
247 * });
248 * ```
249 *
250 * Referencing `webSg` rather than a CIDR means any instance in the web tier can
251 * reach the database, even as the tier's IPs change. This is the preferred way
252 * to wire trust between tiers.
253 *
254 * **Example:** Allow an IPv6 range
255 * ```typescript
256 * const ipv6Rule = yield* AWS.EC2.SecurityGroupRule("HttpsIpv6", {
257 * group: sg,
258 * type: "ingress",
259 * ipProtocol: "tcp",
260 * fromPort: 443,
261 * toPort: 443,
262 * cidrIpv6: "::/0",
263 * description: "Allow HTTPS over IPv6",
264 * });
265 * ```
266 *
267 * Use `cidrIpv6` for dual-stack workloads; `::/0` is the IPv6 equivalent of
268 * `0.0.0.0/0`. IPv4 and IPv6 are separate rules — you'd pair this with a
269 * `cidrIpv4` rule to cover both.
270 *
271 * **Example:** Allow from a managed prefix list
272 * ```typescript
273 * const sshRule = yield* AWS.EC2.SecurityGroupRule("SshFromCorp", {
274 * group: sg,
275 * type: "ingress",
276 * ipProtocol: "tcp",
277 * fromPort: 22,
278 * toPort: 22,
279 * prefixListId: "pl-0123456789abcdef0",
280 * description: "Allow SSH from the corporate prefix list",
281 * });
282 * ```
283 *
284 * A `prefixListId` references a centrally-managed set of CIDRs by ID, so the
285 * rule's effective ranges update automatically whenever the prefix list does.
286 *
287 * ### Protocols & Ports
288 * `ipProtocol` accepts `tcp`, `udp`, `icmp`/`icmpv6`, a protocol number, or `-1`
289 * for all protocols. For ICMP, `fromPort` is the ICMP type and `toPort` is the
290 * ICMP code, with `-1` meaning "all".
291 *
292 * **Example:** Allow all traffic from a trusted CIDR
293 * ```typescript
294 * const allRule = yield* AWS.EC2.SecurityGroupRule("AllFromVpc", {
295 * group: sg,
296 * type: "ingress",
297 * ipProtocol: "-1",
298 * cidrIpv4: "10.0.0.0/16",
299 * description: "Allow all protocols from within the VPC",
300 * });
301 * ```
302 *
303 * With `ipProtocol: "-1"`, ports are ignored and every protocol is permitted —
304 * appropriate only for fully trusted sources such as your own VPC CIDR.
305 *
306 * **Example:** Allow ICMP echo (ping)
307 * ```typescript
308 * const icmpRule = yield* AWS.EC2.SecurityGroupRule("AllowPing", {
309 * group: sg,
310 * type: "ingress",
311 * ipProtocol: "icmp",
312 * fromPort: 8,
313 * toPort: 0,
314 * cidrIpv4: "10.0.0.0/16",
315 * description: "Allow ICMP echo request",
316 * });
317 * ```
318 *
319 * For ICMP the port fields carry the type and code: type `8` / code `0` is an
320 * echo request (ping). Use `fromPort: -1, toPort: -1` to allow every ICMP
321 * type/code instead.
322 *
323 * @resource
324 */
325 export const SecurityGroupRule = Resource<SecurityGroupRule>("AWS.EC2.SecurityGroupRule");
326
327 class InvalidSecurityGroupRuleGroup extends Data.TaggedError("InvalidSecurityGroupRuleGroup")<{
328 message: string;
329 }> {}
330
331 const ruleGroupId = Effect.fn(function* (props: Pick<SecurityGroupRuleProps, "group" | "groupId">) {
332 if ((props.group === undefined) === (props.groupId === undefined)) {
333 return yield* new InvalidSecurityGroupRuleGroup({
334 message: "Specify exactly one of group or groupId.",
335 });
336 }
337 const groupId = props.group?.groupId ?? props.groupId;
338 if (typeof groupId !== "string") {
339 return yield* new InvalidSecurityGroupRuleGroup({
340 message: "The group must provide a groupId.",
341 });
342 }
343 return groupId;
344 });
345
346 class SecurityGroupRuleNotConverged extends Data.TaggedError("SecurityGroupRuleNotConverged")<{
347 ruleId: string;
348 }> {}
349
350 export const SecurityGroupRuleProvider = () =>
351 Provider.effect(
352 SecurityGroupRule,
353 Effect.gen(function* () {
354 const createTags = Effect.fn(function* (id: string, tags?: Record<string, string>) {
355 return {
356 Name: id,
357 ...(yield* createInternalTags(id)),
358 ...tags,
359 };
360 });
361
362 const describeRule = (ruleId: string) =>
363 ec2.describeSecurityGroupRules({ SecurityGroupRuleIds: [ruleId] }).pipe(
364 Effect.map((r) => r.SecurityGroupRules?.[0]),
365 Effect.flatMap((rule) =>
366 rule
367 ? Effect.succeed(rule)
368 : Effect.fail(
369 new SecurityGroupRuleUnexpectedResponse({
370 message: `Security Group Rule ${ruleId} not found`,
371 }),
372 ),
373 ),
374 );
375
376 const toAttrs = (
377 rule: Awaited<
378 ReturnType<
379 typeof describeRule extends (...args: any) => Effect.Effect<infer R, any, any>
380 ? () => Promise<R>
381 : never
382 >
383 >,
384 ): SecurityGroupRule["Attributes"] => ({
385 securityGroupRuleId: rule.SecurityGroupRuleId as SecurityGroupRuleId,
386 groupId: rule.GroupId as SecurityGroupId,
387 groupOwnerId: rule.GroupOwnerId!,
388 isEgress: rule.IsEgress as boolean,
389 ipProtocol: rule.IpProtocol!,
390 fromPort: rule.FromPort,
391 toPort: rule.ToPort,
392 cidrIpv4: rule.CidrIpv4,
393 cidrIpv6: rule.CidrIpv6,
394 referencedGroupId: rule.ReferencedGroupInfo?.GroupId,
395 prefixListId: rule.PrefixListId,
396 description: rule.Description,
397 });
398
399 const tagsMatch = (rule: ec2.SecurityGroupRule, tags: Record<string, string>) => {
400 const { removed, upsert } = diffTags(
401 Object.fromEntries((rule.Tags ?? []).map((tag) => [tag.Key!, tag.Value!])),
402 tags,
403 );
404 return removed.length === 0 && upsert.length === 0;
405 };
406
407 return {
408 stables: ["securityGroupRuleId", "groupOwnerId"],
409
410 read: Effect.fn(function* ({ output }) {
411 if (!output) return undefined;
412 return yield* describeRule(output.securityGroupRuleId).pipe(
413 Effect.map(toAttrs),
414 Effect.catchTag("InvalidSecurityGroupRuleId.NotFound", () => Effect.undefined),
415 );
416 }),
417
418 // Account/region-scoped: every rule is enumerable via
419 // describeSecurityGroupRules with no filter. Paginate exhaustively.
420 list: () =>
421 Effect.gen(function* () {
422 // Rules on the default VPC's "default" security group are
423 // furniture AWS provisions with the default VPC; never
424 // census/nuke them. Rules on user-created groups inside the
425 // default VPC are still listed.
426 const defaultVpc = yield* getDefaultVpcScope;
427 const defaultSgId = yield* getDefaultVpcDefaultSecurityGroupId(defaultVpc.vpcId);
428 const emrManaged = yield* getDefaultVpcEmrManagedSecurityGroupIds(defaultVpc.vpcId);
429 return yield* ec2.describeSecurityGroupRules.pages({}).pipe(
430 Stream.runCollect,
431 Effect.map((chunk) =>
432 Array.from(chunk).flatMap((page) =>
433 (page.SecurityGroupRules ?? [])
434 .filter(
435 (
436 rule,
437 ): rule is ec2.SecurityGroupRule & {
438 SecurityGroupRuleId: string;
439 } => rule.SecurityGroupRuleId != null,
440 )
441 .filter((rule) => defaultSgId === undefined || rule.GroupId !== defaultSgId)
442 .filter((rule) => rule.GroupId === undefined || !emrManaged.has(rule.GroupId))
443 .map((rule) => toAttrs(rule)),
444 ),
445 ),
446 );
447 }),
448
449 diff: Effect.fn(function* ({ id, news, olds, output }) {
450 if (!("type" in news)) return;
451 const { group, groupId, ...rule } = news;
452 if ((group === undefined) === (groupId === undefined)) {
453 return yield* new InvalidSecurityGroupRuleGroup({
454 message: "Specify exactly one of group or groupId.",
455 });
456 }
457 // Updating groups expose stable IDs; creating/replacing groups do not.
458 if (!isResolved(group)) return { action: "replace" };
459 const target = group?.groupId ?? groupId;
460 if (!isResolved(target)) return { action: "replace" };
461 const desiredGroupId = yield* ruleGroupId({ groupId: target });
462 const oldGroupId = olds.group?.groupId ?? olds.groupId ?? output?.groupId;
463 if (desiredGroupId !== oldGroupId) return { action: "replace" };
464 for (const key of [
465 "type",
466 "ipProtocol",
467 "fromPort",
468 "toPort",
469 "cidrIpv4",
470 "cidrIpv6",
471 "referencedGroupId",
472 "prefixListId",
473 ] as const) {
474 if (rule[key] !== olds[key]) {
475 return { action: "replace" };
476 }
477 }
478 if (!isResolved<Omit<SecurityGroupRuleProps, "group" | "groupId">>(rule)) return;
479 const desired = { ...rule, groupId: desiredGroupId };
480 const { group: _group, groupId: _groupId, ...oldRule } = olds;
481 if (output) {
482 const observed = yield* describeRule(output.securityGroupRuleId).pipe(
483 Effect.catchTag("InvalidSecurityGroupRuleId.NotFound", () => Effect.undefined),
484 );
485 if (!observed) {
486 return { action: "update", stables: ["groupOwnerId"] };
487 }
488 if (
489 observed.GroupId !== desiredGroupId ||
490 observed.IsEgress !== (rule.type === "egress")
491 ) {
492 return { action: "replace" };
493 }
494 if (
495 observedSecurityGroupRuleKey(observed) !== securityGroupRuleKey(rule) ||
496 !tagsMatch(observed, yield* createTags(id, rule.tags))
497 ) {
498 return { action: "update" };
499 }
500 // Ignore only the input form and unconsumed parent attributes.
501 if (deepEqual({ ...oldRule, groupId: oldGroupId }, desired)) {
502 return { action: "noop" };
503 }
504 }
505 return { action: "update" };
506 }),
507
508 reconcile: Effect.fn(function* ({ id, news, output, session }) {
509 const groupId = yield* ruleGroupId(news);
510 const desiredTags = yield* createTags(id, news.tags);
511
512 const ipPermission = {
513 IpProtocol: news.ipProtocol,
514 FromPort: news.fromPort,
515 ToPort: news.toPort,
516 IpRanges: news.cidrIpv4
517 ? [{ CidrIp: news.cidrIpv4, Description: news.description }]
518 : undefined,
519 Ipv6Ranges: news.cidrIpv6
520 ? [{ CidrIpv6: news.cidrIpv6, Description: news.description }]
521 : undefined,
522 UserIdGroupPairs: news.referencedGroupId
523 ? [
524 {
525 GroupId: news.referencedGroupId as string,
526 Description: news.description,
527 },
528 ]
529 : undefined,
530 PrefixListIds: news.prefixListId
531 ? [
532 {
533 PrefixListId: news.prefixListId as string,
534 Description: news.description,
535 },
536 ]
537 : undefined,
538 };
539
540 // Observe — find the rule via cached id, else fall through to
541 // create. SG rule identity is the SecurityGroupRuleId.
542 let observed: ec2.SecurityGroupRule | undefined;
543 if (output?.securityGroupRuleId) {
544 const lookup = yield* ec2
545 .describeSecurityGroupRules({
546 SecurityGroupRuleIds: [output.securityGroupRuleId],
547 })
548 .pipe(
549 Effect.catchTag("InvalidSecurityGroupRuleId.NotFound", () =>
550 Effect.succeed({ SecurityGroupRules: [] }),
551 ),
552 );
553 observed = lookup.SecurityGroupRules?.[0];
554 }
555
556 // Ensure — Authorize{Ingress,Egress} when missing.
557 if (observed === undefined) {
558 yield* session.note("Creating Security Group Rule...");
559 const tagSpec = [
560 {
561 ResourceType: "security-group-rule" as const,
562 Tags: createTagsList(desiredTags),
563 },
564 ];
565 const result =
566 news.type === "ingress"
567 ? yield* ec2.authorizeSecurityGroupIngress({
568 GroupId: groupId,
569 IpPermissions: [ipPermission],
570 TagSpecifications: tagSpec,
571 DryRun: false,
572 })
573 : yield* ec2.authorizeSecurityGroupEgress({
574 GroupId: groupId,
575 IpPermissions: [ipPermission],
576 TagSpecifications: tagSpec,
577 DryRun: false,
578 });
579 const newRuleId = result.SecurityGroupRules?.[0]?.SecurityGroupRuleId!;
580 yield* session.note(`Security Group Rule created: ${newRuleId}`);
581 observed = yield* describeRule(newRuleId);
582 }
583
584 const ruleId = observed.SecurityGroupRuleId!;
585
586 const desiredKey = securityGroupRuleKey(news);
587 if (observedSecurityGroupRuleKey(observed) !== desiredKey) {
588 yield* ec2.modifySecurityGroupRules({
589 GroupId: groupId,
590 SecurityGroupRules: [
591 {
592 SecurityGroupRuleId: ruleId,
593 SecurityGroupRule: {
594 IpProtocol: news.ipProtocol,
595 FromPort: news.fromPort,
596 ToPort: news.toPort,
597 CidrIpv4: canonicalCidr(news.cidrIpv4),
598 CidrIpv6: canonicalCidr(news.cidrIpv6),
599 ReferencedGroupId: news.referencedGroupId as string | undefined,
600 PrefixListId: news.prefixListId as string | undefined,
601 Description: news.description ?? "",
602 },
603 },
604 ],
605 });
606 }
607
608 // Sync tags — observed cloud tags vs desired.
609 const currentTags = Object.fromEntries(
610 (observed.Tags ?? []).map((t) => [t.Key!, t.Value!]),
611 ) as Record<string, string>;
612 const { removed, upsert } = diffTags(currentTags, desiredTags);
613 if (removed.length > 0) {
614 yield* ec2.deleteTags({
615 Resources: [ruleId],
616 Tags: removed.map((key) => ({ Key: key })),
617 DryRun: false,
618 });
619 }
620 if (upsert.length > 0) {
621 yield* ec2.createTags({
622 Resources: [ruleId],
623 Tags: upsert,
624 DryRun: false,
625 });
626 }
627
628 const matches = (rule: ec2.SecurityGroupRule) =>
629 observedSecurityGroupRuleKey(rule) === desiredKey && tagsMatch(rule, desiredTags);
630 const final = yield* describeRule(ruleId).pipe(
631 Effect.repeat({
632 until: matches,
633 schedule: Schedule.spaced("1 second"),
634 times: 8,
635 }),
636 );
637 if (!matches(final)) {
638 return yield* new SecurityGroupRuleNotConverged({ ruleId });
639 }
640 return toAttrs(final);
641 }),
642
643 delete: Effect.fn(function* ({ olds, output, session }) {
644 const ruleId = output.securityGroupRuleId;
645 const groupId = (output.groupId ?? olds?.group?.groupId ?? olds?.groupId) as string;
646 // Prefer the observed attribute (`isEgress`) — `olds` may be the
647 // listed Attributes (e.g. during nuke) rather than the Props shape,
648 // in which case `olds.type` is undefined.
649 const isEgress = output.isEgress ?? olds?.type !== "ingress";
650
651 yield* session.note(`Deleting Security Group Rule: ${ruleId}`);
652
653 // The whole security group may already be gone, taking its rules
654 // with it (InvalidGroup.NotFound) — the rule is deleted either way.
655 if (isEgress) {
656 yield* ec2
657 .revokeSecurityGroupEgress({
658 GroupId: groupId,
659 SecurityGroupRuleIds: [ruleId],
660 DryRun: false,
661 })
662 .pipe(
663 Effect.catchTag(
664 ["InvalidPermission.NotFound", "InvalidSecurityGroupRuleId.NotFound"],
665 () => Effect.void,
666 ),
667 Effect.catchTag("InvalidGroup.NotFound", () => Effect.void),
668 );
669 } else {
670 yield* ec2
671 .revokeSecurityGroupIngress({
672 GroupId: groupId,
673 SecurityGroupRuleIds: [ruleId],
674 DryRun: false,
675 })
676 .pipe(
677 Effect.catchTag(
678 ["InvalidPermission.NotFound", "InvalidSecurityGroupRuleId.NotFound"],
679 () => Effect.void,
680 ),
681 Effect.catchTag("InvalidGroup.NotFound", () => Effect.void),
682 );
683 }
684
685 yield* session.note(`Security Group Rule ${ruleId} deleted`);
686 }),
687 };
688 }),
689 );
690
691 // Only current declarations with persisted physical ownership are delegated.
692 export const declaredSecurityGroupRuleIds = Effect.fn(function* (groupId: string) {
693 const stack = yield* Stack;
694 const state = yield* yield* State;
695 const ids = new Set<string>();
696 const resources = Object.values(stack.resources);
697 const upstream: Record<string, object> = {};
698 // flatMap can return a resource absent from the target's syntactic upstreams.
699 for (const source of resources) {
700 const sourceRow = yield* state.get({
701 stack: stack.name,
702 stage: stack.stage,
703 fqn: source.FQN,
704 });
705 if (!sourceRow || isActionState(sourceRow) || sourceRow.resourceType !== source.Type) continue;
706 const sourceAttrs = sourceRow.attr ?? ("old" in sourceRow ? sourceRow.old.attr : undefined);
707 if (sourceAttrs) upstream[source.FQN] = sourceAttrs;
708 }
709 for (const resource of resources) {
710 if (resource.Type !== "AWS.EC2.SecurityGroupRule" || !resource.Props) continue;
711 const row = yield* state.get({
712 stack: stack.name,
713 stage: stack.stage,
714 fqn: resource.FQN,
715 });
716 if (!row || isActionState(row) || row.resourceType !== "AWS.EC2.SecurityGroupRule") continue;
717 const attrs = row.attr ?? ("old" in row ? row.old.attr : undefined);
718 if (attrs?.groupId === groupId && typeof attrs.securityGroupRuleId === "string") {
719 const { group, groupId: declaredId } = resource.Props;
720 if ((group === undefined) === (declaredId === undefined)) continue;
721 const target = group ?? declaredId;
722 // Evaluate only the declared target, never infer ownership from cloud tags.
723 const declared = yield* Output.evaluate(target, upstream).pipe(
724 Effect.catchTag(["MissingSourceError", "InvalidReferenceError"], () => Effect.undefined),
725 );
726 const declaredGroupId = typeof declared === "string" ? declared : declared?.groupId;
727 if (declaredGroupId === groupId) ids.add(attrs.securityGroupRuleId);
728 }
729 }
730 return ids;
731 });
732
733 // The rules this stack's persisted SecurityGroupRule rows own on `groupId`.
734 // `read` has no program to evaluate (drift runs from state alone), so it
735 // trusts the state store rather than the current declarations.
736 export const persistedSecurityGroupRuleIds = Effect.fn(function* (groupId: string) {
737 const stack = yield* Stack;
738 const state = yield* yield* State;
739 const ids = new Set<string>();
740 for (const fqn of yield* state.list({ stack: stack.name, stage: stack.stage })) {
741 const row = yield* state.get({ stack: stack.name, stage: stack.stage, fqn });
742 if (!row || isActionState(row) || row.resourceType !== "AWS.EC2.SecurityGroupRule") continue;
743 const attrs = row.attr ?? ("old" in row ? row.old.attr : undefined);
744 if (attrs?.groupId === groupId && typeof attrs.securityGroupRuleId === "string") {
745 ids.add(attrs.securityGroupRuleId);
746 }
747 }
748 return ids;
749 });
750
751 export const resolveSecurityGroupRules = (
752 rules: SecurityGroupRuleData[] | undefined,
753 isEgress: boolean,
754 ): SecurityGroupRuleData[] =>
755 rules ?? (isEgress ? [{ ipProtocol: "-1", cidrIpv4: "0.0.0.0/0" }] : []);
756
757 const protocols: Record<string, string> = {
758 "6": "tcp",
759 "17": "udp",
760 "1": "icmp",
761 "58": "icmpv6",
762 };
763
764 export const securityGroupRuleKey = (rule: SecurityGroupRuleData) => {
765 const protocol = protocols[rule.ipProtocol] ?? rule.ipProtocol;
766 const hasPorts = ["tcp", "udp", "icmp", "icmpv6"].includes(protocol);
767 return JSON.stringify({
768 protocol,
769 from: hasPorts ? (rule.fromPort ?? (protocol === "icmpv6" ? -1 : undefined)) : undefined,
770 to: hasPorts ? (rule.toPort ?? (protocol === "icmpv6" ? -1 : undefined)) : undefined,
771 ipv4: canonicalCidr(rule.cidrIpv4),
772 ipv6: canonicalCidr(rule.cidrIpv6),
773 group: rule.referencedGroupId,
774 prefix: rule.prefixListId,
775 description: rule.description ?? "",
776 });
777 };
778
779 export const observedSecurityGroupRuleKey = (rule: ec2.SecurityGroupRule) =>
780 securityGroupRuleKey({
781 ipProtocol: rule.IpProtocol!,
782 fromPort: rule.FromPort,
783 toPort: rule.ToPort,
784 cidrIpv4: rule.CidrIpv4,
785 cidrIpv6: rule.CidrIpv6,
786 referencedGroupId: rule.ReferencedGroupInfo?.GroupId as SecurityGroupId | undefined,
787 prefixListId: rule.PrefixListId,
788 description: rule.Description,
789 });
790
791 // EC2 creates one physical rule per source in an IpPermission.
792 export const expandSecurityGroupRules = (rules: SecurityGroupRuleData[]) =>
793 rules.flatMap(({ cidrIpv4, cidrIpv6, referencedGroupId, prefixListId, ...rule }) => [
794 ...(cidrIpv4 === undefined ? [] : [{ ...rule, cidrIpv4 }]),
795 ...(cidrIpv6 === undefined ? [] : [{ ...rule, cidrIpv6 }]),
796 ...(referencedGroupId === undefined ? [] : [{ ...rule, referencedGroupId }]),
797 ...(prefixListId === undefined ? [] : [{ ...rule, prefixListId }]),
798 ]);