cobraphp 0.1.0.dev5__tar.gz → 0.1.0.dev7__tar.gz

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 (53) hide show
  1. {cobraphp-0.1.0.dev5/src/cobraphp.egg-info → cobraphp-0.1.0.dev7}/PKG-INFO +34 -6
  2. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/README.md +33 -5
  3. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/pyproject.toml +1 -1
  4. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/__init__.py +8 -1
  5. cobraphp-0.1.0.dev7/src/cobraphp/analysis/_ast_types.py +27 -0
  6. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/_call_builder.py +7 -20
  7. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/_callee_index.py +18 -2
  8. cobraphp-0.1.0.dev7/src/cobraphp/analysis/_declarations.py +27 -0
  9. cobraphp-0.1.0.dev7/src/cobraphp/analysis/_defuse_assignments.py +40 -0
  10. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/_defuse_builder.py +27 -144
  11. cobraphp-0.1.0.dev7/src/cobraphp/analysis/_defuse_interproc.py +143 -0
  12. cobraphp-0.1.0.dev7/src/cobraphp/analysis/_defuse_values.py +85 -0
  13. cobraphp-0.1.0.dev7/src/cobraphp/analysis/_functions.py +138 -0
  14. cobraphp-0.1.0.dev7/src/cobraphp/analysis/_parsing.py +43 -0
  15. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/_records.py +3 -2
  16. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/_taint_graph.py +5 -0
  17. cobraphp-0.1.0.dev7/src/cobraphp/analysis/_value_dependency.py +109 -0
  18. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/frameworks.toml +8 -0
  19. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/php_ast_types.toml +24 -5
  20. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7/src/cobraphp.egg-info}/PKG-INFO +34 -6
  21. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp.egg-info/SOURCES.txt +7 -0
  22. cobraphp-0.1.0.dev5/src/cobraphp/analysis/_ast_types.py +0 -17
  23. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/LICENSE +0 -0
  24. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/setup.cfg +0 -0
  25. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/__init__.py +0 -0
  26. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/_backend.py +0 -0
  27. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/_placeholder.py +0 -0
  28. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/_call_graph.py +0 -0
  29. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/_call_graph_nodes.py +0 -0
  30. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/_database_write_reach.py +0 -0
  31. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/_database_writes.py +0 -0
  32. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/_errors.py +0 -0
  33. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/_file_filter.py +0 -0
  34. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/_node_order.py +0 -0
  35. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/_project_root.py +0 -0
  36. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/_semgrep_runner.py +0 -0
  37. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/_source_kinds.py +0 -0
  38. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/_taint_propagator.py +0 -0
  39. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/_taint_rules.py +0 -0
  40. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/database_writes.toml +0 -0
  41. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/rules/database_taint.yaml +0 -0
  42. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/analysis/rules/user_input_taint.yaml +0 -0
  43. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/config.py +0 -0
  44. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/entries.py +0 -0
  45. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/errors.py +0 -0
  46. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/graphs.py +0 -0
  47. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/project.py +0 -0
  48. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/py.typed +0 -0
  49. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp/results.py +0 -0
  50. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp.egg-info/dependency_links.txt +0 -0
  51. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp.egg-info/requires.txt +0 -0
  52. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/src/cobraphp.egg-info/top_level.txt +0 -0
  53. {cobraphp-0.1.0.dev5 → cobraphp-0.1.0.dev7}/tests/test_interface.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cobraphp
3
- Version: 0.1.0.dev5
3
+ Version: 0.1.0.dev7
4
4
  Summary: Placeholder for the Python interface of CobraPHP, a static taint analyzer for PHP projects.
5
5
  License-Expression: GPL-2.0-only
6
6
  Requires-Python: >=3.11
