@intentius/behold 0.29.56 → 0.29.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/THIRD_PARTY.md +21 -0
  2. package/dist/cli.js +7611 -6919
  3. package/example-three-cloud/azure/composites/container-app-site.ts +77 -0
  4. package/example-three-cloud/azure/src/site.ts +14 -46
  5. package/example-three-cloud/dns/composites/latency-entry.ts +73 -0
  6. package/example-three-cloud/dns/src/route53.ts +9 -39
  7. package/example-three-cloud/gcp/composites/public-cloud-run.ts +102 -0
  8. package/example-three-cloud/gcp/src/site.ts +16 -96
  9. package/licenses/aws-architecture-icons-TERMS.md +19 -0
  10. package/licenses/azure-architecture-icons-Microsoft_Terms_of_Use.pdf +0 -0
  11. package/licenses/azure-architecture-icons-TERMS.md +20 -0
  12. package/licenses/google-cloud-icons-TERMS.md +15 -0
  13. package/package.json +1 -1
  14. package/web/app.js +557 -18
  15. package/web/edge-weight.d.ts +5 -0
  16. package/web/edge-weight.js +71 -0
  17. package/web/edge-weight.test.js +49 -0
  18. package/web/icons/aws/alb.svg +1 -0
  19. package/web/icons/aws/api-gateway.svg +1 -0
  20. package/web/icons/aws/app-runner.svg +1 -0
  21. package/web/icons/aws/appsync.svg +1 -0
  22. package/web/icons/aws/athena.svg +1 -0
  23. package/web/icons/aws/auto-scaling.svg +1 -0
  24. package/web/icons/aws/backup.svg +1 -0
  25. package/web/icons/aws/batch.svg +1 -0
  26. package/web/icons/aws/bedrock-agentcore.svg +1 -0
  27. package/web/icons/aws/bedrock.svg +1 -0
  28. package/web/icons/aws/certificate-manager.svg +1 -0
  29. package/web/icons/aws/cloud-map.svg +1 -0
  30. package/web/icons/aws/cloud.svg +1 -0
  31. package/web/icons/aws/cloudformation.svg +1 -0
  32. package/web/icons/aws/cloudfront.svg +1 -0
  33. package/web/icons/aws/cloudtrail.svg +1 -0
  34. package/web/icons/aws/cloudwatch-alarm.svg +1 -0
  35. package/web/icons/aws/cloudwatch-logs.svg +1 -0
  36. package/web/icons/aws/cloudwatch.svg +1 -0
  37. package/web/icons/aws/codebuild.svg +1 -0
  38. package/web/icons/aws/codecommit.svg +1 -0
  39. package/web/icons/aws/codedeploy.svg +1 -0
  40. package/web/icons/aws/codepipeline.svg +1 -0
  41. package/web/icons/aws/cognito.svg +1 -0
  42. package/web/icons/aws/config.svg +1 -0
  43. package/web/icons/aws/documentdb.svg +1 -0
  44. package/web/icons/aws/dynamodb-table.svg +1 -0
  45. package/web/icons/aws/dynamodb.svg +1 -0
  46. package/web/icons/aws/ebs-volume.svg +1 -0
  47. package/web/icons/aws/ec2-instance.svg +1 -0
  48. package/web/icons/aws/ec2.svg +1 -0
  49. package/web/icons/aws/ecr-registry.svg +1 -0
  50. package/web/icons/aws/ecr.svg +1 -0
  51. package/web/icons/aws/ecs-service.svg +1 -0
  52. package/web/icons/aws/ecs-task.svg +1 -0
  53. package/web/icons/aws/ecs.svg +1 -0
  54. package/web/icons/aws/efs.svg +1 -0
  55. package/web/icons/aws/eks.svg +1 -0
  56. package/web/icons/aws/elastic-beanstalk.svg +1 -0
  57. package/web/icons/aws/elastic-ip.svg +1 -0
  58. package/web/icons/aws/elasticache.svg +1 -0
  59. package/web/icons/aws/elb.svg +1 -0
  60. package/web/icons/aws/emr.svg +1 -0
  61. package/web/icons/aws/eventbridge.svg +1 -0
  62. package/web/icons/aws/firehose.svg +1 -0
  63. package/web/icons/aws/global-accelerator.svg +1 -0
  64. package/web/icons/aws/glue.svg +1 -0
  65. package/web/icons/aws/guardduty.svg +1 -0
  66. package/web/icons/aws/iam.svg +1 -0
  67. package/web/icons/aws/internet-gateway.svg +1 -0
  68. package/web/icons/aws/keyspaces.svg +1 -0
  69. package/web/icons/aws/kinesis.svg +1 -0
  70. package/web/icons/aws/kms.svg +1 -0
  71. package/web/icons/aws/lambda-function.svg +1 -0
  72. package/web/icons/aws/lambda.svg +1 -0
  73. package/web/icons/aws/mq.svg +1 -0
  74. package/web/icons/aws/msk.svg +1 -0
  75. package/web/icons/aws/nat-gateway.svg +1 -0
  76. package/web/icons/aws/neptune.svg +1 -0
  77. package/web/icons/aws/network-acl.svg +1 -0
  78. package/web/icons/aws/network-firewall.svg +1 -0
  79. package/web/icons/aws/opensearch.svg +1 -0
  80. package/web/icons/aws/organizations.svg +1 -0
  81. package/web/icons/aws/rds-instance.svg +1 -0
  82. package/web/icons/aws/rds.svg +1 -0
  83. package/web/icons/aws/redshift.svg +1 -0
  84. package/web/icons/aws/route-53-hosted-zone.svg +1 -0
  85. package/web/icons/aws/route-53.svg +1 -0
  86. package/web/icons/aws/router.svg +1 -0
  87. package/web/icons/aws/s3-bucket.svg +1 -0
  88. package/web/icons/aws/s3.svg +1 -0
  89. package/web/icons/aws/sagemaker.svg +1 -0
  90. package/web/icons/aws/secrets-manager.svg +1 -0
  91. package/web/icons/aws/ses.svg +1 -0
  92. package/web/icons/aws/shield.svg +1 -0
  93. package/web/icons/aws/sns-topic.svg +1 -0
  94. package/web/icons/aws/sns.svg +1 -0
  95. package/web/icons/aws/sqs-queue.svg +1 -0
  96. package/web/icons/aws/sqs.svg +1 -0
  97. package/web/icons/aws/step-functions.svg +1 -0
  98. package/web/icons/aws/systems-manager.svg +1 -0
  99. package/web/icons/aws/transfer-family.svg +1 -0
  100. package/web/icons/aws/transit-gateway.svg +1 -0
  101. package/web/icons/aws/vpc-endpoints.svg +1 -0
  102. package/web/icons/aws/vpc-lattice.svg +1 -0
  103. package/web/icons/aws/vpc.svg +1 -0
  104. package/web/icons/aws/vpn-gateway.svg +1 -0
  105. package/web/icons/aws/waf.svg +1 -0
  106. package/web/icons/azure/app-service-plan.svg +1 -0
  107. package/web/icons/azure/app-services.svg +1 -0
  108. package/web/icons/azure/application-gateway.svg +1 -0
  109. package/web/icons/azure/container-app.svg +1 -0
  110. package/web/icons/azure/container-apps-environment.svg +1 -0
  111. package/web/icons/azure/container-instances.svg +1 -0
  112. package/web/icons/azure/container-registry.svg +1 -0
  113. package/web/icons/azure/cosmos-db.svg +1 -0
  114. package/web/icons/azure/dns-zone.svg +1 -0
  115. package/web/icons/azure/front-door.svg +1 -0
  116. package/web/icons/azure/function-app.svg +1 -0
  117. package/web/icons/azure/kubernetes-service.svg +1 -0
  118. package/web/icons/azure/load-balancer.svg +1 -0
  119. package/web/icons/azure/log-analytics.svg +1 -0
  120. package/web/icons/azure/managed-identity.svg +1 -0
  121. package/web/icons/azure/mysql.svg +1 -0
  122. package/web/icons/azure/nat.svg +1 -0
  123. package/web/icons/azure/network-security-group.svg +1 -0
  124. package/web/icons/azure/postgresql.svg +1 -0
  125. package/web/icons/azure/public-ip.svg +1 -0
  126. package/web/icons/azure/redis.svg +1 -0
  127. package/web/icons/azure/resource-group.svg +1 -0
  128. package/web/icons/azure/route-table.svg +1 -0
  129. package/web/icons/azure/sql-database.svg +1 -0
  130. package/web/icons/azure/sql-server.svg +1 -0
  131. package/web/icons/azure/subnet.svg +1 -0
  132. package/web/icons/azure/subscription.svg +1 -0
  133. package/web/icons/azure/virtual-machine.svg +1 -0
  134. package/web/icons/azure/virtual-network-gateway.svg +1 -0
  135. package/web/icons/azure/virtual-network.svg +1 -0
  136. package/web/icons/gcp/artifact-registry.svg +1 -0
  137. package/web/icons/gcp/bigquery.svg +1 -0
  138. package/web/icons/gcp/bigtable.svg +1 -0
  139. package/web/icons/gcp/certificate-manager.svg +1 -0
  140. package/web/icons/gcp/cloud-armor.svg +1 -0
  141. package/web/icons/gcp/cloud-build.svg +1 -0
  142. package/web/icons/gcp/cloud-composer.svg +1 -0
  143. package/web/icons/gcp/cloud-dns.svg +1 -0
  144. package/web/icons/gcp/cloud-functions.svg +1 -0
  145. package/web/icons/gcp/cloud-load-balancing.svg +1 -0
  146. package/web/icons/gcp/cloud-logging.svg +1 -0
  147. package/web/icons/gcp/cloud-monitoring.svg +1 -0
  148. package/web/icons/gcp/cloud-nat.svg +1 -0
  149. package/web/icons/gcp/cloud-router.svg +1 -0
  150. package/web/icons/gcp/cloud-run.svg +1 -0
  151. package/web/icons/gcp/cloud-scheduler.svg +1 -0
  152. package/web/icons/gcp/cloud-spanner.svg +1 -0
  153. package/web/icons/gcp/cloud-sql.svg +1 -0
  154. package/web/icons/gcp/cloud-storage.svg +1 -0
  155. package/web/icons/gcp/cloud-tasks.svg +1 -0
  156. package/web/icons/gcp/compute-engine.svg +1 -0
  157. package/web/icons/gcp/dataflow.svg +1 -0
  158. package/web/icons/gcp/external-ip.svg +1 -0
  159. package/web/icons/gcp/firestore.svg +1 -0
  160. package/web/icons/gcp/firewall-rules.svg +1 -0
  161. package/web/icons/gcp/gke.svg +1 -0
  162. package/web/icons/gcp/iam.svg +1 -0
  163. package/web/icons/gcp/kms.svg +1 -0
  164. package/web/icons/gcp/memorystore.svg +1 -0
  165. package/web/icons/gcp/persistent-disk.svg +1 -0
  166. package/web/icons/gcp/project.svg +1 -0
  167. package/web/icons/gcp/pubsub.svg +1 -0
  168. package/web/icons/gcp/secret-manager.svg +1 -0
  169. package/web/icons/gcp/vpc.svg +1 -0
  170. package/web/index.html +34 -0
  171. package/web/net-trace.js +649 -0
  172. package/web/net-trace.test.js +180 -0
  173. package/web/view-url.js +12 -7
