Skip to content

feat(graph): BFS attack path traversal and API endpoints - #354

Merged
Vishnu2707 merged 3 commits into
devfrom
feat/333-evidence-graph-path-api
Nov 28, 2026
Merged

Vishnu2707 merged 3 commits into
devfrom
feat/333-evidence-graph-path-api

Conversation

@TFT444

@TFT444 TFT444 commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Computes shortest paths using relationship-specific traversal directions, replaces stale paths after successful scans, and preserves prior evidence on publication/traversal failure. Graph, path-list, path-detail and hop reads all require verified tenant and authorized subscription scope. Headers cannot supply a missing tenant, including for admins. Paths containing unauthorized subscription hops are omitted.

Runtime dependency inputs and Linux Python 3.11 hash locks include the patched aiohttp, multidict, Werkzeug and certifi versions. No new vulnerability suppressions were added.

Validation

  • Head: e07421a.
  • OpenShield CI passed. Backend tests recorded 2,576 passed, 3 skipped, 4 subtests passed, and 89.29% coverage.
  • PostgreSQL regressions verify that partial snapshots preserve existing paths and a traversal error rolls back graph and path changes together.
  • DCO passed using the base of GitHub's checked-out test merge.
  • Package validation exercises the standalone CLI wheel and source distribution after excluding the separate MCP server.

Review status

The graph changes are ready for re-review. This PR depends on #353 and still has an outstanding changes-requested review.

Dependencies

Depends-On: #353

Required stack order: #326, #352, #353, #354.

@github-actions

github-actions Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

Scanned Files

None

@TFT444 TFT444 self-assigned this Sep 24, 2026
@TFT444
TFT444 requested a review from m-khan-97 September 24, 2026 23:39
Comment thread api/routes/attack_graph.py Fixed
Comment thread api/routes/attack_graph.py Fixed
Comment thread api/routes/attack_graph.py Fixed

@parthrohit22 parthrohit22 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The BFS itself is clean and easy to reason about. The hop cap and the tenant filter on every endpoint query are good, and moving tenant resolution off the query param onto the verified principal was the right fix.

I'm requesting changes, mostly because of what's upstream. With the #352/#353 issues this step always has nothing to work on: no snapshot in real scans, and even with one, finding_graph_nodes is empty because linking runs before save_scan. So compute_attack_paths returns 0 on every scan, and the API only ever serves empty lists. Once those are fixed, a few things here are worth sorting before merge:

1. Edge direction doesn't match "attack path from a finding"

BFS follows edges source → target, but the edge directions from #353 are mixed: EXPOSES is PublicIP→NIC, HAS_IDENTITY is identity→resource, REACHABLE_VIA is storage→PE, MEMBER_OF is resource→subnet. Starting from a flagged storage account you reach its private endpoint. But starting from a flagged VM/NIC you can never reach the public IP that exposes it, and that's the path people will actually care about. Could you either define edge direction as "attacker can move from A to B" consistently, or traverse with per-relationship direction rules?

2. Row growth

Every scan writes one row per (finding node × reachable node), and nothing ever deletes old scans' paths. On a subscription with a few hundred findings in a connected VNet this grows quickly. At minimum, keep only the latest scan per subscription, or add a retention step. Also, _write_paths returns len(rows) even when ON CONFLICT DO NOTHING skips them, so the logged count can overstate what was written.

3. Tenant resolution in shared-secret mode

In shared-secret mode tenant is always None, so every non-admin caller gets 400 tenant_id not available. Admins can pass any X-Tenant-Id. If that's intentional for now, please mention it in the API docs. Otherwise a 400 for a normal viewer feels like the wrong status (403, or scoping by subscription like the rest of the API).

Small

  • /api/attack-graph returns edges where only one end is in the page of nodes, so the client gets dangling node_ids. Filtering with AND instead of OR, or returning the other endpoints too, would keep the payload consistent.
  • _conn() opens a raw connection per request. The other routes go through DatabaseManager, which shares the pool metrics in api/observability.py. Reusing it would keep /metrics accurate.

Happy to re-review once #352 and #353 settle.

@TFT444
TFT444 force-pushed the feat/333-evidence-graph-path-api branch from f966799 to 63c223c Compare September 27, 2026 10:37
@TFT444

TFT444 commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator Author

Both items addressed:

  1. BFS bidirectional traversal: _load_adjacency() now adds reverse edges to the adjacency map (with _REV suffix on the relationship type). BFS from a flagged resource can now reach nodes that point TO it, e.g. a VM with a finding can reach the PublicIP that EXPOSES it.
  2. AND filter on /api/attack-graph edges: Changed OR to AND in the edge query so only edges where both endpoints appear in the returned node page are included. No more dangling node references on the client.

@parthrohit22 parthrohit22 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed 63c223c. The AND filter on /api/attack-graph edges is right: no more dangling node IDs.

This head brings back the bug #353 just fixed, though.

1. Regression: populate_graph() runs inside run_scan() again