@@ -20,7 +20,7 @@ Python interface of [CobraPHP](https://github.com/jhu-seclab-cobra/CobraPHP), th
20
20
 
21
21
  **Placeholder.** The Python binding is not fully implemented. Interfaces and results may change between versions.
22
22
 
23
- The subpackage `cobraphp.analysis` builds a call graph and a data flow, and finds the database writes a value reaches, from a PHP project parsed with [php-parser-py](https://pypi.org/project/php-parser-py/). The version is a pre-release. The name follows the pattern `bindings-<language>-<analyzer>`.
23
+ The subpackage `cobraphp.analysis` lists functions, builds a call graph and a data flow, and finds the database writes a value reaches, from a PHP project parsed with [php-parser-py](https://pypi.org/project/php-parser-py/). The version is a pre-release. The name follows the pattern `bindings-<language>-<analyzer>`.
24
24
 
25
25
  ## Install
26
26
 
@@ -60,21 +60,49 @@ with build_project(Path("/srv/project")) as built:
60
60
  built.export_graphs(Path("graphs.jsonl"))
61
61
  ```
62
62
 
63
+ List declarations and their source lines without building a call graph or running Semgrep:
64
+
65
+ ```python
66
+ from cobraphp.analysis import list_functions, parse_project
67
+
68
+ ast = parse_project("/path/to/project", target_php="8.5")
69
+ for function in list_functions(ast):
70
+ print(function.name, function.class_kind, function.visibility,
71
+ function.is_static, function.is_abstract, function.parameters,
72
+ function.has_body, function.absolute_file, function.start_line, function.end_line)
73
+ ```
74
+
75
+ `parse_project(project_path: str | Path, *, target_php: str, file_filter=None)` accepts a PHP version string and an optional path predicate. Individual parse failures remain in `ast.skipped_files`; directory and runtime failures raise `StaticAnalysisError`.
76
+ `list_functions(project_ast: AST) -> tuple[Function, ...]` returns immutable records;
77
+ [Function declarations](docs/design-analysis-subpackage.md#function-declarations) specifies every field.
78
+
63
79
  Build the call graph and the data flow of a project with `cobraphp.analysis`:
64
80
 
65
81
  ```python
66
82
  from pathlib import Path
67
- from php_parser_py import PHPVersion, parse_project
68
- from cobraphp.analysis import USER_INPUT, backward_slice, build_call_graph, build_data_flow, make_app_file_filter
83
+ from cobraphp.analysis import USER_INPUT, backward_slice, build_call_graph, build_data_flow, make_app_file_filter, parse_project
69
84
 
70
85
  root = Path("/srv/project")
71
- ast = parse_project(str(root), target_php=PHPVersion(8, 5), file_filter=make_app_file_filter(root))
72
- calls = [e for e in build_call_graph(ast).edges if e.type == "CCG_SITE_CALL"]
86
+ ast = parse_project(root, target_php="8.5", file_filter=make_app_file_filter(root))
87
+ graph = build_call_graph(ast)
88
+ calls = [e for e in graph.edges if e.type == "CCG_SITE_CALL"]
89
+ called_names = {n.id: n.props["called_name"] for n in graph.nodes if n.type == "CCG_CALL_SITE"}
73
90
  flow = build_data_flow(ast, timeout_seconds=600)
74
91
  for node_id in flow.tainted[USER_INPUT]:
75
92
  print(node_id, backward_slice(flow, node_id, max_depth=3))
76
93
  ```
77
94
 
95
+ Query a value dependency inside a function or file scope without Semgrep:
96
+
97
+ ```python
98
+ from cobraphp.analysis import is_dependent
99
+
100
+ function = next(f for f in list_functions(ast) if f.name == "total")
101
+ print(is_dependent(ast, function.node_id, sink="$total", source="$amount"))
102
+ ```
103
+
104
+ Names match source expressions exactly after removing all whitespace; `$a` and `$a['k']` are separate names. The query is intraprocedural, transitive and flow-insensitive. [Value dependency](docs/design-value-dependency.md) specifies supported assignments, cost and limitations.
105
+
78
106
  Find the database writes the value of a data-flow node reaches; an empty result means that no path to a recognised write was found, not that the value is never stored. `DatabaseWriteReach` derives the steps of the walk once, for many queries; `reached_database_writes(ast, flow, writes, node_id)` answers one:
79
107
 
80
108
  ```python
@@ -6,7 +6,7 @@ Python interface of [CobraPHP](https://github.com/jhu-seclab-cobra/CobraPHP), th
6
6
 
7
7
  **Placeholder.** The Python binding is not fully implemented. Interfaces and results may change between versions.
8
8
 
9
- The subpackage `cobraphp.analysis` builds a call graph and a data flow, and finds the database writes a value reaches, from a PHP project parsed with [php-parser-py](https://pypi.org/project/php-parser-py/). The version is a pre-release. The name follows the pattern `bindings-<language>-<analyzer>`.
9
+ The subpackage `cobraphp.analysis` lists functions, builds a call graph and a data flow, and finds the database writes a value reaches, from a PHP project parsed with [php-parser-py](https://pypi.org/project/php-parser-py/). The version is a pre-release. The name follows the pattern `bindings-<language>-<analyzer>`.
10
10
 
11
11
  ## Install
12
12
 
@@ -46,21 +46,49 @@ with build_project(Path("/srv/project")) as built:
46
46
  built.export_graphs(Path("graphs.jsonl"))
47
47
  ```
48
48
 
49
+ List declarations and their source lines without building a call graph or running Semgrep:
50
+
51
+ ```python
52
+ from cobraphp.analysis import list_functions, parse_project
53
+
54
+ ast = parse_project("/path/to/project", target_php="8.5")
55
+ for function in list_functions(ast):
56
+ print(function.name, function.class_kind, function.visibility,
57
+ function.is_static, function.is_abstract, function.parameters,
58
+ function.has_body, function.absolute_file, function.start_line, function.end_line)
59
+ ```
60
+
61
+ `parse_project(project_path: str | Path, *, target_php: str, file_filter=None)` accepts a PHP version string and an optional path predicate. Individual parse failures remain in `ast.skipped_files`; directory and runtime failures raise `StaticAnalysisError`.
62
+ `list_functions(project_ast: AST) -> tuple[Function, ...]` returns immutable records;
63
+ [Function declarations](docs/design-analysis-subpackage.md#function-declarations) specifies every field.
64
+
49
65
  Build the call graph and the data flow of a project with `cobraphp.analysis`:
50
66
 
51
67
  ```python
52
68
  from pathlib import Path
53
- from php_parser_py import PHPVersion, parse_project
54
- from cobraphp.analysis import USER_INPUT, backward_slice, build_call_graph, build_data_flow, make_app_file_filter
69
+ from cobraphp.analysis import USER_INPUT, backward_slice, build_call_graph, build_data_flow, make_app_file_filter, parse_project
55
70
 
56
71
  root = Path("/srv/project")
57
- ast = parse_project(str(root), target_php=PHPVersion(8, 5), file_filter=make_app_file_filter(root))
58
- calls = [e for e in build_call_graph(ast).edges if e.type == "CCG_SITE_CALL"]
72
+ ast = parse_project(root, target_php="8.5", file_filter=make_app_file_filter(root))
73
+ graph = build_call_graph(ast)
74
+ calls = [e for e in graph.edges if e.type == "CCG_SITE_CALL"]
75
+ called_names = {n.id: n.props["called_name"] for n in graph.nodes if n.type == "CCG_CALL_SITE"}
59
76
  flow = build_data_flow(ast, timeout_seconds=600)
60
77
  for node_id in flow.tainted[USER_INPUT]:
61
78
  print(node_id, backward_slice(flow, node_id, max_depth=3))
62
79
  ```
63
80
 
81
+ Query a value dependency inside a function or file scope without Semgrep:
82
+
83
+ ```python
84
+ from cobraphp.analysis import is_dependent
85
+
86
+ function = next(f for f in list_functions(ast) if f.name == "total")
87
+ print(is_dependent(ast, function.node_id, sink="$total", source="$amount"))
88
+ ```
89
+
90
+ Names match source expressions exactly after removing all whitespace; `$a` and `$a['k']` are separate names. The query is intraprocedural, transitive and flow-insensitive. [Value dependency](docs/design-value-dependency.md) specifies supported assignments, cost and limitations.
91
+
64
92
  Find the database writes the value of a data-flow node reaches; an empty result means that no path to a recognised write was found, not that the value is never stored. `DatabaseWriteReach` derives the steps of the walk once, for many queries; `reached_database_writes(ast, flow, writes, node_id)` answers one:
65
93
 
66
94
  ```python
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
5
5
 
6
6
  [project]
7
7
  name = "cobraphp"
8
- version = "0.1.0.dev5"
8
+ version = "0.1.0.dev7"
9
9
  description = "Placeholder for the Python interface of CobraPHP, a static taint analyzer for PHP projects."
10
10
  readme = "README.md"
11
11
  license = "GPL-2.0-only"
@@ -1,4 +1,4 @@
1
- """Static analysis of a php-parser-py AST in Python: call graph, data-flow graph, backward slice, and the
1
+ """Static analysis of a php-parser-py AST in Python: functions, call graph, data-flow graph, backward slice, and the
2
2
  database writes a data-flow node reaches.
3
3
 
4
4
  The call graph comes back as CCG records of `cobraphp.GraphExport`; Semgrep runs as the `semgrep` program
@@ -14,9 +14,12 @@ from ._database_write_reach import DatabaseWriteReach, reached_database_writes
14
14
  from ._database_writes import DatabaseWrite, find_database_writes
15
15
  from ._errors import AnalysisTimeoutError, StaticAnalysisError
16
16
  from ._file_filter import app_file_filter, framework_excluded_dirs, make_app_file_filter
17
+ from ._functions import Function, list_functions
18
+ from ._parsing import parse_project
17
19
  from ._records import DataFlowGraph, backward_slice, call_graph_export, data_flow_graph
18
20
  from ._source_kinds import DATABASE, USER_INPUT
19
21
  from ._taint_propagator import TaintPropagator
22
+ from ._value_dependency import is_dependent
20
23
  from ..graphs import GraphExport
21
24
 
22
25
 
@@ -59,6 +62,7 @@ __all__ = [
59
62
  "DataFlowGraph",
60
63
  "DatabaseWrite",
61
64
  "DatabaseWriteReach",
65
+ "Function",
62
66
  "StaticAnalysisError",
63
67
  "app_file_filter",
64
68
  "backward_slice",
@@ -66,6 +70,9 @@ __all__ = [
66
70
  "build_data_flow",
67
71
  "find_database_writes",
68
72
  "framework_excluded_dirs",
73
+ "is_dependent",
74
+ "list_functions",
69
75
  "make_app_file_filter",
76
+ "parse_project",
70
77
  "reached_database_writes",
71
78
  ]
@@ -0,0 +1,27 @@
1
+ """Load the PHP AST node type sets of php_ast_types.toml."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import tomllib
7
+ from importlib import resources
8
+ from typing import cast
9
+
10
+
11
+ @functools.cache
12
+ def _php_ast_types() -> dict[str, dict[str, object]]:
13
+ return tomllib.loads((resources.files("cobraphp.analysis") / "php_ast_types.toml").read_text(encoding="utf-8"))
14
+
15
+
16
+ @functools.cache
17
+ def load_php_ast_types() -> tuple[frozenset[str], frozenset[str], frozenset[str]]:
18
+ """Return (constant, callable, assign) node type sets."""
19
+ raw = _php_ast_types()
20
+ constant = frozenset(cast(list[str], raw["constant_node_types"]["values"]))
21
+ callable_ = frozenset(raw["callable_kinds"])
22
+ assign = frozenset(cast(list[str], raw["assign_node_types"]["values"]))
23
+ return constant, callable_, assign
24
+
25
+
26
+ def declaration_kinds(section: str) -> dict[str, str]:
27
+ return cast(dict[str, str], _php_ast_types()[section])
@@ -7,13 +7,14 @@ from php_parser_py import AST, Node, NodeNotInFileError
7
7
  from ._errors import StaticAnalysisError
8
8
  from ._call_graph import CallGraph
9
9
  from ._callee_index import CALL_SITE_TYPES, NAMED_CALLABLE_TYPES, CalleeIndex
10
+ from ._declarations import (
11
+ ARROW_FUNCTION_TYPE,
12
+ CALLABLE_DECL_TYPES,
13
+ CLOSURE_TYPE,
14
+ callable_name,
15
+ )
10
16
  from ._node_order import nodes_in_path_order
11
17
 
12
- # PHP AST node types of anonymous callables; with the named ones, every callable declaration.
13
- CLOSURE_TYPE = "Expr_Closure"
14
- ARROW_FUNCTION_TYPE = "Expr_ArrowFunction"
15
- CALLABLE_DECL_TYPES = (*NAMED_CALLABLE_TYPES, CLOSURE_TYPE, ARROW_FUNCTION_TYPE)
16
-
17
18
 
18
19
  class CallBuilder:
19
20
  """Builds CallGraph from PHP AST.
@@ -71,21 +72,7 @@ class CallBuilder:
71
72
 
72
73
  def _extract_callable_name(self, callable_node: Node) -> str:
73
74
  """Extract name from a callable declaration node."""
74
- if callable_node.node_type in NAMED_CALLABLE_TYPES:
75
- identifier_node = next(
76
- (child for child in self._ast.succ(callable_node) if child.node_type == "Identifier"), None
77
- )
78
- if not identifier_node:
79
- raise StaticAnalysisError(f"Callable node {callable_node.id} missing Identifier child for name")
80
- callable_name = identifier_node.all_properties.get("name", "")
81
- if not callable_name:
82
- raise StaticAnalysisError(f"Callable {callable_node.id} Identifier missing 'name' property")
83
- return str(callable_name)
84
- if callable_node.node_type == CLOSURE_TYPE:
85
- return "{closure}"
86
- if callable_node.node_type == ARROW_FUNCTION_TYPE:
87
- return "{arrow}"
88
- return "{unknown}"
75
+ return callable_name(self._ast, callable_node)
89
76
 
90
77
  def _extract_return_type(self, callable_node: Node) -> str:
91
78
  """Extract return type hint from a callable node, if present."""
@@ -4,6 +4,8 @@ from __future__ import annotations
4
4
 
5
5
  from php_parser_py import AST, Node
6
6
 
7
+ from ._ast_types import declaration_kinds
8
+
7
9
  # PHP AST node types of the declarations and calls callee resolution relates.
8
10
  FUNCTION_DECL_TYPE = "Stmt_Function"
9
11
  METHOD_DECL_TYPE = "Stmt_ClassMethod"
@@ -16,7 +18,8 @@ _NAME_TYPES = frozenset({"Name", "Name_FullyQualified", "Name_Relative"})
16
18
  _IDENTIFIER_TYPES = frozenset({"Identifier"})
17
19
  _VARIABLE_TYPE = "Expr_Variable"
18
20
  # Declarations that own methods; $this, self, and static refer to the nearest one.
19
- _CLASS_LIKE_TYPES = frozenset({"Stmt_Class", "Stmt_Trait", "Stmt_Interface", "Stmt_Enum"})
21
+ CLASS_LIKE_KINDS = declaration_kinds("class_like_kinds")
22
+ _CLASS_LIKE_TYPES = frozenset(CLASS_LIKE_KINDS)
20
23
  # PHP's receiver variable and class keywords bound to the enclosing class (keywords are case-insensitive).
21
24
  _THIS_VARIABLE = "this"
22
25
  _ENCLOSING_CLASS_KEYWORDS = frozenset({"self", "static"})
@@ -94,7 +97,7 @@ class CalleeIndex:
94
97
 
95
98
  # Name of the nearest enclosing class-like declaration; None when absent or anonymous.
96
99
  def _enclosing_class_name(ast: AST, node: Node) -> str | None:
97
- enclosing = next((a for a in ast.ancestors(node) if a.node_type in _CLASS_LIKE_TYPES), None)
100
+ enclosing = enclosing_class(ast, node)
98
101
  if enclosing is None:
99
102
  return None
100
103
  return _child_name(ast, enclosing, _IDENTIFIER_TYPES)
@@ -112,3 +115,16 @@ def _child_name(ast: AST, node: Node, child_types: frozenset[str]) -> str | None
112
115
  # Segment after the last namespace separator.
113
116
  def _short_name(name: str) -> str:
114
117
  return name.rsplit(NAMESPACE_SEPARATOR, 1)[-1]
118
+
119
+
120
+ def enclosing_class(ast: AST, node: Node) -> Node | None:
121
+ return next((a for a in ast.ancestors(node) if a.node_type in _CLASS_LIKE_TYPES), None)
122
+
123
+
124
+ def called_name(ast: AST, site: Node) -> str | None:
125
+ child = next(iter(ast.succ(site, lambda edge: edge.get("field") == "name")), None)
126
+ types = _NAME_TYPES if site.node_type == FUNCTION_CALL_TYPE else _IDENTIFIER_TYPES
127
+ if child is None or child.node_type not in types:
128
+ return None
129
+ name = child.get("name")
130
+ return _short_name(str(name)) if name else None
@@ -0,0 +1,27 @@
1
+ """Callable declaration classification and names shared by AST consumers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from php_parser_py import AST, Node
6
+
7
+ from ._ast_types import declaration_kinds, load_php_ast_types
8
+ from ._callee_index import NAMED_CALLABLE_TYPES
9
+ from ._errors import StaticAnalysisError
10
+
11
+ CLOSURE_TYPE = "Expr_Closure"
12
+ ARROW_FUNCTION_TYPE = "Expr_ArrowFunction"
13
+ CALLABLE_DECL_TYPES = load_php_ast_types()[1]
14
+ CALLABLE_KINDS = declaration_kinds("callable_kinds")
15
+ _ANONYMOUS_NAMES = {CLOSURE_TYPE: "{closure}", ARROW_FUNCTION_TYPE: "{arrow}"}
16
+
17
+
18
+ def callable_name(ast: AST, node: Node) -> str:
19
+ if node.node_type not in NAMED_CALLABLE_TYPES:
20
+ return _ANONYMOUS_NAMES.get(node.node_type, "{unknown}")
21
+ identifier = next((child for child in ast.succ(node) if child.node_type == "Identifier"), None)
22
+ if identifier is None:
23
+ raise StaticAnalysisError(f"Callable node {node.id} missing Identifier child for name")
24
+ name = identifier.all_properties.get("name", "")
25
+ if not name:
26
+ raise StaticAnalysisError(f"Callable {node.id} Identifier missing 'name' property")
27
+ return str(name)
@@ -0,0 +1,40 @@
1
+ """Assignment decomposition and the values a PHP target writes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import cast
6
+
7
+ from php_parser_py import AST, Node
8
+
9
+ from ._ast_types import _php_ast_types, load_php_ast_types
10
+
11
+ REFERENCE_ASSIGN_TYPES = frozenset(cast(list[str], _php_ast_types()["reference_assign_types"]["values"]))
12
+ PLAIN_ASSIGN_TYPES = frozenset({"Expr_Assign"}) | REFERENCE_ASSIGN_TYPES
13
+ ASSIGN_TYPES = load_php_ast_types()[2] | REFERENCE_ASSIGN_TYPES
14
+ _DESTRUCTURING_TYPES = frozenset({"Expr_List", "Expr_Array"})
15
+
16
+
17
+ def field_children(ast: AST, node: Node, field: str) -> list[Node]:
18
+ return list(ast.succ(node, lambda edge: edge.get("field") == field))
19
+
20
+
21
+ def assignment_parts(ast: AST, node: Node) -> tuple[Node, Node] | None:
22
+ if node.node_type not in ASSIGN_TYPES:
23
+ return None
24
+ children = list(ast.succ(node))
25
+ return (children[0], children[1]) if len(children) >= 2 else None
26
+
27
+
28
+ def written_targets(ast: AST, target: Node) -> list[Node]:
29
+ pending = [target]
30
+ written: list[Node] = []
31
+ while pending:
32
+ node = pending.pop()
33
+ if node.node_type in _DESTRUCTURING_TYPES:
34
+ pending.extend(value for item in field_children(ast, node, "items")
35
+ for value in field_children(ast, item, "value"))
36
+ continue
37
+ written.append(node)
38
+ if node.node_type == "Expr_ArrayDimFetch":
39
+ pending.extend(field_children(ast, node, "var"))
40
+ return written
@@ -13,9 +13,11 @@ from typing import cast
13
13
  from php_parser_py import AST, Node
14
14
 
15
15
  from ._ast_types import load_php_ast_types
16
- from ._call_graph import CallGraph
16
+ from ._defuse_assignments import PLAIN_ASSIGN_TYPES, assignment_parts
17
+ from ._defuse_values import extend_value_edges, scope_nodes
18
+ from ._defuse_interproc import build_interproc_edges as build_interproc_edges
17
19
  from ._node_order import file_nodes_in_path_order, nodes_in_path_order
18
- from ._taint_graph import DataFlowGraph
20
+ from ._taint_graph import DataFlowGraph, ensure_node as _ensure_node
19
21
  from ._taint_rules import CALLABLE_TYPES
20
22
 
21
23
  # Accessor nodes whose taint is inherited from the base Expr_Variable.
@@ -23,7 +25,7 @@ _ACCESSOR_NODE_TYPES = frozenset({"Expr_ArrayDimFetch", "Expr_PropertyFetch"})
23
25
 
24
26
  # Compound assignments (`+=`, `.=`, ...): the target keeps its old value and
25
27
  # folds in the RHS, so the target variable node itself becomes the definition.
26
- _COMPOUND_ASSIGN_TYPES = load_php_ast_types()[2] - {"Expr_Assign"}
28
+ _COMPOUND_ASSIGN_TYPES = load_php_ast_types()[2] - PLAIN_ASSIGN_TYPES
27
29
 
28
30
  # Callables with their own variable scope. An arrow function is absent: PHP
29
31
  # gives it read access to the enclosing scope's variables.
@@ -33,48 +35,35 @@ _NESTED_SCOPE_TYPES = frozenset({"Stmt_Function", "Stmt_ClassMethod", "Expr_Clos
33
35
  def build_intraproc_edges(ast: AST, dataflow_graph: DataFlowGraph) -> None:
34
36
  """Build variable def-use chain edges for all functions and file-level code."""
35
37
  for func_node in nodes_in_path_order(ast, lambda n: n.node_type in CALLABLE_TYPES):
36
- param_defs = _extract_param_defs(ast, func_node)
37
- body_stmts = _get_body_statements(ast, func_node)
38
- _build_defuse_for_stmts(ast, body_stmts, dataflow_graph, initial_defs=param_defs)
38
+ _build_reaching_edges(ast, func_node, dataflow_graph)
39
39
 
40
40
  for file_node in file_nodes_in_path_order(ast):
41
- top_stmts = [c for c in ast.succ(file_node) if c.node_type.startswith("Stmt_")]
42
- _build_defuse_for_stmts(ast, top_stmts, dataflow_graph)
41
+ _build_reaching_edges(ast, file_node, dataflow_graph)
43
42
 
44
43
  _build_accessor_chain_edges(ast, dataflow_graph)
45
44
 
46
45
 
47
- def build_interproc_edges(
48
- ast: AST,
49
- call_graph: CallGraph,
50
- dataflow_graph: DataFlowGraph,
51
- ) -> None:
52
- """Build argument->parameter and return->callsite edges via CallGraph."""
53
- for cg_node_id in call_graph.storage.get_nodes():
54
- node_type = call_graph.storage.get_node_prop(cg_node_id, "node_type")
55
- if node_type != "call_site":
56
- continue
46
+ def build_scope_edges(ast: AST, scope: Node, graph: DataFlowGraph) -> tuple[Node, ...]:
47
+ nodes = scope_nodes(ast, scope)
48
+ reaching = DataFlowGraph()
49
+ _build_reaching_edges(ast, scope, reaching)
50
+ _copy_scope_edges(reaching, graph, {node.id for node in nodes})
51
+ extend_value_edges(ast, nodes, graph)
52
+ return nodes
57
53
 
58
- site_node = call_graph.get_site_node(cg_node_id)
59
- callees = call_graph.get_callees(cg_node_id)
60
54
 
61
- if not callees:
62
- _build_overapprox_edges(ast, site_node.argument_ids, cg_node_id, dataflow_graph)
55
+ def _copy_scope_edges(source: DataFlowGraph, target: DataFlowGraph, owned: set[str]) -> None:
56
+ for source_id, sink_id, _ in source.storage.get_edges():
57
+ if source_id not in owned or sink_id not in owned:
63
58
  continue
59
+ _ensure_node(target, source_id)
60
+ _ensure_node(target, sink_id)
61
+ target.add_structural_edge(source_id, sink_id)
62
+
64
63
 
65
- for callee in callees:
66
- _build_arg_to_param_edges(
67
- ast,
68
- site_node.argument_ids,
69
- callee.parameter_ids,
70
- dataflow_graph,
71
- )
72
- _build_return_to_callsite_edges(
73
- ast,
74
- callee.node_id,
75
- cg_node_id,
76
- dataflow_graph,
77
- )
64
+ def _build_reaching_edges(ast: AST, scope: Node, graph: DataFlowGraph) -> None:
65
+ param_defs = _extract_param_defs(ast, scope)
66
+ _build_defuse_for_stmts(ast, _get_body_statements(ast, scope), graph, initial_defs=param_defs)
78
67
 
79
68
 
80
69
  def _extract_param_defs(ast: AST, func_node: Node) -> dict[str, str]:
@@ -192,10 +181,10 @@ def _assignment_target(ast: AST, node: Node) -> tuple[str, Node, Node] | None:
192
181
  # (variable name, LHS, RHS) of an assignment to a plain variable, else None.
193
182
  if node.node_type != "Expr_Assign" and node.node_type not in _COMPOUND_ASSIGN_TYPES:
194
183
  return None
195
- children = list(ast.succ(node))
196
- if len(children) < 2 or children[0].node_type != "Expr_Variable":
184
+ parts = assignment_parts(ast, node)
185
+ if parts is None or parts[0].node_type != "Expr_Variable":
197
186
  return None
198
- lhs, rhs = children[0], children[1]
187
+ lhs, rhs = parts
199
188
  var_name = cast(str, lhs.all_properties.get("name", ""))
200
189
  if not var_name:
201
190
  return None
@@ -293,109 +282,3 @@ def _walk_accessor_parents(
293
282
  _ensure_node(dataflow_graph, parent.id)
294
283
  dataflow_graph.add_structural_edge(current.id, parent.id)
295
284
  current = parent
296
-
297
-
298
- def _build_arg_to_param_edges(
299
- ast: AST,
300
- argument_ids: list[str],
301
- parameter_ids: list[str],
302
- dataflow_graph: DataFlowGraph,
303
- ) -> None:
304
- """Create edges from call site arguments to callee parameters by position."""
305
- min_len = min(len(argument_ids), len(parameter_ids))
306
- for i in range(min_len):
307
- arg_expr_id = _get_arg_expression_id(ast, argument_ids[i])
308
- if not arg_expr_id:
309
- continue
310
- param_var_id = _get_param_variable_id(ast, parameter_ids[i])
311
- if not param_var_id:
312
- continue
313
- _ensure_node(dataflow_graph, arg_expr_id)
314
- _ensure_node(dataflow_graph, param_var_id)
315
- dataflow_graph.add_structural_edge(arg_expr_id, param_var_id)
316
-
317
-
318
- def _build_overapprox_edges(
319
- ast: AST,
320
- argument_ids: list[str],
321
- callsite_id: str,
322
- dataflow_graph: DataFlowGraph,
323
- ) -> None:
324
- """Over-approximate taint through an unresolved call.
325
-
326
- For a call site with no resolved callee (library, builtin, or dynamic
327
- dispatch), connect each argument expression to the call-site node so a
328
- tainted argument taints the call's result. Semgrep OSS provides no
329
- interprocedural taint to fall back on.
330
- """
331
- for arg_node_id in argument_ids:
332
- arg_expr_id = _get_arg_expression_id(ast, arg_node_id)
333
- if not arg_expr_id:
334
- continue
335
- _ensure_node(dataflow_graph, arg_expr_id)
336
- _ensure_node(dataflow_graph, callsite_id)
337
- dataflow_graph.add_structural_edge(arg_expr_id, callsite_id)
338
-
339
-
340
- def _build_return_to_callsite_edges(
341
- ast: AST,
342
- callee_func_id: str,
343
- callsite_id: str,
344
- dataflow_graph: DataFlowGraph,
345
- ) -> None:
346
- """Create edges from callee return expressions to call site node."""
347
- func_node = ast.node(callee_func_id)
348
- if func_node is None:
349
- return
350
-
351
- for return_stmt in _own_return_statements(ast, func_node):
352
- return_children = list(ast.succ(return_stmt))
353
- if not return_children:
354
- continue
355
- return_expr = return_children[0]
356
- _ensure_node(dataflow_graph, return_expr.id)
357
- _ensure_node(dataflow_graph, callsite_id)
358
- dataflow_graph.add_structural_edge(return_expr.id, callsite_id)
359
-
360
-
361
- def _own_return_statements(ast: AST, func_node: Node) -> list[Node]:
362
- # Stmt_Return nodes at any depth in a callable's body, excluding those of
363
- # callables nested inside it.
364
- found: list[Node] = []
365
- pending = list(ast.succ(func_node))
366
- while pending:
367
- node = pending.pop()
368
- if node.node_type in CALLABLE_TYPES:
369
- continue
370
- if node.node_type == "Stmt_Return":
371
- found.append(node)
372
- pending.extend(ast.succ(node))
373
- return found
374
-
375
-
376
- def _get_arg_expression_id(ast: AST, arg_node_id: str) -> str | None:
377
- """Get the expression node ID inside an Arg wrapper node."""
378
- arg_node = ast.node(arg_node_id)
379
- if arg_node is None:
380
- return None
381
- children = list(ast.succ(arg_node))
382
- if not children:
383
- return None
384
- return cast(str, children[0].id)
385
-
386
-
387
- def _get_param_variable_id(ast: AST, param_node_id: str) -> str | None:
388
- """Get the Expr_Variable node ID inside a Param wrapper node."""
389
- param_node = ast.node(param_node_id)
390
- if param_node is None:
391
- return None
392
- for child in ast.succ(param_node):
393
- if child.node_type == "Expr_Variable":
394
- return cast(str, child.id)
395
- return None
396
-
397
-
398
- def _ensure_node(dataflow_graph: DataFlowGraph, node_id: str) -> None:
399
- """Ensure node exists in graph."""
400
- if not dataflow_graph.storage.contains_node(node_id):
401
- dataflow_graph.add_dataflow_node(node_id)