@@ -0,0 +1,649 @@
1
+ // behold#881: follow traffic hop by hop, and say where it stops.
2
+ //
3
+ // A trace starts outside (the public internet) or at a card, names where the
4
+ // traffic should arrive and on which port, and walks what is declared between
5
+ // them: the way in through a gateway, the network ACLs on the subnets, the
6
+ // security groups, the listener that takes the port and what it forwards to.
7
+ // Each hop is open or closed, with the reason in words, and says where the
8
+ // answer came from: the live estate, when the card was read with the rule on
9
+ // it (`IpPermissions` is the provider's own shape, so it is live by
10
+ // construction), or the source alone.
11
+ //
12
+ // Beside it, findings that need no trace: address ranges that overlap, a
13
+ // public subnet with no way out, a load balancer in one zone, an admin port
14
+ // open to anyone.
15
+ //
16
+ // AWS is read in full (VPC, subnets, route tables, NACLs, security groups,
17
+ // load balancers). GCP follows a forwarding rule to its serverless backend and
18
+ // the invoker grant; Azure reads a container app's environment, its subnet's
19
+ // security group and its ingress. Anything else says it isn't read, rather
20
+ // than guess.
21
+
22
+ export const OUTSIDE = "outside";
23
+
24
+ /** Ports that are someone's way to administer a machine, not to use it. */
25
+ export const ADMIN_PORTS = { 22: "SSH", 3389: "remote desktop", 1433: "SQL Server", 3306: "MySQL", 5432: "Postgres", 6379: "Redis", 9200: "Elasticsearch", 27017: "MongoDB" };
26
+
27
+ // ---------------------------------------------------------------- addresses
28
+
29
+ function ip4(s) {
30
+ const m = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(String(s));
31
+ if (!m) return null;
32
+ const parts = m.slice(1).map(Number);
33
+ if (parts.some((p) => p > 255)) return null;
34
+ return ((parts[0] << 24) >>> 0) + (parts[1] << 16) + (parts[2] << 8) + parts[3];
35
+ }
36
+
37
+ /** `10.20.0.0/16` → { base, bits }, or null for anything that isn't IPv4 CIDR. A bare address is a /32. */
38
+ export function parseCidr(s) {
39
+ if (typeof s !== "string") return null;
40
+ const [addr, bitsStr] = s.trim().split("/");
41
+ const bits = bitsStr === undefined ? 32 : Number(bitsStr);
42
+ const ip = ip4(addr);
43
+ if (ip === null || !Number.isInteger(bits) || bits < 0 || bits > 32) return null;
44
+ const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0;
45
+ return { base: (ip & mask) >>> 0, bits, mask };
46
+ }
47
+
48
+ /** Whether `outer` holds every address in `inner`. */
49
+ export function cidrContains(outer, inner) {
50
+ const a = parseCidr(outer);
51
+ const b = parseCidr(inner);
52
+ if (!a || !b) return false;
53
+ return a.bits <= b.bits && ((b.base & a.mask) >>> 0) === a.base;
54
+ }
55
+
56
+ /** Whether two ranges share any address. */
57
+ export function cidrsOverlap(x, y) {
58
+ return cidrContains(x, y) || cidrContains(y, x);
59
+ }
60
+
61
+ const ANYONE = (c) => c === "0.0.0.0/0" || c === "::/0";
62
+
63
+ // ---------------------------------------------------------------- graph
64
+
65
+ function index(ir) {
66
+ const nodes = ir.nodes || [];
67
+ const byId = new Map(nodes.map((n) => [n.id, n]));
68
+ // A member that declares stacks has qualified ids (`aws/<stack>::sg`) while
69
+ // its `$ref`s keep the bare form (`aws/sg`).
70
+ const bare = new Map();
71
+ for (const n of nodes) {
72
+ const m = /^([^/]+\/)[^/]*::(.+)$/.exec(n.id);
73
+ if (m && !bare.has(m[1] + m[2])) bare.set(m[1] + m[2], n.id);
74
+ }
75
+ const resolve = (ref) => {
76
+ if (typeof ref !== "string") return undefined;
77
+ for (const cand of [ref, ref.replace(/\.[^./]+$/, "")]) {
78
+ if (byId.has(cand)) return cand;
79
+ if (bare.has(cand)) return bare.get(cand);
80
+ }
81
+ return undefined;
82
+ };
83
+ const refsIn = (v, out = []) => {
84
+ if (Array.isArray(v)) for (const x of v) refsIn(x, out);
85
+ else if (v && typeof v === "object") {
86
+ if (typeof v.$ref === "string") {
87
+ const id = resolve(v.$ref);
88
+ if (id && !out.includes(id)) out.push(id);
89
+ } else for (const x of Object.values(v)) refsIn(x, out);
90
+ }
91
+ return out;
92
+ };
93
+ const refIn = (v) => refsIn(v)[0];
94
+ const kindIs = (n, re) => !!n && re.test(n.kind || "");
95
+ const ofKind = (re) => nodes.filter((n) => kindIs(n, re));
96
+ /** Cards of a kind whose attr `key` refers to `id`. */
97
+ const referring = (re, key, id) => ofKind(re).filter((n) => refsIn(n.attrs?.[key]).includes(id));
98
+ return { nodes, byId, resolve, refsIn, refIn, kindIs, ofKind, referring };
99
+ }
100
+
101
+ const seenLive = (n) => n?.attrs?._status === "good" || n?.attrs?._status === "warn";
102
+ const title = (n) => (n ? n.id : "?");
103
+ const portIn = (p, from, to) => (from === undefined || from === null || Number(from) === -1 ? true : p >= Number(from) && p <= Number(to ?? from));
104
+
105
+ // ---------------------------------------------------------------- AWS
106
+
107
+ const AWS = {
108
+ subnet: /^AWS::EC2::Subnet$/,
109
+ sg: /^AWS::EC2::SecurityGroup$/,
110
+ sgIngress: /^AWS::EC2::SecurityGroupIngress$/,
111
+ sgEgress: /^AWS::EC2::SecurityGroupEgress$/,
112
+ rta: /^AWS::EC2::SubnetRouteTableAssociation$/,
113
+ route: /^AWS::EC2::Route$/,
114
+ igw: /^AWS::EC2::InternetGateway$/,
115
+ igwAttach: /^AWS::EC2::VPCGatewayAttachment$/,
116
+ nat: /^AWS::EC2::NatGateway$/,
117
+ naclAssoc: /^AWS::EC2::SubnetNetworkAclAssociation$/,
118
+ naclEntry: /^AWS::EC2::NetworkAclEntry$/,
119
+ lb: /^AWS::ElasticLoadBalancingV2::LoadBalancer$/,
120
+ listener: /^AWS::ElasticLoadBalancingV2::Listener$/,
121
+ listenerRule: /^AWS::ElasticLoadBalancingV2::ListenerRule$/,
122
+ tg: /^AWS::ElasticLoadBalancingV2::TargetGroup$/,
123
+ };
124
+
125
+ function awsSubnetsOf(g, n) {
126
+ const a = n.attrs || {};
127
+ const vpc = a.NetworkConfiguration?.AwsvpcConfiguration;
128
+ const refs = g.refsIn([a.Subnets, a.SubnetId, vpc?.Subnets, a.SubnetMappings, a.NetworkInterfaces, a.VPCZoneIdentifier]);
129
+ return refs.map((id) => g.byId.get(id)).filter((x) => g.kindIs(x, AWS.subnet));
130
+ }
131
+
132
+ function awsSgsOf(g, n) {
133
+ const a = n.attrs || {};
134
+ const vpc = a.NetworkConfiguration?.AwsvpcConfiguration;
135
+ const refs = g.refsIn([a.SecurityGroups, a.SecurityGroupIds, vpc?.SecurityGroups, a.NetworkInterfaces, a.VpcSecurityGroupIds]);
136
+ return refs.map((id) => g.byId.get(id)).filter((x) => g.kindIs(x, AWS.sg));
137
+ }
138
+
139
+ /** A security group's rules one way, from the live read when it carries them. */
140
+ function awsSgRules(g, sg, egress) {
141
+ const a = sg.attrs || {};
142
+ const live = egress ? a.IpPermissionsEgress : a.IpPermissions;
143
+ if (Array.isArray(live)) {
144
+ return {
145
+ basis: "live",
146
+ rules: live.map((r) => ({
147
+ proto: String(r.IpProtocol),
148
+ from: r.FromPort,
149
+ to: r.ToPort,
150
+ cidrs: [...(r.IpRanges || []).map((x) => x.CidrIp), ...(r.Ipv6Ranges || []).map((x) => x.CidrIpv6)].filter(Boolean),
151
+ groups: (r.UserIdGroupPairs || []).map((x) => x.GroupId).filter(Boolean),
152
+ })),
153
+ };
154
+ }
155
+ const inline = (egress ? a.SecurityGroupEgress : a.SecurityGroupIngress) || [];
156
+ const standalone = g.referring(egress ? AWS.sgEgress : AWS.sgIngress, "GroupId", sg.id).map((n) => n.attrs || {});
157
+ const declared = [...(Array.isArray(inline) ? inline : []), ...standalone];
158
+ // No egress declared at all: a security group sends anywhere by default.
159
+ if (egress && !declared.length) return { basis: "source", rules: [{ proto: "-1", cidrs: ["0.0.0.0/0"], groups: [] }], byDefault: true };
160
+ return {
161
+ basis: "source",
162
+ rules: declared.map((r) => ({
163
+ proto: String(r.IpProtocol),
164
+ from: r.FromPort,
165
+ to: r.ToPort,
166
+ cidrs: [r.CidrIp, r.CidrIpv6, r.DestinationCidrIp].filter((c) => typeof c === "string"),
167
+ groups: g.refsIn([r.SourceSecurityGroupId, r.DestinationSecurityGroupId]),
168
+ })),
169
+ };
170
+ }
171
+
172
+ const protoCovers = (proto, port) => (proto === "-1" ? true : (proto === "tcp" || proto === "6") && port !== undefined);
173
+
174
+ /**
175
+ * Whether any of `sgs` lets `port` in (or out) from `src`: `{ cidr }` for an
176
+ * address range, `{ sgs }` for traffic from cards in those groups.
177
+ */
178
+ function awsSgsAllow(g, sgs, port, src, egress = false) {
179
+ let basis = "source";
180
+ for (const sg of sgs) {
181
+ const { rules, basis: b, byDefault } = awsSgRules(g, sg, egress);
182
+ if (b === "live") basis = "live";
183
+ for (const r of rules) {
184
+ if (!protoCovers(r.proto, port) || (r.proto !== "-1" && !portIn(port, r.from, r.to))) continue;
185
+ const byCidr = src.cidr && r.cidrs.some((c) => cidrContains(c, src.cidr));
186
+ const srcGroups = (src.sgs || []).flatMap((s) => [s.id, s.attrs?.GroupId]).filter((x) => typeof x === "string");
187
+ const byGroup = r.groups.some((x) => srcGroups.includes(x));
188
+ if (byCidr || byGroup) {
189
+ const what = byGroup ? "the source's security group" : r.cidrs.find((c) => cidrContains(c, src.cidr));
190
+ return { open: true, by: sg, basis: b, why: byDefault ? `${title(sg)} sends anywhere (no outbound rule declared)` : `${title(sg)} allows ${port} ${egress ? "to" : "from"} ${what}` };
191
+ }
192
+ }
193
+ }
194
+ return { open: false, basis, why: sgs.length ? `no rule in ${sgs.map(title).join(", ")} allows ${port} ${egress ? "to" : "from"} ${src.cidr ?? "the source"}` : "no security group" };
195
+ }
196
+
197
+ /** The route a subnet sends `0.0.0.0/0` along. */
198
+ function awsWayOut(g, subnet) {
199
+ const assoc = g.referring(AWS.rta, "SubnetId", subnet.id)[0];
200
+ const table = assoc && g.refIn(assoc.attrs?.RouteTableId);
201
+ if (!table) return { kind: "unknown", why: `${title(subnet)} has no route table of its own; the VPC's main table decides` };
202
+ const routes = g.referring(AWS.route, "RouteTableId", table).filter((r) => r.attrs?.DestinationCidrBlock === "0.0.0.0/0");
203
+ for (const r of routes) {
204
+ const igw = g.refIn(r.attrs?.GatewayId);
205
+ if (igw && g.kindIs(g.byId.get(igw), AWS.igw)) {
206
+ const attached = g.referring(AWS.igwAttach, "InternetGatewayId", igw).length > 0;
207
+ return { kind: attached ? "igw" : "detached", route: r, gateway: g.byId.get(igw), why: attached ? `${title(r)} sends 0.0.0.0/0 to ${igw}` : `${igw} isn't attached to the VPC` };
208
+ }
209
+ const nat = g.refIn(r.attrs?.NatGatewayId);
210
+ if (nat) return { kind: "nat", route: r, gateway: g.byId.get(nat), why: `${title(r)} sends 0.0.0.0/0 to ${nat}` };
211
+ }
212
+ return { kind: "none", why: `${g.byId.get(table) ? table : "its route table"} has no route to 0.0.0.0/0` };
213
+ }
214
+
215
+ /** Whether a subnet's network ACL lets `port` in (or out) for `cidr`. */
216
+ function awsNaclAllows(g, subnet, port, cidr, egress = false) {
217
+ const assoc = g.referring(AWS.naclAssoc, "SubnetId", subnet.id)[0];
218
+ const acl = assoc && g.refIn(assoc.attrs?.NetworkAclId);
219
+ if (!acl) return { open: true, basis: "source", why: `${title(subnet)}: no network ACL declared, the VPC's default allows all` };
220
+ const entries = g
221
+ .referring(AWS.naclEntry, "NetworkAclId", acl)
222
+ .map((n) => ({ n, a: n.attrs || {} }))
223
+ .filter(({ a }) => String(a.Egress ?? false) === String(egress))
224
+ .sort((x, y) => Number(x.a.RuleNumber) - Number(y.a.RuleNumber));
225
+ for (const { n, a } of entries) {
226
+ const proto = String(a.Protocol);
227
+ if (proto !== "-1" && proto !== "6") continue;
228
+ if (proto === "6" && !portIn(port, a.PortRange?.From, a.PortRange?.To)) continue;
229
+ if (!cidrContains(a.CidrBlock ?? a.Ipv6CidrBlock, cidr)) continue;
230
+ const allow = String(a.RuleAction).toLowerCase() === "allow";
231
+ return { open: allow, by: n, basis: "source", why: `${acl} rule ${a.RuleNumber} ${allow ? "allows" : "denies"} ${port} ${egress ? "to" : "from"} ${cidr}` };
232
+ }
233
+ return { open: false, basis: "source", why: `no rule in ${acl} matches ${port} ${egress ? "to" : "from"} ${cidr}, so it is denied` };
234
+ }
235
+
236
+ /** Each hop says whether the card it is about was read live. */
237
+ function hop(step, card, res) {
238
+ return { step, id: card?.id, open: !!res.open, why: res.why, basis: res.basis || "source", seen: seenLive(card) };
239
+ }
240
+
241
+ /** The first subnet whose result is open, else the first result (the reason it is closed). */
242
+ function anySubnet(subnets, f) {
243
+ const results = subnets.map((s) => ({ s, r: f(s) }));
244
+ return results.find((x) => x.r.open) || results[0];
245
+ }
246
+
247
+ /** Load balancer chains that end at `target`: lb, listeners, the target group. */
248
+ function awsChainsTo(g, target) {
249
+ const out = [];
250
+ for (const lb of g.ofKind(AWS.lb)) {
251
+ const listeners = g.referring(AWS.listener, "LoadBalancerArn", lb.id);
252
+ if (lb.id === target.id) {
253
+ out.push({ lb, listeners, tg: null });
254
+ continue;
255
+ }
256
+ for (const l of listeners) {
257
+ const rules = g.referring(AWS.listenerRule, "ListenerArn", l.id);
258
+ const tgs = g.refsIn([l.attrs?.DefaultActions, ...rules.map((r) => r.attrs?.Actions)]).filter((id) => g.kindIs(g.byId.get(id), AWS.tg));
259
+ for (const tg of tgs) {
260
+ const t = g.byId.get(tg);
261
+ const hits =
262
+ target.id === tg ||
263
+ g.refsIn(target.attrs?.LoadBalancers).includes(tg) ||
264
+ g.refsIn(target.attrs?.TargetGroupARNs).includes(tg) ||
265
+ g.refsIn(t.attrs?.Targets).includes(target.id);
266
+ if (hits) out.push({ lb, listeners, tg: t });
267
+ }
268
+ }
269
+ }
270
+ // An internet-facing one first: that is the way in from outside.
271
+ return out.sort((x, y) => (x.lb.attrs?.Scheme === "internal") - (y.lb.attrs?.Scheme === "internal"));
272
+ }
273
+
274
+ function awsFromOutside(g, target, port) {
275
+ const hops = [];
276
+ const chain = awsChainsTo(g, target)[0];
277
+ if (chain) {
278
+ const { lb, listeners, tg } = chain;
279
+ const internal = lb.attrs?.Scheme === "internal";
280
+ hops.push(hop("way in", lb, { open: !internal, why: internal ? `${lb.id} is internal: it has no address outside the VPC` : `${lb.id} faces the internet` }));
281
+ const lbSubnets = awsSubnetsOf(g, lb);
282
+ const out = anySubnet(lbSubnets, (s) => {
283
+ const w = awsWayOut(g, s);
284
+ return { open: w.kind === "igw", why: w.why, gateway: w.gateway };
285
+ });
286
+ hops.push(hop("gateway", out?.r.gateway || lb, out ? out.r : { open: false, why: `${lb.id} names no subnet` }));
287
+ const nacl = anySubnet(lbSubnets, (s) => awsNaclAllows(g, s, port, "0.0.0.0/0"));
288
+ if (nacl) hops.push(hop("network ACL", nacl.r.by || nacl.s, nacl.r));
289
+ const lbSgs = awsSgsOf(g, lb);
290
+ if (!lbSgs.length && lb.attrs?.Type === "network") hops.push(hop("security group", lb, { open: true, why: `${lb.id} is a network load balancer with no security group: it passes what reaches it` }));
291
+ else {
292
+ const r = awsSgsAllow(g, lbSgs, port, { cidr: "0.0.0.0/0" });
293
+ hops.push(hop("security group", r.by || lbSgs[0] || lb, r));
294
+ }
295
+ const listener = listeners.find((l) => Number(l.attrs?.Port) === port);
296
+ const ports = listeners.map((l) => l.attrs?.Port).filter((p) => p !== undefined);
297
+ hops.push(
298
+ hop("listener", listener || lb, {
299
+ open: !!listener,
300
+ why: listener ? `${listener.id} takes ${port}` : ports.length ? `${lb.id} listens on ${ports.join(", ")}, not ${port}` : `${lb.id} has no listener`,
301
+ }),
302
+ );
303
+ if (!tg) return hops;
304
+ const lbEntry = (target.attrs?.LoadBalancers || []).find((x) => g.refsIn(x).includes(tg.id));
305
+ const tport = Number(lbEntry?.ContainerPort ?? lbEntry?.TargetPort ?? tg.attrs?.Port);
306
+ hops.push(hop("forward", tg, { open: true, why: `${listener?.id ?? "the listener"} forwards to ${tg.id} on ${tport}` }));
307
+ if (target.id === tg.id) return hops;
308
+ const tSubnets = awsSubnetsOf(g, target);
309
+ const lbCidrs = lbSubnets.map((s) => s.attrs?.CidrBlock).filter((c) => typeof c === "string");
310
+ const tn = anySubnet(tSubnets, (s) => {
311
+ const per = lbCidrs.map((c) => awsNaclAllows(g, s, tport, c));
312
+ return per.find((x) => x.open) || per[0] || awsNaclAllows(g, s, tport, "0.0.0.0/0");
313
+ });
314
+ if (tn) hops.push(hop("network ACL", tn.r.by || tn.s, tn.r));
315
+ const tSgs = awsSgsOf(g, target);
316
+ if (tSgs.length) {
317
+ const byGroup = awsSgsAllow(g, tSgs, tport, { sgs: lbSgs });
318
+ const r = byGroup.open ? byGroup : lbCidrs.map((c) => awsSgsAllow(g, tSgs, tport, { cidr: c })).find((x) => x.open) || byGroup;
319
+ hops.push(hop("security group", r.by || tSgs[0], r));
320
+ }
321
+ return hops;
322
+ }
323
+ // No load balancer in front: a card with its own public address.
324
+ const subnets = awsSubnetsOf(g, target);
325
+ if (!subnets.length) return [hop("way in", target, { open: false, why: `nothing in front of ${target.id} takes traffic from outside, and it sits in no subnet` })];
326
+ const vpc = target.attrs?.NetworkConfiguration?.AwsvpcConfiguration;
327
+ const publicIp = vpc ? vpc.AssignPublicIp === "ENABLED" : target.attrs?.NetworkInterfaces?.some?.((x) => x.AssociatePublicIpAddress) || subnets.some((s) => s.attrs?.MapPublicIpOnLaunch === true);
328
+ hops.push(hop("way in", target, { open: !!publicIp, why: publicIp ? `${target.id} gets a public address` : `nothing in front of ${target.id} takes traffic from outside, and it has no public address` }));
329
+ const out = anySubnet(subnets, (s) => {
330
+ const w = awsWayOut(g, s);
331
+ return { open: w.kind === "igw", why: w.why, gateway: w.gateway };
332
+ });
333
+ hops.push(hop("gateway", out.r.gateway || out.s, out.r));
334
+ const nacl = anySubnet(subnets, (s) => awsNaclAllows(g, s, port, "0.0.0.0/0"));
335
+ hops.push(hop("network ACL", nacl.r.by || nacl.s, nacl.r));
336
+ const sgs = awsSgsOf(g, target);
337
+ const r = awsSgsAllow(g, sgs, port, { cidr: "0.0.0.0/0" });
338
+ hops.push(hop("security group", r.by || sgs[0] || target, r));
339
+ return hops;
340
+ }
341
+
342
+ /** The hops from a card out to the internet. */
343
+ function awsWayOutOf(g, source, port) {
344
+ const subnets = awsSubnetsOf(g, source);
345
+ if (!subnets.length) return [hop("way out", source, { open: false, why: `${source.id} sits in no subnet this trace reads` })];
346
+ const vpc = source.attrs?.NetworkConfiguration?.AwsvpcConfiguration;
347
+ const out = anySubnet(subnets, (s) => {
348
+ const w = awsWayOut(g, s);
349
+ const publicIp = vpc ? vpc.AssignPublicIp === "ENABLED" : s.attrs?.MapPublicIpOnLaunch === true;
350
+ const open = w.kind === "nat" || (w.kind === "igw" && publicIp);
351
+ return { open, gateway: w.gateway, why: w.kind === "igw" && !publicIp ? `${w.why}, but ${source.id} has no public address` : w.why };
352
+ });
353
+ const hops = [hop("way out", out.r.gateway || out.s, out.r)];
354
+ const sgs = awsSgsOf(g, source);
355
+ if (sgs.length) {
356
+ const r = awsSgsAllow(g, sgs, port, { cidr: "0.0.0.0/0" }, true);
357
+ hops.push(hop("security group", r.by || sgs[0], r));
358
+ }
359
+ return hops;
360
+ }
361
+
362
+ function awsCardToCard(g, source, target, port) {
363
+ const sSubnets = awsSubnetsOf(g, source);
364
+ const tSubnets = awsSubnetsOf(g, target);
365
+ // Declared, a `$ref`; read live, the provider's own id.
366
+ const vpcOf = (s) => g.refIn(s.attrs?.VpcId) ?? (typeof s.attrs?.VpcId === "string" ? s.attrs.VpcId : undefined);
367
+ const sameVpc = sSubnets.length && tSubnets.length && sSubnets.some((s) => tSubnets.some((t) => vpcOf(s) && vpcOf(s) === vpcOf(t)));
368
+ if (!sameVpc) return null;
369
+ const hops = [hop("route", tSubnets[0], { open: true, why: `inside ${vpcOf(tSubnets[0])}: the local route` })];
370
+ const sSgs = awsSgsOf(g, source);
371
+ const tCidr = tSubnets[0].attrs?.CidrBlock;
372
+ if (sSgs.length) {
373
+ const r = awsSgsAllow(g, sSgs, port, { cidr: tCidr }, true);
374
+ hops.push(hop("security group", r.by || sSgs[0], r));
375
+ }
376
+ const sCidr = sSubnets[0].attrs?.CidrBlock;
377
+ const outAcl = awsNaclAllows(g, sSubnets[0], port, tCidr, true);
378
+ hops.push(hop("network ACL", outAcl.by || sSubnets[0], outAcl));
379
+ const inAcl = anySubnet(tSubnets, (s) => awsNaclAllows(g, s, port, sCidr));
380
+ hops.push(hop("network ACL", inAcl.r.by || inAcl.s, inAcl.r));
381
+ const tSgs = awsSgsOf(g, target);
382
+ if (tSgs.length) {
383
+ const byGroup = awsSgsAllow(g, tSgs, port, { sgs: sSgs });
384
+ const r = byGroup.open ? byGroup : awsSgsAllow(g, tSgs, port, { cidr: sCidr });
385
+ hops.push(hop("security group", r.by || tSgs[0], r));
386
+ }
387
+ if (g.kindIs(target, AWS.lb)) {
388
+ const listener = g.referring(AWS.listener, "LoadBalancerArn", target.id).find((l) => Number(l.attrs?.Port) === port);
389
+ hops.push(hop("listener", listener || target, { open: !!listener, why: listener ? `${listener.id} takes ${port}` : `${target.id} has no listener on ${port}` }));
390
+ }
391
+ return hops;
392
+ }
393
+
394
+ // ---------------------------------------------------------------- GCP
395
+
396
+ const GCP_NEXT = [
397
+ [/::ForwardingRule$/, "target"],
398
+ [/::TargetHTTPS?Proxy$/, "urlMapRef"],
399
+ [/::URLMap$/, ["defaultService", "pathMatcher", "pathMatchers"]],
400
+ [/::BackendService$/, "backend"],
401
+ [/::(Region)?NetworkEndpointGroup$/, ["cloudRun", "cloudFunction", "appEngine"]],
402
+ ];
403
+
404
+ const gcpName = (n) => n?.attrs?.metadata?.name;
405
+
406
+ function gcpPortIn(range, port) {
407
+ if (range === undefined || range === null || range === "") return true;
408
+ const [a, b] = String(range).split("-").map(Number);
409
+ return port >= a && port <= (b || a);
410
+ }
411
+
412
+ /** The invoker grant that opens a Cloud Run service to anyone. */
413
+ function gcpPublicGrant(g, service) {
414
+ const name = gcpName(service);
415
+ return g.ofKind(/^GCP::Iam::Policy(Member|Binding)$/).find((p) => {
416
+ const a = p.attrs || {};
417
+ const members = [a.member, ...(a.members || [])];
418
+ const onIt = a.resourceRef?.name === name || g.refsIn(a.resourceRef).includes(service.id);
419
+ return onIt && a.role === "roles/run.invoker" && members.some((m) => m === "allUsers" || m === "allAuthenticatedUsers");
420
+ });
421
+ }
422
+
423
+ function gcpServiceHops(g, service, viaLb) {
424
+ const ingress = service.attrs?.ingress || "INGRESS_TRAFFIC_ALL";
425
+ const ok = ingress === "INGRESS_TRAFFIC_ALL" || (viaLb && ingress === "INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER");
426
+ const hops = [hop("ingress", service, { open: ok, why: ok ? `${service.id} takes traffic ${viaLb ? "from the load balancer" : "from anywhere"}` : `${service.id} takes ${ingress.replace("INGRESS_TRAFFIC_", "").toLowerCase().replace(/_/g, " ")} traffic only` })];
427
+ const grant = gcpPublicGrant(g, service);
428
+ hops.push(hop("invoker", grant || service, { open: !!grant, why: grant ? `${grant.id} lets ${grant.attrs.member || "anyone"} call it` : `no grant lets anyone call ${service.id}: callers need a credential` }));
429
+ return hops;
430
+ }
431
+
432
+ function gcpFromOutside(g, target, port) {
433
+ const next = (n) => {
434
+ const rule = GCP_NEXT.find(([re]) => re.test(n.kind || ""));
435
+ if (!rule) return [];
436
+ const keys = Array.isArray(rule[1]) ? rule[1] : [rule[1]];
437
+ return g.refsIn(keys.map((k) => n.attrs?.[k]));
438
+ };
439
+ for (const fr of g.ofKind(/^GCP::Compute::ForwardingRule$/)) {
440
+ if (String(fr.attrs?.loadBalancingScheme || "EXTERNAL").startsWith("INTERNAL")) continue;
441
+ const path = [];
442
+ const walk = (id, seen) => {
443
+ if (id === target.id) return true;
444
+ if (seen.has(id)) return false;
445
+ seen.add(id);
446
+ for (const nxt of next(g.byId.get(id))) {
447
+ path.push(nxt);
448
+ if (walk(nxt, seen)) return true;
449
+ path.pop();
450
+ }
451
+ return false;
452
+ };
453
+ if (!walk(fr.id, new Set())) continue;
454
+ const range = fr.attrs?.portRange;
455
+ const hops = [hop("way in", fr, { open: gcpPortIn(range, port), why: gcpPortIn(range, port) ? `${fr.id} takes ${port} from the internet` : `${fr.id} takes ${range}, not ${port}` })];
456
+ for (const id of path) {
457
+ const n = g.byId.get(id);
458
+ if (id === target.id && g.kindIs(n, /^GCP::Run::Service$/)) hops.push(...gcpServiceHops(g, n, true));
459
+ else hops.push(hop("forward", n, { open: true, why: `forwards to ${next(n)[0] ?? id}` }));
460
+ }
461
+ return hops;
462
+ }
463
+ if (g.kindIs(target, /^GCP::Run::Service$/)) {
464
+ const hops = gcpServiceHops(g, target, false);
465
+ if (port !== 443) hops.unshift(hop("way in", target, { open: false, why: `${target.id}'s own address takes 443, not ${port}` }));
466
+ return hops;
467
+ }
468
+ return [hop("way in", target, { open: false, why: `no forwarding rule reaches ${target.id}` })];
469
+ }
470
+
471
+ // ---------------------------------------------------------------- Azure
472
+
473
+ function azNsgRules(g, subnet) {
474
+ const nsgId = g.refIn(subnet.attrs?.networkSecurityGroup ?? subnet.attrs?.properties?.networkSecurityGroup);
475
+ const nsg = nsgId && g.byId.get(nsgId);
476
+ if (!nsg) return null;
477
+ const inline = nsg.attrs?.securityRules ?? nsg.attrs?.properties?.securityRules ?? [];
478
+ const children = g.ofKind(/networkSecurityGroups[/_]securityRules$/).filter((r) => r.id.startsWith(nsg.id) || g.refsIn(r.attrs).includes(nsg.id));
479
+ const rules = [...inline, ...children.map((c) => c.attrs)].map((r) => ({ name: r.name, ...(r.properties || r) }));
480
+ return { nsg, rules };
481
+ }
482
+
483
+ const azFromAnyone = (r) => ["*", "Internet", "0.0.0.0/0", "Any"].includes(r.sourceAddressPrefix) || (r.sourceAddressPrefixes || []).some((p) => ["*", "Internet", "0.0.0.0/0"].includes(p));
484
+ function azPortIn(r, port) {
485
+ const ranges = [r.destinationPortRange, ...(r.destinationPortRanges || [])].filter((x) => x !== undefined);
486
+ return ranges.some((x) => x === "*" || gcpPortIn(x, port));
487
+ }
488
+
489
+ function azureFromOutside(g, target, port) {
490
+ if (!g.kindIs(target, /^Microsoft\.App\/containerApps$/)) return [hop("way in", target, { open: false, why: `the trace reads a container app's way in; ${target.id} isn't one` })];
491
+ const hops = [];
492
+ const envId = g.refIn(target.attrs?.managedEnvironmentId);
493
+ const env = envId && g.byId.get(envId);
494
+ if (env) {
495
+ const internal = env.attrs?.vnetConfiguration?.internal === true;
496
+ hops.push(hop("way in", env, { open: !internal, why: internal ? `${env.id} is internal: it has no public address` : `${env.id} has a public address` }));
497
+ const subnetId = g.refIn(env.attrs?.vnetConfiguration?.infrastructureSubnetId);
498
+ const subnet = subnetId && g.byId.get(subnetId);
499
+ if (subnet) {
500
+ const nsg = azNsgRules(g, subnet);
501
+ if (!nsg) hops.push(hop("security group", subnet, { open: true, why: `${subnet.id} has no network security group` }));
502
+ else {
503
+ const rule = nsg.rules
504
+ .filter((r) => String(r.direction).toLowerCase() === "inbound" && azFromAnyone(r) && azPortIn(r, port))
505
+ .sort((a, b) => Number(a.priority) - Number(b.priority))[0];
506
+ const open = rule ? String(rule.access).toLowerCase() === "allow" : false;
507
+ hops.push(hop("security group", nsg.nsg, { open, why: rule ? `${nsg.nsg.id} rule ${rule.name} ${open ? "allows" : "denies"} ${port}` : `no rule in ${nsg.nsg.id} allows ${port} from the internet` }));
508
+ }
509
+ }
510
+ }
511
+ const ingress = target.attrs?.configuration?.ingress;
512
+ hops.push(hop("ingress", target, { open: ingress?.external === true, why: !ingress ? `${target.id} has no ingress` : ingress.external ? `${target.id} takes traffic from outside the environment` : `${target.id}'s ingress is internal to the environment` }));
513
+ if (ingress) {
514
+ const tcp = ingress.transport === "tcp";
515
+ const listens = tcp ? [Number(ingress.exposedPort)] : [80, 443];
516
+ const restricted = (ingress.ipSecurityRestrictions || []).filter((r) => String(r.action).toLowerCase() === "allow");
517
+ hops.push(hop("listener", target, { open: listens.includes(port), why: listens.includes(port) ? `takes ${port} and forwards to ${ingress.targetPort}` : `takes ${listens.join(" and ")}, not ${port}` }));
518
+ if (restricted.length) {
519
+ const anyone = restricted.some((r) => ANYONE(r.ipAddressRange));
520
+ hops.push(hop("address rules", target, { open: anyone, why: anyone ? "the address rules allow anyone" : `only ${restricted.map((r) => r.ipAddressRange).join(", ")} may call it` }));
521
+ }
522
+ }
523
+ return hops;
524
+ }
525
+
526
+ // ---------------------------------------------------------------- trace
527
+
528
+ const cloudOf = (n) => (/^AWS::/.test(n?.kind || "") ? "aws" : /^GCP::/.test(n?.kind || "") ? "gcp" : /^Microsoft\./.test(n?.kind || "") ? "azure" : null);
529
+
530
+ function fromOutside(g, target, port) {
531
+ const cloud = cloudOf(target);
532
+ if (cloud === "aws") return awsFromOutside(g, target, port);
533
+ if (cloud === "gcp") return gcpFromOutside(g, target, port);
534
+ if (cloud === "azure") return azureFromOutside(g, target, port);
535
+ return null;
536
+ }
537
+
538
+ /** The hops from a card to the internet, for a trace that leaves its network. */
539
+ function wayOutOf(g, source, port) {
540
+ const cloud = cloudOf(source);
541
+ if (cloud === "aws") return awsWayOutOf(g, source, port);
542
+ if (cloud === "gcp") {
543
+ const egress = source.attrs?.template?.vpcAccess?.egress;
544
+ const viaVpc = egress === "ALL_TRAFFIC";
545
+ const nat = g.ofKind(/^GCP::Compute::Router(NAT)?$/).some((r) => r.kind.endsWith("RouterNAT") || r.attrs?.nats);
546
+ return [hop("way out", source, { open: !viaVpc || nat, why: viaVpc ? (nat ? "all traffic leaves through the VPC and its NAT" : "all traffic leaves through the VPC, which declares no NAT") : `${source.id} reaches the internet directly` })];
547
+ }
548
+ if (cloud === "azure") return [hop("way out", source, { open: true, why: `${source.id} reaches the internet through its environment` })];
549
+ return [hop("way out", source, { open: false, why: `${source.id} isn't a card this trace reads` })];
550
+ }
551
+
552
+ /**
553
+ * Trace `port` from `from` (OUTSIDE or a card id) to the card `to`. Returns
554
+ * the hops in order, whether the traffic arrives, and the first hop that stops
555
+ * it; or `{ unread }` with the reason when the trace can't be read here.
556
+ */
557
+ export function traceRoute(ir, { from, to, port }) {
558
+ const g = index(ir);
559
+ const target = g.byId.get(to);
560
+ const p = Number(port);
561
+ if (!target) return { unread: `${to} isn't on this graph` };
562
+ if (!Number.isInteger(p) || p < 1 || p > 65535) return { unread: "a port is 1 to 65535" };
563
+ let hops;
564
+ if (from === OUTSIDE) hops = fromOutside(g, target, p);
565
+ else {
566
+ const source = g.byId.get(from);
567
+ if (!source) return { unread: `${from} isn't on this graph` };
568
+ hops = cloudOf(source) === "aws" && cloudOf(target) === "aws" ? awsCardToCard(g, source, target, p) : null;
569
+ // Another network: out to the internet, and in from outside.
570
+ if (!hops) {
571
+ const inbound = fromOutside(g, target, p);
572
+ hops = inbound && [...wayOutOf(g, source, p), ...inbound];
573
+ }
574
+ }
575
+ if (!hops) return { unread: `the trace reads AWS, GCP and Azure networks; ${to} is ${target.kind}` };
576
+ const stop = hops.find((h) => !h.open);
577
+ return { from, to, port: p, hops, reached: !stop, stop: stop?.id };
578
+ }
579
+
580
+ // ---------------------------------------------------------------- findings
581
+
582
+ /** Address ranges from every cloud, each with the network it belongs to. */
583
+ function ranges(g) {
584
+ const out = [];
585
+ for (const n of g.nodes) {
586
+ const a = n.attrs || {};
587
+ if (n.kind === "AWS::EC2::VPC" && typeof a.CidrBlock === "string") out.push({ id: n.id, cidr: a.CidrBlock, net: n.id, level: "network" });
588
+ if (n.kind === "AWS::EC2::Subnet" && typeof a.CidrBlock === "string") out.push({ id: n.id, cidr: a.CidrBlock, net: g.refIn(a.VpcId) ?? (typeof a.VpcId === "string" ? a.VpcId : n.id), level: "subnet" });
589
+ if (n.kind === "Microsoft.Network/virtualNetworks") for (const c of a.addressSpace?.addressPrefixes || []) out.push({ id: n.id, cidr: c, net: n.id, level: "network" });
590
+ if (/^Microsoft\.Network\/virtualNetworks[/_]subnets$/.test(n.kind || "")) {
591
+ const vnet = g.nodes.find((v) => v.kind === "Microsoft.Network/virtualNetworks" && typeof a.name === "string" && a.name.startsWith(`${v.attrs?.name}/`));
592
+ for (const c of [a.addressPrefix, ...(a.addressPrefixes || [])].filter(Boolean)) out.push({ id: n.id, cidr: c, net: vnet?.id ?? n.id, level: "subnet" });
593
+ }
594
+ if (n.kind === "GCP::Compute::Subnetwork" && typeof a.ipCidrRange === "string") out.push({ id: n.id, cidr: a.ipCidrRange, net: g.refIn(a.networkRef) ?? n.id, level: "network" });
595
+ }
596
+ return out;
597
+ }
598
+
599
+ /**
600
+ * What is wrong with the networks without tracing anything: overlapping
601
+ * ranges, a public subnet with no way out, a load balancer in one zone, and an
602
+ * admin port open to anyone. Each finding names the cards it is about.
603
+ */
604
+ export function networkFindings(ir) {
605
+ const g = index(ir);
606
+ const out = [];
607
+ const rs = ranges(g);
608
+ for (let i = 0; i < rs.length; i++) {
609
+ for (let j = i + 1; j < rs.length; j++) {
610
+ const [a, b] = [rs[i], rs[j]];
611
+ if (a.id === b.id || !cidrsOverlap(a.cidr, b.cidr)) continue;
612
+ // Networks apart from each other, or two subnets of one network.
613
+ const apart = a.level === "network" && b.level === "network" && a.net !== b.net;
614
+ const siblings = a.level === "subnet" && b.level === "subnet" && a.net === b.net;
615
+ if (apart || siblings) out.push({ finding: "overlap", ids: [a.id, b.id], text: `${a.id} (${a.cidr}) and ${b.id} (${b.cidr}) overlap: ${apart ? "traffic between them can't be routed by address" : "one network can't hold both"}` });
616
+ }
617
+ }
618
+ const facing = g.ofKind(AWS.lb).filter((lb) => lb.attrs?.Scheme !== "internal");
619
+ const facingSubnets = new Set(facing.flatMap((lb) => awsSubnetsOf(g, lb).map((s) => s.id)));
620
+ for (const s of g.ofKind(AWS.subnet)) {
621
+ if (s.attrs?.MapPublicIpOnLaunch !== true && !facingSubnets.has(s.id)) continue;
622
+ const w = awsWayOut(g, s);
623
+ if (w.kind !== "igw") out.push({ finding: "no way out", ids: [s.id], text: `${s.id} is public but ${w.why}` });
624
+ }
625
+ for (const lb of g.ofKind(AWS.lb)) {
626
+ const subnets = awsSubnetsOf(g, lb);
627
+ const zones = new Set(subnets.map((s) => (typeof s.attrs?.AvailabilityZone === "string" ? s.attrs.AvailabilityZone : s.id)));
628
+ if (subnets.length && zones.size < 2) out.push({ finding: "one zone", ids: [lb.id], text: `${lb.id} sits in one zone: if it goes, so does the way in` });
629
+ }
630
+ const admin = (from, to, proto) => Object.keys(ADMIN_PORTS).map(Number).filter((p) => proto === "-1" || ((proto === "tcp" || proto === "6") && portIn(p, from, to)));
631
+ const say = (ports) => ports.map((p) => `${p} (${ADMIN_PORTS[p]})`).join(", ");
632
+ for (const sg of g.ofKind(AWS.sg)) {
633
+ const { rules } = awsSgRules(g, sg, false);
634
+ const ports = [...new Set(rules.filter((r) => r.cidrs.some(ANYONE)).flatMap((r) => admin(r.from, r.to, r.proto)))];
635
+ if (ports.length) out.push({ finding: "admin port", ids: [sg.id], text: `${sg.id} lets anyone reach ${say(ports)}` });
636
+ }
637
+ for (const fw of g.ofKind(/^GCP::Compute::Firewall$/)) {
638
+ const a = fw.attrs || {};
639
+ if ((a.direction || "INGRESS") !== "INGRESS" || !(a.sourceRanges || []).some(ANYONE)) continue;
640
+ const ports = [...new Set((a.allow || []).flatMap((x) => (x.protocol === "all" ? admin(-1, -1, "-1") : x.protocol === "tcp" ? (x.ports?.length ? x.ports.flatMap((r) => { const [lo, hi] = String(r).split("-").map(Number); return admin(lo, hi ?? lo, "tcp"); }) : admin(-1, -1, "-1")) : [])))];
641
+ if (ports.length) out.push({ finding: "admin port", ids: [fw.id], text: `${fw.id} lets anyone reach ${say(ports)}` });
642
+ }
643
+ for (const nsg of g.ofKind(/^Microsoft\.Network\/networkSecurityGroups$/)) {
644
+ const rules = (nsg.attrs?.securityRules ?? nsg.attrs?.properties?.securityRules ?? []).map((r) => ({ name: r.name, ...(r.properties || r) }));
645
+ const ports = [...new Set(rules.filter((r) => String(r.direction).toLowerCase() === "inbound" && String(r.access).toLowerCase() === "allow" && azFromAnyone(r)).flatMap((r) => Object.keys(ADMIN_PORTS).map(Number).filter((p) => azPortIn(r, p))))];
646
+ if (ports.length) out.push({ finding: "admin port", ids: [nsg.id], text: `${nsg.id} lets anyone reach ${say(ports)}` });
647
+ }
648
+ return out;
649
+ }