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

main
ts 532 lines 20.7 KB
Raw
1 import * as ec2 from "@distilled.cloud/aws/ec2";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import { AWSEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import type { SecurityGroupArn, SecurityGroupId, SecurityGroupRuleData } from "./SecurityGroup.ts";
12 import {
13 declaredSecurityGroupRuleIds,
14 persistedSecurityGroupRuleIds,
15 expandSecurityGroupRules,
16 observedSecurityGroupRuleKey,
17 resolveSecurityGroupRules,
18 securityGroupRuleKey,
19 } from "./SecurityGroupRule.ts";
20 import type { VpcId } from "./Vpc.ts";
21
22 class DefaultSecurityGroupNotFound extends Data.TaggedError("DefaultSecurityGroupNotFound")<{
23 vpcId: VpcId;
24 }> {}
25
26 class InvalidDefaultSecurityGroupRules extends Data.TaggedError(
27 "InvalidDefaultSecurityGroupRules",
28 )<{ message: string }> {}
29
30 class DefaultSecurityGroupRulesNotConverged extends Data.TaggedError(
31 "DefaultSecurityGroupRulesNotConverged",
32 )<{ groupId: SecurityGroupId }> {}
33
34 /** An observed rule on the AWS-created default security group. */
35 export interface DefaultSecurityGroupRuleAttributes<IsEgress extends boolean> {
36 /** The physical rule ID, retained when only its description changes. */
37 securityGroupRuleId: string;
38 /** The IP protocol name or number returned by AWS. */
39 ipProtocol: string;
40 /** The first port, or ICMP type. */
41 fromPort?: number;
42 /** The last port, or ICMP code. */
43 toPort?: number;
44 /** The canonical IPv4 source or destination CIDR. */
45 cidrIpv4?: string;
46 /** The canonical IPv6 source or destination CIDR. */
47 cidrIpv6?: string;
48 /** The source or destination security group ID. */
49 referencedGroupId?: string;
50 /** The source or destination managed prefix list ID. */
51 prefixListId?: string;
52 /** The description observed in AWS. */
53 description?: string;
54 /** Whether the rule controls outbound rather than inbound traffic. */
55 isEgress: IsEgress;
56 }
57
58 /** Properties for a VPC's AWS-created `default` security group. */
59 export interface DefaultSecurityGroupProps {
60 /** The VPC whose AWS-created `default` security group is managed. */
61 vpcId: VpcId;
62
63 /**
64 * Desired inline inbound rules. Omitted, undefined, and [] all remove inline
65 * inbound rules, including AWS's initial self-reference rule. Standalone
66 * rules owned by current declarations in this stack and stage are preserved.
67 * @default []
68 */
69 ingress?: SecurityGroupRuleData[];
70
71 /**
72 * Desired inline outbound rules. Omitted or undefined restores IPv4
73 * allow-all outbound; [] removes inline outbound rules. Standalone rules
74 * owned by current declarations in this stack and stage are preserved.
75 * @default [{ ipProtocol: "-1", cidrIpv4: "0.0.0.0/0" }]
76 */
77 egress?: SecurityGroupRuleData[];
78 }
79
80 export interface DefaultSecurityGroup extends Resource<
81 "AWS.EC2.DefaultSecurityGroup",
82 DefaultSecurityGroupProps,
83 {
84 /** The ID of the AWS-created default security group. */
85 groupId: SecurityGroupId;
86 /** The ARN of the default security group. */
87 groupArn: SecurityGroupArn;
88 /** The AWS-assigned group name, always `default`. */
89 groupName: string;
90 /** The AWS-assigned description of the group. */
91 description: string;
92 /** The VPC that owns this default security group. */
93 vpcId: VpcId;
94 /** The AWS account that owns the group. */
95 ownerId: string;
96 /** The complete inbound rule set observed after reconciliation. */
97 ingressRules: DefaultSecurityGroupRuleAttributes<false>[];
98 /** The complete outbound rule set observed after reconciliation. */
99 egressRules: DefaultSecurityGroupRuleAttributes<true>[];
100 },
101 never,
102 Providers
103 > {}
104
105 /**
106 * Declaratively manages the rules of the AWS-created `default` security group
107 * in one VPC. AWS creates this group named `default` whenever it creates a
108 * VPC; Alchemy looks it up by VPC ID and name, never creates it, and never
109 * deletes it.
110 *
111 * Inline rules use the same defaults as `SecurityGroup`: omitted or undefined
112 * `ingress` means no inline inbound rules, and omitted or undefined `egress`
113 * means IPv4 allow-all outbound. Passing `[]` means no inline rules in that
114 * direction, not unmanaged rules. Defaults apply on initial management,
115 * property removal, adoption, and drift repair; AWS's initial self-ingress
116 * rule is removed, not restored.
117 *
118 * Current standalone `SecurityGroupRule` declarations in the same stack and
119 * stage retain ownership of their persisted physical rule IDs. Other rules
120 * are removed even if they carry Alchemy tags. This resource manages rules,
121 * not ownership of the AWS-created group; do not also manage this group with
122 * a `SecurityGroup` resource or a second `DefaultSecurityGroup` manager.
123 *
124 * Removing this Alchemy resource leaves both the default group and its last
125 * applied rules unchanged. Deleting its VPC removes the group as part of AWS's
126 * VPC lifecycle.
127 *
128 * ### Default Inline Rules
129 * **Example:** Remove AWS self-ingress and allow outbound IPv4
130 * ```typescript
131 * const vpc = yield* AWS.EC2.Vpc("Vpc", { cidrBlock: "10.0.0.0/16" });
132 * const group = yield* AWS.EC2.DefaultSecurityGroup("DefaultSecurityGroup", {
133 * vpcId: vpc.vpcId,
134 * });
135 * ```
136 *
137 * **Example:** Explicit undefined has the same meaning as omission
138 * ```typescript
139 * yield* AWS.EC2.DefaultSecurityGroup("DefaultSecurityGroup", {
140 * vpcId: vpc.vpcId,
141 * ingress: undefined,
142 * egress: undefined,
143 * });
144 * ```
145 *
146 * ### Closing the Default Security Group
147 * **Example:** Deny all traffic when there are no owned standalone rules
148 * ```typescript
149 * const vpc = yield* AWS.EC2.Vpc("Vpc", { cidrBlock: "10.0.0.0/16" });
150 * yield* AWS.EC2.DefaultSecurityGroup("DefaultSecurityGroup", {
151 * vpcId: vpc.vpcId,
152 * ingress: [],
153 * egress: [],
154 * });
155 * ```
156 *
157 * ### Updating Rules
158 * **Example:** Allow only internal HTTPS
159 * ```typescript
160 * yield* AWS.EC2.DefaultSecurityGroup("DefaultSecurityGroup", {
161 * vpcId: vpc.vpcId,
162 * ingress: [{
163 * ipProtocol: "tcp",
164 * fromPort: 443,
165 * toPort: 443,
166 * cidrIpv4: "10.0.0.0/16",
167 * description: "Internal HTTPS",
168 * }],
169 * egress: [],
170 * });
171 * ```
172 *
173 * Unchanged deployments repair missing rules and remove undeclared rules.
174 * Updates leave unrelated rule IDs untouched; description changes update in
175 * place, and removing a description clears it. Equivalent protocol names,
176 * canonical CIDRs, rule order, and duplicate rules do not cause rule churn.
177 * Duplicates with conflicting descriptions are rejected before any writes.
178 * A rule with several source fields expands into one AWS rule per source.
179 *
180 * ### Restoring Default Inline Rules
181 * **Example:** Remove explicit rule lists to restore defaults
182 * ```diff lang="typescript"
183 * yield* AWS.EC2.DefaultSecurityGroup("DefaultSecurityGroup", {
184 * vpcId: vpc.vpcId,
185 * - ingress: [],
186 * - egress: [],
187 * });
188 * ```
189 *
190 * This still denies inline inbound access but restores IPv4 allow-all outbound.
191 * Removing these properties is different from removing the manager itself:
192 * deleting the manager leaves its last-applied rules, with no baseline restore.
193 *
194 * ### Composing Standalone Rules
195 * **Example:** Restrict outbound traffic with a standalone rule
196 * ```typescript
197 * const group = yield* AWS.EC2.DefaultSecurityGroup("DefaultSecurityGroup", {
198 * vpcId: vpc.vpcId,
199 * ingress: [],
200 * egress: [],
201 * });
202 * yield* AWS.EC2.SecurityGroupRule("HttpsEgress", {
203 * group: group,
204 * type: "egress",
205 * ipProtocol: "tcp",
206 * fromPort: 443,
207 * toPort: 443,
208 * cidrIpv4: "10.0.0.0/16",
209 * });
210 * ```
211 *
212 * Pass the whole manager as `group` so rule creation and updates wait for its
213 * inline reconciliation. Only `group.groupId` is consumed by the rule provider;
214 * unrelated manager attributes do not trigger rule updates. The stable ID is
215 * still available for replacement planning. The ID-only `groupId` form cannot
216 * enforce this ordering when the manager updates without changing its ID.
217 * Standalone ingress composes the same way. Omitting `egress` instead would
218 * retain the default allow-all rule alongside this standalone rule. A current
219 * declaration and its persisted physical ID establish ownership, not cloud
220 * tags. Removing a declaration ends that protection; its provider handles
221 * deletion. Cross-stack or cross-stage rule ownership is unsupported.
222 * Inline and standalone rules must have distinct identities. If a standalone
223 * rule owns IPv4 allow-all egress, set `egress: []` to disable the inline default.
224 *
225 * ### Changing VPCs
226 * **Example:** Manage another VPC's default group
227 * ```typescript
228 * yield* AWS.EC2.DefaultSecurityGroup("DefaultSecurityGroup", {
229 * vpcId: otherVpc.vpcId,
230 * ingress: [],
231 * egress: [],
232 * });
233 * ```
234 *
235 * Changing `vpcId` replaces the Alchemy resource, not either AWS-owned group,
236 * including when the destination VPC is created or replaced in the same deploy.
237 * The previous group's last-applied rules remain unchanged. Keep the old VPC
238 * declared until replacement finishes, then remove it separately if desired.
239 *
240 * @resource
241 */
242 export const DefaultSecurityGroup = Resource<DefaultSecurityGroup>("AWS.EC2.DefaultSecurityGroup");
243
244 export const DefaultSecurityGroupProvider = () =>
245 Provider.effect(
246 DefaultSecurityGroup,
247 Effect.gen(function* () {
248 const describeGroup = (vpcId: VpcId) =>
249 ec2
250 .describeSecurityGroups({
251 Filters: [
252 { Name: "vpc-id", Values: [vpcId] },
253 { Name: "group-name", Values: ["default"] },
254 ],
255 })
256 .pipe(
257 // Filtering by a deleted VPC returns an empty collection.
258 Effect.map((result) => result.SecurityGroups?.[0]),
259 );
260
261 const describeRules = (groupId: SecurityGroupId) =>
262 ec2.describeSecurityGroupRules
263 .items({ Filters: [{ Name: "group-id", Values: [groupId] }] })
264 .pipe(
265 Stream.runCollect,
266 Effect.map((rules) => Array.from(rules)),
267 );
268
269 const toAttrs = Effect.fn(function* (
270 group: ec2.SecurityGroup,
271 rules: ec2.SecurityGroupRule[],
272 ) {
273 const { accountId, region } = yield* AWSEnvironment.current;
274 const toRule =
275 <IsEgress extends boolean>(isEgress: IsEgress) =>
276 (rule: ec2.SecurityGroupRule) => ({
277 securityGroupRuleId: rule.SecurityGroupRuleId!,
278 ipProtocol: rule.IpProtocol!,
279 fromPort: rule.FromPort,
280 toPort: rule.ToPort,
281 cidrIpv4: rule.CidrIpv4,
282 cidrIpv6: rule.CidrIpv6,
283 referencedGroupId: rule.ReferencedGroupInfo?.GroupId,
284 prefixListId: rule.PrefixListId,
285 description: rule.Description,
286 isEgress,
287 });
288 return {
289 groupId: group.GroupId as SecurityGroupId,
290 groupArn:
291 `arn:aws:ec2:${region}:${accountId}:security-group/${group.GroupId}` as SecurityGroupArn,
292 groupName: group.GroupName!,
293 description: group.Description!,
294 vpcId: group.VpcId as VpcId,
295 ownerId: group.OwnerId!,
296 ingressRules: rules.filter((rule) => !rule.IsEgress).map(toRule(false)),
297 egressRules: rules.filter((rule) => rule.IsEgress).map(toRule(true)),
298 } satisfies DefaultSecurityGroup["Attributes"];
299 });
300
301 const toPermission = (rule: SecurityGroupRuleData): ec2.IpPermission => ({
302 IpProtocol: rule.ipProtocol,
303 FromPort: rule.fromPort,
304 ToPort: rule.toPort,
305 IpRanges: rule.cidrIpv4
306 ? [{ CidrIp: rule.cidrIpv4, Description: rule.description }]
307 : undefined,
308 Ipv6Ranges: rule.cidrIpv6
309 ? [{ CidrIpv6: rule.cidrIpv6, Description: rule.description }]
310 : undefined,
311 UserIdGroupPairs: rule.referencedGroupId
312 ? [{ GroupId: rule.referencedGroupId, Description: rule.description }]
313 : undefined,
314 PrefixListIds: rule.prefixListId
315 ? [{ PrefixListId: rule.prefixListId, Description: rule.description }]
316 : undefined,
317 });
318
319 const desiredRules = Effect.fn(function* (rules: SecurityGroupRuleData[]) {
320 if (
321 rules.some(
322 (rule) =>
323 !rule.ipProtocol ||
324 ![rule.cidrIpv4, rule.cidrIpv6, rule.referencedGroupId, rule.prefixListId].some(
325 Boolean,
326 ),
327 )
328 ) {
329 return yield* new InvalidDefaultSecurityGroupRules({
330 message: "Every rule must specify a protocol and a source.",
331 });
332 }
333 const desired = new Map<string, SecurityGroupRuleData>();
334 for (const rule of expandSecurityGroupRules(rules)) {
335 const key = securityGroupRuleKey({ ...rule, description: undefined });
336 const previous = desired.get(key);
337 if (previous && securityGroupRuleKey(previous) !== securityGroupRuleKey(rule)) {
338 return yield* new InvalidDefaultSecurityGroupRules({
339 message: "Duplicate rules must have the same description.",
340 });
341 }
342 desired.set(key, rule);
343 }
344 return desired;
345 });
346
347 const rulesMatch = (
348 rules: ec2.SecurityGroupRule[],
349 ingress: Map<string, SecurityGroupRuleData>,
350 egress: Map<string, SecurityGroupRuleData>,
351 ) =>
352 [false, true].every((isEgress) => {
353 const observed = rules.filter((rule) => !!rule.IsEgress === isEgress);
354 const desired = [...(isEgress ? egress : ingress).values()];
355 return (
356 JSON.stringify(observed.map(observedSecurityGroupRuleKey).sort()) ===
357 JSON.stringify(desired.map(securityGroupRuleKey).sort())
358 );
359 });
360
361 const syncRules = Effect.fn(function* (
362 groupId: SecurityGroupId,
363 isEgress: boolean,
364 desired: Map<string, SecurityGroupRuleData>,
365 observed: ec2.SecurityGroupRule[],
366 ) {
367 const current = new Map(
368 observed.map((rule) => [
369 observedSecurityGroupRuleKey({ ...rule, Description: undefined }),
370 rule,
371 ]),
372 );
373 for (const [key, rule] of current) {
374 const wanted = desired.get(key);
375 if (!wanted) {
376 const request = {
377 GroupId: groupId,
378 SecurityGroupRuleIds: [rule.SecurityGroupRuleId!],
379 DryRun: false,
380 };
381 yield* Effect.gen(function* () {
382 if (isEgress) yield* ec2.revokeSecurityGroupEgress(request);
383 else yield* ec2.revokeSecurityGroupIngress(request);
384 }).pipe(
385 Effect.catchTag(
386 ["InvalidPermission.NotFound", "InvalidSecurityGroupRuleId.NotFound"],
387 () => Effect.void,
388 ),
389 );
390 } else if ((wanted.description ?? "") !== (rule.Description ?? "")) {
391 yield* ec2
392 .modifySecurityGroupRules({
393 GroupId: groupId,
394 SecurityGroupRules: [
395 {
396 SecurityGroupRuleId: rule.SecurityGroupRuleId!,
397 SecurityGroupRule: {
398 IpProtocol: rule.IpProtocol,
399 FromPort: rule.FromPort,
400 ToPort: rule.ToPort,
401 CidrIpv4: rule.CidrIpv4,
402 CidrIpv6: rule.CidrIpv6,
403 ReferencedGroupId: rule.ReferencedGroupInfo?.GroupId,
404 PrefixListId: rule.PrefixListId,
405 Description: wanted.description ?? "",
406 },
407 },
408 ],
409 })
410 .pipe(
411 Effect.catchTag("InvalidSecurityGroupRuleId.NotFound", () =>
412 Effect.fail(new DefaultSecurityGroupRulesNotConverged({ groupId })),
413 ),
414 );
415 }
416 }
417 for (const [key, rule] of desired) {
418 if (current.has(key)) continue;
419 const request = {
420 GroupId: groupId,
421 IpPermissions: [toPermission(rule)],
422 DryRun: false,
423 };
424 yield* (
425 isEgress
426 ? ec2.authorizeSecurityGroupEgress(request)
427 : ec2.authorizeSecurityGroupIngress(request)
428 ).pipe(
429 // Re-observe a racing authorization rather than assuming its description.
430 Effect.catchTag("InvalidPermission.Duplicate", () =>
431 Effect.fail(new DefaultSecurityGroupRulesNotConverged({ groupId })),
432 ),
433 );
434 }
435 });
436
437 return {
438 stables: ["groupId", "groupArn", "groupName", "ownerId"],
439
440 read: Effect.fn(function* ({ olds, output }) {
441 const vpcId = output?.vpcId ?? olds?.vpcId;
442 if (!vpcId) return undefined;
443 const group = yield* describeGroup(vpcId);
444 if (!group?.GroupId) return undefined;
445 // Rules declared as separate SecurityGroupRule resources are theirs,
446 // not the group's (reconcile leaves them out of its attributes too).
447 const owned = yield* persistedSecurityGroupRuleIds(group.GroupId);
448 const rules = yield* describeRules(group.GroupId as SecurityGroupId);
449 return yield* toAttrs(
450 group,
451 rules.filter((rule) => !owned.has(rule.SecurityGroupRuleId!)),
452 );
453 }),
454
455 diff: Effect.fn(function* ({ news, olds }) {
456 // An unresolved VPC must not expose the previous group's stable identity.
457 if (!("vpcId" in news) || !isResolved(news.vpcId) || news.vpcId !== olds.vpcId) {
458 return { action: "replace" };
459 }
460 if (!isResolved(news.ingress) || !isResolved(news.egress)) return;
461 const ingress = yield* desiredRules(resolveSecurityGroupRules(news.ingress, false));
462 const egress = yield* desiredRules(resolveSecurityGroupRules(news.egress, true));
463 const group = yield* describeGroup(news.vpcId);
464 if (!group?.GroupId) return { action: "update", stables: [] };
465 const groupId = group.GroupId as SecurityGroupId;
466 const owned = yield* declaredSecurityGroupRuleIds(groupId);
467 const observed = (yield* describeRules(groupId)).filter(
468 (rule) => !owned.has(rule.SecurityGroupRuleId!),
469 );
470 if (!rulesMatch(observed, ingress, egress)) return { action: "update" };
471 }),
472
473 reconcile: Effect.fn(function* ({ news, session }) {
474 // Validate both directions before changing either one.
475 const ingress = yield* desiredRules(resolveSecurityGroupRules(news.ingress, false));
476 const egress = yield* desiredRules(resolveSecurityGroupRules(news.egress, true));
477 const group = yield* describeGroup(news.vpcId).pipe(
478 Effect.flatMap((group) =>
479 group?.GroupId
480 ? Effect.succeed(group)
481 : Effect.fail(new DefaultSecurityGroupNotFound({ vpcId: news.vpcId })),
482 ),
483 // AWS may expose the VPC before its default group is visible.
484 Effect.retry({
485 while: (error) => error._tag === "DefaultSecurityGroupNotFound",
486 schedule: Schedule.spaced("1 second"),
487 times: 8,
488 }),
489 );
490 const groupId = group.GroupId as SecurityGroupId;
491 const owned = yield* declaredSecurityGroupRuleIds(groupId);
492 const inlineRules = (rules: ec2.SecurityGroupRule[]) =>
493 rules.filter((rule) => !owned.has(rule.SecurityGroupRuleId!));
494 const finalRules = yield* Effect.gen(function* () {
495 const observed = yield* describeRules(groupId);
496 const inline = inlineRules(observed);
497 if (rulesMatch(inline, ingress, egress)) return observed;
498 yield* syncRules(
499 groupId,
500 false,
501 ingress,
502 inline.filter((rule) => !rule.IsEgress),
503 );
504 yield* syncRules(
505 groupId,
506 true,
507 egress,
508 inline.filter((rule) => rule.IsEgress),
509 );
510 const final = yield* describeRules(groupId);
511 if (!rulesMatch(inlineRules(final), ingress, egress)) {
512 return yield* new DefaultSecurityGroupRulesNotConverged({
513 groupId,
514 });
515 }
516 return final;
517 }).pipe(
518 Effect.retry({
519 while: (error) => error._tag === "DefaultSecurityGroupRulesNotConverged",
520 schedule: Schedule.spaced("1 second"),
521 times: 8,
522 }),
523 );
524 yield* session.note(`Reconciled default security group: ${groupId}`);
525 return yield* toAttrs(group, inlineRules(finalRules));
526 }),
527
528 // AWS owns the default group. Intentionally leave it and its rules as-is.
529 delete: () => Effect.void,
530 };
531 }),
532 );