apisec-surface 0.1.13__py3-none-any.whl

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 (164) hide show
  1. apisec_code_bolt/__init__.py +48 -0
  2. apisec_code_bolt/__main__.py +11 -0
  3. apisec_code_bolt/analysis/__init__.py +96 -0
  4. apisec_code_bolt/analysis/analyzer.py +3518 -0
  5. apisec_code_bolt/analysis/binding_tracker.py +384 -0
  6. apisec_code_bolt/analysis/boundary_detection.py +809 -0
  7. apisec_code_bolt/analysis/call_graph.py +1397 -0
  8. apisec_code_bolt/analysis/call_graph_types.py +332 -0
  9. apisec_code_bolt/analysis/call_resolver.py +1155 -0
  10. apisec_code_bolt/analysis/capability_tagger.py +322 -0
  11. apisec_code_bolt/analysis/config_scanner.py +781 -0
  12. apisec_code_bolt/analysis/container_facts.py +320 -0
  13. apisec_code_bolt/analysis/data_flow.py +1972 -0
  14. apisec_code_bolt/analysis/dependency_extractor.py +3539 -0
  15. apisec_code_bolt/analysis/flow_analysis.py +1406 -0
  16. apisec_code_bolt/analysis/hof_catalog.py +61 -0
  17. apisec_code_bolt/analysis/integration_detector.py +1864 -0
  18. apisec_code_bolt/analysis/js_gradle_locks.py +277 -0
  19. apisec_code_bolt/analysis/legacy_contract.py +210 -0
  20. apisec_code_bolt/analysis/literal_scanner.py +579 -0
  21. apisec_code_bolt/analysis/manifest_partitioner.py +500 -0
  22. apisec_code_bolt/analysis/parse_index.py +87 -0
  23. apisec_code_bolt/analysis/path_normalizer.py +55 -0
  24. apisec_code_bolt/analysis/path_resolution_ladder.py +73 -0
  25. apisec_code_bolt/analysis/read_site_detector.py +326 -0
  26. apisec_code_bolt/analysis/request_patterns.py +168 -0
  27. apisec_code_bolt/analysis/route_like.py +23 -0
  28. apisec_code_bolt/analysis/secret_patterns.py +404 -0
  29. apisec_code_bolt/analysis/secrets_policy.py +246 -0
  30. apisec_code_bolt/analysis/sensitivity_classifier.py +249 -0
  31. apisec_code_bolt/analysis/sink_evidence.py +333 -0
  32. apisec_code_bolt/analysis/surface_enrichment.py +519 -0
  33. apisec_code_bolt/analysis/surface_ledger.py +146 -0
  34. apisec_code_bolt/analysis/surface_reconciliation.py +68 -0
  35. apisec_code_bolt/analysis/template_scanner.py +1020 -0
  36. apisec_code_bolt/analysis/tree_resolver.py +203 -0
  37. apisec_code_bolt/analysis/unsupported_frameworks.py +422 -0
  38. apisec_code_bolt/analysis/url_prefix_resolver.py +985 -0
  39. apisec_code_bolt/analysis/version_resolver.py +366 -0
  40. apisec_code_bolt/cli/__init__.py +5 -0
  41. apisec_code_bolt/cli/exit_codes.py +18 -0
  42. apisec_code_bolt/cli/main.py +1785 -0
  43. apisec_code_bolt/cloud/__init__.py +1 -0
  44. apisec_code_bolt/cloud/apisec_client.py +233 -0
  45. apisec_code_bolt/cloud/client.py +446 -0
  46. apisec_code_bolt/core/__init__.py +81 -0
  47. apisec_code_bolt/core/config.py +624 -0
  48. apisec_code_bolt/core/credentials.py +65 -0
  49. apisec_code_bolt/core/discovery.py +523 -0
  50. apisec_code_bolt/core/log_format.py +133 -0
  51. apisec_code_bolt/core/manifest.py +1390 -0
  52. apisec_code_bolt/core/memory_guard.py +423 -0
  53. apisec_code_bolt/core/repo.py +287 -0
  54. apisec_code_bolt/core/runtime_entry_points.py +45 -0
  55. apisec_code_bolt/core/state.py +75 -0
  56. apisec_code_bolt/core/telemetry.py +485 -0
  57. apisec_code_bolt/core/types.py +603 -0
  58. apisec_code_bolt/fingerprinting/__init__.py +1 -0
  59. apisec_code_bolt/frameworks/__init__.py +29 -0
  60. apisec_code_bolt/frameworks/_graphql_common.py +45 -0
  61. apisec_code_bolt/frameworks/_jwt_common.py +50 -0
  62. apisec_code_bolt/frameworks/_weak_random_common.py +140 -0
  63. apisec_code_bolt/frameworks/auth_helpers.py +437 -0
  64. apisec_code_bolt/frameworks/base.py +735 -0
  65. apisec_code_bolt/frameworks/dotnet/__init__.py +19 -0
  66. apisec_code_bolt/frameworks/dotnet/_path_helpers.py +43 -0
  67. apisec_code_bolt/frameworks/dotnet/aspnet_plugin.py +3092 -0
  68. apisec_code_bolt/frameworks/dotnet/grpc_plugin.py +559 -0
  69. apisec_code_bolt/frameworks/dotnet/jwt_config_extractor.py +545 -0
  70. apisec_code_bolt/frameworks/dotnet/legacy_aspnet_plugin.py +732 -0
  71. apisec_code_bolt/frameworks/dotnet/refit_plugin.py +374 -0
  72. apisec_code_bolt/frameworks/dotnet/taint_scanner.py +1597 -0
  73. apisec_code_bolt/frameworks/dotnet/wcf_plugin.py +1239 -0
  74. apisec_code_bolt/frameworks/dotnet/webforms_plugin.py +393 -0
  75. apisec_code_bolt/frameworks/java/__init__.py +7 -0
  76. apisec_code_bolt/frameworks/java/_annotations.py +377 -0
  77. apisec_code_bolt/frameworks/java/_constraints.py +128 -0
  78. apisec_code_bolt/frameworks/java/graphql_plugin.py +280 -0
  79. apisec_code_bolt/frameworks/java/jaxrs_plugin.py +813 -0
  80. apisec_code_bolt/frameworks/java/jwt_config_extractor.py +361 -0
  81. apisec_code_bolt/frameworks/java/micronaut_plugin.py +1121 -0
  82. apisec_code_bolt/frameworks/java/servlet_plugin.py +380 -0
  83. apisec_code_bolt/frameworks/java/spring_plugin.py +1491 -0
  84. apisec_code_bolt/frameworks/java/taint_scanner.py +2910 -0
  85. apisec_code_bolt/frameworks/js/__init__.py +9 -0
  86. apisec_code_bolt/frameworks/js/_route_helpers.py +30 -0
  87. apisec_code_bolt/frameworks/js/express_plugin.py +430 -0
  88. apisec_code_bolt/frameworks/js/fastify_plugin.py +421 -0
  89. apisec_code_bolt/frameworks/js/graphql_plugin.py +191 -0
  90. apisec_code_bolt/frameworks/js/koa_plugin.py +283 -0
  91. apisec_code_bolt/frameworks/js/nestjs_plugin.py +410 -0
  92. apisec_code_bolt/frameworks/js/taint_scanner.py +2715 -0
  93. apisec_code_bolt/frameworks/python/__init__.py +19 -0
  94. apisec_code_bolt/frameworks/python/celery_plugin.py +393 -0
  95. apisec_code_bolt/frameworks/python/click_plugin.py +427 -0
  96. apisec_code_bolt/frameworks/python/django_plugin.py +990 -0
  97. apisec_code_bolt/frameworks/python/fastapi/__init__.py +28 -0
  98. apisec_code_bolt/frameworks/python/fastapi/plugin.py +1741 -0
  99. apisec_code_bolt/frameworks/python/flask_plugin.py +748 -0
  100. apisec_code_bolt/frameworks/python/graphql_plugin.py +257 -0
  101. apisec_code_bolt/frameworks/python/prefect_plugin.py +251 -0
  102. apisec_code_bolt/frameworks/python/taint_scanner.py +1953 -0
  103. apisec_code_bolt/frameworks/python/weak_hash_facts.py +159 -0
  104. apisec_code_bolt/frameworks/python/webhook_plugin.py +255 -0
  105. apisec_code_bolt/frameworks/ruby/__init__.py +24 -0
  106. apisec_code_bolt/frameworks/ruby/_ts_helpers.py +16 -0
  107. apisec_code_bolt/frameworks/ruby/action_cable_plugin.py +152 -0
  108. apisec_code_bolt/frameworks/ruby/grape_plugin.py +486 -0
  109. apisec_code_bolt/frameworks/ruby/graphql_plugin.py +358 -0
  110. apisec_code_bolt/frameworks/ruby/hanami_plugin.py +254 -0
  111. apisec_code_bolt/frameworks/ruby/padrino_plugin.py +114 -0
  112. apisec_code_bolt/frameworks/ruby/rails_plugin.py +1098 -0
  113. apisec_code_bolt/frameworks/ruby/roda_plugin.py +260 -0
  114. apisec_code_bolt/frameworks/ruby/sidekiq_plugin.py +208 -0
  115. apisec_code_bolt/frameworks/ruby/sinatra_plugin.py +478 -0
  116. apisec_code_bolt/frameworks/ruby/taint_scanner.py +2772 -0
  117. apisec_code_bolt/frameworks/ruby/weak_hash_facts.py +192 -0
  118. apisec_code_bolt/parsing/__init__.py +62 -0
  119. apisec_code_bolt/parsing/base.py +555 -0
  120. apisec_code_bolt/parsing/csharp/__init__.py +5 -0
  121. apisec_code_bolt/parsing/csharp/language_services.py +203 -0
  122. apisec_code_bolt/parsing/csharp/literals.py +72 -0
  123. apisec_code_bolt/parsing/csharp/parser.py +1158 -0
  124. apisec_code_bolt/parsing/csharp/type_resolver.py +568 -0
  125. apisec_code_bolt/parsing/js/__init__.py +5 -0
  126. apisec_code_bolt/parsing/js/language_services.py +118 -0
  127. apisec_code_bolt/parsing/js/parser.py +677 -0
  128. apisec_code_bolt/parsing/jvm/__init__.py +7 -0
  129. apisec_code_bolt/parsing/jvm/language_services.py +555 -0
  130. apisec_code_bolt/parsing/jvm/member_reference.py +11 -0
  131. apisec_code_bolt/parsing/jvm/parser.py +954 -0
  132. apisec_code_bolt/parsing/jvm/type_resolver.py +422 -0
  133. apisec_code_bolt/parsing/python/__init__.py +150 -0
  134. apisec_code_bolt/parsing/python/cbv_extractor.py +606 -0
  135. apisec_code_bolt/parsing/python/constant_resolver.py +500 -0
  136. apisec_code_bolt/parsing/python/cross_file_resolver.py +1106 -0
  137. apisec_code_bolt/parsing/python/dynamic_route_detector.py +532 -0
  138. apisec_code_bolt/parsing/python/expression_utils.py +221 -0
  139. apisec_code_bolt/parsing/python/extraction_types.py +271 -0
  140. apisec_code_bolt/parsing/python/language_services.py +487 -0
  141. apisec_code_bolt/parsing/python/parameter_analyzer.py +855 -0
  142. apisec_code_bolt/parsing/python/parser.py +751 -0
  143. apisec_code_bolt/parsing/python/path_resolver.py +576 -0
  144. apisec_code_bolt/parsing/python/router_registry.py +964 -0
  145. apisec_code_bolt/parsing/python/type_resolver.py +730 -0
  146. apisec_code_bolt/parsing/python/visitors.py +1581 -0
  147. apisec_code_bolt/parsing/ruby/__init__.py +5 -0
  148. apisec_code_bolt/parsing/ruby/language_services.py +807 -0
  149. apisec_code_bolt/parsing/ruby/parser.py +342 -0
  150. apisec_code_bolt/parsing/services.py +544 -0
  151. apisec_code_bolt/pkgindex/__init__.py +15 -0
  152. apisec_code_bolt/pkgindex/indexer.py +319 -0
  153. apisec_code_bolt/pkgindex/metadata.py +333 -0
  154. apisec_code_bolt/pkgindex/module_graph.py +318 -0
  155. apisec_code_bolt/pkgindex/package_source.py +447 -0
  156. apisec_code_bolt/query/__init__.py +1 -0
  157. apisec_code_bolt/query/ast_cache.py +215 -0
  158. apisec_code_bolt/query/executor.py +481 -0
  159. apisec_code_bolt/query/handlers.py +1232 -0
  160. apisec_code_bolt/query/manifest_context.py +313 -0
  161. apisec_surface-0.1.13.dist-info/METADATA +541 -0
  162. apisec_surface-0.1.13.dist-info/RECORD +164 -0
  163. apisec_surface-0.1.13.dist-info/WHEEL +4 -0
  164. apisec_surface-0.1.13.dist-info/entry_points.txt +3 -0