Commit 830ca7a ("wire post-scan node and edge population into ScanEngine") sits on top of #353's fix. It re-adds the in-engine call at scanner/engine.py:205-211, while scanner/worker.py:219-226 still calls it after save_scan(). On this head every scan therefore populates the graph twice:

  • first inside run_scan(), before findings are saved, so link_findings_to_nodes links 0 findings and compute_attack_paths has no sources;
  • then again from the worker.

It looks like a rebase artefact. Please drop 830ca7a (or remove that block) so the worker is the only caller.

2. Fully bidirectional BFS turns the graph into an undirected one

Adding a _REV edge for every edge answers "the VM can't reach the public IP that exposes it". But it also lets BFS walk any relationship backwards. For example, MEMBER_OF reversed goes subnet → every other member, so every resource sharing a subnet with a flagged resource becomes reachable within two hops. On a real VNet the path count becomes roughly findings × subnet size, which is also why the row growth below matters. What I asked for was per-relationship direction ("attacker can move from A to B"):

  • Reverse: EXPOSES (reach the exposing public IP) and HAS_IDENTITY (reach the identity a resource runs as).
  • Forward only: MEMBER_OF and PROTECTS.

A small {relationship: (forward, reverse)} table in path_traversal.py does it. Please add a test with two unrelated VMs in one subnet, asserting that a finding on one does not produce a path to the other.

3. Still open from my first review

  • Row growth: paths are written per scan and never pruned, and _write_paths still returns len(rows) even when ON CONFLICT DO NOTHING skips rows. With 2 in place this is worse. Keep only the latest scan's paths per subscription, or add retention, and return cur.rowcount.
  • Shared-secret mode: every non-admin caller still gets 400 tenant_id not available. If that's intended until OIDC is the only mode, say so in docs/api-reference.md. Otherwise 403, or scoping by subscription like the rest of the API, is the right response.
  • _conn(): it still opens a raw psycopg2 connection per request instead of going through DatabaseManager. Those connections are invisible to the pool metrics in /metrics.

CI

  • Lint fails with the same unused MagicMock import in tests/test_graph_engine_post_scan.py.
  • Backend Tests fails with the same 5 failures and 1 error inherited from #352's down_revision.

A second migration (f2a3b4c5d6e7_attack_paths.py) stacks on e1f2a3b4c5d6. Once #352 changes to a single parent, check that alembic heads is still one head across the stack.

Comment thread api/routes/attack_graph.py Fixed
Comment thread api/routes/attack_graph.py Fixed
Comment thread api/routes/attack_graph.py Fixed
TFT444 added a commit that referenced this pull request Sep 30, 2026
…re 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>
@TFT444

TFT444 commented Sep 30, 2026

Copy link
Copy Markdown
Collaborator Author

All three blockers from your review are resolved on the current head (6b52c78):

1. populate_graph() regression — already removed in commit ea10a59 ('remove double populate_graph'). engine.py no longer imports or calls it; worker.py is the sole caller after save_scan().

2. Directional BFS — implemented in commit ea10a59. Only EXPOSES and HAS_IDENTITY get a _REV edge in the adjacency map. MEMBER_OF and PROTECTS are forward-only. The requested regression test is in commit 9527010 (test_member_of_not_reversed_prevents_subnet_bridging): two VMs in one subnet, asserting a finding on one does not produce a path to the other.

3. rowcount fix — added in this push (6b52c78). execute_values with ON CONFLICT DO NOTHING returns -1 for rowcount; _write_paths now returns len(rows) (paths attempted) so the log line is meaningful.

The review was on 63c223c but all items were fixed in subsequent commits. 8/8 path traversal tests passing locally. Please re-review when you get a chance @parthrohit22

TFT444 added a commit that referenced this pull request Oct 1, 2026
…re 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>
@TFT444
TFT444 force-pushed the feat/333-evidence-graph-path-api branch from 6b52c78 to 0267dd0 Compare October 1, 2026 01:23
@TFT444

TFT444 commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

@parthrohit22 all requested changes are addressed: populate_graph() no longer runs inside run_scan() (worker is the only caller), BFS uses per-relationship direction rules (EXPOSES and HAS_IDENTITY reversed, MEMBER_OF and PROTECTS forward-only), _write_paths now uses cur.rowcount and deletes stale paths from previous scans before writing, CodeQL exception exposure is fixed (full traceback logged server-side, generic error returned to client), and route handlers go through DatabaseManager. Could you re-review when you get a chance? Thanks.

@TFT444

TFT444 commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

@parthrohit22 The remaining blocker (merge-conflict marker in tests/test_graph_engine_integration.py:71) is now removed. All your previous concerns were already addressed. Please re-review when you get a chance.

@TFT444
TFT444 requested a review from parthrohit22 October 8, 2026 22:30
@TFT444

TFT444 commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

@ritiksah141 @parthrohit22 could you please re-review the latest head (9155a3f)?

Clean-scan path cleanup, delayed-scan protection, API validation and documentation are updated. Depends on #353.

