@intentius/chant-lexicon-aws 0.33.1 → 0.34.1

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.
@@ -0,0 +1,73 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { stampProviderDefaults, canDetectDefault, DEFAULT_AWARE_KINDS } from "./defaults";
3
+ import type { ResourceMetadata } from "@intentius/chant/lexicon";
4
+
5
+ const res = (type: string, attributes: Record<string, unknown>): ResourceMetadata => ({
6
+ type,
7
+ status: "OBSERVED",
8
+ physicalId: "x",
9
+ attributes,
10
+ });
11
+
12
+ const flag = (type: string, attributes: Record<string, unknown>) =>
13
+ stampProviderDefaults({ r: res(type, attributes) }).r.attributes?.providerDefault;
14
+
15
+ // Every account arrives with resources nobody wrote. Asked which security
16
+ // groups were unused, agents split three ways on the same correct set of four,
17
+ // because chant gave them no way to tell a VPC's default group from one someone
18
+ // created.
19
+ describe("provider defaults (#1278)", () => {
20
+ it("reads the marker AWS already sets, per kind", () => {
21
+ expect(flag("AWS::EC2::VPC", { IsDefault: true })).toBe(true);
22
+ expect(flag("AWS::EC2::Subnet", { DefaultForAz: true })).toBe(true);
23
+ expect(flag("AWS::EC2::NetworkAcl", { IsDefault: true })).toBe(true);
24
+ expect(flag("AWS::KMS::Key", { KeyManager: "AWS" })).toBe(true);
25
+ expect(flag("AWS::IAM::ManagedPolicy", { Arn: "arn:aws:iam::aws:policy/ReadOnlyAccess" })).toBe(true);
26
+ });
27
+
28
+ it("does not mark what the account holder created", () => {
29
+ expect(flag("AWS::EC2::VPC", { IsDefault: false })).toBeUndefined();
30
+ expect(flag("AWS::EC2::Subnet", { DefaultForAz: false })).toBeUndefined();
31
+ expect(flag("AWS::KMS::Key", { KeyManager: "CUSTOMER" })).toBeUndefined();
32
+ expect(flag("AWS::IAM::ManagedPolicy", { Arn: "arn:aws:iam::000000000000:policy/Mine" })).toBeUndefined();
33
+ });
34
+
35
+ it("treats the reserved group name as the marker it is", () => {
36
+ // AWS refuses `default` on create, so a group carrying it is the one AWS
37
+ // made with the VPC.
38
+ expect(flag("AWS::EC2::SecurityGroup", { GroupName: "default" })).toBe(true);
39
+ expect(flag("AWS::EC2::SecurityGroup", { GroupName: "default-web" })).toBeUndefined();
40
+ expect(flag("AWS::EC2::SecurityGroup", { GroupName: "webSecurityGroup" })).toBeUndefined();
41
+ });
42
+
43
+ it("finds the main route table through its associations", () => {
44
+ expect(flag("AWS::EC2::RouteTable", { Associations: [{ Main: true }] })).toBe(true);
45
+ expect(flag("AWS::EC2::RouteTable", { Associations: [{ Main: false }, { Main: true }] })).toBe(true);
46
+ expect(flag("AWS::EC2::RouteTable", { Associations: [{ Main: false }] })).toBeUndefined();
47
+ expect(flag("AWS::EC2::RouteTable", {})).toBeUndefined();
48
+ });
49
+
50
+ it("leaves a kind it cannot judge unmarked rather than guessing", () => {
51
+ // Absent means "not a default, or chant cannot tell". A blanket false would
52
+ // hide the difference.
53
+ expect(flag("AWS::EC2::Instance", { InstanceId: "i-1" })).toBeUndefined();
54
+ expect(canDetectDefault("AWS::EC2::Instance")).toBe(false);
55
+ expect(canDetectDefault("AWS::EC2::VPC")).toBe(true);
56
+ });
57
+
58
+ it("keeps every attribute it was given", () => {
59
+ const out = stampProviderDefaults({
60
+ r: res("AWS::EC2::SecurityGroup", { GroupName: "default", GroupId: "sg-1", region: "us-east-1" }),
61
+ }).r.attributes;
62
+ expect(out).toMatchObject({ GroupId: "sg-1", region: "us-east-1", providerDefault: true });
63
+ });
64
+
65
+ it("survives a payload it cannot read", () => {
66
+ expect(flag("AWS::EC2::RouteTable", { Associations: "not-a-list" })).toBeUndefined();
67
+ });
68
+
69
+ it("reports the kinds it can judge, so a caller need not guess", () => {
70
+ expect(DEFAULT_AWARE_KINDS).toContain("AWS::EC2::SecurityGroup");
71
+ expect(DEFAULT_AWARE_KINDS.every(canDetectDefault)).toBe(true);
72
+ });
73
+ });
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Which resources the provider created, rather than anyone's infrastructure code.
3
+ *
4
+ * Every account arrives with resources nobody wrote: a default VPC and its
5
+ * subnets, a default security group per VPC, a main route table, AWS-managed
6
+ * KMS keys and IAM policies. They are yours to account for and were never
7
+ * yours to declare, and until now chant recorded them looking exactly like
8
+ * everything else.
9
+ *
10
+ * That matters wherever a question is about what you built. Asked which
11
+ * security groups were unused, agents split three ways on the same correct set
12
+ * of four — one excluded the three VPC defaults as "not real cleanup
13
+ * candidates" and answered one, another counted something extra and answered
14
+ * five. The answers that were accepted all did the same thing: listed all four
15
+ * and said which were defaults. They could only do that by recognising them,
16
+ * and chant gave them nothing to recognise them by.
17
+ *
18
+ * This records a fact and stops. `providerDefault: true` says the provider
19
+ * created this; it does not say the resource is unused, safe to ignore, or
20
+ * exempt from anything. Deciding that here would put a conclusion in an
21
+ * observation — the mistake `liveInternetFacing` made and #1271 undid — and it
22
+ * would be wrong in this very case, since the accepted answers count defaults
23
+ * as unused.
24
+ *
25
+ * Almost none of this is chant's judgement. AWS marks these itself, on the same
26
+ * payloads chant already reads; the fields were simply being dropped. The one
27
+ * derivation is the security group, and it is safe because `default` is a
28
+ * reserved group name — AWS rejects it on create, so a group called `default`
29
+ * is that VPC's default group.
30
+ */
31
+
32
+ import type { ResourceMetadata } from "@intentius/chant/lexicon";
33
+
34
+ type Attrs = Record<string, unknown>;
35
+
36
+ /**
37
+ * Per kind, the provider's own marker. Extending this is the way to widen.
38
+ *
39
+ * Each predicate reads a field AWS already returns, so this is a passthrough
40
+ * rather than a heuristic — a resource is a default because the provider says
41
+ * so, not because it looks like one.
42
+ */
43
+ const PROVIDER_DEFAULT: Record<string, (attrs: Attrs) => boolean> = {
44
+ "AWS::EC2::VPC": (a) => a.IsDefault === true,
45
+ "AWS::EC2::Subnet": (a) => a.DefaultForAz === true,
46
+ "AWS::EC2::NetworkAcl": (a) => a.IsDefault === true,
47
+ // `default` is a reserved group name: AWS refuses it on create, so a group
48
+ // carrying it is the one AWS made with the VPC.
49
+ "AWS::EC2::SecurityGroup": (a) => a.GroupName === "default",
50
+ // The main route table is the one a subnet falls back to when it has no
51
+ // explicit association — created with the VPC and not by anyone.
52
+ "AWS::EC2::RouteTable": (a) =>
53
+ Array.isArray(a.Associations) &&
54
+ a.Associations.some((x) => (x as Attrs | null)?.Main === true),
55
+ "AWS::KMS::Key": (a) => a.KeyManager === "AWS",
56
+ "AWS::IAM::ManagedPolicy": (a) =>
57
+ typeof a.Arn === "string" && a.Arn.startsWith("arn:aws:iam::aws:policy/"),
58
+ "AWS::IAM::Policy": (a) =>
59
+ typeof a.Arn === "string" && a.Arn.startsWith("arn:aws:iam::aws:policy/"),
60
+ };
61
+
62
+ /** True when this lexicon can tell whether the kind is a provider default. */
63
+ export function canDetectDefault(kind: string): boolean {
64
+ return kind in PROVIDER_DEFAULT;
65
+ }
66
+
67
+ /** The kinds whose provider-default status this lexicon can report. */
68
+ export const DEFAULT_AWARE_KINDS: string[] = Object.keys(PROVIDER_DEFAULT);
69
+
70
+ /**
71
+ * Mark the resources the provider created.
72
+ *
73
+ * Only ever sets the attribute to `true`, and only for kinds with a known
74
+ * marker: absent means "not a default, or chant cannot tell", and those are
75
+ * genuinely different from each other in a way a blanket `false` would hide.
76
+ */
77
+ export function stampProviderDefaults(
78
+ resources: Record<string, ResourceMetadata>,
79
+ ): Record<string, ResourceMetadata> {
80
+ const stamped: Record<string, ResourceMetadata> = {};
81
+ for (const [name, meta] of Object.entries(resources)) {
82
+ const test = PROVIDER_DEFAULT[meta.type];
83
+ const attrs = (meta.attributes ?? {}) as Attrs;
84
+ let isDefault = false;
85
+ try {
86
+ isDefault = test ? test(attrs) : false;
87
+ } catch {
88
+ // A malformed payload is not a default; it is a payload chant could not
89
+ // read, and the rest of the observation is still good.
90
+ isDefault = false;
91
+ }
92
+ stamped[name] = isDefault
93
+ ? { ...meta, attributes: { ...attrs, providerDefault: true } }
94
+ : meta;
95
+ }
96
+ return stamped;
97
+ }
@@ -0,0 +1,208 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+
3
+ // Every AWS interaction is a mocked `spawn` — the reader's only edge is the
4
+ // runtime adapter, and nothing here constructs a client or reaches a network.
5
+ const spawnMock = vi.fn();
6
+ vi.mock("@intentius/chant/runtime-adapter", async (importOriginal) => {
7
+ const actual = await importOriginal<typeof import("@intentius/chant/runtime-adapter")>();
8
+ return { ...actual, getRuntime: () => ({ ...actual.getRuntime(), spawn: spawnMock }) };
9
+ });
10
+
11
+ const { toIngressRules, observeAwsDependencies } = await import("./dependencies");
12
+
13
+ const ok = (body: unknown) => ({ stdout: JSON.stringify(body), stderr: "", exitCode: 0 });
14
+
15
+ /** Route the mock by the AWS subcommand, so ordering is not load-bearing. */
16
+ function respond(handlers: Record<string, unknown>) {
17
+ spawnMock.mockImplementation((...args: unknown[]) => {
18
+ const argv = (args[0] ?? []) as string[];
19
+ const at = argv.indexOf("aws");
20
+ const key = argv.slice(at + 1, at + 3).join(" ");
21
+ const body = handlers[key];
22
+ return Promise.resolve(body ? ok(body) : { stdout: "", stderr: "not mocked: " + key, exitCode: 255 });
23
+ });
24
+ }
25
+
26
+ // #1276 — the two AWS surfaces disagree about the same concept. A template's
27
+ // SecurityGroupIngress carries CidrIp flat; describe-security-groups nests
28
+ // sources under IpRanges[]/Ipv6Ranges[]/UserIdGroupPairs[], and one permission
29
+ // can hold several. Handing the describe shape to the fold unchanged renders
30
+ // every source as `?`, which matches no CIDR query and narrows the answer.
31
+ describe("toIngressRules (#1276)", () => {
32
+ it("flattens an IPv4 range into the flat rule the fold reads", () => {
33
+ expect(
34
+ toIngressRules([{ IpProtocol: "tcp", FromPort: 22, ToPort: 22, IpRanges: [{ CidrIp: "0.0.0.0/0" }] }]),
35
+ ).toEqual([{ IpProtocol: "tcp", FromPort: 22, ToPort: 22, CidrIp: "0.0.0.0/0" }]);
36
+ });
37
+
38
+ it("emits one rule per source, because that is what the flat shape means", () => {
39
+ const rules = toIngressRules([
40
+ {
41
+ IpProtocol: "tcp",
42
+ FromPort: 443,
43
+ ToPort: 443,
44
+ IpRanges: [{ CidrIp: "10.0.0.0/8" }, { CidrIp: "192.168.0.0/16" }],
45
+ UserIdGroupPairs: [{ GroupId: "sg-peer" }],
46
+ },
47
+ ]);
48
+ expect(rules).toHaveLength(3);
49
+ expect(rules.map((r) => r.CidrIp ?? r.SourceSecurityGroupId)).toEqual([
50
+ "10.0.0.0/8",
51
+ "192.168.0.0/16",
52
+ "sg-peer",
53
+ ]);
54
+ });
55
+
56
+ it("carries IPv6 sources through their own key", () => {
57
+ expect(toIngressRules([{ IpProtocol: "tcp", Ipv6Ranges: [{ CidrIpv6: "::/0" }] }])).toEqual([
58
+ { IpProtocol: "tcp", CidrIpv6: "::/0" },
59
+ ]);
60
+ });
61
+
62
+ it("an all-protocols rule keeps the -1 the fold expects, and omits absent ports", () => {
63
+ // FromPort absent is "all ports" to normalizeIngress; emitting FromPort:
64
+ // undefined would render as a port range rather than `all`.
65
+ expect(toIngressRules([{ IpRanges: [{ CidrIp: "0.0.0.0/0" }] }])).toEqual([
66
+ { IpProtocol: "-1", CidrIp: "0.0.0.0/0" },
67
+ ]);
68
+ });
69
+
70
+ it("a permission with no source contributes nothing", () => {
71
+ expect(toIngressRules([{ IpProtocol: "tcp", FromPort: 22, ToPort: 22 }])).toEqual([]);
72
+ });
73
+ });
74
+
75
+
76
+ // #1276 — the case the benchmark estate deliberately cannot exercise, because
77
+ // it declares every security group. The fix matters precisely where an instance
78
+ // is guarded by a group nobody declared, so it is proven here rather than by
79
+ // changing a scenario a published comparison depends on.
80
+ describe("undeclared security groups (#1276)", () => {
81
+ beforeEach(() => spawnMock.mockReset());
82
+
83
+ const observedInstanceOnly = {
84
+ webServer: { type: "AWS::EC2::Instance", status: "CREATE_COMPLETE", physicalId: "i-1" },
85
+ };
86
+
87
+ it("reports a security group the estate never declared, with its rules", async () => {
88
+ respond({
89
+ "ec2 describe-instances": {
90
+ Reservations: [
91
+ {
92
+ Instances: [
93
+ { InstanceId: "i-1", SubnetId: "subnet-1", VpcId: "vpc-1", SecurityGroups: [{ GroupId: "sg-shared" }] },
94
+ ],
95
+ },
96
+ ],
97
+ },
98
+ "ec2 describe-route-tables": { RouteTables: [] },
99
+ "ec2 describe-security-groups": {
100
+ SecurityGroups: [
101
+ {
102
+ GroupId: "sg-shared",
103
+ VpcId: "vpc-1",
104
+ IpPermissions: [
105
+ { IpProtocol: "tcp", FromPort: 22, ToPort: 22, IpRanges: [{ CidrIp: "0.0.0.0/0" }] },
106
+ ],
107
+ },
108
+ ],
109
+ },
110
+ });
111
+
112
+ const { resources, edges } = await observeAwsDependencies({ observed: observedInstanceOnly });
113
+
114
+ // The group is a node now, so the fold can read its rules at all.
115
+ expect(resources["sg-shared"]).toMatchObject({
116
+ type: "AWS::EC2::SecurityGroup",
117
+ physicalId: "sg-shared",
118
+ referencedBy: ["webServer"],
119
+ });
120
+ // In the flat shape the fold reads — not the nested describe shape, which
121
+ // would render every source as `?` and match no CIDR query.
122
+ expect(resources["sg-shared"].attributes?.SecurityGroupIngress).toEqual([
123
+ { IpProtocol: "tcp", FromPort: 22, ToPort: 22, CidrIp: "0.0.0.0/0" },
124
+ ]);
125
+ expect(edges).toContainEqual({ from: "webServer", to: "sg-shared", kind: "ref", viaAttr: "SecurityGroupIds" });
126
+ });
127
+
128
+ it("does not report a group the estate already declares", async () => {
129
+ respond({
130
+ "ec2 describe-instances": {
131
+ Reservations: [
132
+ { Instances: [{ InstanceId: "i-1", SubnetId: "subnet-1", SecurityGroups: [{ GroupId: "sg-mine" }] }] },
133
+ ],
134
+ },
135
+ "ec2 describe-route-tables": { RouteTables: [] },
136
+ });
137
+
138
+ const { resources } = await observeAwsDependencies({
139
+ observed: {
140
+ ...observedInstanceOnly,
141
+ webSg: { type: "AWS::EC2::SecurityGroup", status: "CREATE_COMPLETE", physicalId: "sg-mine" },
142
+ },
143
+ });
144
+
145
+ // Declared resources are the managed observation's job. Reporting one here
146
+ // too would double it as both managed and dependency.
147
+ expect(resources["sg-mine"]).toBeUndefined();
148
+ });
149
+
150
+ it("follows a launch template to the groups it attaches", async () => {
151
+ respond({
152
+ "ec2 describe-instances": {
153
+ Reservations: [
154
+ {
155
+ Instances: [
156
+ {
157
+ InstanceId: "i-1",
158
+ SubnetId: "subnet-1",
159
+ SecurityGroups: [],
160
+ LaunchTemplate: { LaunchTemplateId: "lt-1" },
161
+ },
162
+ ],
163
+ },
164
+ ],
165
+ },
166
+ "ec2 describe-route-tables": { RouteTables: [] },
167
+ "ec2 describe-launch-template-versions": {
168
+ LaunchTemplateVersions: [{ LaunchTemplateData: { SecurityGroupIds: ["sg-via-lt"] } }],
169
+ },
170
+ "ec2 describe-security-groups": {
171
+ SecurityGroups: [
172
+ {
173
+ GroupId: "sg-via-lt",
174
+ IpPermissions: [
175
+ { IpProtocol: "tcp", FromPort: 22, ToPort: 22, IpRanges: [{ CidrIp: "0.0.0.0/0" }] },
176
+ ],
177
+ },
178
+ ],
179
+ },
180
+ });
181
+
182
+ const { resources, edges } = await observeAwsDependencies({ observed: observedInstanceOnly });
183
+
184
+ // The indirect hop — the one a flat describe-instances sweep misses, and
185
+ // the reason effectiveIngress is a fold rather than a passthrough.
186
+ expect(resources["lt-1"]).toMatchObject({ type: "AWS::EC2::LaunchTemplate" });
187
+ expect(resources["sg-via-lt"]).toMatchObject({ type: "AWS::EC2::SecurityGroup" });
188
+ expect(edges).toContainEqual({ from: "webServer", to: "lt-1", kind: "ref", viaAttr: "LaunchTemplateId" });
189
+ expect(edges).toContainEqual({ from: "lt-1", to: "sg-via-lt", kind: "ref", viaAttr: "SecurityGroupIds" });
190
+ });
191
+
192
+ it("an instance with no internet route still reports its groups", async () => {
193
+ // effectiveIngress is asked about instances that are not internet-facing
194
+ // too; guarding must not be conditional on routing.
195
+ respond({
196
+ "ec2 describe-instances": {
197
+ Reservations: [
198
+ { Instances: [{ InstanceId: "i-1", SubnetId: "subnet-private", SecurityGroups: [{ GroupId: "sg-shared" }] }] },
199
+ ],
200
+ },
201
+ "ec2 describe-route-tables": { RouteTables: [] },
202
+ "ec2 describe-security-groups": { SecurityGroups: [{ GroupId: "sg-shared", IpPermissions: [] }] },
203
+ });
204
+
205
+ const { resources } = await observeAwsDependencies({ observed: observedInstanceOnly });
206
+ expect(resources["sg-shared"]).toBeDefined();
207
+ });
208
+ });