@@ -0,0 +1,3518 @@
1
+ """
2
+ Main analysis orchestrator for generating manifests.
3
+
4
+ This module coordinates:
5
+ - File discovery
6
+ - Parsing (Python, Java)
7
+ - Framework detection and extraction
8
+ - Data flow analysis
9
+ - Manifest generation
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import logging
16
+ import time
17
+ from dataclasses import dataclass, field
18
+ from datetime import datetime
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from pydantic import ValidationError
23
+
24
+ from ..core.config import CodeBoltConfig
25
+ from ..core.discovery import DiscoveryResult, discover_files
26
+ from ..core.manifest import (
27
+ MANIFEST_VERSION,
28
+ AnalysisMetadataModel,
29
+ AuthDependencyModel,
30
+ AuthModel,
31
+ AuthSchemeModel,
32
+ BodyFieldModel,
33
+ CallContextModel,
34
+ CapabilityModel,
35
+ ClassModel,
36
+ ConfigurationModel,
37
+ ContainerPrivilegeFactModel,
38
+ DataFlowModel,
39
+ EnvVarUsageModel,
40
+ FunctionCallModel,
41
+ FunctionModel,
42
+ HttpBodyModel,
43
+ HttpParameterModel,
44
+ IntegrationModel,
45
+ JwtConfigModel,
46
+ LiteralPatternModel,
47
+ LiteralsModel,
48
+ LocationModel,
49
+ Manifest,
50
+ MiddlewareModel,
51
+ ParameterModel,
52
+ ProjectMetadata,
53
+ RouteAuthModel,
54
+ RouteModel,
55
+ SchemaFieldModel,
56
+ SchemaModel,
57
+ WeakHashFactModel,
58
+ is_global_auth_middleware,
59
+ stable_id,
60
+ )
61
+ from ..core.memory_guard import MemoryWatchdog
62
+ from ..core.types import Framework, Language
63
+ from ..frameworks import dotnet as _dotnet_fw # noqa: F401 — registers AspNetCorePlugin
64
+ from ..frameworks import java as _java_fw # noqa: F401 — registers SpringBootPlugin
65
+ from ..frameworks.base import FrameworkPluginRegistry
66
+ from ..parsing import csharp as _csharp_pkg # noqa: F401 — registers CSharpParser
67
+ from ..parsing import js as _js_pkg # noqa: F401 — registers JavaScriptParser
68
+ from ..parsing import jvm as _jvm_pkg # noqa: F401 — registers JavaParser
69
+ from ..parsing import ruby as _ruby_pkg # noqa: F401 — registers RubyParser
70
+ from ..parsing.base import ParsedFile, ParserRegistry
71
+ from ..parsing.csharp.language_services import CSharpLanguageServices
72
+ from ..parsing.js.language_services import JavaScriptLanguageServices
73
+ from ..parsing.jvm import language_services as _jvm_lang_services # noqa: F401
74
+ from ..parsing.jvm.language_services import JavaLanguageServices
75
+ from ..parsing.python.language_services import PythonLanguageServices
76
+ from ..parsing.python.parser import PythonProjectParser
77
+ from ..parsing.python.type_resolver import SchemaBuilder, TypeResolver
78
+ from ..parsing.ruby.language_services import RubyLanguageServices
79
+ from ..parsing.services import AnalysisContext, LanguageServices
80
+ from .boundary_detection import (
81
+ BoundaryDetectionResult,
82
+ build_boundary_index,
83
+ detect_boundaries,
84
+ match_boundary,
85
+ )
86
+ from .call_graph import CallGraph, build_call_graph_with_context
87
+ from .data_flow import DataFlowAnalyzer
88
+ from .dependency_extractor import DependencyExtractor
89
+ from .flow_analysis import build_flow_sensitive_bindings
90
+ from .manifest_partitioner import PartitionedManifest, partition_manifest
91
+ from .unsupported_frameworks import detect_unsupported_frameworks
92
+
93
+
94
+ def _auto_discover_plugins() -> None:
95
+ """Import all framework plugins to trigger their self-registration."""
96
+ import importlib
97
+ import pkgutil
98
+
99
+ from .. import frameworks as _fw_pkg
100
+
101
+ for _importer, mod_name, _is_pkg in pkgutil.walk_packages(
102
+ _fw_pkg.__path__,
103
+ prefix=_fw_pkg.__name__ + ".",
104
+ ):
105
+ if "plugin" in mod_name or mod_name.endswith("_plugin"):
106
+ try:
107
+ importlib.import_module(mod_name)
108
+ except Exception as e: # noqa: BLE001
109
+ logger.debug("Could not load framework plugin %s: %s", mod_name, e)
110
+
111
+
112
+ _auto_discover_plugins()
113
+
114
+
115
+ logger = logging.getLogger(__name__)
116
+
117
+
118
+ def _get_probe_version() -> str:
119
+ try:
120
+ from .. import __version__
121
+
122
+ return __version__
123
+ except Exception:
124
+ return "0.1.0"
125
+
126
+
127
+ # =============================================================================
128
+ # Analysis Result
129
+ # =============================================================================
130
+
131
+
132
+ @dataclass
133
+ class AnalysisWarning:
134
+ """A non-fatal issue encountered during analysis."""
135
+
136
+ phase: str
137
+ message: str
138
+ file: str | None = None
139
+ detail: str | None = None
140
+
141
+
142
+ @dataclass
143
+ class AnalysisResult:
144
+ """Result of analysis containing manifest and metadata."""
145
+
146
+ manifest: Manifest
147
+
148
+ # Statistics
149
+ files_analyzed: int = 0
150
+ files_failed: int = 0
151
+ parse_errors: list[str] = field(default_factory=list)
152
+
153
+ # Non-fatal warnings accumulated during analysis
154
+ warnings: list[AnalysisWarning] = field(default_factory=list)
155
+
156
+ # Timing — top-level
157
+ discovery_time_ms: int = 0
158
+ parse_time_ms: int = 0
159
+ extraction_time_ms: int = 0
160
+ total_time_ms: int = 0
161
+
162
+ # Timing — full per-stage breakdown (stage_name → ms)
163
+ stage_times_ms: dict[str, int] = field(default_factory=dict)
164
+
165
+ # Timing — per-framework-plugin extraction (framework_name → ms across all files)
166
+ extractor_times_ms: dict[str, int] = field(default_factory=dict)
167
+
168
+ # Per-language file counts (language name → count)
169
+ files_by_language: dict[str, int] = field(default_factory=dict)
170
+
171
+ # Per-language parse failures (language name → count)
172
+ failures_by_language: dict[str, int] = field(default_factory=dict)
173
+
174
+ # Files excluded by discovery (gitignore, --exclude, --max-files, unknown extension)
175
+ files_skipped: int = 0
176
+
177
+ # Per-framework route counts (framework_name → route count)
178
+ routes_by_framework: dict[str, int] = field(default_factory=dict)
179
+
180
+ # Structured parse errors with file + line + message (replaces plain strings)
181
+ parse_error_details: list[dict[str, Any]] = field(default_factory=list)
182
+
183
+ # Detected frameworks
184
+ frameworks_detected: list[Framework] = field(default_factory=list)
185
+
186
+ # Monorepo sub-project partitions of `manifest` — always at least one
187
+ # element (the whole-manifest wrapper when no boundaries are detected).
188
+ partitions: list[PartitionedManifest] = field(default_factory=list)
189
+
190
+
191
+ # =============================================================================
192
+ # Analyzer
193
+ # =============================================================================
194
+
195
+
196
+ class ProjectAnalyzer:
197
+ """
198
+ Main analyzer for extracting manifest from a project.
199
+
200
+ Coordinates:
201
+ 1. File discovery
202
+ 2. Parsing files by language
203
+ 3. Framework detection
204
+ 4. Route/dependency/auth extraction
205
+ 5. Data flow analysis
206
+ 6. Manifest generation
207
+ """
208
+
209
+ def __init__(self, config: CodeBoltConfig) -> None:
210
+ self.config = config
211
+
212
+ # Parsers
213
+ self._python_parser = PythonProjectParser()
214
+ self._type_resolver = TypeResolver()
215
+ self._schema_builder = SchemaBuilder(self._type_resolver)
216
+
217
+ # Language services (builds context for each language)
218
+ self._language_services: dict[Language, LanguageServices] = {
219
+ Language.PYTHON: PythonLanguageServices(),
220
+ Language.JAVA: JavaLanguageServices(),
221
+ Language.CSHARP: CSharpLanguageServices(),
222
+ Language.JAVASCRIPT: JavaScriptLanguageServices(),
223
+ Language.RUBY: RubyLanguageServices(),
224
+ }
225
+
226
+ # Analysis contexts per language (built during analysis)
227
+ self._analysis_contexts: dict[Language, AnalysisContext] = {}
228
+
229
+ # Express parent-router auth middleware map, built during context setup.
230
+ # Maps resolved file path str → list of auth middleware variable names
231
+ # that apply to routes in that file (inherited from parent router mounts).
232
+ self._express_parent_auth_map: dict[str, list[str]] = {}
233
+
234
+ # Parsed data
235
+ self._parsed_files: dict[Path, ParsedFile] = {}
236
+ self._discovery_result: DiscoveryResult | None = None
237
+
238
+ # Monorepo sub-project boundaries — computed once during the discover
239
+ # stage (needs only project_root + file_discovery config, not any
240
+ # parsed data) and reused both by auth-middleware scoping during
241
+ # extraction and by manifest partitioning at the end of analyze().
242
+ self._boundary_result: BoundaryDetectionResult | None = None
243
+
244
+ # Call graph
245
+ self._call_graph: CallGraph | None = None
246
+
247
+ # Data flow analysis results (for manifest metadata)
248
+ self._data_flow_stats: dict[str, int] = {}
249
+
250
+ # Shared flow-sensitive bindings (built once, reused by call graph + data flow)
251
+ self._flow_bindings: Any = None
252
+
253
+ # Framework plugins
254
+ self._detected_frameworks: set[Framework] = set()
255
+
256
+ # Per-plugin extraction timing (populated by _extract_all_routes)
257
+ self._extractor_times_ms: dict[str, int] = {}
258
+
259
+ # Accumulated non-fatal warnings
260
+ self._warnings: list[AnalysisWarning] = []
261
+
262
+ self._entry_points_withheld_unresolved: int = 0
263
+ self._runtime_gate_warnings: list[str] = []
264
+ self._surface_ledger: Any = None
265
+ self._enrichment_rejected: dict[str, int] = {}
266
+
267
+ # Proactive memory guard (see core/memory_guard.py). A long large-repo
268
+ # run used to end as an OS kill — rc=-9, empty result, no message — and
269
+ # SIGKILL cannot be caught, so the only defence is to notice the
270
+ # process is heading for that wall and stop first with a diagnostic.
271
+ self._memory_watchdog = MemoryWatchdog(project_root=config.project_root)
272
+
273
+ # Pipeline stage definitions: (name, method_name)
274
+ _PIPELINE_STAGES: list[tuple[str, str]] = [
275
+ ("discover", "_stage_discover"),
276
+ ("parse", "_stage_parse"),
277
+ ("resolve", "_stage_resolve"),
278
+ ("detect_frameworks", "_stage_detect_frameworks"),
279
+ ("flow_bindings", "_stage_flow_bindings"),
280
+ ("call_graph", "_stage_call_graph"),
281
+ ("extract", "_stage_extract"),
282
+ ("analyze_flows", "_stage_analyze_flows"),
283
+ ("enrich", "_stage_enrich"),
284
+ ]
285
+
286
+ def analyze(self) -> AnalysisResult:
287
+ """
288
+ Analyze the project and generate manifest.
289
+
290
+ Runs a named pipeline of stages. Each stage is independently
291
+ testable and reports its own timing.
292
+ """
293
+ start_time = time.perf_counter()
294
+ stage_times: dict[str, int] = {}
295
+ ctx: dict[str, Any] = {}
296
+
297
+ for stage_name, method_name in self._PIPELINE_STAGES:
298
+ # Safe point for the memory guard: the stage that follows is about
299
+ # to allocate, so this is the last cheap place to stop cleanly.
300
+ self._check_memory(stage_name)
301
+ stage_start = time.perf_counter()
302
+ stage_fn = getattr(self, method_name)
303
+ stage_fn(ctx)
304
+ stage_times[stage_name] = int((time.perf_counter() - stage_start) * 1000)
305
+ logger.debug("Stage '%s' completed in %dms", stage_name, stage_times[stage_name])
306
+
307
+ total_time_ms = int((time.perf_counter() - start_time) * 1000)
308
+
309
+ # The manifest build allocates most of the result at once (every route,
310
+ # function, class and flow becomes a model), so it gets its own check.
311
+ self._check_memory("manifest")
312
+ manifest = self._build_manifest(
313
+ routes=ctx["routes"],
314
+ functions=ctx["functions"],
315
+ classes=ctx["classes"],
316
+ calls=ctx["calls"],
317
+ data_flows=ctx["data_flows"],
318
+ auth=ctx["auth"],
319
+ middleware=ctx["middleware"],
320
+ dependencies=ctx["pkg_dependencies"],
321
+ integrations=ctx["integrations"],
322
+ capabilities=ctx["capabilities"],
323
+ schemas=ctx["schemas"],
324
+ literals=ctx["literals"],
325
+ weak_hash_facts=ctx["weak_hash_facts"],
326
+ container_facts=ctx["container_facts"],
327
+ configuration=ctx["config_data"],
328
+ analysis_time_ms=total_time_ms,
329
+ )
330
+
331
+ # Monorepo boundary detection + partitioning — a read-only view over
332
+ # the manifest just built above; `_build_manifest` itself is never
333
+ # touched. Detection is gated to 0 or 1 boundary => a single-element
334
+ # identity wrapper, so single-project repos are byte-for-byte
335
+ # unaffected by this step. Reuses the same BoundaryDetectionResult
336
+ # computed during the discover stage (also used to scope
337
+ # auth-middleware attribution in _populate_route_auth_mapping) rather
338
+ # than detecting boundaries a second time.
339
+ boundary_result = self._boundary_result or BoundaryDetectionResult()
340
+ partitions = partition_manifest(
341
+ manifest, boundary_result.boundaries, self.config.project_root, self._parsed_files
342
+ )
343
+
344
+ # Build both legacy string errors and structured error details
345
+ parse_errors: list[str] = []
346
+ parse_error_details: list[dict[str, Any]] = []
347
+ for path, parsed in self._parsed_files.items():
348
+ if not parsed.success and parsed.error:
349
+ err = parsed.error
350
+ parse_errors.append(f"{path}: {err}")
351
+ detail: dict[str, Any] = {
352
+ "file": str(path),
353
+ "error": str(err),
354
+ }
355
+ if hasattr(err, "line") and err.line is not None:
356
+ detail["line"] = err.line
357
+ if hasattr(err, "column") and err.column is not None:
358
+ detail["column"] = err.column
359
+ parse_error_details.append(detail)
360
+
361
+ # Per-language file counts from the parsed file registry
362
+ files_by_language: dict[str, int] = {}
363
+ failures_by_language: dict[str, int] = {}
364
+ for parsed in self._parsed_files.values():
365
+ lang_name = parsed.language.name.lower() if parsed.language else "unknown"
366
+ if parsed.success:
367
+ files_by_language[lang_name] = files_by_language.get(lang_name, 0) + 1
368
+ else:
369
+ failures_by_language[lang_name] = failures_by_language.get(lang_name, 0) + 1
370
+
371
+ # Per-framework route counts from the manifest
372
+ routes_by_framework: dict[str, int] = {}
373
+ for ep in manifest.entry_points:
374
+ fw = (ep.framework or "unknown").lower()
375
+ routes_by_framework[fw] = routes_by_framework.get(fw, 0) + 1
376
+
377
+ return AnalysisResult(
378
+ manifest=manifest,
379
+ files_analyzed=len([p for p in self._parsed_files.values() if p.success]),
380
+ files_failed=len([p for p in self._parsed_files.values() if not p.success]),
381
+ files_skipped=self._discovery_result.total_skipped if self._discovery_result else 0,
382
+ parse_errors=parse_errors,
383
+ parse_error_details=parse_error_details,
384
+ warnings=list(self._warnings),
385
+ discovery_time_ms=stage_times.get("discover", 0),
386
+ parse_time_ms=stage_times.get("parse", 0),
387
+ extraction_time_ms=stage_times.get("extract", 0),
388
+ total_time_ms=total_time_ms,
389
+ stage_times_ms=dict(stage_times),
390
+ extractor_times_ms=self._extractor_times_ms,
391
+ files_by_language=files_by_language,
392
+ failures_by_language=failures_by_language,
393
+ routes_by_framework=routes_by_framework,
394
+ frameworks_detected=list(self._detected_frameworks),
395
+ partitions=partitions,
396
+ )
397
+
398
+ # -- Pipeline stage implementations ----------------------------------------
399
+
400
+ def _check_memory(self, stage: str, files_processed: int | None = None) -> None:
401
+ """Proactive RSS check at a safe point in the pipeline.
402
+
403
+ Called at stage boundaries and inside the loops whose memory grows with
404
+ the size of the repository (the parse and extract loops). Under the
405
+ ceiling it is a no-op, so an ordinary run is unaffected; over it, the
406
+ guard raises `MemoryLimitExceeded` and the run stops with a diagnostic
407
+ naming the limit — instead of being killed by the OS with no message.
408
+ Must stay outside any broad `except Exception` in this module: an abort
409
+ the pipeline swallows is an abort nobody hears.
410
+ """
411
+ files = len(self._parsed_files) if files_processed is None else files_processed
412
+ self._memory_watchdog.check(stage=stage, files_processed=files)
413
+
414
+ def _stage_discover(self, ctx: dict[str, Any]) -> None:
415
+ logger.info("Discovering files in %s", self.config.project_root)
416
+ self._discovery_result = discover_files(
417
+ self.config.project_root,
418
+ self.config.analysis.file_discovery,
419
+ )
420
+ logger.info(
421
+ "Discovered %d files, skipped %d",
422
+ self._discovery_result.total_selected,
423
+ self._discovery_result.total_skipped,
424
+ )
425
+ self._boundary_result = detect_boundaries(
426
+ self.config.project_root, self.config.analysis.file_discovery
427
+ )
428
+
429
+ def _stage_parse(self, ctx: dict[str, Any]) -> None:
430
+ self._parse_all_files()
431
+
432
+ def _stage_resolve(self, ctx: dict[str, Any]) -> None:
433
+ self._build_cross_file_resolver()
434
+
435
+ def _stage_detect_frameworks(self, ctx: dict[str, Any]) -> None:
436
+ self._detect_frameworks()
437
+
438
+ def _stage_flow_bindings(self, ctx: dict[str, Any]) -> None:
439
+ self._build_shared_flow_bindings()
440
+
441
+ def _stage_call_graph(self, ctx: dict[str, Any]) -> None:
442
+ self._build_call_graph()
443
+
444
+ def _stage_extract(self, ctx: dict[str, Any]) -> None:
445
+ raw_routes = self._extract_all_routes()
446
+ ctx["routes"] = self._apply_group_prefixes(raw_routes)
447
+ ctx["dependencies"] = self._extract_all_dependencies()
448
+ ctx["auth"] = self._extract_auth_data()
449
+ ctx["middleware"] = self._extract_middleware()
450
+ self._propagate_file_auth_to_routes(ctx["routes"], ctx["auth"])
451
+ self._propagate_express_parent_auth_to_routes(ctx["routes"])
452
+ self._propagate_django_class_auth_to_routes(ctx["routes"], ctx["auth"])
453
+ self._propagate_django_decorator_auth_to_routes(ctx["routes"], ctx["auth"])
454
+ self._propagate_rails_auth_to_routes(ctx["routes"], ctx["auth"])
455
+ self._apply_spring_filter_chain_policy(ctx["routes"])
456
+ self._populate_route_object_references(ctx["routes"])
457
+ # Compute route_auth_mapping AFTER all propagation passes so that
458
+ # router_name set by Rails/Django/Spring propagation is considered.
459
+ self._populate_route_auth_mapping(ctx["auth"], ctx["routes"], ctx["middleware"])
460
+ self._populate_route_authorization(ctx["auth"], ctx["routes"])
461
+ # Link routes to auth schemes using the freshly computed mapping.
462
+ self._link_routes_to_auth_schemes(ctx["routes"], ctx["auth"])
463
+ self._infer_pydantic_route_bodies(ctx["routes"])
464
+ ctx["calls"] = self._extract_all_calls()
465
+ self._surface_ledger = self._build_project_surface_ledger(ctx["routes"])
466
+ self._apply_runtime_entry_point_gate(ctx)
467
+
468
+ def _apply_runtime_entry_point_gate(self, ctx: dict[str, Any]) -> None:
469
+ from ..core.runtime_entry_points import (
470
+ partition_runtime_entry_points,
471
+ withheld_entry_point_warnings,
472
+ )
473
+
474
+ all_routes: list[RouteModel] = ctx["routes"]
475
+ kept, withheld = partition_runtime_entry_points(all_routes)
476
+ self._entry_points_withheld_unresolved = len(withheld)
477
+ self._runtime_gate_warnings = withheld_entry_point_warnings(withheld)
478
+ kept_ids = {route.id for route in kept}
479
+ ctx["routes"] = kept
480
+ self._prune_auth_route_mappings(ctx["auth"], kept_ids)
481
+
482
+ @staticmethod
483
+ def _prune_auth_route_mappings(auth: AuthModel, kept_route_ids: set[str]) -> None:
484
+ if not kept_route_ids:
485
+ auth.route_auth_mapping = []
486
+ return
487
+ auth.route_auth_mapping = [
488
+ mapping for mapping in auth.route_auth_mapping if mapping.route_id in kept_route_ids
489
+ ]
490
+
491
+ def _build_project_surface_ledger(self, routes: list[Any]) -> Any:
492
+ from ..frameworks.base import FrameworkPluginRegistry
493
+ from .surface_ledger import _rel_path, build_surface_ledger
494
+
495
+ plugins = []
496
+ for fw in self._detected_frameworks:
497
+ p = FrameworkPluginRegistry.get_plugin(fw)
498
+ if p is not None:
499
+ plugins.append(p)
500
+ by_file: dict[str, int] = {}
501
+ for route in routes:
502
+ loc = getattr(route, "handler_location", None)
503
+ if loc is None:
504
+ continue
505
+ rel = _rel_path(loc.file, self.config.project_root)
506
+ by_file[rel] = by_file.get(rel, 0) + 1
507
+ return build_surface_ledger(
508
+ project_root=self.config.project_root,
509
+ parsed_files=self._parsed_files,
510
+ plugins=plugins,
511
+ static_routes_by_file=by_file,
512
+ )
513
+
514
+ def _index_dependency_internals(self, dependencies: Any) -> None:
515
+ """
516
+ Fill the platform's transitive-reachability cache for this project's
517
+ dependencies (docs: ApisecSoftwareCompositionAnalysis REACHABILITY.md).
518
+
519
+ A scan's own call graph only names directly-imported packages; the cache
520
+ supplies each dependency's internal graph so a transitive advisory can be
521
+ judged reachable or not.
522
+
523
+ Deliberately best-effort. It is network work that a scan does not depend
524
+ on: a published version is immutable, so the first project to encounter it
525
+ pays once and everyone after reads the cache. Any failure here must leave
526
+ the scan's own results untouched.
527
+ """
528
+ cfg = self.config.package_index
529
+ if not cfg.enabled or not cfg.platform_url:
530
+ return
531
+
532
+ packages = [
533
+ (p.name, p.version)
534
+ for p in getattr(dependencies, "packages", [])
535
+ if p.version and (p.ecosystem or cfg.ecosystem) == cfg.ecosystem
536
+ ]
537
+ if not packages:
538
+ return
539
+
540
+ try:
541
+ from apisec_code_bolt.pkgindex import PackageIndexer
542
+
543
+ indexer = PackageIndexer(
544
+ cfg.platform_url,
545
+ admin_key=cfg.admin_key,
546
+ ecosystem=cfg.ecosystem,
547
+ timeout=cfg.timeout_seconds,
548
+ )
549
+ result = indexer.run(packages)
550
+ logger.info(
551
+ "Package index: %d considered, %d already cached, %d newly indexed, %d failed",
552
+ result.considered,
553
+ result.already_indexed,
554
+ result.indexed,
555
+ result.failed,
556
+ )
557
+ except Exception as e: # noqa: BLE001 - never fail a scan on enrichment
558
+ logger.warning("Package indexing skipped: %s", e)
559
+
560
+ def _stage_analyze_flows(self, ctx: dict[str, Any]) -> None:
561
+ ctx["data_flows"], _ = self._analyze_data_flows(ctx["routes"])
562
+ ctx["integrations"] = self._detect_integrations()
563
+ ctx["literals"] = self._scan_literals()
564
+ ctx["weak_hash_facts"] = self._detect_weak_hash_facts()
565
+ self._classify_sensitivity(ctx["integrations"], ctx["literals"])
566
+
567
+ def _stage_enrich(self, ctx: dict[str, Any]) -> None:
568
+ dep_extractor = DependencyExtractor(
569
+ self.config.project_root,
570
+ self._parsed_files,
571
+ maven_resolve=self.config.analysis.jvm.maven_resolve,
572
+ )
573
+ ctx["pkg_dependencies"] = dep_extractor.extract()
574
+ self._index_dependency_internals(ctx["pkg_dependencies"])
575
+ ctx["config_data"] = self._extract_configuration()
576
+ ctx["container_facts"] = self._detect_container_facts()
577
+ ctx["literals"].secret_patterns.extend(self._scan_config_file_secrets())
578
+ ctx["capabilities"] = self._tag_capabilities(
579
+ ctx["integrations"],
580
+ ctx["routes"],
581
+ ctx["config_data"],
582
+ )
583
+ functions, func_id_index = self._collect_all_functions()
584
+ ctx["functions"] = functions
585
+ ctx["classes"] = self._collect_all_classes(func_id_index)
586
+ ctx["schemas"] = self._collect_schemas(ctx["routes"])
587
+
588
+ # =========================================================================
589
+ # Parsing
590
+ # =========================================================================
591
+
592
+ def _parse_all_files(self) -> None:
593
+ """Parse all discovered files using registry-based language dispatch."""
594
+ if not self._discovery_result:
595
+ return
596
+
597
+ # Group files by language
598
+ files_by_lang: dict[Language, list[Path]] = {}
599
+ for f in self._discovery_result.files:
600
+ if f.language:
601
+ files_by_lang.setdefault(f.language, []).append(f.path)
602
+
603
+ for language, file_paths in files_by_lang.items():
604
+ parser = ParserRegistry.get_parser(language)
605
+ if parser is None:
606
+ logger.info(
607
+ "Found %d %s files (no parser registered)",
608
+ len(file_paths),
609
+ language.name,
610
+ )
611
+ continue
612
+
613
+ logger.info("Parsing %d %s files", len(file_paths), language.name)
614
+
615
+ # Use PythonProjectParser for Python (has cross-file resolution).
616
+ # The bulk parse is where a large repo grows fastest (every file's
617
+ # AST is kept for the rest of the run), so it reports progress back
618
+ # to the memory guard once per parsed file.
619
+ if language == Language.PYTHON:
620
+ self._parsed_files.update(
621
+ self._python_parser.parse_project(
622
+ file_paths,
623
+ progress=lambda done: self._check_memory("parse", done),
624
+ )
625
+ )
626
+ else:
627
+ for files_parsed, path in enumerate(file_paths):
628
+ # Sampled at most once per watchdog interval, so a per-file
629
+ # ask costs nothing measurable.
630
+ self._check_memory("parse", files_parsed)
631
+ try:
632
+ parsed = parser.parse_file(path)
633
+ self._parsed_files[path] = parsed
634
+ except Exception as e:
635
+ logger.warning("Failed to parse %s: %s", path, e)
636
+
637
+ def _build_analysis_contexts(self) -> None:
638
+ """
639
+ Build analysis contexts for each language using LanguageServices.
640
+
641
+ This replaces the old approach of manually building each resolver.
642
+ Now each language provides a factory that builds all required services.
643
+ """
644
+ if not self._parsed_files:
645
+ return
646
+
647
+ # Group parsed files by language
648
+ files_by_language: dict[Language, list[ParsedFile]] = {}
649
+ for parsed in self._parsed_files.values():
650
+ if not parsed.success:
651
+ continue
652
+ lang = parsed.language
653
+ if lang not in files_by_language:
654
+ files_by_language[lang] = []
655
+ files_by_language[lang].append(parsed)
656
+
657
+ # Build context for each language
658
+ for language, files in files_by_language.items():
659
+ if language not in self._language_services:
660
+ logger.warning(f"No language services available for {language.name}")
661
+ continue
662
+
663
+ services = self._language_services[language]
664
+
665
+ # Detect primary framework for this language
666
+ framework = self._detect_primary_framework(files, language)
667
+ framework_name = framework.name.lower() if framework else None
668
+
669
+ # Every framework present in this language's files. The primary
670
+ # picks the analysis context; per-framework wiring below keys off
671
+ # the full set so a second framework in the same language is not
672
+ # silently skipped.
673
+ frameworks_present = self._detect_frameworks_for_files(files)
674
+
675
+ logger.info(
676
+ f"Building analysis context for {language.name} (framework: {framework_name})"
677
+ )
678
+
679
+ # Build context using the language services factory
680
+ context = services.build_context(
681
+ parsed_files=files,
682
+ project_root=self.config.project_root,
683
+ framework=framework_name,
684
+ )
685
+
686
+ # Wire URL prefix maps for Django, Flask, and Express/NestJS.
687
+ #
688
+ # Gated on every framework present in this language's files rather
689
+ # than on the single primary. Gating on the primary meant a repo
690
+ # holding two Python frameworks built only the winner's map: crAPI
691
+ # scanned at its root resolves Python to Django, so the Flask
692
+ # service's Blueprint prefixes were never composed and all 8 of its
693
+ # routes kept their uncomposed paths. Scanning that one service
694
+ # directly worked, which is why it passed review and failed QA.
695
+ if language == Language.PYTHON:
696
+ if Framework.DJANGO in frameworks_present:
697
+ try:
698
+ from .url_prefix_resolver import build_django_prefix_map
699
+
700
+ pm = build_django_prefix_map(files, project_root=self.config.project_root)
701
+ context.language_services["_url_prefix_map"] = pm
702
+ logger.debug("Django prefix map built: %d entries", len(pm))
703
+ if not pm:
704
+ logger.info(
705
+ "Django detected but its URL prefix map is empty; "
706
+ "routes will be reported at their unprefixed paths"
707
+ )
708
+ except Exception as e:
709
+ # Was logger.debug: a failure here silently downgrades
710
+ # every Django route to an unprefixed path, with no
711
+ # operator signal that the paths are wrong.
712
+ logger.warning("Django prefix map failed: %s", e)
713
+
714
+ if Framework.FLASK in frameworks_present:
715
+ try:
716
+ from .url_prefix_resolver import build_flask_prefix_map
717
+
718
+ # Distinct key from Django/Express's "_url_prefix_map":
719
+ # Flask's map is keyed per-Blueprint-variable within a
720
+ # file, not just per-file (see build_flask_prefix_map's
721
+ # docstring for why a file-level map isn't precise enough
722
+ # here).
723
+ pm = build_flask_prefix_map(files, project_root=self.config.project_root)
724
+ context.language_services["_flask_blueprint_prefix_map"] = pm
725
+ logger.debug("Flask blueprint prefix map built: %d entries", len(pm))
726
+ if not pm:
727
+ logger.info(
728
+ "Flask detected but no Blueprint url_prefix was resolved; "
729
+ "routes will be reported at their unprefixed paths"
730
+ )
731
+ except Exception as e:
732
+ logger.warning("Flask blueprint prefix map failed: %s", e)
733
+ elif language == Language.JAVASCRIPT:
734
+ try:
735
+ from .url_prefix_resolver import (
736
+ build_express_auth_middleware_map,
737
+ build_express_prefix_map,
738
+ )
739
+
740
+ pm = build_express_prefix_map(files, project_root=self.config.project_root)
741
+ context.language_services["_url_prefix_map"] = pm
742
+ logger.debug("Express prefix map built: %d entries", len(pm))
743
+
744
+ am = build_express_auth_middleware_map(files)
745
+ self._express_parent_auth_map = am
746
+ logger.debug("Express auth middleware map built: %d entries", len(am))
747
+ except Exception as e:
748
+ logger.warning("Express prefix/auth map failed: %s", e)
749
+
750
+ self._analysis_contexts[language] = context
751
+
752
+ # Log statistics
753
+ if context.type_resolver:
754
+ models = context.type_resolver.get_all_models()
755
+ logger.info(f" - Resolved {len(models)} model types")
756
+
757
+ if context.constant_resolver:
758
+ constants = context.constant_resolver.get_all_constants()
759
+ logger.info(f" - Resolved {len(constants)} constants")
760
+
761
+ if context.router_registry:
762
+ routers = context.router_registry.get_all_routers()
763
+ logger.info(f" - Registered {len(routers)} routers")
764
+
765
+ def _detect_frameworks_for_files(
766
+ self,
767
+ files: list[ParsedFile],
768
+ ) -> set[Framework]:
769
+ """Every framework detected among ``files``, not just the most common.
770
+
771
+ ``_detect_primary_framework`` collapses a language down to one winner,
772
+ which is the right input for building a single analysis context but the
773
+ wrong gate for per-framework wiring: a repo holding both a Django and a
774
+ Flask service resolves Python to whichever has more files, and anything
775
+ keyed off that primary is skipped entirely for the other framework.
776
+ """
777
+ detected: set[Framework] = set()
778
+ for parsed_file in files:
779
+ detected.update(FrameworkPluginRegistry.detect_frameworks(parsed_file))
780
+ return detected
781
+
782
+ def _detect_primary_framework(
783
+ self,
784
+ files: list[ParsedFile],
785
+ language: Language,
786
+ ) -> Framework | None:
787
+ """Detect the primary framework for a set of files."""
788
+ framework_counts: dict[Framework, int] = {}
789
+
790
+ for parsed_file in files:
791
+ detected = FrameworkPluginRegistry.detect_frameworks(parsed_file)
792
+ for fw in detected:
793
+ framework_counts[fw] = framework_counts.get(fw, 0) + 1
794
+
795
+ if not framework_counts:
796
+ return None
797
+
798
+ # Return the most common framework
799
+ return max(framework_counts, key=framework_counts.get)
800
+
801
+ # Backward compatibility alias
802
+ def _build_cross_file_resolver(self) -> None:
803
+ """Build cross-file resolution (alias for _build_analysis_contexts)."""
804
+ self._build_analysis_contexts()
805
+
806
+ def _build_shared_flow_bindings(self) -> None:
807
+ """Build flow-sensitive bindings once for reuse by call graph and data flow."""
808
+ successful_files = [p for p in self._parsed_files.values() if p.success]
809
+ if not successful_files:
810
+ return
811
+ try:
812
+ self._flow_bindings = build_flow_sensitive_bindings(successful_files)
813
+ logger.info("Built shared flow-sensitive bindings for %d files", len(successful_files))
814
+ except Exception as e:
815
+ logger.warning("Could not build flow-sensitive bindings: %s", e)
816
+ self._flow_bindings = None
817
+
818
+ def _build_call_graph(self) -> None:
819
+ """Build the call graph for inter-procedural analysis."""
820
+ if not self._parsed_files:
821
+ return
822
+
823
+ logger.info("Building call graph...")
824
+
825
+ # Get successfully parsed files
826
+ successful_files = [parsed for parsed in self._parsed_files.values() if parsed.success]
827
+
828
+ if not successful_files:
829
+ logger.warning("No successfully parsed files for call graph")
830
+ return
831
+
832
+ # Get the primary analysis context (prefer Python, fall back to Java, then C#)
833
+ context = (
834
+ self._analysis_contexts.get(Language.PYTHON)
835
+ or self._analysis_contexts.get(Language.JAVA)
836
+ or self._analysis_contexts.get(Language.CSHARP)
837
+ )
838
+
839
+ try:
840
+ if context:
841
+ self._call_graph = build_call_graph_with_context(
842
+ successful_files,
843
+ context,
844
+ flow_bindings=self._flow_bindings,
845
+ )
846
+ else:
847
+ from .call_graph import build_call_graph
848
+
849
+ self._call_graph = build_call_graph(
850
+ successful_files,
851
+ project_root=self.config.project_root,
852
+ flow_bindings=self._flow_bindings,
853
+ )
854
+
855
+ stats = self._call_graph.get_statistics()
856
+ logger.info(
857
+ f"Call graph built: {stats['internal_nodes']} internal functions, "
858
+ f"{stats['total_edges']} call edges"
859
+ )
860
+ logger.info(f" - Entry points: {stats['entry_points']}")
861
+ logger.info(f" - Resolution confidence: {stats['resolution_confidence']}")
862
+
863
+ except ImportError as e:
864
+ logger.warning(f"Could not build call graph: {e}")
865
+
866
+ def _detect_frameworks(self) -> None:
867
+ """Detect frameworks used in parsed files."""
868
+ for parsed_file in self._parsed_files.values():
869
+ if not parsed_file.success:
870
+ continue
871
+
872
+ detected = FrameworkPluginRegistry.detect_frameworks(parsed_file)
873
+ self._detected_frameworks.update(detected)
874
+
875
+ logger.info(f"Detected frameworks: {[f.name for f in self._detected_frameworks]}")
876
+
877
+ # =========================================================================
878
+ # Route Extraction
879
+ # =========================================================================
880
+
881
+ def _extract_all_routes(self) -> list[RouteModel]:
882
+ """Extract routes from all parsed files using analysis contexts."""
883
+ routes: list[RouteModel] = []
884
+
885
+ # Build plugin list from the language-keyed registry so that multiple
886
+ # plugins sharing the same Framework enum value (e.g. GraphQLPythonPlugin
887
+ # and GraphQLJavaPlugin both register as Framework.GRAPHQL) are both
888
+ # included. get_plugin(fw) returns only one entry per framework key and
889
+ # would silently drop the second registrant.
890
+ seen_plugin_ids: set[int] = set()
891
+ plugins = []
892
+ for language in Language:
893
+ for plugin in FrameworkPluginRegistry.get_plugins_for_language(language):
894
+ if (
895
+ plugin.framework in self._detected_frameworks
896
+ and id(plugin) not in seen_plugin_ids
897
+ ):
898
+ seen_plugin_ids.add(id(plugin))
899
+ plugins.append(plugin)
900
+
901
+ # Per-plugin wall-clock accumulator: framework_name → total ms
902
+ plugin_times: dict[str, int] = {}
903
+
904
+ # Extract routes from each file
905
+ files_extracted = 0
906
+ for parsed_file in self._parsed_files.values():
907
+ if not parsed_file.success:
908
+ continue
909
+
910
+ self._check_memory("extract", files_extracted)
911
+ files_extracted += 1
912
+
913
+ # Get analysis context for this file's language
914
+ context = self._analysis_contexts.get(parsed_file.language)
915
+
916
+ for plugin in plugins:
917
+ if not plugin.detect(parsed_file):
918
+ continue
919
+
920
+ # Extract routes, passing context when supported
921
+ if hasattr(plugin, "extract_routes"):
922
+ fw_key = plugin.framework.name.lower()
923
+ _t0 = time.perf_counter()
924
+ try:
925
+ extracted_routes = plugin.extract_routes(parsed_file, context=context)
926
+ except TypeError:
927
+ self._setup_legacy_plugin(plugin, parsed_file.language)
928
+ extracted_routes = plugin.extract_routes(parsed_file)
929
+
930
+ elapsed_ms = int((time.perf_counter() - _t0) * 1000)
931
+ plugin_times[fw_key] = plugin_times.get(fw_key, 0) + elapsed_ms
932
+
933
+ framework_name = plugin.framework.name.lower()
934
+ for route in extracted_routes:
935
+ ep_id = stable_id(
936
+ "ep",
937
+ route.method.name,
938
+ route.path,
939
+ route.handler_function.full,
940
+ )
941
+ routes.append(self._convert_route(route, ep_id, framework=framework_name))
942
+
943
+ self._extractor_times_ms = plugin_times
944
+ return routes
945
+
946
+ # =========================================================================
947
+ # Group Prefix Propagation (cross-file module → endpoint extension pattern)
948
+ # =========================================================================
949
+
950
+ def _apply_group_prefixes(self, routes: list[RouteModel]) -> list[RouteModel]:
951
+ """Prepend MapGroup prefix to routes registered via the module-extension pattern.
952
+
953
+ Handles three patterns:
954
+ 1. Cross-file: module file calls MapGroup + extension methods; handler files
955
+ define those methods.
956
+ 2. Same-file: file calls MapGroup and registers routes on the result directly
957
+ (e.g. ``var api = app.MapGroup("x"); api.MapGet("/y", ...)``)
958
+ 3. Program.cs auth: an outer file calls ``handler.MapXxxApi().RequireAuthorization()``
959
+ without its own MapGroup; auth is propagated to the handler file's routes.
960
+ """
961
+ import re as _re
962
+
963
+ _STANDARD_MAP = frozenset(
964
+ {
965
+ "MapGet",
966
+ "MapPost",
967
+ "MapPut",
968
+ "MapDelete",
969
+ "MapPatch",
970
+ "MapIdentityApi",
971
+ "MapGroup",
972
+ "MapHub",
973
+ }
974
+ )
975
+
976
+ # ── Step 1: collect extension-method names per file ──────────────────
977
+ # Static methods whose first parameter is IEndpointRouteBuilder or similar.
978
+ ext_methods_by_file: dict[str, set[str]] = {}
979
+ for file_path, parsed_file in self._parsed_files.items():
980
+ if not parsed_file.success:
981
+ continue
982
+ for cls in parsed_file.classes:
983
+ for method in cls.methods:
984
+ if method.binding != "static" or not method.parameters:
985
+ continue
986
+ first_type = (method.parameters[0].type_annotation or "").split("<")[0].strip()
987
+ if first_type in (
988
+ "IEndpointRouteBuilder",
989
+ "RouteGroupBuilder",
990
+ "WebApplication",
991
+ "IApplicationBuilder",
992
+ ):
993
+ ext_methods_by_file.setdefault(str(file_path), set()).add(method.name)
994
+
995
+ # Reverse map: extension method name → file that defines it
996
+ ext_method_to_file: dict[str, str] = {}
997
+ for file_path, method_names in ext_methods_by_file.items():
998
+ for method_name in method_names:
999
+ ext_method_to_file[method_name] = file_path
1000
+
1001
+ # ── Step 2: scan all files for group patterns ─────────────────────────
1002
+ # group_registry: ext_method_name → (prefix, auth, anon) [cross-file pattern]
1003
+ group_registry: dict[str, tuple[str, bool, bool]] = {}
1004
+ # same_file_prefix_map: file_path → (prefix, auth, anon) [same-file pattern, single prefix]
1005
+ same_file_prefix_map: dict[str, tuple[str, bool, bool]] = {}
1006
+ # same_file_multi_map: file_path → sorted [(group_line, prefix, has_auth)]
1007
+ # Used when a file has multiple MapGroup prefixes (e.g. versioned API)
1008
+ same_file_multi_map: dict[str, list[tuple[int, str, bool]]] = {}
1009
+ # program_auth_overrides: handler file paths that get auth from an outer caller
1010
+ program_auth_overrides: set[str] = set()
1011
+
1012
+ for file_path_obj, parsed_file in self._parsed_files.items():
1013
+ file_path = str(file_path_obj)
1014
+ if not parsed_file.success:
1015
+ continue
1016
+
1017
+ # Find MapGroup calls with literal prefix arguments
1018
+ group_lines: dict[int, str] = {} # start_line → prefix
1019
+ for call in parsed_file.call_sites:
1020
+ if call.callee_name.split(".")[-1] != "MapGroup":
1021
+ continue
1022
+ if not call.arguments or not call.arguments[0].is_literal:
1023
+ continue
1024
+ raw = str(call.arguments[0].literal_value or "")
1025
+ # Resolve API versioning placeholder → v1
1026
+ raw = _re.sub(r"v\{[^}]*[Vv]ersion[^}]*\}", "v1", raw)
1027
+ # Strip remaining route constraints: {id:int} → {id}
1028
+ raw = _re.sub(r"\{([^:}]+):[^}]+\}", r"{\1}", raw)
1029
+ prefix = "/" + raw.strip("/") if raw else ""
1030
+ line = call.location.line if call.location else -1
1031
+ if line > 0:
1032
+ group_lines[line] = prefix
1033
+
1034
+ # Build the full chain-line set for fluent group chaining
1035
+ chain_lines: set[int] = set(group_lines.keys())
1036
+ changed = True
1037
+ while changed:
1038
+ changed = False
1039
+ for call in parsed_file.call_sites:
1040
+ recv = call.receiver_expression or ""
1041
+ if not recv.startswith("line:"):
1042
+ continue
1043
+ try:
1044
+ target = int(recv[5:])
1045
+ except ValueError:
1046
+ continue
1047
+ if target in chain_lines:
1048
+ ln = call.location.line if call.location else -1
1049
+ if ln > 0 and ln not in chain_lines:
1050
+ chain_lines.add(ln)
1051
+ changed = True
1052
+
1053
+ # Group-level auth: RequireAuthorization chained on the group
1054
+ has_group_auth = False
1055
+ for call in parsed_file.call_sites:
1056
+ if call.callee_name.split(".")[-1] != "RequireAuthorization":
1057
+ continue
1058
+ recv = call.receiver_expression or ""
1059
+ if not recv.startswith("line:"):
1060
+ continue
1061
+ if recv[5:].isdigit() and int(recv[5:]) in chain_lines:
1062
+ has_group_auth = True
1063
+ break
1064
+
1065
+ # Find calls to custom Map* extension methods (non-standard, non-chained).
1066
+ # These are calls like ``group.MapCreateBrandEndpoint()`` where the method
1067
+ # is a project-defined extension, not one of the standard Map* helpers.
1068
+ # Note: _STANDARD_MAP filters out MapGet/Post/etc; we keep any custom Map*
1069
+ # regardless of receiver name so that group variables named "api", "v1" etc.
1070
+ # are also captured.
1071
+ ext_call_lines: dict[str, int] = {}
1072
+ for call in parsed_file.call_sites:
1073
+ method_name = call.callee_name.split(".")[-1]
1074
+ recv = call.receiver_expression or ""
1075
+ # Skip: no receiver, class-name receiver (uppercase), chained receiver
1076
+ if not recv or recv[0].isupper() or recv.startswith("line:"):
1077
+ continue
1078
+ # Skip: standard Map* methods and the IEndpointGroup groupBuilder receiver
1079
+ if not method_name.startswith("Map") or method_name in _STANDARD_MAP:
1080
+ continue
1081
+ if recv == "groupBuilder":
1082
+ continue
1083
+ ln = call.location.line if call.location else -1
1084
+ if ln > 0:
1085
+ ext_call_lines[method_name] = ln
1086
+
1087
+ # Per-extension-method auth overrides (.AllowAnonymous() / .RequireAuthorization()
1088
+ # chained on group.MapXxxEndpoint() in the caller file).
1089
+ ext_auth_override: dict[str, str | None] = dict.fromkeys(ext_call_lines, None)
1090
+ for call in parsed_file.call_sites:
1091
+ method_name = call.callee_name.split(".")[-1]
1092
+ recv = call.receiver_expression or ""
1093
+ if not recv.startswith("line:"):
1094
+ continue
1095
+ try:
1096
+ target = int(recv[5:])
1097
+ except ValueError:
1098
+ continue
1099
+ for ext_name, ext_line in ext_call_lines.items():
1100
+ if target == ext_line and method_name in (
1101
+ "AllowAnonymous",
1102
+ "RequireAuthorization",
1103
+ ):
1104
+ ext_auth_override[ext_name] = method_name
1105
+
1106
+ # --- Pattern A: same-file MapGroup with local Map* route calls ---
1107
+ # Detect files that call MapGroup AND register routes on the result directly
1108
+ # (e.g. eShop OrdersApi.cs: ``var api = app.MapGroup("x"); api.MapPut(...)``)
1109
+ if group_lines:
1110
+ has_local_map_calls = any(
1111
+ (m := call.callee_name.split(".")[-1]) in _STANDARD_MAP
1112
+ and m != "MapGroup"
1113
+ and (recv := call.receiver_expression or "")
1114
+ and not recv.startswith("line:")
1115
+ and not recv[0].isupper()
1116
+ and recv != "groupBuilder"
1117
+ for call in parsed_file.call_sites
1118
+ )
1119
+ unique_prefixes = set(group_lines.values())
1120
+ if has_local_map_calls and len(unique_prefixes) == 1:
1121
+ grp_prefix = next(iter(unique_prefixes))
1122
+ same_file_prefix_map[file_path] = (grp_prefix, has_group_auth, False)
1123
+ elif has_local_map_calls and len(unique_prefixes) > 1:
1124
+ # Multi-prefix file (e.g. versioned API): assign each route the
1125
+ # nearest preceding MapGroup prefix by line number
1126
+ same_file_multi_map[file_path] = sorted(
1127
+ [(ln, pfx, has_group_auth) for ln, pfx in group_lines.items()],
1128
+ key=lambda t: t[0],
1129
+ )
1130
+
1131
+ # --- Pattern B: cross-file extension method (with MapGroup in caller) ---
1132
+ # OR: auth-only from Program.cs (no MapGroup in caller)
1133
+ if ext_call_lines:
1134
+ if group_lines:
1135
+ # Module file: MapGroup + custom extension method calls → cross-file
1136
+ unique_prefixes = set(group_lines.values())
1137
+ if len(unique_prefixes) == 1:
1138
+ grp_prefix = next(iter(unique_prefixes))
1139
+ for ext_name in ext_call_lines:
1140
+ override = ext_auth_override.get(ext_name)
1141
+ allow_anon = override == "AllowAnonymous"
1142
+ route_auth = (
1143
+ has_group_auth and not allow_anon
1144
+ ) or override == "RequireAuthorization"
1145
+ group_registry[ext_name] = (grp_prefix, route_auth, allow_anon)
1146
+ else:
1147
+ # Program.cs-like file: no MapGroup, but ext method calls with auth
1148
+ # (e.g. ``orders.MapOrdersApiV1().RequireAuthorization()``)
1149
+ for ext_name, override in ext_auth_override.items():
1150
+ if override == "RequireAuthorization":
1151
+ handler_file = ext_method_to_file.get(ext_name)
1152
+ if handler_file:
1153
+ program_auth_overrides.add(handler_file)
1154
+
1155
+ # ── Step 3: build unified file_path → (prefix, route_auth, allow_anon) ──
1156
+ # Same-file patterns take precedence for prefix resolution.
1157
+ file_prefix_map: dict[str, tuple[str, bool, bool]] = dict(same_file_prefix_map)
1158
+ # Cross-file patterns fill in files not already covered by same-file
1159
+ for file_path, method_names in ext_methods_by_file.items():
1160
+ for method_name in method_names:
1161
+ if method_name in group_registry and file_path not in file_prefix_map:
1162
+ file_prefix_map[file_path] = group_registry[method_name]
1163
+ break
1164
+
1165
+ if not file_prefix_map and not same_file_multi_map and not program_auth_overrides:
1166
+ return routes
1167
+
1168
+ # ── Step 4: apply prefix + auth to matching routes ───────────────────
1169
+ updated: list[RouteModel] = []
1170
+ for route in routes:
1171
+ handler_file = route.handler_location.file if route.handler_location else None
1172
+ if not handler_file:
1173
+ updated.append(route)
1174
+ continue
1175
+
1176
+ has_prog_auth = handler_file in program_auth_overrides
1177
+
1178
+ # Multi-prefix: find the nearest preceding MapGroup by route line
1179
+ multi_entries = same_file_multi_map.get(handler_file)
1180
+ if multi_entries and route.handler_location:
1181
+ route_line = route.handler_location.line
1182
+ chosen_pfx, chosen_auth = multi_entries[0][1], multi_entries[0][2]
1183
+ for grp_line, grp_pfx, grp_auth in multi_entries:
1184
+ if grp_line <= route_line:
1185
+ chosen_pfx, chosen_auth = grp_pfx, grp_auth
1186
+ else:
1187
+ break
1188
+ prefix_entry: tuple[str, bool, bool] | None = (chosen_pfx, chosen_auth, False)
1189
+ else:
1190
+ prefix_entry = file_prefix_map.get(handler_file)
1191
+
1192
+ if prefix_entry:
1193
+ prefix, route_auth, allow_anon = prefix_entry
1194
+ # Program.cs-level auth override (e.g. .RequireAuthorization() on the
1195
+ # extension method call) takes precedence over no-auth from same-file group
1196
+ if has_prog_auth:
1197
+ route_auth = True
1198
+ allow_anon = False
1199
+
1200
+ new_path = prefix.rstrip("/") + "/" + route.path.lstrip("/")
1201
+ new_path = _re.sub(r"/+", "/", new_path)
1202
+
1203
+ new_deps = list(route.dependencies or [])
1204
+ if allow_anon:
1205
+ new_deps = [d for d in new_deps if "Authorize" not in d]
1206
+ elif route_auth:
1207
+ if not any("Authorize" in d or "permission" in d.lower() for d in new_deps):
1208
+ new_deps.insert(0, "Authorize@group")
1209
+
1210
+ updated.append(
1211
+ route.model_copy(
1212
+ update={
1213
+ "path": new_path,
1214
+ "id": stable_id(
1215
+ "ep",
1216
+ route.method,
1217
+ new_path,
1218
+ route.handler_function,
1219
+ ),
1220
+ "dependencies": new_deps,
1221
+ }
1222
+ )
1223
+ )
1224
+
1225
+ elif has_prog_auth:
1226
+ # Auth-only override without a prefix change (extension method defines
1227
+ # its own routes directly, prefix already correct in the route)
1228
+ new_deps = list(route.dependencies or [])
1229
+ if not any("Authorize" in d or "permission" in d.lower() for d in new_deps):
1230
+ new_deps.insert(0, "Authorize@group")
1231
+ updated.append(route.model_copy(update={"dependencies": new_deps}))
1232
+
1233
+ else:
1234
+ updated.append(route)
1235
+
1236
+ return updated
1237
+
1238
+ def _setup_legacy_plugin(self, plugin, language: Language) -> None:
1239
+ """
1240
+ Set up a legacy plugin that doesn't use AnalysisContext.
1241
+
1242
+ This provides backward compatibility with plugins that use
1243
+ the old setter-based approach.
1244
+ """
1245
+ context = self._analysis_contexts.get(language)
1246
+ if not context:
1247
+ return
1248
+
1249
+ # Get successfully parsed files for this language
1250
+ successful_files = [
1251
+ p for p in self._parsed_files.values() if p.success and p.language == language
1252
+ ]
1253
+
1254
+ # Set up legacy services from context
1255
+ if hasattr(plugin, "set_cross_file_resolver"):
1256
+ # Get raw resolver from language services
1257
+ raw_resolver = context.language_services.get("_raw_cross_file_resolver")
1258
+ if raw_resolver:
1259
+ plugin.set_cross_file_resolver(raw_resolver)
1260
+
1261
+ if hasattr(plugin, "set_router_registry"):
1262
+ raw_registry = context.language_services.get("_raw_router_registry")
1263
+ if raw_registry:
1264
+ plugin.set_router_registry(raw_registry)
1265
+
1266
+ if hasattr(plugin, "set_path_resolver"):
1267
+ raw_path_resolver = context.language_services.get("_raw_path_resolver")
1268
+ if raw_path_resolver:
1269
+ plugin.set_path_resolver(raw_path_resolver)
1270
+
1271
+ if hasattr(plugin, "set_project_context"):
1272
+ plugin.set_project_context(
1273
+ successful_files,
1274
+ project_root=self.config.project_root,
1275
+ )
1276
+
1277
+ def _convert_route(self, route, route_id: str, framework: str = "fastapi") -> RouteModel:
1278
+ """Convert ExtractedRoute to RouteModel (framework from plugin)."""
1279
+ # Convert parameters, using the actual ParameterLocation name when available
1280
+ path_params = [
1281
+ HttpParameterModel(
1282
+ name=p.name,
1283
+ location=p.location.name.lower() if hasattr(p.location, "name") else "path",
1284
+ type_annotation=p.type_annotation,
1285
+ required=p.required,
1286
+ default_value=p.default_value,
1287
+ alias=p.alias,
1288
+ constraints=p.constraints,
1289
+ )
1290
+ for p in route.path_params
1291
+ ]
1292
+
1293
+ query_params = [
1294
+ HttpParameterModel(
1295
+ name=p.name,
1296
+ location=p.location.name.lower() if hasattr(p.location, "name") else "query",
1297
+ type_annotation=p.type_annotation,
1298
+ required=p.required,
1299
+ default_value=p.default_value,
1300
+ alias=p.alias,
1301
+ constraints=p.constraints,
1302
+ )
1303
+ for p in route.query_params
1304
+ ]
1305
+
1306
+ header_params = [
1307
+ HttpParameterModel(
1308
+ name=p.name,
1309
+ location="header",
1310
+ type_annotation=p.type_annotation,
1311
+ required=p.required,
1312
+ default_value=p.default_value,
1313
+ )
1314
+ for p in route.header_params
1315
+ ]
1316
+
1317
+ cookie_params = [
1318
+ HttpParameterModel(
1319
+ name=p.name,
1320
+ location="cookie",
1321
+ type_annotation=p.type_annotation,
1322
+ required=p.required,
1323
+ default_value=p.default_value,
1324
+ )
1325
+ for p in route.cookie_params
1326
+ ]
1327
+
1328
+ # Convert body — enrich field list with types from the resolver
1329
+ body = None
1330
+ if route.body:
1331
+ enriched_fields = self._enrich_body_fields(
1332
+ route.body.model_name,
1333
+ route.body.body_fields,
1334
+ route.handler_location.file if route.handler_location else None,
1335
+ )
1336
+ body = HttpBodyModel(
1337
+ content_type=route.body.content_type,
1338
+ model_name=route.body.model_name,
1339
+ body_fields=enriched_fields,
1340
+ required=route.body.required,
1341
+ )
1342
+
1343
+ return RouteModel(
1344
+ id=route_id,
1345
+ kind=route.kind,
1346
+ surface_kind=route.surface_kind,
1347
+ method=route.method.name,
1348
+ path=route.path,
1349
+ path_params=path_params,
1350
+ query_params=query_params,
1351
+ header_params=header_params,
1352
+ cookie_params=cookie_params,
1353
+ body=body,
1354
+ handler_function=route.handler_function.full,
1355
+ handler_location=LocationModel(
1356
+ file=str(route.handler_location.file),
1357
+ line=route.handler_location.line,
1358
+ column=route.handler_location.column,
1359
+ ),
1360
+ framework=framework,
1361
+ router_name=route.router_name,
1362
+ tags=route.tags,
1363
+ operation_id=route.operation_id,
1364
+ summary=route.summary,
1365
+ deprecated=route.deprecated,
1366
+ intended_public=route.intended_public,
1367
+ dependencies=route.dependency_refs,
1368
+ response_model=route.response.model_name if route.response else None,
1369
+ response_status_code=route.response.status_code if route.response else 200,
1370
+ path_fully_resolved=route.path_fully_resolved,
1371
+ path_resolution_source=route.path_resolution_source,
1372
+ path_dynamic_reason=route.path_dynamic_reason,
1373
+ extraction_source=route.extraction_source,
1374
+ )
1375
+
1376
+ # =========================================================================
1377
+ # Body Field Enrichment & Schema Collection
1378
+ # =========================================================================
1379
+
1380
+ def _enrich_body_fields(
1381
+ self,
1382
+ model_name: str | None,
1383
+ raw_field_names: list[str],
1384
+ in_file: Path | None,
1385
+ ) -> list[BodyFieldModel]:
1386
+ """Resolve raw field name strings into typed BodyFieldModel objects."""
1387
+ if not model_name:
1388
+ return [BodyFieldModel(name=n) for n in raw_field_names]
1389
+
1390
+ type_resolver = self._get_type_resolver()
1391
+ if not type_resolver:
1392
+ return [BodyFieldModel(name=n) for n in raw_field_names]
1393
+
1394
+ known_models = set(type_resolver.get_all_models().keys())
1395
+ resolved_fields = type_resolver.get_model_fields(model_name, in_file)
1396
+ resolved_by_name = {f.name: f for f in resolved_fields}
1397
+ result: list[BodyFieldModel] = []
1398
+
1399
+ # When raw_field_names is empty (e.g. Ardalis pattern where body type is
1400
+ # known but fields were not pre-populated), use the resolved fields directly.
1401
+ names_to_process = raw_field_names if raw_field_names else [f.name for f in resolved_fields]
1402
+
1403
+ for name in names_to_process:
1404
+ rf = resolved_by_name.get(name)
1405
+ if rf:
1406
+ inner_type = self._unwrap_inner_type(rf.type_annotation)
1407
+ is_complex = self._is_known_model(inner_type, known_models)
1408
+ result.append(
1409
+ BodyFieldModel(
1410
+ name=name,
1411
+ type_annotation=rf.type_annotation,
1412
+ required=rf.is_required,
1413
+ is_complex=is_complex,
1414
+ nested_model=inner_type if is_complex else None,
1415
+ constraints=rf.constraints,
1416
+ )
1417
+ )
1418
+ else:
1419
+ result.append(BodyFieldModel(name=name))
1420
+
1421
+ return result
1422
+
1423
+ _ORM_BASE_CLASSES = frozenset(
1424
+ {
1425
+ "SQLModel",
1426
+ "DeclarativeBase",
1427
+ "Base",
1428
+ "Model",
1429
+ "db.Model",
1430
+ "Document",
1431
+ "EmbeddedDocument",
1432
+ }
1433
+ )
1434
+
1435
+ def _collect_schemas(self, routes: list[RouteModel]) -> dict[str, SchemaModel]:
1436
+ """
1437
+ Transitively collect all schemas referenced by route bodies.
1438
+
1439
+ Walks the body model for every route, resolves each nested model,
1440
+ and keeps going until no new models are discovered.
1441
+ """
1442
+ type_resolver = self._get_type_resolver()
1443
+ if not type_resolver:
1444
+ return {}
1445
+
1446
+ known_models = set(type_resolver.get_all_models().keys())
1447
+ simple_to_qualified: dict[str, str] = {}
1448
+ for qname in known_models:
1449
+ simple = qname.rsplit(".", 1)[-1]
1450
+ simple_to_qualified[simple] = qname
1451
+
1452
+ # Pre-compute usage sets from routes
1453
+ request_body_names: set[str] = set()
1454
+ response_model_names: set[str] = set()
1455
+ for route in routes:
1456
+ if route.body and route.body.model_name:
1457
+ request_body_names.add(route.body.model_name)
1458
+ if route.response_model:
1459
+ response_model_names.add(route.response_model)
1460
+
1461
+ schemas: dict[str, SchemaModel] = {}
1462
+ queue: list[str] = []
1463
+
1464
+ for name in request_body_names:
1465
+ if name not in schemas:
1466
+ queue.append(name)
1467
+
1468
+ for name in response_model_names:
1469
+ if name not in schemas:
1470
+ queue.append(name)
1471
+
1472
+ for model_qname in type_resolver.get_all_models():
1473
+ simple_name = model_qname.rsplit(".", 1)[-1]
1474
+ if simple_name not in schemas:
1475
+ queue.append(simple_name)
1476
+
1477
+ visited: set[str] = set()
1478
+
1479
+ while queue:
1480
+ model_name = queue.pop(0)
1481
+ if model_name in visited:
1482
+ continue
1483
+ visited.add(model_name)
1484
+
1485
+ resolved_fields = type_resolver.get_model_fields(model_name, None)
1486
+ if not resolved_fields:
1487
+ continue
1488
+
1489
+ resolved_type = type_resolver.resolve_type(model_name, None)
1490
+ qualified_name = resolved_type.qualified_name if resolved_type else None
1491
+ base_classes = (
1492
+ list(resolved_type.base_classes)
1493
+ if resolved_type and resolved_type.base_classes
1494
+ else []
1495
+ )
1496
+ is_enum = resolved_type.is_enum if resolved_type else False
1497
+
1498
+ # Determine usage based on discovery source and base classes
1499
+ usage: list[str] = []
1500
+ if model_name in request_body_names:
1501
+ usage.append("request_body")
1502
+ if model_name in response_model_names:
1503
+ usage.append("response")
1504
+ base_simple_names = {b.rsplit(".", 1)[-1] for b in base_classes}
1505
+ if base_simple_names & self._ORM_BASE_CLASSES:
1506
+ usage.append("orm")
1507
+ if not usage:
1508
+ usage.append("domain")
1509
+
1510
+ schema_fields: list[SchemaFieldModel] = []
1511
+ for rf in resolved_fields:
1512
+ inner_type = self._unwrap_inner_type(rf.type_annotation)
1513
+ is_complex = self._is_known_model(inner_type, known_models)
1514
+ schema_fields.append(
1515
+ SchemaFieldModel(
1516
+ name=rf.name,
1517
+ type_annotation=rf.type_annotation,
1518
+ required=rf.is_required,
1519
+ default_value=rf.default_value,
1520
+ is_complex=is_complex,
1521
+ nested_model=inner_type if is_complex else None,
1522
+ alias=rf.alias,
1523
+ constraints=rf.constraints,
1524
+ )
1525
+ )
1526
+ if is_complex and inner_type and inner_type not in visited:
1527
+ queue.append(inner_type)
1528
+
1529
+ schemas[model_name] = SchemaModel(
1530
+ name=model_name,
1531
+ qualified_name=qualified_name,
1532
+ fields=schema_fields,
1533
+ base_classes=base_classes,
1534
+ is_enum=is_enum,
1535
+ usage=usage,
1536
+ )
1537
+
1538
+ return schemas
1539
+
1540
+ @staticmethod
1541
+ def _unwrap_inner_type(type_annotation: str | None) -> str | None:
1542
+ """Strip Optional[...] and list[...] wrappers to get the core type name."""
1543
+ if not type_annotation:
1544
+ return None
1545
+ t = type_annotation
1546
+ for prefix in ("Optional[", "optional["):
1547
+ if t.startswith(prefix) and t.endswith("]"):
1548
+ t = t[len(prefix) : -1].strip()
1549
+ for prefix in (
1550
+ "list[",
1551
+ "List[",
1552
+ "Sequence[",
1553
+ "set[",
1554
+ "Set[",
1555
+ "frozenset[",
1556
+ "FrozenSet[",
1557
+ "tuple[",
1558
+ "Tuple[",
1559
+ ):
1560
+ if t.startswith(prefix) and t.endswith("]"):
1561
+ t = t[len(prefix) : -1].strip()
1562
+ # Handle list[Optional[X]]
1563
+ for inner_prefix in ("Optional[", "optional["):
1564
+ if t.startswith(inner_prefix) and t.endswith("]"):
1565
+ t = t[len(inner_prefix) : -1].strip()
1566
+ break
1567
+ return t
1568
+
1569
+ @staticmethod
1570
+ def _is_known_model(type_name: str | None, known_models: set[str]) -> bool:
1571
+ """Check whether a (simple) type name matches any known model."""
1572
+ if not type_name:
1573
+ return False
1574
+ if type_name in known_models:
1575
+ return True
1576
+ # known_models contains qualified names; check if the simple name
1577
+ # matches the suffix of any qualified name.
1578
+ return any(qn.endswith("." + type_name) for qn in known_models)
1579
+
1580
+ # -------------------------------------------------------------------------
1581
+ # Pydantic body inference
1582
+ # -------------------------------------------------------------------------
1583
+
1584
+ # Frameworks whose plugins don't natively parse Pydantic request bodies.
1585
+ # FastAPI and Django Ninja are excluded because their plugins already set
1586
+ # route.body from route signature annotations.
1587
+ _PYDANTIC_INFER_FRAMEWORKS: frozenset[str] = frozenset(
1588
+ {"flask", "django", "generic", "webhook", ""}
1589
+ )
1590
+
1591
+ # Pydantic instantiation patterns we recognise in call sites.
1592
+ # A call site contributes a candidate model name when:
1593
+ # (a) its callee_name exactly matches a known Pydantic model class name, OR
1594
+ # (b) its callee_name is "ModelName.parse_obj", "ModelName.model_validate",
1595
+ # or "ModelName.from_orm".
1596
+ _PYDANTIC_CLASS_METHODS: frozenset[str] = frozenset(
1597
+ {"parse_obj", "model_validate", "from_orm", "model_validate_json"}
1598
+ )
1599
+
1600
+ # Receiver expressions that indicate the argument came from the HTTP request.
1601
+ _REQUEST_RECEIVERS: frozenset[str] = frozenset({"request", "req"})
1602
+
1603
+ def _infer_pydantic_route_bodies(self, routes: list[RouteModel]) -> None:
1604
+ """Set body.model_name for Python routes that instantiate a Pydantic model.
1605
+
1606
+ Flask, Django, and similar frameworks don't emit Pydantic body metadata
1607
+ from their plugins — the handler just calls ``Model(**request.get_json())``
1608
+ directly. This pass scans call sites to recover those model references,
1609
+ so _collect_schemas can assign usage="request_body" instead of "domain".
1610
+ """
1611
+ py_ctx = self._analysis_contexts.get(Language.PYTHON)
1612
+ if not py_ctx or not py_ctx.type_resolver:
1613
+ return
1614
+
1615
+ all_models = py_ctx.type_resolver.get_all_models()
1616
+ if not all_models:
1617
+ return
1618
+
1619
+ # simple class name → first matching qualified name
1620
+ simple_to_qname: dict[str, str] = {}
1621
+ for qname in all_models:
1622
+ simple = qname.rsplit(".", 1)[-1]
1623
+ if simple not in simple_to_qname:
1624
+ simple_to_qname[simple] = qname
1625
+ model_simple_names: frozenset[str] = frozenset(simple_to_qname)
1626
+
1627
+ # caller qualified name → list of ParsedCallSite
1628
+ caller_calls: dict[str, list] = {}
1629
+ for parsed in self._parsed_files.values():
1630
+ if not parsed.success or parsed.language != Language.PYTHON:
1631
+ continue
1632
+ for cs in parsed.call_sites or []:
1633
+ if cs.caller_function:
1634
+ key = cs.caller_function.full
1635
+ caller_calls.setdefault(key, []).append(cs)
1636
+
1637
+ for i, route in enumerate(routes):
1638
+ if route.body is not None:
1639
+ continue
1640
+ if route.method not in ("POST", "PUT", "PATCH"):
1641
+ continue
1642
+ if route.framework not in self._PYDANTIC_INFER_FRAMEWORKS:
1643
+ continue
1644
+
1645
+ call_sites = caller_calls.get(route.handler_function, [])
1646
+ if not call_sites:
1647
+ continue
1648
+
1649
+ model_name = self._pick_pydantic_body_model(call_sites, model_simple_names)
1650
+ if model_name:
1651
+ routes[i] = route.model_copy(
1652
+ update={
1653
+ "body": HttpBodyModel(
1654
+ content_type="application/json",
1655
+ model_name=model_name,
1656
+ body_fields=[],
1657
+ required=True,
1658
+ )
1659
+ }
1660
+ )
1661
+
1662
+ def _pick_pydantic_body_model(
1663
+ self,
1664
+ call_sites: list,
1665
+ model_simple_names: frozenset[str],
1666
+ ) -> str | None:
1667
+ """Return the first Pydantic model instantiated with what looks like request data.
1668
+
1669
+ Prefers calls that directly spread request data (**request.json, **data where
1670
+ data came from get_json). Falls back to any Pydantic model instantiation found
1671
+ in the handler — these are almost always the request schema for POST handlers.
1672
+ """
1673
+ # Check if this handler reads from an HTTP request object at all
1674
+ has_request_read = any(
1675
+ cs.receiver_expression in self._REQUEST_RECEIVERS
1676
+ or "get_json" in cs.callee_name
1677
+ or "request.json" in cs.callee_name
1678
+ or "request.data" in cs.callee_name
1679
+ or "request.body" in cs.callee_name
1680
+ for cs in call_sites
1681
+ )
1682
+
1683
+ candidates: list[tuple[int, str]] = [] # (priority, model_name)
1684
+
1685
+ for cs in call_sites:
1686
+ callee = cs.callee_name
1687
+
1688
+ # Direct instantiation: UserCreate(**data)
1689
+ if callee in model_simple_names:
1690
+ has_spread = any(getattr(arg, "is_keyword_spread", False) for arg in cs.arguments)
1691
+ priority = 0 if has_spread else 1
1692
+ candidates.append((priority, callee))
1693
+
1694
+ # Class-method call: UserCreate.parse_obj(data) / UserCreate.model_validate(data)
1695
+ elif "." in callee:
1696
+ obj, _, method = callee.rpartition(".")
1697
+ if obj in model_simple_names and method in self._PYDANTIC_CLASS_METHODS:
1698
+ candidates.append((0, obj))
1699
+
1700
+ if not candidates:
1701
+ return None
1702
+
1703
+ # If no request read was found, be conservative: only infer if there's a spread call
1704
+ if not has_request_read:
1705
+ candidates = [(p, m) for p, m in candidates if p == 0]
1706
+ if not candidates:
1707
+ return None
1708
+
1709
+ candidates.sort(key=lambda x: x[0])
1710
+ return candidates[0][1]
1711
+
1712
+ def _get_type_resolver(self):
1713
+ """Get the type resolver from whichever analysis context is available."""
1714
+ ctx = (
1715
+ self._analysis_contexts.get(Language.PYTHON)
1716
+ or self._analysis_contexts.get(Language.JAVA)
1717
+ or self._analysis_contexts.get(Language.CSHARP)
1718
+ )
1719
+ return ctx.type_resolver if ctx else None
1720
+
1721
+ # =========================================================================
1722
+ # Dependency Extraction
1723
+ # =========================================================================
1724
+
1725
+ def _extract_all_dependencies(self) -> list[dict]:
1726
+ """Extract all dependency definitions."""
1727
+ dependencies = []
1728
+
1729
+ for parsed_file in self._parsed_files.values():
1730
+ if not parsed_file.success:
1731
+ continue
1732
+
1733
+ for fw in self._detected_frameworks:
1734
+ plugin = FrameworkPluginRegistry.get_plugin(fw)
1735
+ if plugin and plugin.detect(parsed_file):
1736
+ deps = plugin.extract_dependencies(parsed_file)
1737
+ dependencies.extend(deps)
1738
+
1739
+ return dependencies
1740
+
1741
+ # =========================================================================
1742
+ # Auth Extraction
1743
+ # =========================================================================
1744
+
1745
+ def _extract_auth_data(self) -> AuthModel:
1746
+ """Extract authentication data from all files."""
1747
+ schemes: list[AuthSchemeModel] = []
1748
+ auth_deps: list[AuthDependencyModel] = []
1749
+ jwt_config = JwtConfigModel()
1750
+
1751
+ # Pre-pass: collect all Depends() argument names and all auth-scheme
1752
+ # variable names across the entire project. This bridges the standard
1753
+ # FastAPI pattern where auth deps are defined in deps.py but used via
1754
+ # Depends() in routers/*.py — both sets will be non-empty even though
1755
+ # neither file contains both halves.
1756
+ import re as _re
1757
+
1758
+ all_project_depends_names: set[str] = set()
1759
+ all_project_scheme_names: set[str] = set()
1760
+ for _pf in self._parsed_files.values():
1761
+ if not _pf.success:
1762
+ continue
1763
+ for _call in _pf.call_sites:
1764
+ if getattr(_call, "callee_name", None) == "Depends":
1765
+ for _arg in _call.arguments:
1766
+ if getattr(_arg, "is_variable", False) and _arg.variable_name:
1767
+ # Direct reference: Depends(get_current_user)
1768
+ all_project_depends_names.add(_arg.variable_name)
1769
+ if getattr(_arg, "literal_value", None):
1770
+ all_project_depends_names.add(str(_arg.literal_value))
1771
+ # Factory-call pattern: Depends(get_current_user_authorizer())
1772
+ _expr = getattr(_arg, "expression_text", None) or ""
1773
+ _fm = _re.match(r"(\w+)\s*\(", _expr)
1774
+ if _fm:
1775
+ all_project_depends_names.add(_fm.group(1))
1776
+ for _func in _pf.functions:
1777
+ for _param in _func.parameters:
1778
+ if _param.default_value:
1779
+ for _m in _re.finditer(r"Depends\s*\(\s*(\w+)", _param.default_value):
1780
+ all_project_depends_names.add(_m.group(1))
1781
+ for _fw in self._detected_frameworks:
1782
+ _plugin = FrameworkPluginRegistry.get_plugin(_fw)
1783
+ if _plugin and _plugin.detect(_pf):
1784
+ for _scheme in _plugin.extract_auth_schemes(_pf):
1785
+ if _scheme.name:
1786
+ all_project_scheme_names.add(_scheme.name)
1787
+
1788
+ for parsed_file in self._parsed_files.values():
1789
+ if not parsed_file.success:
1790
+ continue
1791
+
1792
+ for fw in self._detected_frameworks:
1793
+ plugin = FrameworkPluginRegistry.get_plugin(fw)
1794
+ if plugin and plugin.detect(parsed_file):
1795
+ # Extract schemes and collect names for dependency correlation
1796
+ file_scheme_names: set[str] = set()
1797
+ for scheme in plugin.extract_auth_schemes(parsed_file):
1798
+ file_scheme_names.add(scheme.name)
1799
+ try:
1800
+ schemes.append(
1801
+ AuthSchemeModel(
1802
+ id=stable_id(
1803
+ "scheme",
1804
+ scheme.scheme_type.name,
1805
+ str(scheme.location.file),
1806
+ str(scheme.location.line),
1807
+ ),
1808
+ type=scheme.scheme_type.name,
1809
+ framework=fw.name.lower(),
1810
+ location=LocationModel(
1811
+ file=str(scheme.location.file),
1812
+ line=scheme.location.line,
1813
+ ),
1814
+ config=scheme.config,
1815
+ )
1816
+ )
1817
+ except ValidationError as exc:
1818
+ # Malformed scheme record — skip rather than abort the entire
1819
+ # analysis. This was previously a hard-crash path (see
1820
+ # dispatch-main repro) because a single framework plugin
1821
+ # producing a bad LocationModel killed the whole run.
1822
+ logger.warning(
1823
+ "Skipping malformed AuthSchemeModel for scheme=%r file=%s: %s",
1824
+ scheme.name,
1825
+ getattr(scheme.location, "file", "<unknown>"),
1826
+ exc,
1827
+ )
1828
+ continue
1829
+
1830
+ # Extract auth dependencies using cross-file pre-pass sets
1831
+ # so that deps defined in deps.py and used in routers/*.py
1832
+ # are correctly detected in both directions.
1833
+ auth_context = self._analysis_contexts.get(parsed_file.language)
1834
+ for dep in plugin.extract_auth_dependencies(
1835
+ parsed_file,
1836
+ known_scheme_names=file_scheme_names | all_project_scheme_names,
1837
+ all_project_depends_names=all_project_depends_names,
1838
+ context=auth_context,
1839
+ ):
1840
+ try:
1841
+ auth_deps.append(
1842
+ AuthDependencyModel(
1843
+ id=stable_id("dep", dep.name, dep.dependency_type.name),
1844
+ name=dep.name,
1845
+ type=dep.dependency_type.name,
1846
+ location=LocationModel(
1847
+ file=str(dep.location.file),
1848
+ line=dep.location.line,
1849
+ ),
1850
+ uses_schemes=list(dep.uses_schemes),
1851
+ extracts=dep.extracts_fields,
1852
+ validates=dep.validates,
1853
+ requires_roles=list(dep.requires_roles),
1854
+ requires_scopes=list(dep.requires_scopes),
1855
+ jwt_operations=dep.jwt_operations,
1856
+ controller_module=dep.qualified_name.module
1857
+ if dep.qualified_name
1858
+ else "",
1859
+ only_actions=list(dep.only_actions),
1860
+ except_actions=list(dep.except_actions),
1861
+ )
1862
+ )
1863
+ except ValidationError as exc:
1864
+ logger.warning(
1865
+ "Skipping malformed AuthDependencyModel for dep=%r file=%s: %s",
1866
+ dep.name,
1867
+ getattr(dep.location, "file", "<unknown>"),
1868
+ exc,
1869
+ )
1870
+ continue
1871
+
1872
+ # Extract JWT config
1873
+ jwt = plugin.extract_jwt_config(parsed_file)
1874
+ if jwt and jwt.detected:
1875
+ jwt_config.detected = True
1876
+ jwt_config.library = jwt.library
1877
+ jwt_config.algorithms = jwt.algorithms
1878
+
1879
+ # Framework-independent JWT scan: detect JWT usage in files that
1880
+ # framework plugins don't cover (e.g. service modules without FastAPI imports).
1881
+ if not jwt_config.detected:
1882
+ jwt_libraries = {"jose", "python-jose", "pyjwt", "jwt", "authlib"}
1883
+ for parsed_file in self._parsed_files.values():
1884
+ if not parsed_file.success:
1885
+ continue
1886
+ for imp in parsed_file.imports:
1887
+ if imp.module in jwt_libraries or any(
1888
+ imp.module.startswith(f"{lib}.") for lib in jwt_libraries
1889
+ ):
1890
+ jwt_config.detected = True
1891
+ jwt_config.library = imp.module.split(".")[0]
1892
+ for call in parsed_file.call_sites:
1893
+ if (
1894
+ "decode" in call.callee_name.lower()
1895
+ or "encode" in call.callee_name.lower()
1896
+ ):
1897
+ jwt_config.locations.append(call.location)
1898
+ break
1899
+ if jwt_config.detected:
1900
+ break
1901
+
1902
+ # Synthetic fallback: if JWT usage is detected (via any library) but no
1903
+ # framework-specific security objects were found, create an inferred
1904
+ # JWT_BEARER scheme so downstream auth mapping has something to match.
1905
+ if jwt_config.detected and not schemes:
1906
+ # jwt_config.locations contains CodeLocation objects (file: Path);
1907
+ # AuthSchemeModel.location expects a LocationModel (file: str).
1908
+ # Always construct explicitly to avoid Pydantic validation failures.
1909
+ if jwt_config.locations:
1910
+ raw_loc = jwt_config.locations[0]
1911
+ loc = LocationModel(
1912
+ file=str(getattr(raw_loc, "file", "unknown")),
1913
+ line=getattr(raw_loc, "line", 0) or 0,
1914
+ )
1915
+ else:
1916
+ loc = LocationModel(file="unknown", line=0)
1917
+ try:
1918
+ schemes.append(
1919
+ AuthSchemeModel(
1920
+ id=stable_id("scheme", "JWT_BEARER", jwt_config.library or "jwt"),
1921
+ type="JWT_BEARER",
1922
+ framework="generic",
1923
+ location=loc,
1924
+ config={
1925
+ "library": jwt_config.library,
1926
+ "algorithms": jwt_config.algorithms,
1927
+ "synthetic": True,
1928
+ },
1929
+ )
1930
+ )
1931
+ except ValidationError as exc:
1932
+ logger.warning("Skipping synthetic JWT_BEARER AuthSchemeModel: %s", exc)
1933
+
1934
+ return AuthModel(
1935
+ schemes_detected=schemes,
1936
+ auth_dependencies=auth_deps,
1937
+ jwt_config=jwt_config,
1938
+ )
1939
+
1940
+ # ------------------------------------------------------------------
1941
+ # Sub-project boundary scoping for auth propagation
1942
+ # ------------------------------------------------------------------
1943
+
1944
+ def _auth_boundary_index(self) -> Any | None:
1945
+ """Boundary index for scoping auth, or None in a single-project repo.
1946
+
1947
+ Returns None when fewer than two boundaries were detected, which makes
1948
+ every `_boundary_of` lookup below return None — i.e. one shared bucket,
1949
+ exactly the pre-monorepo behaviour.
1950
+ """
1951
+ boundaries = self._boundary_result.boundaries if self._boundary_result else []
1952
+ return build_boundary_index(boundaries) if boundaries else None
1953
+
1954
+ def _boundary_of(self, location: LocationModel | None, index: Any | None) -> str | None:
1955
+ """Which sub-project a location belongs to, or None if unscoped.
1956
+
1957
+ Auth propagation that matches on a *name* (a Rails controller resource,
1958
+ a Django view class or decorator, a Spring filter chain policy) rather
1959
+ than on a file path will otherwise attribute one service's guard to a
1960
+ sibling service that happens to use the same name — marking genuinely
1961
+ unauthenticated routes as protected, which is the same failure the
1962
+ middleware scoping in `_populate_route_auth_mapping` prevents.
1963
+ """
1964
+ if index is None or location is None or not location.file:
1965
+ return None
1966
+ hit = match_boundary(location.file, index, self.config.project_root)
1967
+ return hit.relative_path if hit else None
1968
+
1969
+ def _propagate_file_auth_to_routes(
1970
+ self,
1971
+ routes: list[RouteModel],
1972
+ auth_model: AuthModel,
1973
+ ) -> None:
1974
+ """
1975
+ Propagate file-level auth dependencies to routes that have no per-route
1976
+ auth signal (router_name is None).
1977
+
1978
+ Middleware-based auth frameworks (Express, NestJS without per-route guards)
1979
+ express auth as router.use(middleware) at the sub-router level.
1980
+ extract_auth_dependencies() correctly detects these as MIDDLEWARE-type deps,
1981
+ but the routes themselves carry no router_name because the middleware is not
1982
+ an inline argument to the route registration call.
1983
+
1984
+ This pass closes that gap: for each route without router_name, if its
1985
+ handler file has a MIDDLEWARE auth dependency, set router_name to that
1986
+ dependency's name so the benchmark's auth signal is populated.
1987
+
1988
+ Only MIDDLEWARE-type deps are used — CLASS/DECORATOR/ANNOTATION deps are
1989
+ already captured directly on routes during extraction.
1990
+ """
1991
+ # Build file → first MIDDLEWARE auth dep name
1992
+ file_to_auth_dep: dict[str, str] = {}
1993
+ for dep in auth_model.auth_dependencies:
1994
+ if dep.type != "MIDDLEWARE":
1995
+ continue
1996
+ if not dep.location or not dep.location.file:
1997
+ continue
1998
+ file_key = dep.location.file
1999
+ if file_key not in file_to_auth_dep:
2000
+ file_to_auth_dep[file_key] = dep.name
2001
+
2002
+ if not file_to_auth_dep:
2003
+ return
2004
+
2005
+ for route in routes:
2006
+ if route.router_name is not None:
2007
+ continue # already has a per-route auth signal
2008
+ if not route.handler_location or not route.handler_location.file:
2009
+ continue
2010
+ dep_name = file_to_auth_dep.get(route.handler_location.file)
2011
+ if dep_name:
2012
+ route.router_name = dep_name
2013
+
2014
+ def _propagate_express_parent_auth_to_routes(self, routes: list[RouteModel]) -> None:
2015
+ """Propagate auth middleware from parent Express router files to child routes.
2016
+
2017
+ A parent router file may call router.use(apikey) before mounting sub-routers
2018
+ via router.use('/path', subRouter). Routes in those sub-router files inherit
2019
+ the middleware even though it doesn't appear in their own file.
2020
+
2021
+ The parent auth map is built by build_express_auth_middleware_map() and stored
2022
+ on self._express_parent_auth_map during context setup. Each entry maps a
2023
+ resolved file path to the list of auth middleware variable names accumulated
2024
+ from all ancestor router.use() calls that precede the mount of that file.
2025
+ """
2026
+ if not self._express_parent_auth_map:
2027
+ return
2028
+ for route in routes:
2029
+ if route.router_name is not None:
2030
+ continue
2031
+ if not route.handler_location or not route.handler_location.file:
2032
+ continue
2033
+ auth_middlewares = self._express_parent_auth_map.get(route.handler_location.file, [])
2034
+ if auth_middlewares:
2035
+ route.router_name = "+".join(auth_middlewares)
2036
+
2037
+ def _propagate_django_class_auth_to_routes(
2038
+ self,
2039
+ routes: list[RouteModel],
2040
+ auth_model: AuthModel,
2041
+ ) -> None:
2042
+ """Link Django CBV CLASS-type auth dependencies to their routes.
2043
+
2044
+ DRF APIView subclasses that inherit from an auth mixin (e.g. ApiAuthMixin)
2045
+ are emitted as CLASS-type auth dependencies by the Django plugin. The
2046
+ generic _propagate_file_auth_to_routes only handles MIDDLEWARE-type deps,
2047
+ so this pass closes the gap for class-based auth.
2048
+
2049
+ Matching logic: route handler_function strings look like
2050
+ "urls.FileStandardUploadApi.post" (module.ClassName.method). We split on "."
2051
+ and check every component against a global class-name → dep-name map so
2052
+ the lookup works regardless of module prefix.
2053
+
2054
+ File-key matching is intentionally skipped — Django view classes are defined
2055
+ in apis.py but routes are extracted from urls.py, so the handler_location
2056
+ file and the dep location file differ.
2057
+ """
2058
+ # Scoped per sub-project: the class-name map is deliberately not
2059
+ # file-keyed (views live in apis.py, routes come from urls.py), so
2060
+ # without a boundary key one service's ApiAuthMixin would protect a
2061
+ # same-named view class in an unrelated service.
2062
+ index = self._auth_boundary_index()
2063
+ class_to_dep: dict[str | None, dict[str, str]] = {}
2064
+ for dep in auth_model.auth_dependencies:
2065
+ if dep.type != "CLASS":
2066
+ continue
2067
+ bucket = class_to_dep.setdefault(self._boundary_of(dep.location, index), {})
2068
+ bucket[dep.name] = dep.name
2069
+
2070
+ if not class_to_dep:
2071
+ return
2072
+
2073
+ for route in routes:
2074
+ if route.router_name is not None:
2075
+ continue
2076
+ # Only apply to Django/DRF routes — Spring Boot CLASS-type deps
2077
+ # are handled by the Spring filter chain policy, not here.
2078
+ if route.framework not in ("django", "drf", "flask"):
2079
+ continue
2080
+ scoped = class_to_dep.get(self._boundary_of(route.handler_location, index), {})
2081
+ handler = str(route.handler_function or "")
2082
+ for part in handler.split("."):
2083
+ dep_name = scoped.get(part)
2084
+ if dep_name:
2085
+ route.router_name = dep_name
2086
+ break
2087
+
2088
+ def _propagate_django_decorator_auth_to_routes(
2089
+ self,
2090
+ routes: list[RouteModel],
2091
+ auth_model: AuthModel,
2092
+ ) -> None:
2093
+ """Link Django FBV/CBV-method DECORATOR-type auth dependencies to routes.
2094
+
2095
+ The Django plugin emits a DECORATOR-type dep named either
2096
+ ``func_name`` (module-level FBV) or ``ClassName.method_name`` (a CBV
2097
+ method decorated with e.g. ``@jwt_auth_required``). Routes carry
2098
+ ``handler_function`` as ``module.func_name`` (FBV) or
2099
+ ``module.ClassName.method_name`` (CBV) — match a lone component for
2100
+ the FBV case, or any adjacent dot-separated pair for the CBV case.
2101
+ """
2102
+ decorator_deps = [d for d in auth_model.auth_dependencies if d.type == "DECORATOR"]
2103
+ if not decorator_deps:
2104
+ return
2105
+
2106
+ # Scoped per sub-project — matching is by decorator name, so an
2107
+ # unscoped map lets one service's guard cover a sibling service's
2108
+ # same-named handler component.
2109
+ index = self._auth_boundary_index()
2110
+ by_simple_name: dict[str | None, dict[str, str]] = {}
2111
+ by_qualified_name: dict[str | None, dict[str, str]] = {}
2112
+ for d in decorator_deps:
2113
+ target = by_qualified_name if "." in d.name else by_simple_name
2114
+ target.setdefault(self._boundary_of(d.location, index), {})[d.name] = d.name
2115
+ if not by_simple_name and not by_qualified_name:
2116
+ return
2117
+
2118
+ for route in routes:
2119
+ if route.router_name is not None:
2120
+ continue
2121
+ if route.framework not in ("django", "drf"):
2122
+ continue
2123
+ parts = str(route.handler_function or "").split(".")
2124
+ route_boundary = self._boundary_of(route.handler_location, index)
2125
+ simple = by_simple_name.get(route_boundary, {})
2126
+ qualified = by_qualified_name.get(route_boundary, {})
2127
+
2128
+ matched = next((simple[p] for p in parts if p in simple), None)
2129
+ if matched is None:
2130
+ matched = next(
2131
+ (
2132
+ qualified[pair]
2133
+ for pair in (f"{a}.{b}" for a, b in zip(parts, parts[1:], strict=False))
2134
+ if pair in qualified
2135
+ ),
2136
+ None,
2137
+ )
2138
+ if matched is not None:
2139
+ route.router_name = matched
2140
+
2141
+ def _propagate_rails_auth_to_routes(
2142
+ self,
2143
+ routes: list[RouteModel],
2144
+ auth_model: AuthModel,
2145
+ ) -> None:
2146
+ """Link Rails before_action guards to routes using controller + action matching.
2147
+
2148
+ Deps extracted by the Rails plugin carry qualified_name.module = controller
2149
+ resource name (e.g. 'articles') and only_actions/except_actions filters.
2150
+ Routes carry handler_function.module = same controller name and
2151
+ handler_function.name = action name.
2152
+
2153
+ A route is covered by a dep when:
2154
+ - dep.qualified_name.module == route.handler_function.module (same controller)
2155
+ - action is in dep.only_actions (if only_actions is set), OR
2156
+ action is NOT in dep.except_actions (if except_actions is set), OR
2157
+ no filter is set (applies to all actions)
2158
+
2159
+ Special case — Ruby GraphQL routes (path starts with /graphql:):
2160
+ graphql-ruby routes are served by a single GraphqlController whose
2161
+ controller_module is "graphql". Their handler_function.module is the
2162
+ type-file stem ("query_type", "mutation_type"), NOT "graphql", so the
2163
+ regular controller matching never fires. We match them unconditionally
2164
+ against any dep whose controller_module is "graphql" — action-level
2165
+ only:/except: filters on that dep target controller actions ("execute"),
2166
+ not individual GraphQL field names, so coverage is treated as global.
2167
+ """
2168
+ rails_deps = [
2169
+ dep
2170
+ for dep in auth_model.auth_dependencies
2171
+ if dep.type == "FUNCTION" and dep.controller_module
2172
+ ]
2173
+ if not rails_deps:
2174
+ return
2175
+
2176
+ # Scoped per sub-project: matching is by controller resource *name*,
2177
+ # so two Rails services that both have an `articles` controller would
2178
+ # otherwise share each other's before_action guards. "application"
2179
+ # deps are inherited repo-wide only within their own service, for the
2180
+ # same reason.
2181
+ index = self._auth_boundary_index()
2182
+ deps_by_boundary: dict[str | None, list[Any]] = {}
2183
+ for dep in rails_deps:
2184
+ deps_by_boundary.setdefault(self._boundary_of(dep.location, index), []).append(dep)
2185
+
2186
+ for route in routes:
2187
+ if route.router_name is not None:
2188
+ continue
2189
+ hf = route.handler_function
2190
+ if not hf:
2191
+ continue
2192
+
2193
+ scoped_deps = deps_by_boundary.get(self._boundary_of(route.handler_location, index), [])
2194
+ graphql_ctrl_deps = [d for d in scoped_deps if d.controller_module == "graphql"]
2195
+ # ApplicationController is the standard Rails base class. Its
2196
+ # before_action callbacks are inherited by ALL controllers that
2197
+ # subclass it. We treat deps on "application" as applying to every
2198
+ # route, but only as a fallback — specific controller deps take
2199
+ # priority (checked first in the loop below).
2200
+ base_ctrl_deps = [d for d in scoped_deps if d.controller_module == "application"]
2201
+
2202
+ # Ruby GraphQL routes: match against GraphqlController deps only.
2203
+ if route.path.startswith("/graphql:") and graphql_ctrl_deps:
2204
+ route.router_name = graphql_ctrl_deps[0].name
2205
+ continue
2206
+
2207
+ # handler_function stored as "controller.action" string in RouteModel
2208
+ hf_str = str(hf)
2209
+ parts = hf_str.split(".")
2210
+ ctrl_module = parts[0] if len(parts) > 1 else ""
2211
+ action = parts[-1]
2212
+
2213
+ matched = False
2214
+ # Pass 1: specific controller deps (non-base, non-graphql).
2215
+ for dep in scoped_deps:
2216
+ if dep.controller_module in ("application", "graphql"):
2217
+ continue
2218
+ # Rails singular `resource :user` stores module "user" but
2219
+ # the controller class is UsersController → dep module "users".
2220
+ # Try exact match first, then simple +s pluralization as fallback.
2221
+ # Namespaced controllers (Api::V1::AnnouncementsController →
2222
+ # "api/v1/announcements") only store the resource name in the
2223
+ # routes file ("announcements"), so also match on the last segment.
2224
+ dep_mod = dep.controller_module
2225
+ dep_suffix = dep_mod.rsplit("/", 1)[-1]
2226
+ candidates = {ctrl_module, ctrl_module + "s"}
2227
+ if dep_mod not in candidates and dep_suffix not in candidates:
2228
+ continue
2229
+ only = dep.only_actions
2230
+ excl = dep.except_actions
2231
+ if only:
2232
+ covered = action in only
2233
+ elif excl:
2234
+ covered = action not in excl
2235
+ else:
2236
+ covered = True
2237
+ if covered:
2238
+ route.router_name = dep.name
2239
+ matched = True
2240
+ break
2241
+
2242
+ # Pass 2: ApplicationController base class deps (fallback).
2243
+ if not matched:
2244
+ for dep in base_ctrl_deps:
2245
+ only = dep.only_actions
2246
+ excl = dep.except_actions
2247
+ if only:
2248
+ covered = action in only
2249
+ elif excl:
2250
+ covered = action not in excl
2251
+ else:
2252
+ covered = True
2253
+ if covered:
2254
+ route.router_name = dep.name
2255
+ break
2256
+
2257
+ def _apply_spring_filter_chain_policy(self, routes: list[RouteModel]) -> None:
2258
+ """Apply a Spring SecurityFilterChain policy to Spring/GraphQL routes.
2259
+
2260
+ Routes already carrying a router_name (per-method annotations) are left
2261
+ alone. Routes with no auth signal are marked router_name="SecurityFilterChain"
2262
+ if the global policy says they require authentication.
2263
+ """
2264
+ from ..frameworks.java.spring_plugin import FilterChainPolicy, SpringBootPlugin
2265
+
2266
+ plugin = FrameworkPluginRegistry.get_plugin(Framework.SPRING_BOOT)
2267
+ if not isinstance(plugin, SpringBootPlugin):
2268
+ return
2269
+
2270
+ # One policy per sub-project, not one for the whole repo. A
2271
+ # SecurityFilterChain bean is scoped to the Spring context that
2272
+ # declares it, so building a single policy from every parsed file lets
2273
+ # one service's chain mark a sibling service's routes as
2274
+ # authenticated — the same masking of exposed endpoints this PR fixes
2275
+ # for middleware.
2276
+ index = self._auth_boundary_index()
2277
+ files_by_boundary: dict[str | None, list[Any]] = {}
2278
+ for path, parsed in self._parsed_files.items():
2279
+ key = (
2280
+ None
2281
+ if index is None
2282
+ else self._boundary_of(LocationModel(file=str(path), line=1), index)
2283
+ )
2284
+ files_by_boundary.setdefault(key, []).append(parsed)
2285
+
2286
+ policy_by_boundary: dict[str | None, FilterChainPolicy] = {}
2287
+ for key, parsed_files in files_by_boundary.items():
2288
+ policy = plugin.get_filter_chain_policy(parsed_files)
2289
+ if policy is not None and policy.any_request_auth:
2290
+ policy_by_boundary[key] = policy
2291
+
2292
+ if not policy_by_boundary:
2293
+ return
2294
+
2295
+ for route in routes:
2296
+ if route.router_name is not None:
2297
+ continue
2298
+ if route.framework not in ("spring_boot", "graphql"):
2299
+ continue
2300
+ policy = policy_by_boundary.get(self._boundary_of(route.handler_location, index))
2301
+ if policy is not None and policy.requires_auth(route.path):
2302
+ route.router_name = "SecurityFilterChain"
2303
+
2304
+ def _populate_route_object_references(self, routes: list[RouteModel]) -> None:
2305
+ """Record which routes select a record by a request parameter, and
2306
+ whether anything ties that record to the caller (CWE-639).
2307
+
2308
+ Only plugins that analyse parameter handling report evidence
2309
+ (``extract_object_references`` defaults to empty), and only routes where
2310
+ a parameter actually reaches a lookup get the key at all. A route
2311
+ without it is therefore never being called safe — it is either not
2312
+ selecting a record by request input, or its framework was not analysed.
2313
+ """
2314
+ evidence: dict[str, Any] = {}
2315
+ for parsed_file in self._parsed_files.values():
2316
+ if not parsed_file.success:
2317
+ continue
2318
+ for fw in self._detected_frameworks:
2319
+ plugin = FrameworkPluginRegistry.get_plugin(fw)
2320
+ if plugin is None or not plugin.detect(parsed_file):
2321
+ continue
2322
+ for item in plugin.extract_object_references(parsed_file):
2323
+ # First writer wins, so a second plugin matching the same
2324
+ # file cannot overwrite a found ownership check with a blank.
2325
+ evidence.setdefault(item.handler, item)
2326
+
2327
+ if not evidence:
2328
+ return
2329
+
2330
+ for route in routes:
2331
+ item = evidence.get(route.handler_function)
2332
+ if item is None:
2333
+ continue
2334
+ route.object_reference = {
2335
+ "parameter": item.parameter,
2336
+ "lookup": item.lookup,
2337
+ "ownership_checked": item.ownership_checked,
2338
+ "ownership_evidence": item.ownership_evidence,
2339
+ }
2340
+
2341
+ def _populate_route_auth_mapping(
2342
+ self,
2343
+ auth_model: AuthModel,
2344
+ routes: list[RouteModel],
2345
+ middleware_list: list[MiddlewareModel] | None = None,
2346
+ ) -> None:
2347
+ """Generate route_auth_mapping by correlating route dependencies with auth deps.
2348
+
2349
+ A route is considered authenticated if any of its ``dependencies``
2350
+ reference a known auth dependency (by name match). Auth dependencies
2351
+ are identified by their name appearing in ``auth_model.auth_dependencies``.
2352
+
2353
+ Heuristic fallback: if no formal auth dependencies were detected but
2354
+ routes have dependency names containing auth-related keywords
2355
+ (``auth``, ``user``, ``token``, ``permission``, ``login``, ``verify``),
2356
+ we still treat those as auth-related.
2357
+
2358
+ Middleware-based auth (e.g. ``app.add_middleware(AuthMiddleware, ...)``)
2359
+ is also propagated: if any globally-applied middleware declares
2360
+ ``operations=['auth']``, every route without route-level auth *in the
2361
+ same monorepo sub-project as that middleware* is marked authenticated
2362
+ with mechanism ``middleware:<name>`` so the engine's missing_auth rule
2363
+ will not fire for middleware-protected apps. Scoped by boundary
2364
+ (falling back to unscoped/global when no boundaries are detected, the
2365
+ single-project case) so a middleware registered as "global" inside
2366
+ one service of a polyglot monorepo cannot leak onto an unrelated
2367
+ sibling service's routes.
2368
+ """
2369
+ AUTH_KEYWORDS = {
2370
+ "auth",
2371
+ "user",
2372
+ "token",
2373
+ "permission",
2374
+ "login",
2375
+ "verify",
2376
+ "current_user",
2377
+ "principal",
2378
+ "credential",
2379
+ "identity",
2380
+ "session",
2381
+ "bearer",
2382
+ "api_key",
2383
+ "apikey",
2384
+ "security",
2385
+ "authorize",
2386
+ "authenticated",
2387
+ }
2388
+
2389
+ # Scoped like the middleware below: a route is only credited to an
2390
+ # auth dependency declared inside its own sub-project, so a guard in
2391
+ # one service cannot vouch for a same-named symbol in another.
2392
+ auth_index = self._auth_boundary_index()
2393
+ auth_names_by_boundary: dict[str | None, set[str]] = {}
2394
+ auth_deps_by_boundary: dict[str | None, dict[str, AuthDependencyModel]] = {}
2395
+ for dep in auth_model.auth_dependencies:
2396
+ boundary = self._boundary_of(dep.location, auth_index)
2397
+ auth_names_by_boundary.setdefault(boundary, set()).add(dep.name)
2398
+ bucket = auth_deps_by_boundary.setdefault(boundary, {})
2399
+ bucket[dep.name] = dep
2400
+ short = dep.name.rsplit(".", 1)[-1]
2401
+ bucket.setdefault(short, dep)
2402
+
2403
+ def lookup_auth_dep(boundary: str | None, ref_name: str) -> AuthDependencyModel | None:
2404
+ bucket = auth_deps_by_boundary.get(boundary, {})
2405
+ return bucket.get(ref_name) or bucket.get(ref_name.rsplit(".", 1)[-1])
2406
+
2407
+ def merge_auth_dep_onto_route(
2408
+ route_auth: RouteAuthModel, auth_dep: AuthDependencyModel
2409
+ ) -> None:
2410
+ if auth_dep.requires_roles:
2411
+ route_auth.roles_required = sorted(
2412
+ set(route_auth.roles_required) | set(auth_dep.requires_roles)
2413
+ )
2414
+ if auth_dep.requires_scopes:
2415
+ route_auth.scopes_required = sorted(
2416
+ set(route_auth.scopes_required) | set(auth_dep.requires_scopes)
2417
+ )
2418
+ if auth_dep.requires_permissions:
2419
+ route_auth.permissions_required = sorted(
2420
+ set(route_auth.permissions_required) | set(auth_dep.requires_permissions)
2421
+ )
2422
+ if auth_dep.type in ("ANNOTATION", "DECORATOR"):
2423
+ route_auth.authorization_checked = True
2424
+
2425
+ def merge_refs_onto_route(
2426
+ route_auth: RouteAuthModel,
2427
+ ref_names: list[str],
2428
+ boundary: str | None,
2429
+ ) -> None:
2430
+ for ref in ref_names:
2431
+ dep = lookup_auth_dep(boundary, ref)
2432
+ if dep is not None:
2433
+ merge_auth_dep_onto_route(route_auth, dep)
2434
+
2435
+ global_auth_middleware: list[MiddlewareModel] = [
2436
+ mw for mw in (middleware_list or []) if is_global_auth_middleware(mw)
2437
+ ]
2438
+
2439
+ # Scope "global" middleware to the sub-project that actually registers
2440
+ # it — applies_to=["all"] means global *within the service that mounts
2441
+ # it*, not across every other, unrelated service that happens to live
2442
+ # in the same repo. Without this, a monorepo's global auth middleware
2443
+ # in one service (e.g. a Spring identity service's JwtAuthTokenFilter)
2444
+ # leaks onto every route in every sibling service — including ones in
2445
+ # a different language that could never run alongside it — masking
2446
+ # genuinely unauthenticated endpoints as protected.
2447
+ boundaries = self._boundary_result.boundaries if self._boundary_result else []
2448
+ boundary_index = build_boundary_index(boundaries) if boundaries else None
2449
+
2450
+ def boundary_for(location: LocationModel) -> str | None:
2451
+ if boundary_index is None:
2452
+ return None
2453
+ hit = match_boundary(location.file, boundary_index, self.config.project_root)
2454
+ return hit.relative_path if hit else None
2455
+
2456
+ middleware_by_boundary: dict[str | None, list[MiddlewareModel]] = {}
2457
+ for mw in global_auth_middleware:
2458
+ middleware_by_boundary.setdefault(boundary_for(mw.location), []).append(mw)
2459
+
2460
+ mapping: list[RouteAuthModel] = []
2461
+ for route in routes:
2462
+ route_boundary = boundary_for(route.handler_location)
2463
+ known_auth_names = auth_names_by_boundary.get(route_boundary, set())
2464
+ scoped_middleware = middleware_by_boundary.get(route_boundary, [])
2465
+ has_global_auth_middleware = bool(scoped_middleware)
2466
+ middleware_mechanisms = [f"middleware:{mw.name}" for mw in scoped_middleware]
2467
+ # If a propagation pass (Rails before_action, Django decorator,
2468
+ # Spring filter chain, etc.) already set router_name on this
2469
+ # route AND it matches a known auth dependency, treat it as
2470
+ # authenticated. router_name is overloaded — for Spring Boot it
2471
+ # stores the controller class name, so we only count it as auth
2472
+ # when it matches a known auth dep name.
2473
+ if route.router_name and (
2474
+ route.router_name in known_auth_names
2475
+ or route.router_name.rsplit(".", 1)[-1] in known_auth_names
2476
+ or route.router_name == "SecurityFilterChain"
2477
+ ):
2478
+ router_auth = RouteAuthModel(
2479
+ route_id=route.id,
2480
+ auth_required=True,
2481
+ mechanisms=[route.router_name],
2482
+ )
2483
+ merge_refs_onto_route(router_auth, [route.router_name], route_boundary)
2484
+ mapping.append(router_auth)
2485
+ continue
2486
+
2487
+ if not route.dependencies:
2488
+ # No route-level Depends(), but a global auth middleware may
2489
+ # still protect this endpoint.
2490
+ if has_global_auth_middleware:
2491
+ mapping.append(
2492
+ RouteAuthModel(
2493
+ route_id=route.id,
2494
+ auth_required=True,
2495
+ mechanisms=list(middleware_mechanisms),
2496
+ )
2497
+ )
2498
+ else:
2499
+ mapping.append(
2500
+ RouteAuthModel(
2501
+ route_id=route.id,
2502
+ auth_required=False,
2503
+ )
2504
+ )
2505
+ continue
2506
+
2507
+ matched_mechanisms: list[str] = []
2508
+ for dep_name in route.dependencies:
2509
+ dep_base = dep_name.rsplit(".", 1)[-1]
2510
+
2511
+ if dep_base in known_auth_names or dep_name in known_auth_names:
2512
+ matched_mechanisms.append(dep_name)
2513
+ continue
2514
+
2515
+ name_lower = dep_base.lower()
2516
+ if any(kw in name_lower for kw in AUTH_KEYWORDS):
2517
+ matched_mechanisms.append(dep_name)
2518
+
2519
+ # Even if route-level deps didn't match, middleware can still
2520
+ # provide auth.
2521
+ if not matched_mechanisms and has_global_auth_middleware:
2522
+ matched_mechanisms = list(middleware_mechanisms)
2523
+
2524
+ route_auth = RouteAuthModel(
2525
+ route_id=route.id,
2526
+ auth_required=bool(matched_mechanisms),
2527
+ mechanisms=matched_mechanisms,
2528
+ )
2529
+ merge_refs_onto_route(route_auth, route.dependencies, route_boundary)
2530
+ mapping.append(route_auth)
2531
+
2532
+ auth_model.route_auth_mapping = mapping
2533
+ # Whole-repo informational flag: was any global auth middleware
2534
+ # detected anywhere, regardless of which service it scopes to (see
2535
+ # per-route scoping above for route_auth_mapping itself).
2536
+ auth_model.global_middleware_auth = bool(global_auth_middleware)
2537
+
2538
+ def _populate_route_authorization(
2539
+ self,
2540
+ auth_model: AuthModel,
2541
+ routes: list[RouteModel],
2542
+ ) -> None:
2543
+ """Record per route whether a function-level authorization check gates it.
2544
+
2545
+ Authorization is not authentication. ``auth_required`` says a caller
2546
+ must be signed in; this says whether anything limits WHICH signed-in
2547
+ caller may act — the distinction CWE-285 is about, and the reason an
2548
+ admin action with a bare [Authorize] and no permission check is still a
2549
+ finding.
2550
+
2551
+ Only plugins that analyse authorization report evidence
2552
+ (``extract_route_authorization`` defaults to empty), so a route whose
2553
+ framework does not is left None rather than being called unprotected.
2554
+ The roles and permissions found become the evidence in the existing
2555
+ ``roles_required`` / ``permissions_required`` fields, which nothing
2556
+ populated until now.
2557
+ """
2558
+ evidence: dict[str, Any] = {}
2559
+ for parsed_file in self._parsed_files.values():
2560
+ if not parsed_file.success:
2561
+ continue
2562
+ for fw in self._detected_frameworks:
2563
+ plugin = FrameworkPluginRegistry.get_plugin(fw)
2564
+ if plugin is None or not plugin.detect(parsed_file):
2565
+ continue
2566
+ route_auth_context = self._analysis_contexts.get(parsed_file.language)
2567
+ try:
2568
+ route_auth_items = plugin.extract_route_authorization(
2569
+ parsed_file, context=route_auth_context
2570
+ )
2571
+ except TypeError:
2572
+ route_auth_items = plugin.extract_route_authorization(parsed_file)
2573
+ for item in route_auth_items:
2574
+ # First writer wins: a handler is analysed once, and a
2575
+ # later plugin that also matches the file must not
2576
+ # overwrite a positive finding with its own blank.
2577
+ evidence.setdefault(item.handler, item)
2578
+
2579
+ if not evidence:
2580
+ return
2581
+
2582
+ by_route_id = {ra.route_id: ra for ra in auth_model.route_auth_mapping}
2583
+ for route in routes:
2584
+ item = evidence.get(route.handler_function)
2585
+ if item is None:
2586
+ continue
2587
+ route_auth = by_route_id.get(route.id)
2588
+ if route_auth is None:
2589
+ continue
2590
+ route_auth.authorization_checked = item.checked
2591
+ if item.roles:
2592
+ route_auth.roles_required = sorted(set(route_auth.roles_required) | set(item.roles))
2593
+ if item.permissions:
2594
+ route_auth.permissions_required = sorted(
2595
+ set(route_auth.permissions_required) | set(item.permissions)
2596
+ )
2597
+ if item.source:
2598
+ note = f"authorization check via {item.source}"
2599
+ if note not in route_auth.notes:
2600
+ route_auth.notes.append(note)
2601
+
2602
+ def _link_routes_to_auth_schemes(
2603
+ self,
2604
+ routes: list[RouteModel],
2605
+ auth_model: AuthModel,
2606
+ ) -> None:
2607
+ """Populate ``auth_config_ref`` on each route from the auth model.
2608
+
2609
+ Strategy:
2610
+ 1. Build a dep-name → scheme-id index from ``auth_dependencies.uses_schemes``.
2611
+ 2. For each authenticated route, look up its mechanisms (dep names) in
2612
+ that index and set ``auth_config_ref`` to the first matching scheme.
2613
+ 3. Fallback: if the index yields no match but auth *is* required,
2614
+ assign the first scheme detected in the route's own sub-project
2615
+ boundary AND framework — a scheme from a sibling service in another
2616
+ language can never authenticate this route, so when no
2617
+ same-service/framework scheme exists the ref is left unset rather
2618
+ than guessed across services. A repo with exactly one detected
2619
+ scheme keeps the original behaviour (assign it): with a single
2620
+ candidate repo-wide there is no cross-service ambiguity to resolve,
2621
+ and single-scheme apps — the common case this fallback exists for —
2622
+ keep working unchanged.
2623
+ """
2624
+ scheme_by_dep: dict[str, str] = {}
2625
+ for dep in auth_model.auth_dependencies:
2626
+ for scheme_id in dep.uses_schemes:
2627
+ scheme_by_dep[dep.name] = scheme_id
2628
+
2629
+ mapping_by_route: dict[str, RouteAuthModel] = {
2630
+ m.route_id: m for m in auth_model.route_auth_mapping
2631
+ }
2632
+ schemes_detected = auth_model.schemes_detected
2633
+ # Single-scheme repos: first-detected is the only-detected, so it
2634
+ # stays the fallback regardless of where it lives.
2635
+ single_scheme = schemes_detected[0].id if len(schemes_detected) == 1 else None
2636
+ scheme_index = self._auth_boundary_index()
2637
+
2638
+ def scoped_fallback_scheme(route: RouteModel) -> str | None:
2639
+ """First scheme detected in the route's own service and framework.
2640
+
2641
+ Mirrors the name-scoped propagation passes above: without this, a
2642
+ route whose mechanism matches no scheme-carrying dependency gets
2643
+ whichever scheme was detected first anywhere in the repo — on a
2644
+ polyglot monorepo that is usually a sibling service's scheme (the
2645
+ crAPI bug: every Spring/Django route pointed at the Flask
2646
+ chatbot's JWT scheme). Boundary is None for every location in a
2647
+ single-project repo, so there the scope reduces to the framework
2648
+ check alone; among qualifying schemes, first-detected order wins
2649
+ as before.
2650
+ """
2651
+ route_boundary = self._boundary_of(route.handler_location, scheme_index)
2652
+ for scheme in schemes_detected:
2653
+ if scheme.framework != route.framework:
2654
+ continue
2655
+ if self._boundary_of(scheme.location, scheme_index) != route_boundary:
2656
+ continue
2657
+ return scheme.id
2658
+ return None
2659
+
2660
+ for route in routes:
2661
+ mapping = mapping_by_route.get(route.id)
2662
+ if not mapping or not mapping.auth_required:
2663
+ continue
2664
+ for mech in mapping.mechanisms:
2665
+ mech_base = mech.rsplit(".", 1)[-1]
2666
+ if mech_base in scheme_by_dep:
2667
+ route.auth_config_ref = scheme_by_dep[mech_base]
2668
+ break
2669
+ if mech in scheme_by_dep:
2670
+ route.auth_config_ref = scheme_by_dep[mech]
2671
+ break
2672
+ if not route.auth_config_ref:
2673
+ route.auth_config_ref = single_scheme or scoped_fallback_scheme(route)
2674
+
2675
+ # =========================================================================
2676
+ # Middleware Extraction
2677
+ # =========================================================================
2678
+
2679
+ def _extract_middleware(self) -> list[MiddlewareModel]:
2680
+ """Extract middleware from all files."""
2681
+ middleware: list[MiddlewareModel] = []
2682
+
2683
+ for parsed_file in self._parsed_files.values():
2684
+ if not parsed_file.success:
2685
+ continue
2686
+
2687
+ for fw in self._detected_frameworks:
2688
+ plugin = FrameworkPluginRegistry.get_plugin(fw)
2689
+ if plugin and plugin.detect(parsed_file):
2690
+ for mw in plugin.extract_middleware(parsed_file):
2691
+ middleware.append(
2692
+ MiddlewareModel(
2693
+ id=stable_id("mw", mw.name, mw.middleware_type),
2694
+ name=mw.name,
2695
+ type=mw.middleware_type,
2696
+ location=LocationModel(
2697
+ file=str(mw.location.file),
2698
+ line=mw.location.line,
2699
+ ),
2700
+ order=mw.order,
2701
+ applies_to=mw.applies_to_patterns or ["all"]
2702
+ if mw.applies_to_all
2703
+ else [],
2704
+ operations=mw.operations,
2705
+ )
2706
+ )
2707
+
2708
+ return middleware
2709
+
2710
+ # =========================================================================
2711
+ # Call Site Extraction
2712
+ # =========================================================================
2713
+
2714
+ def _extract_all_calls(self) -> list[FunctionCallModel]:
2715
+ """Extract all function call sites from the call graph.
2716
+
2717
+ Assigns a ``sequence_index`` to each call so the reasoning engine
2718
+ can reason about intra-function ordering (e.g. mutation-before-authz).
2719
+ """
2720
+ if not self._call_graph:
2721
+ return []
2722
+
2723
+ raw_calls = list(self._call_graph.to_manifest_calls())
2724
+
2725
+ # Group by caller and sort by line number to assign sequence_index.
2726
+ from collections import defaultdict
2727
+
2728
+ by_caller: dict[str, list[dict]] = defaultdict(list)
2729
+ for cd in raw_calls:
2730
+ by_caller[cd["caller"]].append(cd)
2731
+ for group in by_caller.values():
2732
+ group.sort(key=lambda c: c["location"].get("line", 0))
2733
+ for idx, cd in enumerate(group):
2734
+ cd["_sequence_index"] = idx
2735
+
2736
+ calls: list[FunctionCallModel] = []
2737
+ for call_dict in raw_calls:
2738
+ try:
2739
+ ctx = call_dict.get("context", {})
2740
+ call = FunctionCallModel(
2741
+ id=call_dict["id"],
2742
+ caller=call_dict["caller"],
2743
+ callee=call_dict["callee"],
2744
+ callee_resolved=call_dict["callee_resolved"],
2745
+ location=LocationModel(
2746
+ file=call_dict["location"]["file"],
2747
+ line=call_dict["location"]["line"],
2748
+ column=call_dict["location"].get("column", 0),
2749
+ ),
2750
+ context=CallContextModel(
2751
+ in_try_block=ctx.get("in_try_block", False),
2752
+ in_conditional=ctx.get("in_conditional", False),
2753
+ in_loop=ctx.get("in_loop", False),
2754
+ ),
2755
+ possible_callees=call_dict.get("possible_callees", []),
2756
+ sequence_index=call_dict.get("_sequence_index"),
2757
+ )
2758
+ calls.append(call)
2759
+ except (KeyError, ValueError, TypeError) as e:
2760
+ logger.error("Failed to convert call: %s", e, exc_info=True)
2761
+ self._warnings.append(
2762
+ AnalysisWarning(
2763
+ phase="call_extraction",
2764
+ message=f"Failed to convert call: {e}",
2765
+ file=call_dict.get("location", {}).get("file"),
2766
+ )
2767
+ )
2768
+ continue
2769
+
2770
+ return calls
2771
+
2772
+ # =========================================================================
2773
+ # Data Flow Analysis
2774
+ # =========================================================================
2775
+
2776
+ def _analyze_data_flows(
2777
+ self, routes: list[RouteModel]
2778
+ ) -> tuple[list[DataFlowModel], dict[str, int]]:
2779
+ """
2780
+ Analyze data flows from entry points to sinks.
2781
+
2782
+ Uses inter-procedural taint tracking through the call graph.
2783
+ Returns (flows, stats) for manifest metadata.
2784
+ """
2785
+ flows: list[DataFlowModel] = []
2786
+ self._data_flow_stats = {
2787
+ "entry_points_analyzed": 0,
2788
+ "origins_identified": 0,
2789
+ "flows_discovered": 0,
2790
+ "truncated_flows": 0,
2791
+ }
2792
+
2793
+ # ── Ruby intra-method taint (runs without a call graph) ──────────────
2794
+ ruby_files = [
2795
+ pf for pf in self._parsed_files.values() if pf.success and pf.language == Language.RUBY
2796
+ ]
2797
+ if ruby_files:
2798
+ from ..frameworks.ruby.taint_scanner import RubyTaintScanner
2799
+
2800
+ # P5: pass the TypeResolver from the Ruby AnalysisContext so the
2801
+ # taint scanner can make structural type checks.
2802
+ ruby_ctx = self._analysis_contexts.get(Language.RUBY)
2803
+ type_resolver = ruby_ctx.type_resolver if ruby_ctx else None
2804
+
2805
+ for flow_dict in RubyTaintScanner(ruby_files, type_resolver=type_resolver).scan():
2806
+ try:
2807
+ flows.append(DataFlowModel(**flow_dict))
2808
+ self._data_flow_stats["flows_discovered"] += 1
2809
+ except (KeyError, ValueError, TypeError) as exc:
2810
+ logger.warning("Ruby taint flow model error: %s", exc)
2811
+
2812
+ # ── JS/TS intra-method taint (runs without a call graph) ─────────────
2813
+ js_files = [
2814
+ pf
2815
+ for pf in self._parsed_files.values()
2816
+ if pf.success and pf.language == Language.JAVASCRIPT
2817
+ ]
2818
+ if js_files:
2819
+ from ..frameworks.js.taint_scanner import JSTaintScanner
2820
+
2821
+ for flow_dict in JSTaintScanner(js_files).scan():
2822
+ try:
2823
+ flows.append(DataFlowModel(**flow_dict))
2824
+ self._data_flow_stats["flows_discovered"] += 1
2825
+ except (KeyError, ValueError, TypeError) as exc:
2826
+ logger.warning("JS taint flow model error: %s", exc)
2827
+
2828
+ # ── Stored-content (DB read) → unescaped Handlebars named-channel
2829
+ # taint (own .hbs discovery — not a registered Language/parser;
2830
+ # see template_scanner.py) ───────────────────────────────────────
2831
+ from .template_scanner import HandlebarsStoredXssTaintScanner
2832
+
2833
+ for flow_dict in HandlebarsStoredXssTaintScanner(
2834
+ self.config.project_root, js_files
2835
+ ).scan():
2836
+ try:
2837
+ flows.append(DataFlowModel(**flow_dict))
2838
+ self._data_flow_stats["flows_discovered"] += 1
2839
+ except (KeyError, ValueError, TypeError) as exc:
2840
+ logger.warning("Handlebars stored-content taint flow model error: %s", exc)
2841
+
2842
+ # ── Python intra-method taint (runs without a call graph) ──────────
2843
+ py_files = [
2844
+ pf
2845
+ for pf in self._parsed_files.values()
2846
+ if pf.success and pf.language == Language.PYTHON
2847
+ ]
2848
+ if py_files:
2849
+ from ..frameworks.python.taint_scanner import PythonTaintScanner
2850
+
2851
+ for flow_dict in PythonTaintScanner(py_files).scan():
2852
+ try:
2853
+ flows.append(DataFlowModel(**flow_dict))
2854
+ self._data_flow_stats["flows_discovered"] += 1
2855
+ except (KeyError, ValueError, TypeError) as exc:
2856
+ logger.warning("Python taint flow model error: %s", exc)
2857
+
2858
+ # ── Java intra-method taint (runs without a call graph) ───────────
2859
+ java_files = [
2860
+ pf for pf in self._parsed_files.values() if pf.success and pf.language == Language.JAVA
2861
+ ]
2862
+ if java_files:
2863
+ from ..frameworks.java.taint_scanner import JavaTaintScanner
2864
+
2865
+ for flow_dict in JavaTaintScanner(java_files).scan():
2866
+ try:
2867
+ flows.append(DataFlowModel(**flow_dict))
2868
+ self._data_flow_stats["flows_discovered"] += 1
2869
+ except (KeyError, ValueError, TypeError) as exc:
2870
+ logger.warning("Java taint flow model error: %s", exc)
2871
+
2872
+ # C# / .NET taint analysis
2873
+ cs_files = [
2874
+ pf
2875
+ for pf in self._parsed_files.values()
2876
+ if pf.success and pf.language == Language.CSHARP
2877
+ ]
2878
+ if cs_files:
2879
+ from ..frameworks.dotnet.taint_scanner import CSharpTaintScanner
2880
+
2881
+ for flow_dict in CSharpTaintScanner(cs_files).scan():
2882
+ try:
2883
+ flows.append(DataFlowModel(**flow_dict))
2884
+ self._data_flow_stats["flows_discovered"] += 1
2885
+ except (KeyError, ValueError, TypeError) as exc:
2886
+ logger.warning("C# taint flow model error: %s", exc)
2887
+
2888
+ # ── ERB template output taint (own file discovery — not a registered
2889
+ # Language/parser; see template_scanner.py) ─────────────────────────
2890
+ from .template_scanner import ErbTemplateTaintScanner
2891
+
2892
+ for flow_dict in ErbTemplateTaintScanner(self.config.project_root, routes).scan():
2893
+ try:
2894
+ flows.append(DataFlowModel(**flow_dict))
2895
+ self._data_flow_stats["flows_discovered"] += 1
2896
+ except (KeyError, ValueError, TypeError) as exc:
2897
+ logger.warning("ERB template taint flow model error: %s", exc)
2898
+
2899
+ if not self._call_graph:
2900
+ return flows, self._data_flow_stats
2901
+
2902
+ successful_files = [p for p in self._parsed_files.values() if p.success]
2903
+ if not successful_files:
2904
+ return flows, self._data_flow_stats
2905
+
2906
+ entry_points = [
2907
+ {
2908
+ "id": r.id,
2909
+ # Carry the entry point's transport (http / cli / task /
2910
+ # websocket / ...) into flow construction. Without this the
2911
+ # origin classifier defaulted every entry point to "http" and
2912
+ # emitted HTTP_* origin types for CLI commands, Celery tasks,
2913
+ # socket events, etc. — see the transport-on-origin defect.
2914
+ "kind": r.kind,
2915
+ "path": r.path,
2916
+ "handler_qualified_name": r.handler_function,
2917
+ "framework": r.framework,
2918
+ "path_params": [{"name": p.name} for p in (r.path_params or [])],
2919
+ "query_params": [{"name": p.name} for p in (r.query_params or [])],
2920
+ "header_params": [{"name": p.name} for p in (r.header_params or [])],
2921
+ "cookie_params": [{"name": p.name} for p in (r.cookie_params or [])],
2922
+ "body": {
2923
+ "body_fields": [
2924
+ {"name": f.name} if hasattr(f, "name") else {"name": f}
2925
+ for f in (r.body.body_fields or [])
2926
+ ]
2927
+ }
2928
+ if r.body
2929
+ else None,
2930
+ }
2931
+ for r in routes
2932
+ ]
2933
+
2934
+ # Reuse shared flow-sensitive bindings (built once in _build_shared_flow_bindings)
2935
+ flow_bindings = self._flow_bindings
2936
+
2937
+ # Resolve handler names to call graph symbols (qualified name consistency)
2938
+ entry_points = self._resolve_entry_points(entry_points)
2939
+
2940
+ max_depth = self.config.analysis.data_flow.max_depth
2941
+
2942
+ try:
2943
+ df_analyzer = DataFlowAnalyzer(
2944
+ call_graph=self._call_graph,
2945
+ parsed_files=successful_files,
2946
+ entry_points=entry_points,
2947
+ flow_bindings=flow_bindings,
2948
+ max_depth=max_depth,
2949
+ )
2950
+ df_analyzer.analyze()
2951
+ self._data_flow_stats = df_analyzer.get_statistics()
2952
+
2953
+ # Convert to manifest format
2954
+ for flow_dict in df_analyzer.to_manifest_flows():
2955
+ try:
2956
+ flow_model = DataFlowModel(**flow_dict)
2957
+ flows.append(flow_model)
2958
+ except (KeyError, ValueError, TypeError) as e:
2959
+ logger.error("Failed to convert data flow to model: %s", e, exc_info=True)
2960
+ self._warnings.append(
2961
+ AnalysisWarning(
2962
+ phase="data_flow",
2963
+ message=f"Failed to convert data flow: {e}",
2964
+ )
2965
+ )
2966
+
2967
+ except Exception as e:
2968
+ logger.error("Data flow analysis failed: %s", e, exc_info=True)
2969
+ self._warnings.append(
2970
+ AnalysisWarning(
2971
+ phase="data_flow",
2972
+ message=f"Data flow analysis failed: {e}",
2973
+ )
2974
+ )
2975
+
2976
+ return flows, self._data_flow_stats
2977
+
2978
+ def _resolve_entry_points(self, entry_points: list[dict[str, Any]]) -> list[dict[str, Any]]:
2979
+ """
2980
+ Resolve handler qualified names to call graph symbols.
2981
+
2982
+ Handles mismatches between route extraction and call graph naming
2983
+ (e.g., module path variations), and the interface-handler pattern where
2984
+ the route annotations live on an interface method but the body lives in
2985
+ an implementing class (e.g. Micronaut operation interfaces: routes are
2986
+ declared on ``*Operations`` interfaces and the ``@Controller`` class
2987
+ implements them). Taint must seed from the concrete implementation —
2988
+ the interface method has no body, so a manifest handler pointing at it
2989
+ yields zero data flows.
2990
+ """
2991
+ if not self._call_graph:
2992
+ return entry_points
2993
+
2994
+ cg = self._call_graph
2995
+ symbols = set(cg._symbols.keys())
2996
+
2997
+ # interface simple-name -> {implementing class qualified names}. Sourced
2998
+ # from parsed classes (base_classes includes Java `implements`); the
2999
+ # built CallGraph does not expose the builder's class-base map.
3000
+ iface_impls: dict[str, set[str]] = {}
3001
+ for pf in self._parsed_files.values():
3002
+ if not getattr(pf, "success", False):
3003
+ continue
3004
+ for cls in getattr(pf, "classes", None) or []:
3005
+ try:
3006
+ cls_qname = cls.qualified_name.full
3007
+ except AttributeError:
3008
+ continue
3009
+ for base in getattr(cls, "base_classes", None) or []:
3010
+ iface_impls.setdefault(base.rsplit(".", 1)[-1], set()).add(cls_qname)
3011
+
3012
+ def _redirect_to_impl(handler_qn: str) -> str:
3013
+ """If handler is declared on an interface a concrete class implements,
3014
+ redirect to that class's method (where the body/params live)."""
3015
+ if "." not in handler_qn:
3016
+ return handler_qn
3017
+ owner, method = handler_qn.rsplit(".", 1)
3018
+ impls = iface_impls.get(owner.rsplit(".", 1)[-1])
3019
+ if not impls:
3020
+ return handler_qn
3021
+ fallback = None
3022
+ for impl_cls in impls:
3023
+ cand = f"{impl_cls}.{method}"
3024
+ if cand == handler_qn or cand not in symbols:
3025
+ continue
3026
+ node = cg.get_node(cand)
3027
+ # Prefer a concrete implementation with a body (call edges) or one
3028
+ # not flagged abstract; keep the interface handler otherwise.
3029
+ if cg.get_callees(cand) or not getattr(node, "is_abstract", False):
3030
+ return cand
3031
+ fallback = fallback or cand
3032
+ return fallback or handler_qn
3033
+
3034
+ resolved = []
3035
+ for ep in entry_points:
3036
+ handler = ep.get("handler_qualified_name")
3037
+ if not handler:
3038
+ resolved.append(ep)
3039
+ continue
3040
+
3041
+ chosen = handler if handler in symbols else None
3042
+ if chosen is None:
3043
+ # Try common variations (module-path prefix stripping, __init__).
3044
+ candidates = [handler, handler.replace(".__init__", "")]
3045
+ if "." in handler:
3046
+ parts = handler.split(".")
3047
+ candidates += [".".join(parts[i:]) for i in range(1, len(parts))]
3048
+ for cand in candidates:
3049
+ if cand in symbols:
3050
+ chosen = cand
3051
+ break
3052
+ # Suffix match on the handler tail. Some plugins record the
3053
+ # handler module as the *routing* file rather than the view's
3054
+ # module (e.g. Django: `urls.UserSessionLoginApi.post` or the
3055
+ # function-based `api_router.favorite_post`, while the symbols
3056
+ # are `app.authentication.apis.UserSessionLoginApi.post` and
3057
+ # `app.api.views.favorite_post`). Prefix stripping can't bridge
3058
+ # that. Try the `Class.method` tail first, then the bare name,
3059
+ # accepting a match only when it is unambiguous.
3060
+ if chosen is None and "." in handler:
3061
+ parts = handler.split(".")
3062
+ for depth in (2, 1):
3063
+ if depth > len(parts):
3064
+ continue
3065
+ tail = "." + ".".join(parts[-depth:])
3066
+ tail_matches = [s for s in symbols if s.endswith(tail)]
3067
+ if len(tail_matches) == 1:
3068
+ chosen = tail_matches[0]
3069
+ break
3070
+ chosen = chosen or handler
3071
+
3072
+ # Interface-handler → concrete implementation (Micronaut operation
3073
+ # interfaces, and any handler declared on an implemented interface).
3074
+ redirected = _redirect_to_impl(chosen)
3075
+ if redirected != handler:
3076
+ ep = dict(ep)
3077
+ ep["handler_qualified_name"] = redirected
3078
+ resolved.append(ep)
3079
+
3080
+ return resolved
3081
+
3082
+ return resolved
3083
+
3084
+ # =========================================================================
3085
+ # Integration Detection
3086
+ # =========================================================================
3087
+
3088
+ def _detect_integrations(self) -> list[IntegrationModel]:
3089
+ """Detect external integrations with usage tracking and SDK analysis."""
3090
+ from .integration_detector import IntegrationDetector
3091
+
3092
+ detector = IntegrationDetector(
3093
+ list(self._parsed_files.values()),
3094
+ type_resolver=self._get_type_resolver(),
3095
+ )
3096
+ return detector.to_manifest_models()
3097
+
3098
+ def _scan_literals(self) -> LiteralsModel:
3099
+ """Scan all string literals for URLs, SQL fragments, and connection strings."""
3100
+ from .literal_scanner import LiteralScanner
3101
+
3102
+ scanner = LiteralScanner(list(self._parsed_files.values()))
3103
+ return scanner.to_manifest_models()
3104
+
3105
+ def _detect_weak_hash_facts(self) -> list[WeakHashFactModel]:
3106
+ """Record each weak/fast hash applied to password/credential-named data.
3107
+
3108
+ A FACT layer (not a taint sink): dispatches Python files to the Python
3109
+ scanner and Ruby files to the Ruby scanner, mirroring how `_scan_literals`
3110
+ and the language-split flow analysis handle files by language.
3111
+ """
3112
+ facts: list[WeakHashFactModel] = []
3113
+
3114
+ py_files = [
3115
+ pf
3116
+ for pf in self._parsed_files.values()
3117
+ if pf.success and pf.language == Language.PYTHON
3118
+ ]
3119
+ if py_files:
3120
+ from ..frameworks.python.weak_hash_facts import PythonWeakHashScanner
3121
+
3122
+ try:
3123
+ facts.extend(PythonWeakHashScanner(py_files).scan())
3124
+ except Exception as exc: # pragma: no cover - defensive
3125
+ logger.warning("Python weak-hash-fact scan failed: %s", exc)
3126
+
3127
+ ruby_files = [
3128
+ pf for pf in self._parsed_files.values() if pf.success and pf.language == Language.RUBY
3129
+ ]
3130
+ if ruby_files:
3131
+ from ..frameworks.ruby.weak_hash_facts import RubyWeakHashScanner
3132
+
3133
+ try:
3134
+ facts.extend(RubyWeakHashScanner(ruby_files).scan())
3135
+ except Exception as exc: # pragma: no cover - defensive
3136
+ logger.warning("Ruby weak-hash-fact scan failed: %s", exc)
3137
+
3138
+ return facts
3139
+
3140
+ def _classify_sensitivity(
3141
+ self,
3142
+ integrations: list[IntegrationModel],
3143
+ literals: LiteralsModel,
3144
+ ) -> None:
3145
+ """Classify sensitivity on integrations and SQL patterns (mutates in place)."""
3146
+ from .sensitivity_classifier import SensitivityClassifier
3147
+
3148
+ classifier = SensitivityClassifier()
3149
+ classifier.enrich_integrations(integrations)
3150
+ classifier.enrich_sql_patterns(literals.sql_patterns)
3151
+
3152
+ def _tag_capabilities(
3153
+ self,
3154
+ integrations: list[IntegrationModel],
3155
+ routes: list[RouteModel],
3156
+ configuration: ConfigurationModel,
3157
+ ) -> list[CapabilityModel]:
3158
+ """Infer business capabilities from integrations, routes, and config."""
3159
+ from .capability_tagger import CapabilityTagger
3160
+
3161
+ tagger = CapabilityTagger()
3162
+ return tagger.tag(integrations, routes, configuration)
3163
+
3164
+ # =========================================================================
3165
+ # Configuration Extraction
3166
+ # =========================================================================
3167
+
3168
+ def _extract_configuration(self) -> ConfigurationModel:
3169
+ """Extract configuration usage from code and .env files."""
3170
+ from .config_scanner import ConfigScanner
3171
+
3172
+ env_var_names: dict[str, list[LocationModel]] = {}
3173
+
3174
+ # Phase 1: env vars referenced in code (os.getenv, os.environ.get)
3175
+ for parsed_file in self._parsed_files.values():
3176
+ if not parsed_file.success:
3177
+ continue
3178
+ for call in parsed_file.call_sites:
3179
+ if call.callee_name in {"os.environ.get", "os.getenv", "environ.get"}:
3180
+ for arg in call.arguments:
3181
+ if arg.position == 0 and arg.literal_value:
3182
+ var_name = str(arg.literal_value)
3183
+ if var_name not in env_var_names:
3184
+ env_var_names[var_name] = []
3185
+ env_var_names[var_name].append(
3186
+ LocationModel(
3187
+ file=str(call.location.file),
3188
+ line=call.location.line,
3189
+ )
3190
+ )
3191
+
3192
+ env_vars: list[EnvVarUsageModel] = [
3193
+ EnvVarUsageModel(name=name, locations=locations)
3194
+ for name, locations in env_var_names.items()
3195
+ ]
3196
+
3197
+ # Phase 2: discover .env files and merge any new variable names
3198
+ scanner = ConfigScanner(self.config.project_root)
3199
+ env_file_vars = scanner.to_env_var_models()
3200
+ existing_names = {ev.name for ev in env_vars}
3201
+ for ev_model in env_file_vars:
3202
+ if ev_model.name not in existing_names:
3203
+ env_vars.append(ev_model)
3204
+
3205
+ # Phase 3: discover config files
3206
+ config_files = scanner.to_config_file_models()
3207
+
3208
+ # Phase 4: capture allow-listed framework settings (actuator exposure,
3209
+ # datasource driver/scheme, active profile, H2 console) for downstream
3210
+ # framework-mediated reachability.
3211
+ framework_settings = scanner.to_framework_config_models()
3212
+
3213
+ return ConfigurationModel(
3214
+ env_vars_used=env_vars,
3215
+ config_files=config_files,
3216
+ framework_settings=framework_settings,
3217
+ )
3218
+
3219
+ def _scan_config_file_secrets(self) -> list[LiteralPatternModel]:
3220
+ """Scan every discovered config file's values for known secret
3221
+ value formats (not just .env variable names — see config_scanner.py).
3222
+ """
3223
+ from .config_scanner import ConfigScanner
3224
+
3225
+ scanner = ConfigScanner(self.config.project_root)
3226
+ return scanner.to_secret_pattern_models()
3227
+
3228
+ def _detect_container_facts(self) -> list[ContainerPrivilegeFactModel]:
3229
+ """Record whether each discovered Dockerfile runs its container as root.
3230
+
3231
+ A deployment FACT (CWE-250, execution with unnecessary privileges),
3232
+ not a taint sink: a Dockerfile isn't program source, so this reads the
3233
+ files collected by the discover stage directly — never the parsed-code
3234
+ pipeline — and stays independent of the language/framework plugins.
3235
+ """
3236
+ from .container_facts import DockerfileUserExtractor
3237
+
3238
+ dockerfiles = (
3239
+ [f.path for f in self._discovery_result.dockerfiles]
3240
+ if self._discovery_result is not None
3241
+ else []
3242
+ )
3243
+ if not dockerfiles:
3244
+ return []
3245
+
3246
+ try:
3247
+ return DockerfileUserExtractor(self.config.project_root, dockerfiles).extract()
3248
+ except Exception as exc: # pragma: no cover - defensive
3249
+ logger.warning("Dockerfile container-fact scan failed: %s", exc)
3250
+ return []
3251
+
3252
+ # =========================================================================
3253
+ # Function/Class Collection
3254
+ # =========================================================================
3255
+
3256
+ def _collect_all_functions(self) -> tuple[list[FunctionModel], dict[str, str]]:
3257
+ """Collect all functions (free + class methods) from parsed files.
3258
+
3259
+ Returns the function list and a qualified_name -> func_id index
3260
+ so that _collect_all_classes can resolve method IDs.
3261
+ """
3262
+ functions: list[FunctionModel] = []
3263
+ qn_to_id: dict[str, str] = {}
3264
+
3265
+ def _normalize_body(source: str | None) -> str:
3266
+ """Normalize function body for hashing: strip comments, blank lines, and collapse whitespace."""
3267
+ if not source:
3268
+ return ""
3269
+ lines = []
3270
+ for line in source.splitlines():
3271
+ stripped = line.strip()
3272
+ if not stripped or stripped.startswith("#"):
3273
+ continue
3274
+ if "#" in stripped:
3275
+ stripped = stripped[: stripped.index("#")].rstrip()
3276
+ if stripped:
3277
+ lines.append(stripped)
3278
+ return "\n".join(lines)
3279
+
3280
+ def _content_hash(func: ParsedFunction) -> str: # noqa: F821
3281
+ parts = []
3282
+ for p in func.parameters:
3283
+ parts.append(f"{p.name}:{p.type_annotation or ''}")
3284
+ parts.append(f"ret:{func.return_type or ''}")
3285
+ parts.append(f"ann:{','.join(d.name for d in func.decorators)}")
3286
+ body = _normalize_body(func.body_source)
3287
+ parts.append(f"body:{hashlib.sha256(body.encode()).hexdigest()[:16]}")
3288
+ raw = "|".join(parts)
3289
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
3290
+
3291
+ def _append(func: ParsedFunction) -> None: # noqa: F821
3292
+ func_id = stable_id("func", func.qualified_name.full)
3293
+ qn_to_id[func.qualified_name.full] = func_id
3294
+ functions.append(
3295
+ FunctionModel(
3296
+ id=func_id,
3297
+ qualified_name=func.qualified_name.full,
3298
+ name=func.name,
3299
+ location=LocationModel(
3300
+ file=str(func.location.file),
3301
+ line=func.location.line,
3302
+ column=func.location.column,
3303
+ end_line=func.location.end_line,
3304
+ ),
3305
+ is_async=func.is_async,
3306
+ binding=func.binding,
3307
+ visibility=self._infer_visibility(func.name),
3308
+ parameters=[
3309
+ ParameterModel(
3310
+ name=p.name,
3311
+ type_annotation=p.type_annotation,
3312
+ default_value=p.default_value,
3313
+ is_variadic=p.is_variadic,
3314
+ is_keyword_variadic=p.is_keyword_variadic,
3315
+ )
3316
+ for p in func.parameters
3317
+ ],
3318
+ return_type=func.return_type,
3319
+ annotations=[d.name for d in func.decorators],
3320
+ docstring=func.docstring,
3321
+ owner_type=func.owner_type,
3322
+ content_hash=_content_hash(func),
3323
+ )
3324
+ )
3325
+
3326
+ files_collected = 0
3327
+ for parsed_file in self._parsed_files.values():
3328
+ if not parsed_file.success:
3329
+ continue
3330
+ self._check_memory("enrich", files_collected)
3331
+ files_collected += 1
3332
+ for func in parsed_file.functions:
3333
+ _append(func)
3334
+ for cls in parsed_file.classes:
3335
+ for method in cls.methods:
3336
+ _append(method)
3337
+
3338
+ return functions, qn_to_id
3339
+
3340
+ @staticmethod
3341
+ def _infer_visibility(name: str) -> str | None:
3342
+ """Infer visibility from Python naming convention."""
3343
+ if name.startswith("__") and name.endswith("__"):
3344
+ return "public"
3345
+ if name.startswith("__") or name.startswith("_"):
3346
+ return "private"
3347
+ return "public"
3348
+
3349
+ def _collect_all_classes(self, func_id_index: dict[str, str]) -> list[ClassModel]:
3350
+ """Collect all classes from parsed files.
3351
+
3352
+ Args:
3353
+ func_id_index: qualified_name -> func_id mapping built by
3354
+ _collect_all_functions, used to resolve method IDs.
3355
+ """
3356
+ classes: list[ClassModel] = []
3357
+
3358
+ classes_scanned = 0
3359
+ for parsed_file in self._parsed_files.values():
3360
+ if not parsed_file.success:
3361
+ continue
3362
+
3363
+ self._check_memory("enrich", classes_scanned)
3364
+ classes_scanned += 1
3365
+
3366
+ for cls in parsed_file.classes:
3367
+ method_ids = [func_id_index.get(m.qualified_name.full, m.name) for m in cls.methods]
3368
+ classes.append(
3369
+ ClassModel(
3370
+ id=stable_id("cls", cls.qualified_name.full),
3371
+ qualified_name=cls.qualified_name.full,
3372
+ name=cls.name,
3373
+ location=LocationModel(
3374
+ file=str(cls.location.file),
3375
+ line=cls.location.line,
3376
+ column=cls.location.column,
3377
+ end_line=cls.location.end_line,
3378
+ ),
3379
+ base_classes=cls.base_classes,
3380
+ annotations=[d.name for d in cls.decorators],
3381
+ methods=method_ids,
3382
+ docstring=cls.docstring,
3383
+ )
3384
+ )
3385
+
3386
+ return classes
3387
+
3388
+ # =========================================================================
3389
+ # Manifest Building
3390
+ # =========================================================================
3391
+
3392
+ def _build_analysis_metadata(self) -> AnalysisMetadataModel:
3393
+ """Build analysis metadata from real statistics."""
3394
+ truncated_flows = self._data_flow_stats.get("truncated_flows", 0)
3395
+ unresolved_calls = 0
3396
+
3397
+ if self._call_graph:
3398
+ cg_stats = self._call_graph.get_statistics()
3399
+ resolution = cg_stats.get("resolution_confidence", {})
3400
+ unresolved_calls = resolution.get("UNRESOLVED", 0)
3401
+
3402
+ warnings = list(self._runtime_gate_warnings)
3403
+ surface_ledger_dict = None
3404
+ if self._surface_ledger is not None:
3405
+ surface_ledger_dict = self._surface_ledger.to_manifest_dict()
3406
+
3407
+ return AnalysisMetadataModel(
3408
+ data_flow_mode=self.config.analysis.data_flow.mode,
3409
+ data_flow_depth=self.config.analysis.data_flow.max_depth,
3410
+ truncated_flows=truncated_flows,
3411
+ unresolved_calls=unresolved_calls,
3412
+ entry_points_withheld_unresolved=self._entry_points_withheld_unresolved,
3413
+ warnings=warnings,
3414
+ surface_ledger=surface_ledger_dict,
3415
+ enrichment_rejected=dict(self._enrichment_rejected),
3416
+ )
3417
+
3418
+ def _build_manifest(
3419
+ self,
3420
+ routes: list[RouteModel],
3421
+ functions: list[FunctionModel],
3422
+ classes: list[ClassModel],
3423
+ calls: list[FunctionCallModel],
3424
+ data_flows: list[DataFlowModel],
3425
+ auth: AuthModel,
3426
+ middleware: list[MiddlewareModel],
3427
+ dependencies: DependenciesModel, # noqa: F821
3428
+ integrations: list[IntegrationModel],
3429
+ capabilities: list[CapabilityModel],
3430
+ schemas: dict[str, SchemaModel],
3431
+ literals: LiteralsModel,
3432
+ weak_hash_facts: list[WeakHashFactModel],
3433
+ container_facts: list[ContainerPrivilegeFactModel],
3434
+ configuration: ConfigurationModel,
3435
+ analysis_time_ms: int,
3436
+ ) -> Manifest:
3437
+ """Build the final manifest."""
3438
+ # Get project name
3439
+ project_name = self.config.project_root.name
3440
+ pyproject = self.config.project_root / "pyproject.toml"
3441
+ if pyproject.exists():
3442
+ try:
3443
+ import tomllib
3444
+
3445
+ data = tomllib.loads(pyproject.read_text())
3446
+ project_name = data.get("project", {}).get("name", project_name)
3447
+ except Exception as e:
3448
+ logger.debug("Could not read project name from pyproject.toml: %s", e)
3449
+
3450
+ # Determine languages — every Language with at least one discovered
3451
+ # file, in enum order. Derived from the enum (not a hand-kept list) so
3452
+ # a newly supported language can't be silently left out, as Ruby was.
3453
+ present = (
3454
+ {f.language for f in self._discovery_result.files} if self._discovery_result else set()
3455
+ )
3456
+ languages = [lang.name.lower() for lang in Language if lang in present]
3457
+
3458
+ # Determine frameworks
3459
+ frameworks = [fw.name.lower() for fw in self._detected_frameworks]
3460
+ try:
3461
+ frameworks_unsupported = detect_unsupported_frameworks(
3462
+ dependencies,
3463
+ self._discovery_result.skipped_files if self._discovery_result else [],
3464
+ )
3465
+ except Exception as e: # noqa: BLE001 - never fail a scan on the census
3466
+ logger.warning("Unsupported-framework census skipped: %s", e)
3467
+ frameworks_unsupported = []
3468
+
3469
+ return Manifest(
3470
+ manifest_version=MANIFEST_VERSION,
3471
+ generated_at=datetime.utcnow(),
3472
+ probe_version=_get_probe_version(),
3473
+ project=ProjectMetadata(
3474
+ root=str(self.config.project_root),
3475
+ name=project_name,
3476
+ languages_detected=languages,
3477
+ frameworks_detected=frameworks,
3478
+ frameworks_unsupported=frameworks_unsupported,
3479
+ files_analyzed=len([p for p in self._parsed_files.values() if p.success]),
3480
+ files_skipped=len([p for p in self._parsed_files.values() if not p.success]),
3481
+ analysis_duration_ms=analysis_time_ms,
3482
+ ),
3483
+ entry_points=routes,
3484
+ functions=functions,
3485
+ classes=classes,
3486
+ calls=calls,
3487
+ data_flows=data_flows,
3488
+ auth=auth,
3489
+ middleware=middleware,
3490
+ dependencies=dependencies,
3491
+ integrations=integrations,
3492
+ capabilities=capabilities,
3493
+ schemas=schemas,
3494
+ literals=literals,
3495
+ weak_hash_facts=weak_hash_facts,
3496
+ container_facts=container_facts,
3497
+ configuration=configuration,
3498
+ analysis_metadata=self._build_analysis_metadata(),
3499
+ )
3500
+
3501
+
3502
+ # =============================================================================
3503
+ # Convenience Function
3504
+ # =============================================================================
3505
+
3506
+
3507
+ def analyze_project(config: CodeBoltConfig) -> AnalysisResult:
3508
+ """
3509
+ Analyze a project and generate manifest.
3510
+
3511
+ Args:
3512
+ config: Configuration for the analysis
3513
+
3514
+ Returns:
3515
+ AnalysisResult containing manifest and metadata
3516
+ """
3517
+ analyzer = ProjectAnalyzer(config)
3518
+ return analyzer.analyze()