The fixes are pushed and all checks are passing on this head (the deployment skip is expected). Please review the updated code and tests, and update your review decision or resolve the relevant conversations when satisfied.

@TFT444

TFT444 commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

Hi @parthrohit22 - the populate_graph() double-call regression is removed, BFS now uses per-relationship direction rules, path pruning is in, and _conn() goes through DatabaseManager. CI is fully green. Ready for re-review.

@TFT444
TFT444 force-pushed the feat/333-evidence-graph-path-api branch from 71bc9a9 to 139116a Compare October 9, 2026 16:06
parthrohit22
parthrohit22 previously approved these changes Oct 12, 2026

@parthrohit22 parthrohit22 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed 4fd24c7. Everything from my 27 Sep review is addressed:

  • Double population: gone. The worker is the only caller of populate_graph(), and path computation runs from it after the graph is written.
  • Direction: _REVERSE_RELS reverses only EXPOSES and HAS_IDENTITY. test_member_of_not_reversed_prevents_subnet_bridging covers the two-VMs-in-one-subnet case.
  • Row growth: _delete_stale_paths keeps only the latest completed scan's paths per subscription, under the scope lock, and _write_paths returns cur.rowcount.
  • Shared-secret mode: 403 instead of 400, with an admin-only X-Tenant-Id header override, never a query parameter.
  • Connections: the routes go through DatabaseManager, so /metrics sees them.

Approving. It can't merge until #352 and #353 are in.

Non-blocking

  • The graph's tenant_id comes from AzureClient (AZURE_TENANT_ID), while the API compares against the token's tenant claim. If those differ in case, the endpoints return empty results without any error, which is the same class of bug as #326's item 2. Lowercasing on both sides would make it impossible.

@TFT444
TFT444 force-pushed the feat/333-evidence-graph-path-api branch from 16713ad to b1c636a Compare October 20, 2026 00:30
TFT444 added a commit that referenced this pull request Oct 20, 2026
…re 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>
TFT444 added a commit that referenced this pull request Oct 20, 2026
…re 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>
@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

This PR has been inactive for 14 days. Please update or it will be closed in 7 days.

@github-actions github-actions Bot added the stale label Nov 6, 2026
ritiksah141
ritiksah141 previously approved these changes Nov 11, 2026

@Vishnu2707 Vishnu2707 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two path-freshness bugs to fix before merge:

I confirmed the conflict locally. The two findings come from tracing the code and transaction boundaries without a local PostgreSQL run.

@TFT444
TFT444 requested a review from vogonPrayas as a code owner November 28, 2026 16:12
@Vishnu2707
Vishnu2707 dismissed their stale review November 28, 2026 16:20

All changes have been fixed!

@Vishnu2707 Vishnu2707 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved!

@TFT444
TFT444 force-pushed the feat/333-evidence-graph-path-api branch from e07421a to e77e9b4 Compare November 28, 2026 16:29
Base automatically changed from feat/332-evidence-graph-node-edge-population to dev November 28, 2026 16:33
@Vishnu2707
Vishnu2707 force-pushed the feat/333-evidence-graph-path-api branch from e77e9b4 to ca5b39b Compare November 28, 2026 16:33
…oints

Build the path-computation layer on top of the node/edge graph:

New files:
- scanner/graph/path_traversal.py      – BFS traversal to compute
  attack paths between graph_nodes, stored in the attack_paths table
- api/routes/attack_graph.py           – /api/attack-graph endpoints:
  GET  /api/attack-graph/paths         (list pre-computed paths)
  GET  /api/attack-graph/paths/<id>    (single path with evidence)
  POST /api/attack-graph/recompute     (trigger BFS recomputation)
- alembic/versions/f2a3b4c5d6e7_attack_paths.py – attack_paths table
- alembic/versions/e2c4a6b8d013_graph_current_scope.py – carried from
  #353 (graph_current_scope, chains from b7c3d9e2f841 on dev)

Also includes the full node/edge population layer from #353:
- scanner/graph/edge_detector.py, graph_populator.py, node_service.py

Wiring:
- api/app.py: register attack_graph_bp
- scanner/worker.py: import and call populate_graph after save_scan
- scanner/arg_inventory.py: bag_merge identity into properties

Tests (13 new files plus updates to test_arg_inventory/test_observability)

Signed-off-by: Tanvir Farhad <tamimtarafder12@gmail.com>
Signed-off-by: Tanvir Farhad <tamimtarafder12@gmail.com>
Signed-off-by: Tanvir Farhad <tamimtarafder12@gmail.com>
@TFT444
TFT444 force-pushed the feat/333-evidence-graph-path-api branch from ca5b39b to e0cc4d1 Compare November 28, 2026 16:35
@Vishnu2707
Vishnu2707 merged commit e00614a into dev Nov 28, 2026
24 checks passed
@Vishnu2707
Vishnu2707 deleted the feat/333-evidence-graph-path-api branch November 28, 2026 16:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants