Skip to content

Commit 2478c87

Browse files
committed
fix(graph): synthesise subnet nodes from VNet properties.subnets before edge detection
ARG Resources has no top-level rows for subnets; they are nested inside the parent VNet's properties.subnets. Without this, SubnetToResourceDetector and NsgToSubnetDetector produce edges whose target has no graph_node row, and _UPSERT_EDGE_SQL silently drops them (INSERT ... SELECT JOIN graph_nodes). _synthesise_subnet_resources() walks VNet resources, extracts each entry in properties.subnets, and returns synthetic InventoryResource objects inheriting the VNet's tenant_id, subscription_id, location and resource_group. populate_graph builds an augmented snapshot (dataclasses.replace on the frozen dataclass) before calling populate_nodes and detect_all_edges, so subnets get graph_nodes and the NSG->subnet->NIC path is traversable by BFS in #354. 7 new tests in test_graph_populator_subnet_synthesis.py use realistic ARG response fixtures (VNet with subnet, NSG, NIC, VM with user-assigned identity) and assert both the synthesis behaviour and the original bug (edge dropped without synthesis). Signed-off-by: Tanvir Farhad <tamimtarafder12@gmail.com>
1 parent 06db8ce commit 2478c87

2 files changed

Lines changed: 260 additions & 2 deletions

File tree

‎scanner/graph/graph_populator.py‎

Lines changed: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,13 @@
44

55
import logging
66
import uuid
7+
from dataclasses import replace as dc_replace
78
from typing import TYPE_CHECKING
89

910
import psycopg2
1011
import psycopg2.extras
1112

13+
from scanner.arg_inventory import InventoryResource
1214
from scanner.graph.node_service import link_findings_to_nodes, populate_nodes
1315
from scanner.graph.edge_detector import detect_all_edges
1416

@@ -69,17 +71,64 @@ def _write_edges(edges: list, snapshot_id: str, tenant_id: str, dsn: str) -> int
6971
return written
7072

7173

74+
_VNET_TYPE = "microsoft.network/virtualnetworks"
75+
_SUBNET_TYPE = "microsoft.network/virtualnetworks/subnets"
76+
77+
78+
def _synthesise_subnet_resources(snapshot: InventorySnapshot) -> list[InventoryResource]:
79+
"""Return synthetic InventoryResource entries for subnets nested inside VNets.
80+
81+
ARG Resources has no top-level rows for subnets; they appear only as
82+
properties.subnets on the parent VNet. Without this step, SubnetToResourceDetector
83+
and NsgToSubnetDetector produce edges whose target has no matching graph_node,
84+
and _UPSERT_EDGE_SQL silently drops them (INSERT ... SELECT JOIN graph_nodes).
85+
"""
86+
subnets: list[InventoryResource] = []
87+
for resource in snapshot.resources:
88+
if resource.resource_type.lower() != _VNET_TYPE:
89+
continue
90+
for subnet in resource.properties.get("subnets") or []:
91+
subnet_id = subnet.get("id") if isinstance(subnet, dict) else None
92+
if not subnet_id:
93+
continue
94+
subnet_name = subnet.get("name", subnet_id.split("/")[-1])
95+
subnets.append(
96+
InventoryResource(
97+
snapshot_id=resource.snapshot_id,
98+
tenant_id=resource.tenant_id,
99+
subscription_id=resource.subscription_id,
100+
resource_id=subnet_id,
101+
resource_type=_SUBNET_TYPE,
102+
name=subnet_name,
103+
location=resource.location,
104+
resource_group=resource.resource_group,
105+
tags={},
106+
properties=subnet.get("properties") or {},
107+
)
108+
)
109+
return subnets
110+
111+
72112
def populate_graph(scan_id: str, snapshot: InventorySnapshot, dsn: str) -> None:
73113
"""Populate nodes, edges, and finding links for one scan. Failure is non-fatal."""
114+
subnet_resources = _synthesise_subnet_resources(snapshot)
115+
if subnet_resources:
116+
logger.debug("graph: synthesised %d subnet nodes from VNet properties", len(subnet_resources))
117+
118+
augmented_snapshot = dc_replace(
119+
snapshot,
120+
resources=snapshot.resources + tuple(subnet_resources),
121+
)
122+
74123
try:
75-
node_count = populate_nodes(snapshot, dsn)
124+
node_count = populate_nodes(augmented_snapshot, dsn)
76125
logger.info("graph: upserted %d nodes for scan %s", node_count, scan_id)
77126
except Exception as exc:
78127
logger.warning("graph: node population failed for scan %s: %s", scan_id, exc)
79128
return
80129

81130
try:
82-
edges = detect_all_edges(snapshot)
131+
edges = detect_all_edges(augmented_snapshot)
83132
edge_count = _write_edges(edges, snapshot.snapshot_id, snapshot.tenant_id, dsn)
84133
logger.info("graph: wrote %d edges for scan %s", edge_count, scan_id)
85134
except Exception as exc:
Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
"""Tests for subnet node synthesis in graph_populator.
2+
3+
ARG Resources has no top-level rows for subnets — they are nested under the
4+
parent VNet's properties.subnets. _synthesise_subnet_resources extracts them
5+
so populate_graph can write graph_nodes for subnets and edge upserts succeed.
6+
"""
7+
8+
from scanner.arg_inventory import InventoryResource, InventorySnapshot, InventoryStatus
9+
from scanner.graph.graph_populator import _synthesise_subnet_resources
10+
11+
# Realistic ARG response shapes -------------------------------------------------
12+
# These mirror what Azure Resource Graph returns for a VNet with one subnet,
13+
# a NIC attached to that subnet, and a VM with a user-assigned identity.
14+
15+
_TENANT = "00000000-0000-0000-0000-000000000001"
16+
_SUB = "00000000-0000-0000-0000-000000000002"
17+
_SNAP = "snap-test-1"
18+
19+
_VNET_ID = (
20+
"/subscriptions/00000000-0000-0000-0000-000000000002"
21+
"/resourceGroups/rg-prod"
22+
"/providers/Microsoft.Network/virtualNetworks/vnet-prod"
23+
)
24+
_SUBNET_ID = _VNET_ID + "/subnets/default"
25+
_NSG_ID = (
26+
"/subscriptions/00000000-0000-0000-0000-000000000002"
27+
"/resourceGroups/rg-prod"
28+
"/providers/Microsoft.Network/networkSecurityGroups/nsg-prod"
29+
)
30+
_NIC_ID = (
31+
"/subscriptions/00000000-0000-0000-0000-000000000002"
32+
"/resourceGroups/rg-prod"
33+
"/providers/Microsoft.Network/networkInterfaces/nic-prod"
34+
)
35+
_VM_ID = (
36+
"/subscriptions/00000000-0000-0000-0000-000000000002"
37+
"/resourceGroups/rg-prod"
38+
"/providers/Microsoft.Compute/virtualMachines/vm-prod"
39+
)
40+
_IDENTITY_ID = (
41+
"/subscriptions/00000000-0000-0000-0000-000000000002"
42+
"/resourceGroups/rg-prod"
43+
"/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id-prod"
44+
)
45+
46+
47+
def _resource(resource_id, resource_type, properties=None):
48+
return InventoryResource(
49+
snapshot_id=_SNAP,
50+
tenant_id=_TENANT,
51+
subscription_id=_SUB,
52+
resource_id=resource_id,
53+
resource_type=resource_type,
54+
name=resource_id.split("/")[-1],
55+
location="uksouth",
56+
resource_group="rg-prod",
57+
tags={},
58+
properties=properties or {},
59+
)
60+
61+
62+
# ARG returns subnets nested inside the VNet properties.subnets array
63+
_VNET = _resource(
64+
_VNET_ID,
65+
"microsoft.network/virtualnetworks",
66+
{
67+
"subnets": [
68+
{
69+
"id": _SUBNET_ID,
70+
"name": "default",
71+
"properties": {
72+
"addressPrefix": "10.0.0.0/24",
73+
"networkSecurityGroup": {"id": _NSG_ID},
74+
},
75+
}
76+
],
77+
"addressSpace": {"addressPrefixes": ["10.0.0.0/16"]},
78+
},
79+
)
80+
81+
_NSG = _resource(
82+
_NSG_ID,
83+
"microsoft.network/networksecuritygroups",
84+
{"subnets": [{"id": _SUBNET_ID}]},
85+
)
86+
87+
# ARG returns NIC with ipConfigurations.properties.subnet.id
88+
_NIC = _resource(
89+
_NIC_ID,
90+
"microsoft.network/networkinterfaces",
91+
{
92+
"ipConfigurations": [
93+
{
94+
"properties": {
95+
"subnet": {"id": _SUBNET_ID},
96+
"privateIPAddress": "10.0.0.4",
97+
}
98+
}
99+
]
100+
},
101+
)
102+
103+
_VM = _resource(
104+
_VM_ID,
105+
"microsoft.compute/virtualmachines",
106+
{
107+
"identity": {
108+
"type": "UserAssigned",
109+
"userAssignedIdentities": {_IDENTITY_ID: {}},
110+
}
111+
},
112+
)
113+
114+
115+
def _snapshot(*resources):
116+
return InventorySnapshot(
117+
snapshot_id=_SNAP,
118+
tenant_id=_TENANT,
119+
requested_subscriptions=(_SUB,),
120+
status=InventoryStatus.COMPLETE,
121+
collected_at="2026-09-30T00:00:00+00:00",
122+
duration_ms=42,
123+
pages=1,
124+
resources=tuple(resources),
125+
errors=(),
126+
)
127+
128+
129+
# Tests -------------------------------------------------------------------------
130+
131+
132+
def test_synthesise_extracts_subnet_from_vnet():
133+
"""Subnet nested in VNet properties.subnets must produce a synthetic node."""
134+
snapshot = _snapshot(_VNET, _NSG, _NIC, _VM)
135+
subnets = _synthesise_subnet_resources(snapshot)
136+
assert len(subnets) == 1
137+
subnet = subnets[0]
138+
assert subnet.resource_id == _SUBNET_ID
139+
assert subnet.resource_type == "microsoft.network/virtualnetworks/subnets"
140+
assert subnet.tenant_id == _TENANT
141+
assert subnet.subscription_id == _SUB
142+
assert subnet.name == "default"
143+
assert subnet.location == "uksouth"
144+
145+
146+
def test_synthesise_subnet_inherits_vnet_metadata():
147+
"""Synthesised subnet must carry VNet's tenant_id, subscription_id and location."""
148+
snapshot = _snapshot(_VNET)
149+
subnets = _synthesise_subnet_resources(snapshot)
150+
assert subnets[0].snapshot_id == _SNAP
151+
assert subnets[0].resource_group == "rg-prod"
152+
153+
154+
def test_synthesise_subnet_properties_from_arg():
155+
"""Subnet properties block from ARG (addressPrefix, NSG link) must be preserved."""
156+
snapshot = _snapshot(_VNET)
157+
subnets = _synthesise_subnet_resources(snapshot)
158+
assert "addressPrefix" in subnets[0].properties
159+
assert subnets[0].properties["addressPrefix"] == "10.0.0.0/24"
160+
161+
162+
def test_synthesise_no_subnets_returns_empty():
163+
"""VNet with empty subnets list must not produce any synthetic nodes."""
164+
vnet_no_subnets = _resource(_VNET_ID, "microsoft.network/virtualnetworks", {"subnets": []})
165+
snapshot = _snapshot(vnet_no_subnets)
166+
assert _synthesise_subnet_resources(snapshot) == []
167+
168+
169+
def test_synthesise_non_vnet_resources_ignored():
170+
"""NSGs, NICs, and VMs must not produce subnet synthetics."""
171+
snapshot = _snapshot(_NSG, _NIC, _VM)
172+
assert _synthesise_subnet_resources(snapshot) == []
173+
174+
175+
def test_synthesise_missing_subnet_id_skipped():
176+
"""Subnet entry with no id field must be silently skipped."""
177+
vnet = _resource(
178+
_VNET_ID,
179+
"microsoft.network/virtualnetworks",
180+
{"subnets": [{"name": "broken", "properties": {}}]},
181+
)
182+
snapshot = _snapshot(vnet)
183+
assert _synthesise_subnet_resources(snapshot) == []
184+
185+
186+
def test_nsg_to_subnet_edge_requires_subnet_in_resource_ids():
187+
"""Confirm the original problem: SubnetToResourceDetector drops NIC->subnet
188+
when subnet is not in resource_ids. After synthesis it must be present."""
189+
from scanner.graph.edge_detector import SubnetToResourceDetector
190+
191+
# Without synthesis: NIC->subnet edge is dropped
192+
snapshot_no_subnet = _snapshot(_NSG, _NIC, _VM)
193+
edges_without = SubnetToResourceDetector().detect(snapshot_no_subnet)
194+
assert not any(e.target_resource_id == _SUBNET_ID for e in edges_without), (
195+
"subnet should not appear in edges when it has no node"
196+
)
197+
198+
# With synthesis: subnet is in resource_ids, edge is emitted
199+
subnets = _synthesise_subnet_resources(_snapshot(_VNET, _NSG, _NIC, _VM))
200+
from dataclasses import replace as dc_replace
201+
202+
augmented = dc_replace(
203+
snapshot_no_subnet,
204+
resources=snapshot_no_subnet.resources + tuple(subnets),
205+
)
206+
edges_with = SubnetToResourceDetector().detect(augmented)
207+
assert any(e.target_resource_id == _SUBNET_ID for e in edges_with), (
208+
"NIC->subnet MEMBER_OF edge must be present after subnet synthesis"
209+
)

0 commit comments

Comments
 (0)