cobraphp 0.1.0.dev4__py3-none-any.whl → 0.1.0.dev6__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.
@@ -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
@@ -10,12 +10,16 @@ from __future__ import annotations
10
10
  from php_parser_py import AST
11
11
 
12
12
  from ._call_builder import CallBuilder
13
- from ._database_writes import DatabaseWrite, find_database_writes, reached_database_writes
13
+ from ._database_write_reach import DatabaseWriteReach, reached_database_writes
14
+ from ._database_writes import DatabaseWrite, find_database_writes
14
15
  from ._errors import AnalysisTimeoutError, StaticAnalysisError
15
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
16
19
  from ._records import DataFlowGraph, backward_slice, call_graph_export, data_flow_graph
17
20
  from ._source_kinds import DATABASE, USER_INPUT
18
21
  from ._taint_propagator import TaintPropagator
22
+ from ._value_dependency import is_dependent
19
23
  from ..graphs import GraphExport
20
24
 
21
25
 
@@ -37,10 +41,12 @@ def build_data_flow(
37
41
 
38
42
  Semgrep finds the expressions each Source kind's rule matches; def-use edges inside each function,
39
43
  argument and return edges over the call graph, then a breadth-first walk from those expressions mark the
40
- reached nodes. `timeout_seconds` bounds each Semgrep run; `target_files` (project-relative) restricts
41
- Semgrep to those files, and when none of them exists Semgrep does not run.
44
+ reached nodes. Semgrep scans exactly the files of `project_ast`, from the project root, whatever the
45
+ caller's working directory. `timeout_seconds` bounds the Semgrep run of each Source kind; `target_files`
46
+ (project-relative) restricts Semgrep to those files, and when none of them exists Semgrep does not run.
42
47
 
43
- Raises `DependencyUnavailableError` when the `semgrep` program is not on PATH, `AnalysisTimeoutError`
48
+ Raises `DependencyUnavailableError` when the `semgrep` program is neither in the scripts directory of the
49
+ running Python environment nor on PATH, `AnalysisTimeoutError`
44
50
  when a Semgrep run exceeds `timeout_seconds`, and `StaticAnalysisError` when Semgrep fails, its output is
45
51
  malformed or the AST is malformed.
46
52
  """
@@ -55,6 +61,8 @@ __all__ = [
55
61
  "AnalysisTimeoutError",
56
62
  "DataFlowGraph",
57
63
  "DatabaseWrite",
64
+ "DatabaseWriteReach",
65
+ "Function",
58
66
  "StaticAnalysisError",
59
67
  "app_file_filter",
60
68
  "backward_slice",
@@ -62,6 +70,9 @@ __all__ = [
62
70
  "build_data_flow",
63
71
  "find_database_writes",
64
72
  "framework_excluded_dirs",
73
+ "is_dependent",
74
+ "list_functions",
65
75
  "make_app_file_filter",
76
+ "parse_project",
66
77
  "reached_database_writes",
67
78
  ]
@@ -5,13 +5,23 @@ from __future__ import annotations
5
5
  import functools
6
6
  import tomllib
7
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"))
8
14
 
9
15
 
10
16
  @functools.cache
11
17
  def load_php_ast_types() -> tuple[frozenset[str], frozenset[str], frozenset[str]]:
12
18
  """Return (constant, callable, assign) node type sets."""
13
- raw = tomllib.loads((resources.files("cobraphp.analysis") / "php_ast_types.toml").read_text(encoding="utf-8"))
14
- constant = frozenset(raw["constant_node_types"]["values"])
15
- callable_ = frozenset(raw["callable_types"]["values"])
16
- assign = frozenset(raw["assign_node_types"]["values"])
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"]))
17
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,11 +7,13 @@ 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
-
11
- # PHP AST node types of anonymous callables; with the named ones, every callable declaration.
12
- CLOSURE_TYPE = "Expr_Closure"
13
- ARROW_FUNCTION_TYPE = "Expr_ArrowFunction"
14
- CALLABLE_DECL_TYPES = (*NAMED_CALLABLE_TYPES, CLOSURE_TYPE, ARROW_FUNCTION_TYPE)
10
+ from ._declarations import (
11
+ ARROW_FUNCTION_TYPE,
12
+ CALLABLE_DECL_TYPES,
13
+ CLOSURE_TYPE,
14
+ callable_name,
15
+ )
16
+ from ._node_order import nodes_in_path_order
15
17
 
16
18
 
17
19
  class CallBuilder:
@@ -45,7 +47,7 @@ class CallBuilder:
45
47
  resolution targets.
46
48
  """
47
49
  callee_index = CalleeIndex(self._ast)
48
- for callable_node in self._ast.nodes(lambda n: n.node_type in CALLABLE_DECL_TYPES):
50
+ for callable_node in nodes_in_path_order(self._ast, lambda n: n.node_type in CALLABLE_DECL_TYPES):
49
51
  callable_name = self._register_callable(call_graph, callable_node)
50
52
  if callable_node.node_type in NAMED_CALLABLE_TYPES:
51
53
  callee_index.add(callable_node, callable_name)
@@ -70,21 +72,7 @@ class CallBuilder:
70
72
 
71
73
  def _extract_callable_name(self, callable_node: Node) -> str:
72
74
  """Extract name from a callable declaration node."""
73
- if callable_node.node_type in NAMED_CALLABLE_TYPES:
74
- identifier_node = next(
75
- (child for child in self._ast.succ(callable_node) if child.node_type == "Identifier"), None
76
- )
77
- if not identifier_node:
78
- raise StaticAnalysisError(f"Callable node {callable_node.id} missing Identifier child for name")
79
- callable_name = identifier_node.all_properties.get("name", "")
80
- if not callable_name:
81
- raise StaticAnalysisError(f"Callable {callable_node.id} Identifier missing 'name' property")
82
- return str(callable_name)
83
- if callable_node.node_type == CLOSURE_TYPE:
84
- return "{closure}"
85
- if callable_node.node_type == ARROW_FUNCTION_TYPE:
86
- return "{arrow}"
87
- return "{unknown}"
75
+ return callable_name(self._ast, callable_node)
88
76
 
89
77
  def _extract_return_type(self, callable_node: Node) -> str:
90
78
  """Extract return type hint from a callable node, if present."""
@@ -100,7 +88,7 @@ class CallBuilder:
100
88
 
101
89
  def _build_call_sites(self, call_graph: CallGraph, callee_index: CalleeIndex) -> None:
102
90
  """Extract call sites and link to callees."""
103
- call_site_nodes = list(self._ast.nodes(lambda n: n.node_type in CALL_SITE_TYPES))
91
+ call_site_nodes = nodes_in_path_order(self._ast, lambda n: n.node_type in CALL_SITE_TYPES)
104
92
 
105
93
  for call_site_node in call_site_nodes:
106
94
  try:
@@ -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"})
@@ -32,8 +35,10 @@ class CalleeIndex:
32
35
  self, and static denote the enclosing class and a literal class name
33
36
  denotes that class by short name. With no receiver class (parent, a
34
37
  variable, an expression) or no such method in it, the call resolves to
35
- the first method of that name in AST order. A call whose name is an
36
- expression has no callee. For every key, the first declaration wins.
38
+ the first method of that name. A call whose name is an expression has
39
+ no callee. For every key, the first declaration wins, with declarations
40
+ taken in files sorted by POSIX relative path and in source order within
41
+ a file.
37
42
  """
38
43
 
39
44
  def __init__(self, ast: AST) -> None:
@@ -92,7 +97,7 @@ class CalleeIndex:
92
97
 
93
98
  # Name of the nearest enclosing class-like declaration; None when absent or anonymous.
94
99
  def _enclosing_class_name(ast: AST, node: Node) -> str | None:
95
- enclosing = next((a for a in ast.ancestors(node) if a.node_type in _CLASS_LIKE_TYPES), None)
100
+ enclosing = enclosing_class(ast, node)
96
101
  if enclosing is None:
97
102
  return None
98
103
  return _child_name(ast, enclosing, _IDENTIFIER_TYPES)
@@ -110,3 +115,16 @@ def _child_name(ast: AST, node: Node, child_types: frozenset[str]) -> str | None
110
115
  # Segment after the last namespace separator.
111
116
  def _short_name(name: str) -> str:
112
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,208 @@
1
+ """The database writes the value of a data-flow node reaches (docs/design-analysis-subpackage.md).
2
+
3
+ `DatabaseWriteReach` derives the steps of the walk once from a project AST and a data-flow graph: the
4
+ successor lists of the graph, the step from a node to the expression that holds its value, and the step from
5
+ a closure's `use` variable to the variables of that name in the closure. A query then walks only the steps
6
+ within `max_depth` of its node.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import threading
12
+ import weakref
13
+
14
+ from php_parser_py import AST, Node
15
+
16
+ from ._database_writes import _INTERPOLATED_TYPE, _SCOPE_TYPES, _VARIABLE_TYPE, DatabaseWrite, _name
17
+ from ._node_order import nodes_in_path_order
18
+ from ._records import DataFlowGraph
19
+
20
+ # Expressions whose value is computed from the value of each child: casts, unary and binary operators
21
+ # (concatenation and null coalescing among them) and interpolated strings. An array literal holds the values
22
+ # of its items' children. A ternary's result is its second and third child; its condition is not part of the
23
+ # result, except in the short form `a ?: b`, whose first child is also the result.
24
+ _CAST_PREFIX = "Expr_Cast_"
25
+ _BINARY_PREFIX = "Expr_BinaryOp_"
26
+ _UNARY_TYPES = frozenset({"Expr_UnaryMinus", "Expr_UnaryPlus", "Expr_BitwiseNot", "Expr_BooleanNot"})
27
+ _ARRAY_TYPE = "Expr_Array"
28
+ _ARRAY_ITEM_TYPE = "ArrayItem"
29
+ _TERNARY_TYPE = "Expr_Ternary"
30
+ _CLOSURE_USE_TYPE = "ClosureUse"
31
+ _CLOSURE_TYPE = "Expr_Closure"
32
+
33
+
34
+ class DatabaseWriteReach:
35
+ """The steps of the reach walk over one project AST and data-flow graph, with the writes to test.
36
+
37
+ The constructor reads `project_ast` and `graph` once and keeps its own copy of every step, so a later
38
+ change to either does not change the results of this object; it keeps no reference to them.
39
+ """
40
+
41
+ __slots__ = ("_steps", "_writes", "_operand_writes")
42
+
43
+ def __init__(self, project_ast: AST, graph: DataFlowGraph, writes: tuple[DatabaseWrite, ...]) -> None:
44
+ self._steps = _walk_steps(project_ast, graph)
45
+ self._writes, self._operand_writes = _write_index(writes)
46
+
47
+ @classmethod
48
+ def _with_steps(cls, steps: dict[str, tuple[str, ...]], writes: tuple[DatabaseWrite, ...]) -> DatabaseWriteReach:
49
+ reach = cls.__new__(cls)
50
+ reach._steps = steps
51
+ reach._writes, reach._operand_writes = _write_index(writes)
52
+ return reach
53
+
54
+ def reached_database_writes(self, node_id: str, *, max_depth: int = 10) -> tuple[DatabaseWrite, ...]:
55
+ """The writes that the value of `node_id` reaches within `max_depth` steps, in the order of `writes`.
56
+
57
+ The reached nodes are `node_id` itself and the nodes a breadth-first walk reaches within `max_depth`
58
+ steps; a negative `max_depth` counts as 0, and a node outside the graph and the AST reaches only
59
+ itself. A write is reached when one of its `operand_ids` is a reached node. An empty result means that
60
+ no path within `max_depth` steps leads to a recognised write, not that the value is never stored.
61
+ """
62
+ steps = self._steps
63
+ visited = {node_id}
64
+ frontier = [node_id]
65
+ for _ in range(max_depth):
66
+ following: list[str] = []
67
+ for current in frontier:
68
+ for step in steps.get(current, ()):
69
+ if step not in visited:
70
+ visited.add(step)
71
+ following.append(step)
72
+ if not following:
73
+ break
74
+ frontier = following
75
+ operand_writes = self._operand_writes
76
+ indices = {index for node in visited for index in operand_writes.get(node, ())}
77
+ return tuple(self._writes[index] for index in sorted(indices))
78
+
79
+
80
+ def reached_database_writes(
81
+ project_ast: AST,
82
+ graph: DataFlowGraph,
83
+ writes: tuple[DatabaseWrite, ...],
84
+ node_id: str,
85
+ *,
86
+ max_depth: int = 10,
87
+ ) -> tuple[DatabaseWrite, ...]:
88
+ """The `writes` that the value of `node_id` reaches within `max_depth` steps.
89
+
90
+ Equal to `DatabaseWriteReach(project_ast, graph, writes).reached_database_writes(node_id, max_depth=...)`.
91
+ The steps of the most recent call are kept and reused while the call passes the same `project_ast` object
92
+ and a `graph` whose `predecessors` equal the ones the steps were derived from; any other call derives
93
+ them again.
94
+ """
95
+ return _reach_for(project_ast, graph, writes).reached_database_writes(node_id, max_depth=max_depth)
96
+
97
+
98
+ class _CacheEntry:
99
+ __slots__ = ("ast", "predecessors", "reach", "writes")
100
+
101
+ def __init__(
102
+ self,
103
+ ast: weakref.ref[AST],
104
+ predecessors: dict[str, tuple[str, ...]],
105
+ writes: tuple[DatabaseWrite, ...],
106
+ reach: DatabaseWriteReach,
107
+ ) -> None:
108
+ self.ast = ast
109
+ self.predecessors = predecessors
110
+ self.writes = writes
111
+ self.reach = reach
112
+
113
+
114
+ # The steps of the most recent `reached_database_writes` call, replaced as a whole under the lock. The entry
115
+ # refers to the AST weakly and holds a copy of the graph's `predecessors`, which a later call compares with.
116
+ _cache: list[_CacheEntry] = []
117
+ _cache_lock = threading.Lock()
118
+
119
+
120
+ def _reach_for(ast: AST, graph: DataFlowGraph, writes: tuple[DatabaseWrite, ...]) -> DatabaseWriteReach:
121
+ with _cache_lock:
122
+ entry = _cache[0] if _cache else None
123
+ if entry is None or entry.ast() is not ast or entry.predecessors != graph.predecessors:
124
+ predecessors = {node: tuple(ids) for node, ids in graph.predecessors.items()}
125
+ reach = DatabaseWriteReach(ast, graph, writes)
126
+ _cache[:] = [_CacheEntry(weakref.ref(ast), predecessors, writes, reach)]
127
+ return reach
128
+ if entry.writes is not writes and entry.writes != writes:
129
+ entry.reach = DatabaseWriteReach._with_steps(entry.reach._steps, writes)
130
+ entry.writes = writes
131
+ return entry.reach
132
+
133
+
134
+ def _write_index(writes: tuple[DatabaseWrite, ...]) -> tuple[tuple[DatabaseWrite, ...], dict[str, tuple[int, ...]]]:
135
+ lists: dict[str, list[int]] = {}
136
+ for index, write in enumerate(writes):
137
+ for operand in write.operand_ids:
138
+ indices = lists.setdefault(operand, [])
139
+ if not indices or indices[-1] != index:
140
+ indices.append(index)
141
+ return tuple(writes), {operand: tuple(indices) for operand, indices in lists.items()}
142
+
143
+
144
+ # Every step of the walk: the graph's successor lists (the reverse of `predecessors`), then the step from each
145
+ # AST node to the expression that holds its value, and from each closure `use` variable to the variables of
146
+ # that name in the closure's own scope.
147
+ def _walk_steps(ast: AST, graph: DataFlowGraph) -> dict[str, tuple[str, ...]]:
148
+ lists: dict[str, list[str]] = {}
149
+ for node_id, predecessors in graph.predecessors.items():
150
+ for predecessor in predecessors:
151
+ lists.setdefault(predecessor, []).append(node_id)
152
+ for node in nodes_in_path_order(ast, lambda n: _holds_values(n.node_type)):
153
+ for child, targets in _holding_steps(ast, node):
154
+ lists.setdefault(child, []).extend(targets)
155
+ return {node_id: tuple(ids) for node_id, ids in lists.items()}
156
+
157
+
158
+ def _holds_values(node_type: str) -> bool:
159
+ return (
160
+ node_type in (_ARRAY_TYPE, _TERNARY_TYPE, _CLOSURE_TYPE, _INTERPOLATED_TYPE)
161
+ or node_type in _UNARY_TYPES
162
+ or node_type.startswith((_CAST_PREFIX, _BINARY_PREFIX))
163
+ )
164
+
165
+
166
+ # (child id, target ids) for the children of `node` whose value `node` holds, or for a closure the variables
167
+ # of its `use` list.
168
+ def _holding_steps(ast: AST, node: Node) -> list[tuple[str, list[str]]]:
169
+ node_type = node.node_type
170
+ if node_type == _ARRAY_TYPE:
171
+ return [
172
+ (child.id, [node.id])
173
+ for item in ast.succ(node)
174
+ if item.node_type == _ARRAY_ITEM_TYPE
175
+ for child in ast.succ(item)
176
+ ]
177
+ if node_type == _CLOSURE_TYPE:
178
+ uses = [
179
+ variable
180
+ for use in ast.succ(node)
181
+ if use.node_type == _CLOSURE_USE_TYPE
182
+ for variable in ast.succ(use)
183
+ if variable.node_type == _VARIABLE_TYPE
184
+ ]
185
+ if not uses:
186
+ return []
187
+ scope = _scope_variables(ast, node)
188
+ return [(variable.id, scope.get(_name(variable), [])) for variable in uses]
189
+ children = list(ast.succ(node))
190
+ if node_type == _TERNARY_TYPE and len(children) == 3:
191
+ children = children[1:]
192
+ return [(child.id, [node.id]) for child in children]
193
+
194
+
195
+ # Variable nodes of a closure's own scope by name: its body and its nested arrow functions, and the `use`
196
+ # variables of closures nested in it, which read this scope.
197
+ def _scope_variables(ast: AST, closure: Node) -> dict[str, list[str]]:
198
+ variables: dict[str, list[str]] = {}
199
+ pending = [child for child in ast.succ(closure) if child.node_type != _CLOSURE_USE_TYPE]
200
+ while pending:
201
+ node = pending.pop()
202
+ if node.node_type in _SCOPE_TYPES:
203
+ pending.extend(child for child in ast.succ(node) if child.node_type == _CLOSURE_USE_TYPE)
204
+ continue
205
+ if node.node_type == _VARIABLE_TYPE and _name(node):
206
+ variables.setdefault(_name(node), []).append(node.id)
207
+ pending.extend(ast.succ(node))
208
+ return variables